Home > Software design >  Create a new column in pandas that is based on two other columns of bools
Create a new column in pandas that is based on two other columns of bools

Time:09-22

I have a dataframe df that has two columns consisting of bools.

df['trial']
df['subscribe']

I want to create a new column df['without_trial'] that is true when df['subscribe'] is true and df['trial'] is false, and false otherwise.

How can I do that? I have tried with the df.loc but it never gives me the right values.

CodePudding user response:

If you have pure boolean columns as input, use the AND (&) and NOT (~) operators:

df['without_trial'] = df['trial'] & ~df['subscribe']

If you potentially have mixed values use eq (equal) and ne (not equal):

df['without_trial'] = (df['trial'].eq(True)
                     & df['subscribe'].ne(True)
                      )

CodePudding user response:

You can just outright define the new column using the operators ~ (NOT in pandas) and & (AND):

df['without_trial'] = df['subscribe'] & ~df['trial']
  • Related