Pandas: get the first row value of a column
Codemia Knowledge Hub ·
Use df["column"].iloc[0]. It selects the column, then takes the first row by position, regardless of what the index labels are.
Position-based access with iloc
This prints Alice. Because iloc works by position, not by index label, it gives the first row even when the index labels are unusual.
Scalar access with iat
iat is optimized for reading a single cell by row and column position:
It is a little less readable because you have to look up the column position first. For most analysis code, df["name"].iloc[0] is the better choice: clarity matters more than shaving a tiny amount of overhead from one lookup, especially after filters and sorts have changed what "first row" means.
Why loc[0] is not the same
loc uses labels. df.loc[0, "name"] only works when the index actually contains the label 0:
Use iloc for "first row by position" and loc for "row with this label".
Guarding against an empty DataFrame
On an empty DataFrame, iloc[0] raises IndexError. Check first when the data may be filtered down to nothing or comes from an external source:
First row vs first non-null value
If you actually want the first value that is not missing, drop nulls before taking the first one:
Only do this when skipping nulls is really what you want, because it no longer returns the first row.
Mistakes to avoid
- Treating
iloc[0]as a label lookup. It means the first row by position, not the row labeled0. - Using
loc[0, "name"]on a DataFrame whose index does not contain the label0. It fails. - Reading row
0from an empty DataFrame, which raises an error. - Reaching for
iatby default. It is fast for one cell, butdf["name"].iloc[0]is usually easier to read.
Related reading
- pandas get rows which are NOT in other dataframe
- Pandas get topmost n records within each group
- pandas GroupBy columns with NaN missing values
- pandas groupby, then sort within groups
- Pandas join issue columns overlap but no suffix specified
- Pandas Looking up the list of sheets in an excel file
- pandas loc vs. iloc vs. at vs. iat?
- pandas merge join two data frames on multiple columns
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.