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
Generally, ix is label based and acts just as the .loc indexer. However, .ix also supports integer type selections (as in .iloc) where passed an integer. This only works where the index of the DataFrame is not integer based .ix will accept any of the inputs of .loc and .iloc.
If you only want to access a scalar value, the fastest way is to use the at and iat methods, which are implemented on all of the data structures. Similarly to loc, at provides label based scalar lookups, while, iat provides integer based lookups analogously to iloc
Indexing with a Single Index. Another method for accessing elements of an array is to use only a single index, regardless of the size or dimensions of the array. This method is known as linear indexing. While MATLAB displays arrays according to their defined sizes and shapes, they are actually stored in memory as a single column of elements.
Logical Indexing. Another indexing variation, logical indexing, has proven to be both useful and expressive. In logical indexing, you use a single, logical array for the matrix subscript. MATLAB extracts the matrix elements corresponding to the nonzero values of the logical array.
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:
loc
(or at
) for label indexing.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With