-2

I have a problem with the if statement when I want to add a new column.

import pandas as pd
scan = pd.DataFrame([[1,2,3],['a','b','c']], columns=['st','nd','rd'])
scan['th'] = 0 if scan['st'] == 0 else 1

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How can I fix this?

4

1 Answer 1

0

Use numpy.where to apply those conditions and values to the whole array:

scan['th'] = np.where(scan['st'] == 0, 0, 1)

It might be interesting to benchmark the former approach against this one:

scan['th'] = (scan['st'] != 0).astype(int)
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.