简体   繁体   中英

How to compare two columns in Pandas?

Df1:

Id   Name
 1     A
 2     B
 3     B
 3     A
 2     A
 6     B

I need to create a new column Based on Id and Name Column. If same Id is present Name Column Values. For Example Id 3,2 present for both A and B.

Df1:

Id   Name  New_Col
 1     A    Unique
 2     B    Common
 3     B    Common
 3     A    Common
 2     A    Common
 6     B    Unique

Try with transform + nunique

df'[out'] = np.where( df.groupby('Id')['Name'].transform('nunique').eq(1), 'Unique', 'Common')

Out[519]: 
0    Unique
1    common
2    common
3    common
4    common
5    Unique
Name: Name, dtype: object

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