嗨,我有以下数据框:

   Fruit  metric
0  Apple     NaN
1  Apple   100.0
2  Apple     NaN
3  Peach    70.0
4   Pear   120.0
5   Pear   100.0
6   Pear     NaN

我的目标是按水果分组,并按顺序将每个不为空的metric值添加到具有独立列的累积列表中,如下所示:
   Fruit  metric  metric_cum
0  Apple     NaN          []
1  Apple   100.0       [100]
2  Apple     NaN       [100]
3  Peach    70.0        [70]
4   Pear   120.0       [120]
5   Pear   100.0  [120, 100]
6   Pear     NaN  [120, 100]

我试过这样做:
df['metric1'] = df['metric'].astype(str)
df.groupby('Fruit')['metric1'].cumsum()

但这会导致DataError: No numeric types to aggregate
我也试过这样做:
df.groupby('Fruit')['metric'].apply(list)

导致:
Fruit
Apple      [nan, 100.0, nan]
Peach                 [70.0]
Pear     [120.0, 100.0, nan]
Name: metric, dtype: object

但这不是累积的,也不能制成列。
谢谢你的帮助

最佳答案

Use:

df['metric'] = df['metric'].apply(lambda x: [] if pd.isnull(x) else [int(x)])
df['metric_cum'] = df.groupby('Fruit')['metric'].apply(lambda x: x.cumsum())
print (df)
   Fruit metric  metric_cum
0  Apple     []          []
1  Apple  [100]       [100]
2  Apple     []       [100]
3  Peach   [70]        [70]
4   Pear  [120]       [120]
5   Pear  [100]  [120, 100]
6   Pear     []  [120, 100]

或:
a = df['metric'].apply(lambda x: [] if pd.isnull(x) else [int(x)])
df['metric_cum'] = a.groupby(df['Fruit']).apply(lambda x: x.cumsum())
print (df)
   Fruit  metric  metric_cum
0  Apple     NaN          []
1  Apple   100.0       [100]
2  Apple     NaN       [100]
3  Peach    70.0        [70]
4   Pear   120.0       [120]
5   Pear   100.0  [120, 100]
6   Pear     NaN  [120, 100]

关于python - 使用groupby的列的累积列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44719855/

10-16 11:36