将groupby变成带有新列的单行

时间:2019-04-07 11:00:07

标签: python python-3.x pandas pandas-groupby

我希望能够将groupby变成一行,但是如果没有足够的数据,那么该groupby中第二列的值将被汇总为新列或-99。

在使用以下输入对session_id进行分组之后:

             user_id     session_id   timestamp  step  impressions   n_clicks
0       004A07DM0IDW  1d688ec168932  1541555799     7      2059240        5.0
1       004A07DM0IDW  1d688ec168932  1541555799     7      2033381        3.0
2       004A07DM0IDW  1d688ec168932  1541555799     7      1724779        4.0
3       004A07DM0IDW  1d688ec168932  1541555799     7       127131        2.0
4       004A07DM0IDW  1d688ec168932  1541555799     7       399441        1.0
5       004A07DM0IDW  1d688ec168932  1541555799     7       103357        3.0
6       004A07DM0IDW  1d688ec168932  1541555799     7       127132        3.0
7       004A07DM0IDW  1d688ec168932  1541555799     7      1167004        1.0
8       004A07DM0IDW  1d688ec168932  1541555799     7      4491766        4.0
9       004A07DM0IDW  1d688ec168932  1541555799     7      2249874        5.0
10      00Y1Z24X8084  26b6d294d66e7  1541651823     3      4476010        4.0
11      00Y1Z24X8084  26b6d294d66e7  1541651823     3      3843244        5.0

我想产生这个输出

             user_id     session_id   timestamp  step  count_0 count_1 count_2 count... count_24
0       004A07DM0IDW  1d688ec168932  1541555799     7      5.0     3.0    4.0    2.0         -99
1       00Y1Z24X8084  26b6d294d66e7  1541555799     3      4.0     5.0    -99    -99         -99

我们正在寻找的是user_id session_id timestamp step对于每一行都将始终相同。但是,印象是不同的。对于每一行(最多25行),click列中的值都映射到count_x上,但是,如果行数不足,则后续值将为-99。

由于第一组分组帧中有10行,这意味着列count_10count_24的值将为-99。对于第二个分组框,列count_2count_24的值为-99。

1 个答案:

答案 0 :(得分:3)

使用:

cols = ['user_id','session_id','timestamp','step']
df['g'] = df.groupby(cols).cumcount()
df = (df.set_index(cols + ['g'])['n_clicks']
        .unstack(fill_value=-99)
        .reindex(range(25), fill_value=-99, axis=1)
        .add_prefix('count_')
        .reset_index()
        .rename_axis(None, axis=1))
print (df)
        user_id     session_id   timestamp  step  count_0  count_1  count_2  \
0  004A07DM0IDW  1d688ec168932  1541555799     7      5.0      3.0      4.0   
1  00Y1Z24X8084  26b6d294d66e7  1541651823     3      4.0      5.0    -99.0   

   count_3  count_4  count_5  ...  count_15  count_16  count_17  count_18  \
0      2.0      1.0      3.0  ...       -99       -99       -99       -99   
1    -99.0    -99.0    -99.0  ...       -99       -99       -99       -99   

   count_19  count_20  count_21  count_22  count_23  count_24  
0       -99       -99       -99       -99       -99       -99  
1       -99       -99       -99       -99       -99       -99  

[2 rows x 29 columns]

说明

  1. 通过GroupBy.cumcount为计数器创建列
  2. 通过DataFrame.set_index创建MultiIndex并通过Series.unstack重塑
  3. range(25)DataFrame.reindex添加缺失的列
  4. 通过DataFrame.add_prefix重命名列名
  5. 最后一次清洁-DataFrame.rename_axis DataFrame.reset_index