【问题标题】:Pandas, create new column applying groupby valuesPandas,创建应用 groupby 值的新列
【发布时间】:2017-11-22 13:40:55
【问题描述】:

我有一个 DF:

Col1   Col2    Label
0      0        5345
1      0        7574
2      0        3445
0      1        2126
1      1        4653
2      1        9566 

所以我试图在 Col1 和 Col2 上进行分组,以根据 Label 列获取索引值,如下所示:

df_gb = df.groupby(['Col1','Col2'])['Label'].agg(['sum', 'count']) 
df_gb['sum_count'] = df_gb['sum'] / df_gb['count']
sum_count_total = df_gb['sum_count'].sum() 
index = df_gb['sum_count'] / 10 

Col2  Col1       
0     0          2.996036
      1          3.030063
      2          3.038579

1     0          2.925314
      1          2.951295
      2          2.956083

2     0          2.875549
      1          2.899254
      2          2.905063

到目前为止,一切都如我所料。但现在我想根据这两个 groupby 列将此“索引”groupby df 分配给我原来的“df”。如果它只有一列,它正在使用 map() 函数,但如果我想根据两列顺序分配索引值,则不是。

df_index = df.copy()
df_index['index'] = df.groupby([]).apply(index)
TypeError: 'Series' objects are mutable, thus they cannot be hashed

尝试了 agg() 和 transform() 但没有成功。任何想法如何进行?

提前致谢。 赫里斯托。

【问题讨论】:

    标签: pandas group-by multiple-columns


    【解决方案1】:

    相信你需要join:

    a = df.join(index.rename('new'), on=['Col1','Col2'])
    print (a)
       Col1  Col2  Label    new
    0     0     0   5345  534.5
    1     1     0   7574  757.4
    2     2     0   3445  344.5
    3     0     1   2126  212.6
    4     1     1   4653  465.3
    5     2     1   9566  956.6
    

    或GroupBy.transform:

    df['new']=df.groupby(['Col1','Col2'])['Label'].transform(lambda x: x.sum() / x.count()) / 10
    print (df)
       Col1  Col2  Label    new
    0     0     0   5345  534.5
    1     1     0   7574  757.4
    2     2     0   3445  344.5
    3     0     1   2126  212.6
    4     1     1   4653  465.3
    5     2     1   9566  956.6
    

    如果Label 列中没有NaNs,请使用Zero 建议的解决方案,谢谢:

    df.groupby(['Col1','Col2'])['Label'].transform('mean') / 10
    

    如果只需要计算count 的非NaNs 值,请使用transform 的解决方案。

    【讨论】:

    • 与 join 工作完美。也将尝试使用 GroupBy.transform() 。感谢一百万的伙伴! :)
    • 是的,第二种解决方案应该更快。不客气!
    • 第二个可以是df.groupby(['Col1','Col2'])['Label'].transform('mean') / 10?
    • @Zero - 谢谢,已添加到答案中。
    猜你喜欢
    • 2021-10-09
    • 2022-10-13
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 2020-02-05
    • 2022-11-23
    相关资源
    最近更新 更多