使用groupby的列的累积列表

时间:2017-06-23 11:03:03

标签: python list pandas dataframe

大家好,我有以下数据框:

   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

但这不是累积的,也不能成为一个专栏。 谢谢你的帮助

2 个答案:

答案 0 :(得分:5)

使用:

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]

答案 1 :(得分:2)

f = lambda x: pd.Series(x).dropna().astype(int).tolist()
c = pd.Series.cumsum
df.assign(metric_cum=df.metric.apply(f).groupby(df.Fruit).apply(c))

   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]