Home > Software design >  How to make a new column with different values using "AND" in pandas?
How to make a new column with different values using "AND" in pandas?

Time:08-24

I have a dataframe,containing values of name and verified columns, i want to see if the conditions meet and it generates a new column with different valuess based on the condition, For eg:

Name Verified
Mary Yes
Julie No
Mary No

Expected data:

Name Verified Identity
Mary Yes Bot
Julie No Bot
Mary No Human

What i have done: I require a field where condition is if name is Mary and verified is No then print Human else Bot,

df['Identity']=df((df['name'] == 'Mary') & (df['Verified'] == 'No)), I am not sure how to print human or bot based on the condition, can anyone please help?Thank you

CodePudding user response:

You were close. Once you correct the structure of your conditional statement, you could do something like map, or use numpy where

df['Identity'] = ((df['Name'].eq('Mary')) & (df['Verified'].eq('No'))).map({True:'Human',False:'Bot'})

Or using numpy where

import numpy as np
df['Identity'] = np.where((df['Name'].eq('Mary')) & (df['Verified'].eq('No')),'Human','Bot')

CodePudding user response:

here is another way to it using np.where

df['Identify']=np.where(df['Name'].eq('Mary') & df['Verified'].eq('No'), 'Human', 'Bot')
df
    Name    Verified    Identify
0   Mary    Yes         Bot
1   Julie   No          Bot
2   Mary    No          Human

CodePudding user response:

You can use masks, it's faster than apply and map methods:

mask = (df['name'] == 'Mary') & (df['Verified'] == 'No')
df.loc[mask,'Identity'] = 'Human'
df.loc[~mask,'Identity'] = 'Bot'

CodePudding user response:

How about this:

df['Identity'] = "Bot"
df.loc[(df['Name'] == "Mary") & (df['Verified'] == "No"), 'Identity'] = "Human"

Similar to this q: Creating a new column based on if-elif-else condition

  • Related