0

In a pandas df, all cells in columns from index 4 to the end have null value or one of two possible strings, let's use "a" and "b". I want to replace each value with a number: "a" with 1, "b" with 2, and null with 0. I would prefer to change multiple columns simultaneously rather than using a loop.

I've tried using apply with lambda because it worked for an earlier project, but it doesn't work for this one, and when I use it on only one column, it changes everything to 0. I've also tried assigning the values with the other piece of code below.

df.iloc[:, 4:] = df.iloc[:, 4:].apply(lambda x:1 if x == 'a' else(2 if x == 'b' else 0))

df[df.iloc[:,4]=='a',4] = 1

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().','occurred at index [B]

'Series' objects are mutable, thus they cannot be hashed

1 Answer 1

0

You can use replace and fillna methods

df.iloc[:, 4:] = df.iloc[:, 4:].replace({'a':1,'b':2}).fillna(0)

Your Answer

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

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