我的dtaframe看起来像这样:
import pandas as pd
import numpy as np
df = pd.DataFrame({'ID': [332, 332, 332, 315, 315, 315, 315, 315, 310, 310], \
'Name': ['Alex', 'Alex', 'Alex', 'Sara', 'Sara', 'Sara', 'Sara', 'Sara', 'Franck','Franck'], \
'Shift': ['Day', 'Day', 'Night', 'Day', 'Night', 'Night', 'Day', 'Day', 'Night', 'Night']})
df
Output
ID Name Shift
0 332 Alex Day
1 332 Alex Day
2 332 Alex Night
3 315 Sara Day
4 315 Sara Night
5 315 Sara Night
6 315 Sara Day
7 315 Sara Day
8 310 Franck Night
9 310 Franck Night
我想添加一个像这样的新列:
ID Name Shift Two_Shift
0 332 Alex Day Yes
1 332 Alex Day Yes
2 332 Alex Night Yes
3 315 Sara Day Yes
4 315 Sara Night Yes
5 315 Sara Night Yes
6 315 Sara Day Yes
7 315 Sara Day Yes
8 310 Franck Night No
9 310 Franck Night No
为此,我尝试了这段代码:
df['Two_Shift'] = np.where((df['ID'] == df['ID']) & (df['Shift'] != df['Shift']), 'Yes', 'No')
但它不起作用。
谢谢!
答案 0 :(得分:4)
IIUC:
df['Two_Shift'] = np.where(df.groupby('ID')['Shift'].transform('nunique') == 2,'Yes','No')
输出:
ID Name Shift Two_Shift
0 332 Alex Day Yes
1 332 Alex Day Yes
2 332 Alex Night Yes
3 315 Sara Day Yes
4 315 Sara Night Yes
5 315 Sara Night Yes
6 315 Sara Day Yes
7 315 Sara Day Yes
8 310 Franck Night No
9 310 Franck Night No
答案 1 :(得分:2)
将transform
nunique
与map
df.groupby('ID').Shift.transform('nunique').eq(2).map({True:'Yes',False:'No'})
Out[296]:
0 Yes
1 Yes
2 Yes
3 Yes
4 Yes
5 Yes
6 Yes
7 Yes
8 No
9 No
Name: Shift, dtype: object