Pandas DataFrame: shortcut not in list and KeyError

I'm trying to get the value of a specific cell.

  main_id   name  code
  0    1345  Jones    32
  1    1543   Jack    62
  2    9874   Buck    86
  3    2456   Slim    94

      

I want the cell to say code = 94 since I already know the main_id, but nothing else.

raw_data = {'main_id': ['1345', '1543', '9874', '2456'],
        'name': ['Jones', 'Jack', 'Buck', 'Slim'],
        'code': [32, 62, 86, 94]}

    df=pd.DataFrame(raw_data, columns = ['main_id', 'name', 'code'])


    v=df.loc[str(df['main_id']) == str(2456)]['code'].values
    print(df.loc['name'])

      

print (df.loc ['name']) claims the label is not in the index

and v = df.loc [str (df ['main_id']) == str (2456)] ['code']. values ​​says 'KeyError False'

+3


source to share


2 answers


df.loc['name']

Raises a KeyError because it is name

not in the index; it is in columns. When you use loc

, the first argument is for the index. You can use df['name']

or df.loc[:, 'name']

.

You can also pass boolean arrays in loc

(for both index and columns). For example,

df.loc[df['main_id']=='2456']
Out:
   main_id  name    code
3  2456     Slim    94

      

You can also select a specific column for this:



df.loc[df['main_id']=='2456', 'code']
Out:
3    94
Name: code, dtype: int64

      

With boolean indices, the returned object will always be Series, even if you only have one value. This way you can access the underlying array and select the first value:

df.loc[df['main_id']=='2456', 'code'].values[0]
Out:
94

      

+3


source


Alternative solution:



In [76]: df.set_index('main_id').at['2456','code']
Out[76]: 94

      

+1


source







All Articles