Home > Software engineering >  I can only slice my pandas dataframe with a slicing window such as [0:1] to get a specific row, doin
I can only slice my pandas dataframe with a slicing window such as [0:1] to get a specific row, doin

Time:06-02

I have a dataframe df.

type(df) # pandas.core.frame.DataFrame

df[0] # KeyError 0

df[0:1] # Gives row 0 as expected

What is going on? I am sorry I come from an R background and have done some work with Python in the past but thought this was possible. What am I missing?

CodePudding user response:

You're close! If you use .iloc it will return what you are expecting. So for this case you would be

first_row = df.iloc[0]

When you do df[0] it is looking for a column named 0.

reference: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iloc.html

  • Related