Skip to content
Advertisement

How do I create a new dataframe column based on two other columns?

I want to create a binary column which indicates 1 if the values of both columns in the following table are within the same range. For example, if the value on cat_1 is between 5-10 and the value in cat_2 is also between 5-10 then it should indicate 1, otherwise, it should be 0.

JavaScript

So far, I have tried the following code but it return an error:

JavaScript

and here is the error:

JavaScript

Advertisement

Answer

The reason why you’re getting an error is that evaluation of & has priority over >=. To fix your snippet, add parentheses around column comparisons:

JavaScript

Even better, it is preferred to define the new column as a whole, without subsetting using .loc. Consider e.g.:

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