Question:
My dataframe is like this:df = pd.DataFrame({'A': [1,2,3], 'B': [1,4,5]})
If column A has the same value as column B, output 1, else 0.
I want to output like this:
df['is_equal'] = np.where((df['A'] == df['B']), 1, 0)
worked fine.But I want to use lambda here because I used a similar line in another case before.
df['is_equals'] = df.apply(lambda x: 1 if df['A']==1 else 0, axis=1)
won’t work. It threw the error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Why did this error happen and how can I fix the code.Thank you in advance.
Answer:
I also agree with DYZ’s opinion. But if you want to use.apply
anyway, I can suggest something like this.If you have better answer, please add a comment about this, thank you!