how to get back 10 from df.iloc[10]
where df = pd.DataFrame({'a':np.arange(1,12)})
?
I tried df.index but it returns a weird np.array which doesn't contain anything close to 10.
CodePudding user response:
With df.iloc
or df.loc
, you obtain a series that corresponds to the columns of a given row in the dataframe:
>>> df
foo
a 44
b 34
c 65
>>> df.iloc[1]
foo 34
Name: b, dtype: int64
>>> df.index[1]
'b'
>>> df.loc['b']
foo 34
Name: b, dtype: int64
You can see that the index of this second row, here b
, is kept as the name of the series. Hence we can use it to find the position in the index:
>>> ser = df.iloc[1]
>>> df.index.get_indexer([ser.name])[0]
1
Note that Index.get_indexer
only works with arrays, hence the need to get the first element of the answer.
Alternately you can always convert the index to a list and use list.index
to find the element position, but this will likely be much slower:
>>> df.index.to_list().index(ser.name)
1
CodePudding user response:
The most simple solution if the index matches the row numbers is df.iloc[10].name
which returns 10