python - get value by key from different column

Viewed 1241

I have a dataframe with 'key' and 'value' columns, I would like to input a key and get output a value.

import pandas as pd

df = pd.DataFrame({
    'key': ['A', 'B', 'C', 'D'],
    'value': [2, 8, 10, 12]})

print(df)

key = 'B'
value = df[df['key'] == key]['value']
print(value)

Current output as below:

  key  value
0   A      2
1   B      8
2   C     10
3   D     12
1    8
Name: value, dtype: int64

How can I get the output value: 8 in this case since the key is 'B'.

3 Answers

Try this. It is pretty simple.

print(df['B'])

You have to use df.loc to get the specific value. You can give something like this.

df.loc[df.key == 'B','value'].item()

The output of this will be:

8

Or you can also give:

df.loc[df.key == 'B']['value'].item()

Or you can give:

df[df.key == 'B']['value'].iloc[0]

Or you can give:

df.loc[df.key == 'B', 'value'].values[0]

If you know for sure that you have only one item in the dataframe with key 'B', use .item(). If you are not sure, then I recommend that you use .values[0] as it will pick the first one from the result.

All of these will give you a value of 8

This should be good enough !!

df[df['key']=='B']['value'].iloc[0]
Related