![](/img/trans.png)
[英]Pandas fillna from mean with groupby for multiple columns
[英]Python Pandas - Groupby multiple columns, filter for certain value certain column, and fillna
我有一个包含混乱数据的大型数据集。 数据如下所示:
df1 = pd.DataFrame({'Batch':[1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
'Case':[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2],
'Live':['Yes', 'Yes', 'No', 'Yes', 'No', 'No', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'No', 'Yes', 'Yes', 'No'],
'Task':['Download', nan, 'Download', 'Report', 'Report', nan, 'Download', nan, nan, nan, 'Download', 'Download', 'Report', nan, 'Report']
})
出于示例的目的,请想象'nan'实际上是一个空单元格(而不是一个表示'nan'的字符串)
我需要按“批次”分组,然后按“案例”分组,过滤“实时”值为“是”的实例,然后向下填充。
我本质上希望它看起来像这样
我当前的方法是:
df['Task'] = df.groupby(['Batch','Case'])['Live'].filter(lambda x: x == 'Yes')['Task'].fillna(method='ffill')
我已经尝试了多种变体,但不断收到诸如“过滤器必须返回布尔结果”之类的错误
有人知道我该怎么做吗?
您不需要filter
,可以在groupby
之前切片实时的Yes
df1.Task=df1.loc[df1.Live=='Yes'].groupby(['Batch','Case']).Task.ffill()
df1
Out[620]:
Batch Case Live Task
0 1 1 Yes Download
1 1 1 Yes Download
2 1 1 No NaN
3 1 2 Yes Report
4 1 2 No NaN
5 1 2 No NaN
6 1 2 Yes Download
7 1 2 Yes Download
8 1 2 Yes Download
9 2 1 Yes NaN
10 2 1 Yes Download
11 2 1 No NaN
12 2 2 Yes Report
13 2 2 Yes Report
14 2 2 No NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.