user3447653
user3447653

Reputation: 4148

Check for a specific value in pandas dataframe column

I am trying to retrieve the value in A if the value of B is 1. But the below code throws the error "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()"

    A   B
0   a1  18
1   b1  25229
2   c2  2
3   d3  12
4   e4  1

Code:

for a,b in df7.iteritems():
  if (df7['b'] == 1):
    print (df7['a'])

Upvotes: 2

Views: 10029

Answers (2)

Shahir Ansari
Shahir Ansari

Reputation: 1848

Another simple code would be

df7[df7['b'] == 1]['a']

will give a dataframe of column a where b=1.

Upvotes: 0

Jan
Jan

Reputation: 43169

You could use a simple comparison like

import pandas as pd

df = pd.DataFrame({'A': ['a1', 'b1', 'c2', 'd3', 'e4'], 'B': [18, 25229, 2, 12, 1]})
print(df[df['B'] == 1]['A'])

Which yields

4    e4
Name: A, dtype: object

Upvotes: 5

Related Questions