Search code examples
pythonpandasif-statementcalculated-columns

How to apply conditional statements like 'And' and 'Or' while adding a new column in a dataframe?


I want to add a new column to my Data frame in the following manner:

df['new']= np.where(df['code']== 0 or 1, 1, 0 )

Here, I want to assign the value 1 to the 'new' column when the values in the code column is either 0 or 1. It gives an error. But if I'm using only one condition, the statement works.

The following statement works:

df['new']= np.where(df['code']== 0, 1, 0 )

How do I use both conditions while assigning values to the new column?


Solution

  • Try:

    df["new"] = np.where(df["code"].isin([0,1]), 1, 0)