search
Search
Unlock 100+ guides
search toc
close
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

# Getting first row value of a column in Pandas DataFrame

schedule Aug 10, 2023
Last updated
local_offer
PythonPandas
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
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 ```
Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!