6

To get a scalar at integer location 0 and column label 'A' in a data frame df, I do chained indexing: df.iloc[0]['A']. This works, but pandas documentation says that chained indexing should be avoided.

An alternative I could come up with is df.iat[0, df.columns.get_loc('A')], which is just too much typing compared with the chained indexing. Is there a shorter way to do this?

Note: .ix indexer is deprecated.

Example:

df=pd.DataFrame({'A':[10,20,30,40]}, index=[3,2,1,0])

    A
------
3   10
2   20
1   30
0   40

The scalar at integer location 0 in column A is 10 and not 40:
df.iat[0, df.columns.get_loc('A')]
Otuput: 10

SergiyKolesnikov
  • 7,369
  • 2
  • 26
  • 47

2 Answers2

6

You can refer to this other post on loc, iloc, at, iat


To answer your question directly:
This is called mixed type indexing. You want to access one dimension by position and the other by label.

To solve this problem, we need to translate either:

  • the position into a label then use loc (or at) for label indexing.
  • the label into a position then use iloc (or iat) for position indexing.

Using loc

We get the label at the 0 position

df.loc[df.index[0], 'A']

Or

df.at[df.index[0], 'A']

Or

df.get_value(df.index[0], 'A')

Using iloc
We get the position of the label using pd.Index.get_loc

df.iloc[0, df.columns.get_loc('A')]

Or

df.iat[0, df.columns.get_loc('A')]

Or

df.get_value(0, df.columns.get_loc('A'), takable=True)

I also included examples of using pd.DataFrame.get_value

piRSquared
  • 285,575
  • 57
  • 475
  • 624
0

Here's Pandas Official Guide on doing Indexing with both Integer and Label. Hope this is helpful.

  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/33837412) – Azhar Khan Feb 16 '23 at 08:47