David Hancock David Hancock - 5 months ago 51
Python Question

How to get the cell at a location in pandas dataframe using a column as the index

Example dataframe:

class fred bill
0 a 23 35
1 b 123 45
2 c 34 45
3 d 4 45


(pandas adds the index (0->3) which isn't needed)

What i want is to say something like:

fred_b_class = df.at['fred','b']
>>> 123


I tried setting the column
'class'
as the index by
pd.set_index('class')


However when calling
df.index.name
it returned
none

Answer

I think you need set_index from column class and then swap arguments in at, because first argument is index and second column name:

df = df.set_index('class')
#df.set_index('class', inplace=True)
print (df)
       fred  bill
class            
a        23    35
b       123    45
c        34    45
d         4    45

print (df.at['b','fred'] )
123
Comments