R group_by%&%;%汇总为 pandas [英] R group_by %>% summarise equivalent in pandas
本文介绍了R group_by%&%;%汇总为 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将一些代码从R重写为python.
I'm trying to rewrite some code from R to python.
我的df很像
size = 20
np.random.seed(456)
df = pd.DataFrame({"names": np.random.choice(["bob", "alb", "jr"], size=size, replace=True),
"income": np.random.normal(size=size, loc=1000, scale=100),
"costs": np.random.normal(size=size, loc=500, scale=100),
"date": np.random.choice(pd.date_range("2018-01-01", "2018-01-06"),
size=size, replace=True)
})
现在,我需要按名称对df进行分组,然后执行一些汇总操作.
Now I need to group the df by name and then perform some summarize operations.
在R,dplyr,我在做
In R, dplyr, I'm doing
dfg <- group_by(df, names) %>%
summarise(
income.acc = sum(income),
costs.acc = sum(costs),
net = sum(income) - sum(costs),
income.acc.bymax = sum(income[date==max(date)]),
cost.acc.bymax = sum(costs[date==max(date)]),
growth = income.acc.bymax + cost.acc.bymax - net
)
请注意,我只是想揭露我的数据,这并不意味着什么.
Please note that I'm just trying to ilustrate my data, it doesn't mean anything.
如何使用熊猫获得相同的结果?
How can I achieve the same result using pandas?
我很难受,因为df.groupby().agg()非常有限!
I'm having a hard time because df.groupby().agg() is very limited!
使用R我得到:
> print(dfg)
# A tibble: 3 x 7
names income.acc costs.acc net income.acc.bymax cost.acc.bymax growth
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 alb 7997 3996 4001 2998 1501 497
2 bob 6003 3004 3000 2002 1002 3.74
3 jr 6002 3000 3002 1000 499 -1503
使用@Jezrael答案:
Using @Jezrael answer:
我知道
income_acc costs_acc net income_acc_bymax \
names
alb 7997.466538 3996.053670 4001.412868 2997.855009
bob 6003.488978 3003.540598 2999.948380 2001.533870
jr 6002.056904 3000.346010 3001.710894 999.833162
cost_acc_bymax growth
names
alb 1500.876851 497.318992
bob 1002.151162 3.736652
jr 499.328510 -1502.549221
推荐答案
我认为您需要自定义功能:
I think you need custom function:
def f(x):
income_acc = x.income.sum()
costs_acc = x.costs.sum()
net = income_acc - costs_acc
income_acc_bymax = x.loc[x.date == x.date.max(), 'income'].sum()
cost_acc_bymax = x.loc[x.date == x.date.max(), 'costs'].sum()
growth = income_acc_bymax + cost_acc_bymax - net
c = ['income_acc','costs_acc','net','income_acc_bymax','cost_acc_bymax','growth']
return pd.Series([income_acc, costs_acc, net, income_acc_bymax, cost_acc_bymax, growth],
index=c)
df1 = df.groupby('names').apply(f)
print (df1)
income_acc costs_acc net income_acc_bymax \
names
alb 7746.653816 3605.367002 4141.286814 2785.500946
bob 6348.897809 3354.059777 2994.838032 2153.386953
jr 6205.690386 3034.601030 3171.089356 983.316234
cost_acc_bymax growth
names
alb 1587.685103 231.899235
bob 1215.116245 373.665167
jr 432.851030 -1754.922093
这篇关于R group_by%&%;%汇总为 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文