根据条件使用前一列的聚合创建列

2024-06-01 08:41:58 发布

您现在位置:Python中文网/ 问答频道 /正文

具有3列的数据帧:

FLAG CLASS   STUDENT
yes 'Sci'   'Francy'
no  'Sci'   'Alex'
yes 'math'  'Arthur'
yes 'math'   NaN
yes 'eng'   'Jack'
yes 'math'  'Paul'
yes 'eng'   'Zach'

我想增加一个新的列所有的学生在每个班级。但是,仅对FLAG=yes的行执行此操作。结果如下:

FLAG CLASS   STUDENT   ALL_STUD
yes 'Sci'   'Francy'  'Francy, Alex'
no  'Sci'   'Alex'     NaN
yes 'math'  'Arthur'  'Arthur, Paul'
yes 'math'   NaN      'Arthur, Paul'
yes 'eng'   'Jack'    'Jack, Zach'
yes 'math'  'Paul'    'Arthur, Paul'
yes 'eng'   'Zach'    'Jack, Zach'

我一直在尝试这样的事情:

df.loc[df['FLAG']=='yes', 'ALL_STU'] = df.groupby('CLASS').STUDENT.transform(','.join)

但是“math”类的学生不能用(','.join)转换成'Arthur, Paul',因为math类中有一个空名称NaN。有什么解决办法,或者其他方法?你知道吗

从这个question继续。你知道吗


Tags: dfmathnanstudentengclassyesflag
1条回答
网友
1楼 · 发布于 2024-06-01 08:41:58

使用^{}

f = lambda x: ','.join(x.dropna())
#alternative 
#f = lambda x: ','.join(y for y in x if y == y)
df.loc[df['FLAG']=='yes', 'ALL_STU'] = df.groupby('CLASS').STUDENT.transform(f)
print (df)
  FLAG   CLASS   STUDENT          ALL_STU
0  yes   'Sci'  'Francy'  'Francy','Alex'
1   no   'Sci'    'Alex'              NaN
2  yes  'math'  'Arthur'  'Arthur','Paul'
3  yes  'math'       NaN  'Arthur','Paul'
4  yes   'eng'    'Jack'    'Jack','Zach'
5  yes  'math'    'Paul'  'Arthur','Paul'
6  yes   'eng'    'Zach'    'Jack','Zach'

也可以在两侧进行筛选,以避免附加不匹配条件的值:

mask = df['FLAG']=='yes'
f = lambda x: ','.join(x.dropna())
df.loc[mask, 'ALL_STU'] = df.loc[mask, 'STUDENT'].groupby(df['CLASS']).transform(f)
print (df)
  FLAG   CLASS   STUDENT          ALL_STU
0  yes   'Sci'  'Francy'         'Francy'
1   no   'Sci'    'Alex'              NaN
2  yes  'math'  'Arthur'  'Arthur','Paul'
3  yes  'math'       NaN  'Arthur','Paul'
4  yes   'eng'    'Jack'    'Jack','Zach'
5  yes  'math'    'Paul'  'Arthur','Paul'
6  yes   'eng'    'Zach'    'Jack','Zach'

相关问题 更多 >