Home > database >  Can I mix Python dataframe positional index and column name?
Can I mix Python dataframe positional index and column name?

Time:02-07

Can I get an entry in dataframe using negative/positional index and column name? For example,

import pandas as pd
df = pd.DataFrame({'a':[0,1,2], 'b':[3,4,5]})
# df is:
#    a  b
# 0  0  3
# 1  1  4
# 2  2  5
df.iloc[-1]['a']  # got 2
df['a'].iloc[-1]  # got 2
df.loc[1,'a']     # got 1
df.loc[-1,'a']    # got KeyError: -1

CodePudding user response:

No you can't mix both within the same iloc/loc (this used to be the case with the now deprecated ix indexer)

The correct approach would be one of the double slice:

df.iloc[-1]['a']

Note that the "issue" is not specific to negative positional indices. When you do df.loc[1,'a'] you are not slicing per position, but per name. This would also fail with a KeyError if you had no 1 in the index.

CodePudding user response:

No, use df.columns and get_loc, to convert column header label to index location:

df.iloc[-1, df.columns.get_loc('a')]

Output:

2
  •  Tags:  
  • Related