草庐IT

python Pandas : Add column to grouped DataFrame with method chaining

coder 2023-08-21 原文

首先让我说我是 pandas 的新手。

我正在尝试在 DataFrame 中创建一个新列。我能够按照我的示例中所示执行此操作。但我想通过链接方法来做到这一点,所以我不必分配新变量。首先让我展示一下我想要实现的目标,以及到目前为止我做了什么:

In [1]:
import numpy as np
from pandas import Series,DataFrame
import pandas as pd

In [2]:
np.random.seed(10)
df=pd.DataFrame(np.random.randint(1,5,size=(10, 3)), columns=list('ABC'))
df

Out [2]:
A  B  C
2  2  1
4  1  2
4  1  2
2  1  2
2  3  1
2  1  3
1  3  1
4  1  1
4  4  3
1  4  3
In [3]:
filtered_DF = df[df['B']<2].copy()
grouped_DF = filtered_DF.groupby('A')
filtered_DF['C_Share_By_Group'] =filtered_DF.C.div(grouped_DF.C.transform("sum"))
filtered_DF

Out [3]:
A  B  C  C_Share_By_Group
4  1  2               0.4
4  1  2               0.4
2  1  2               0.4
2  1  3               0.6
4  1  1               0.2

我想通过链接方法实现相同的目的。在带有 dplyr 包的 R 中,我可以做类似的事情:

df %>% 
  filter(B<2) %>%
  group_by(A) %>% 
  mutate('C_Share_By_Group'=C/sum(C))

pandas documentation它说 R(dplyr) 中的 mutate 等于 pandas 中的 assign,但 assign 不适用于分组对象。 当我尝试将某些内容分配给分组数据框时,出现错误:

"AttributeError: Cannot access callable attribute 'assign' of 'DataFrameGroupBy' objects, try using the 'apply' method"

我尝试了以下方法,但不知道如何添加新列,或者是否有可能通过链接方法实现:

(df.loc[df.B<2]
   .groupby('A')
    #****WHAT GOES HERE?**** apply(something)?
)

最佳答案

你可以试试assign :

print df[df['B']<2].assign(C_Share_By_Group=lambda df: 
                       df.C
                         .div(df.groupby('A')
                           .C
                           .transform("sum")))

   A  B  C  C_Share_By_Group
1  4  1  2               0.4
2  4  1  2               0.4
3  2  1  2               0.4
5  2  1  3               0.6
7  4  1  1               0.2

关于 python Pandas : Add column to grouped DataFrame with method chaining,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37142012/

有关python Pandas : Add column to grouped DataFrame with method chaining的更多相关文章

随机推荐