Getting first row value of a column in Pandas DataFrame
Start your free 7-days trial now!
To get the first row value of a column in Pandas DataFrame, use the iloc property.
As an example, consider the following DataFrame:
df = pd.DataFrame({"A":[3,4],"B":[5,6]}, index=["a","b"])df
A Ba 3 5b 4 6
Solution
To get the first row value of column B:
df.iloc[0, df.columns.get_loc("B")]
5
Explanation
Since iloc requires integer index rather than labels, we first get the integer index of column B like so:
df.columns.get_loc("B")
1
Anti-pattern
There are other ways of getting the first row value of a column, such as:
df.iloc[0]["B"]
5
Although this solution looks more concise, a problem arises when we try to perform assignment:
df.iloc[0]["B"] = 9 # df may or may not updatedf
A Ba 3 9b 4 6
Here, df.iloc[0] is first called and there is no guarantee whether the returned value is a view or a copy (click here to learn more about the difference). We then extract the value at column B using ["B"] and perform assignment using =. Since we don't know whether df.iloc[0] is a view or a copy, this assignment may or may not end up updating df. In this particular case, the assignment did update df, but in some other cases, df might not get updated.
To avoid these ambiguous cases, we can directly update the value at a particular entry with a single indexing operation using iloc:
df.iloc[0, df.columns.get_loc("B")] = 9 # df will always be updateddf
A Ba 3 9b 4 6