python Pandas : Add column to grouped DataFrame with method chaining

标签 python python-2.7 pandas dataframe

首先让我说我是 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 - 如何让 "python -m flask run"运行main函数?

python - 如何在 python-bash 环境中管理进程?

Python webbrowser 模块适用于 Windows 但不适用于 Ubuntu

python - 在 python 中添加一周一小时列

python - 索引错误 : index 1491188345 is out of bounds for axis 0 with size 1491089723

python - 循环获取 pandas 时间索引数据帧的滚动 future 值,我可以让它更快吗?

python - 加入两个numpy矩阵

python - 在 Matplotlib 中显示所有 xlabels 和 xticks

python - 获取 "No Module Named Spotipy"

Python正则表达式错误: "Can' t assign to operator"