简体   繁体   中英

Add a column based on values present in another column

I have a dataframe as:

id Value
0 Auto
1 Manual
2 Auto
3 Manual
4 Manual

I want to add another column based on values present in second column as:

id Value Flag
0 Auto Yes
1 Manual
2 auto Yes
3 manual
4 Manual

I tried below code:

mask = df['Purchase Order Num'].str.contains('Auto', na= False, case=False)
df['Flag'] = np.where(df[mask], 'Yes', '')

I get the error as:

Length of values (2) does not match length of index (5)

What went wrong?

When we doing the np.where we need pass the whole Boolean to it

mask = df['Purchase Order Num'].str.contains('Auto', na= False, case=False)
df['Flag'] = np.where(mask, 'Yes', '')

pandas assign can do

df['Flag'] = ''
df.loc[mask, 'Flag'] = 'Yes'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM