Skip to content
Advertisement

Python looping over a list to check if any of the list elements are equal to variable values in pandas dataframe

I have a pandas dataframe and I want to create a new dummy variable based on if the values of a variable in my dataframe equal values in a list.

JavaScript

How can I create a new dummy variable for the dataframe, called variable 3, that equals 1 if variable 2 is present in the list and 0 if not?

I tried this using:

JavaScript

However, this throws a ValueError: The truth value of a Series is ambiguous.

I’ve been looking for an answer for this for a long time but none were sufficient for this problem.

Do you have any suggestions?

Advertisement

Answer

You’re almost there. When you want to check if the value of a dataframe column matches some list or another dataframe column, you can use df.isin.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement