Access Rows by integers and Columns by labels Pandas

sir_osthara picture sir_osthara · Jul 26, 2017 · Viewed 7.2k times · Source

My data is like this:

[First row is headers]

Name,Email,Age
Sachith,[email protected],23
Sim,[email protected],234
Yoshi,[email protected],2345
sarla,[email protected],234

I would like to access elements such that rows are specified as integers and columns by labels. i.e for Sim I would like to access it as [1,'Name'] and so-on

My question is should I use loc or ix?

Looking at the documentation, I am confused as to what is a pandas index? Is it used to access rows or columns or both? When I try to print the indices of this data, I get a (4,) dtype=int64 array of [0,1,2,3]. So , are columns not part of the index?

Answer

jezrael picture jezrael · Jul 26, 2017

Use loc or iloc, because ix is deprecated.

print (df)
      Name             Email   Age
0  Sachith      [email protected]    23
1      Sim      [email protected]   234
2    Yoshi  [email protected]  2345
3    sarla   [email protected]   234

#select by label 1 and label Name    
a = df.loc[1, 'Name']
print (a)
Sim

But if need select index by position (need iloc) and columns by labels (need loc) together:

df = df.set_index('Email')
print (df)
                     Name   Age
Email                          
[email protected]      Sachith    23
[email protected]          Sim   234
[email protected]    Yoshi  2345
[email protected]     sarla   234

get label of second index by df.index[1]:

a = df.loc[df.index[1], 'Name']
print (a)
Sim

Or get position of label by get_loc:

a = df.iloc[1, df.columns.get_loc('Name')]
print (a)
Sim