3

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

4

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

Try this. It is pretty simple.

print(df['B'])

2 Comments

this wont work. You can't give 'B' since it is not a column name
Not sure how this got an upvote. This is incorrect answer. Please clarify.
1

This should be good enough !!

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.