gpt4 book ai didi

Pandas,应用 groupby 值创建新列

转载 作者:行者123 更新时间:2023-12-02 09:25:20 25 4
gpt4 key购买 nike

我有一个 DF:

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

所以我尝试对 Col1 和 Col2 进行分组,以根据标签列获取索引值,如下所示:

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()但没有成功。有什么想法如何继续吗?

提前致谢。赫里斯托。

最佳答案

我相信你需要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 列中没有 NaN,请使用 Zero 中的解决方案建议,谢谢:

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

如果需要仅按 count 计算非 NaN 值使用带有 transform 的解决方案。

关于Pandas,应用 groupby 值创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47436198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com