Home > Software engineering >  Why can't I use negative indexing for this pandas dataframe column?
Why can't I use negative indexing for this pandas dataframe column?

Time:07-15

My dataframe is like this:

a = pd.DataFrame({
'Column A': [1, np.nan, 7],
'Column B': [np.nan, 2, 3],
'Column C': [np.nan, 2, np.nan]
})

I can use this index below and get the desired outcome 7.

a["Column A"][2]

However, when I want to find the last one, this one below doesn't work. What could be the reason for that?

a["Column A"][-1]

CodePudding user response:

Because indexing is not positional but by label. For positional indexing use iloc:

a["Column A"].iloc[-1]

CodePudding user response:

If you use square brackets or loc you use this index:

    ||
   \  /
    \/
       Column A  Column B  Column C
    0       1.0       NaN       NaN
    1       NaN       2.0       2.0
    2       7.0       3.0       NaN

Do you see -1 somewhere?

  • Related