[英]equivalent python and pandas operation for group_by + mutate + indexing column vectors within mutate in R
[英]add group property in pandas within a chain (analogous to dplyr group_by - mutate in R)
我想將一些組屬性作為新列添加到 pandas dataframe 但不破壞鏈。 我知道這在 R 中使用 dplyr 是可能的,但我無法讓它在 pandas 中工作。
dplyr 代碼將是(用於在 A 列中每組添加最大 B 列):
df %>%
group_by(A) %>%
mutate(max = max(B)) %>%
ungroup() %>%
... more operations
我可以讓它在 pandas 中工作的唯一方法是:
df['max'] = df.groupby('A')['B'].transform('max')
但這需要單獨的行來分配新列,而我想在鏈中執行它。 任何幫助,將不勝感激。
df.assign(max=df.groupby('A')['B'].transform('max'))....more operations
現在您可以使用datar
順利完成
from datar import f
from datar.base import max
from datar.dplyr import group_by, mutate, ungroup
df >> \
group_by(f.A) >> \
mutate(max = max(f.B)) >> \
ungroup() # >>
# ... more operations
我是 package 的作者。 如果您有任何問題,請隨時提交問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.