我有一个大数据集,里面有凌乱的数据。数据如下所示:
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
之前切
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