2

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'])
3
  • Try df7.loc[df7.b.eq(1), 'A']? Commented Feb 23, 2018 at 17:20
  • df.loc[df.B==1,'A'] Commented Feb 23, 2018 at 17:21
  • You wouldn't do for a,b in df7.iteritems(): and then try to reference the columns by df7['a'], df7['b'], that will return you the entire column. Commented Apr 21, 2019 at 10:42

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

how would I just get e4 and not '4'?
0

Another simple code would be

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

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

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.