2

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'.

Troll
  • 1,895
  • 3
  • 15
  • 34
lucky1928
  • 8,708
  • 10
  • 43
  • 92
  • Does this answer your question? [How to get a value from a cell of a dataframe?](https://stackoverflow.com/questions/16729574/how-to-get-a-value-from-a-cell-of-a-dataframe) – Albin Paul Nov 07 '21 at 04:39
  • `print(value.values[0])` will get you the answer. – Albin Paul Nov 07 '21 at 04:39
  • btw, i did find another SO post that is similar.... https://stackoverflow.com/questions/53255796/how-to-get-a-single-value-as-a-string-from-pandas-data-frame – Joe Ferndz Nov 07 '21 at 05:23
  • 1
    Does this answer your question? [How to get a single value as a string from pandas data frame](https://stackoverflow.com/questions/53255796/how-to-get-a-single-value-as-a-string-from-pandas-data-frame) – Joe Ferndz Nov 07 '21 at 05:23

3 Answers3

1

Try this. It is pretty simple.

print(df['B'])
Joshua
  • 551
  • 4
  • 13
1

This should be good enough !!

df[df['key']=='B']['value'].iloc[0]
Tamil Selvan
  • 1,600
  • 1
  • 9
  • 25
1

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

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33