我有以下名为 matches 的 Pandas 数据框:
id | name | age
1 | a | 19
1 | b | 25
2 | c | 19
2 | d | 22
我使用 groupby + count() , 如果某个列的值 ( age ) 满足条件 ( x < 21 )。结果写入新列 ( new_col ):
matches['new_col'] = matches.groupby(['id'])['age'].transform(lambda x: x[x < 21].count())
数据框看起来像这样:
id | name | age | new_col
1 | a | 19 | 1
1 | b | 25 | 1
2 | c | 19 | 2
2 | d | 18 | 2
现在我想以一种更具可读性的方式输出结果,即 name - 满足条件(年龄 < 21)的每一行的列应写入新列,例如 result .
我期待这样的事情(但是,可能还有其他方法可以实现这一点。甚至可能在第一步中就已经这样做了,我在其中添加了 new_col ):
id | name | age | new_col | result
1 | a | 19 | 1 | a
1 | b | 25 | 1 | a
2 | c | 19 | 2 | c,d
2 | d | 18 | 2 | c,d
最后一步(添加 result 列)是我现在卡住的地方。
请您参考如下方法:
首先按 boolean indexing 筛选行然后 aggregate , 最后 join转为原文:
matches1 = matches[matches.age < 21]
.groupby(['id'])['name'].agg({'result':', '.join, 'new_col': len})
print (matches1)
new_col result
id
1 1 a
2 2 c, d
print (matches.join(matches1, on='id'))
id name age new_col result
0 1 a 19 1 a
1 1 b 25 1 a
2 2 c 19 2 c, d
3 2 d 18 2 c, d
另一种解决方法是double transform,但首先需要sort_values下次使用 ffill >=21 的值:
matches = matches.sort_values(['id','age'])
g = matches[matches.age < 21].groupby(['id'])['name']
matches['new_col'] = g.transform(len)
matches['result'] = g.transform(', '.join)
matches[['new_col','result']] = matches[['new_col','result']].ffill()
print (matches)
id name age new_col result
0 1 a 19 1 a
1 1 b 25 1 a
3 2 d 18 2 d, c
2 2 c 19 2 d, c
更好地解释必要的排序 df:
print (matches)
id name age
0 1 a 25 > first value is filter out by condition
1 1 b 12
2 2 c 19
3 2 d 18
matches = matches.sort_values(['id','age'])
g = matches[matches.age < 21].groupby(['id'])['name']
matches['new_col'] = g.transform(len)
matches['result'] = g.transform(', '.join)
matches[['new_col','result']] = matches[['new_col','result']].ffill()
print (matches)
id name age new_col result
1 1 b 12 1 b
0 1 a 25 1 b
3 2 d 18 2 d, c
2 2 c 19 2 d, c
print (matches.sort_index())
id name age new_col result
0 1 a 25 1 b
1 1 b 12 1 b
2 2 c 19 2 d, c
3 2 d 18 2 d, c
