Python数据表:sum,groupby,列< 0 [英] Python datatable: sum, groupby, column < 0
本文介绍了Python数据表:sum,groupby,列< 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力将一些R代码转换为Python代码。
Hi I am struggling to translate some R code into Python code.
这是我的R代码:
df_sum <- df[, .(
Inflow = sum(subset(Amount, Amount>0)),
Outflow = sum(subset(Amount, Amount<0)),
Net = sum(Amount)
), by = Account]
这是我到目前为止的Python代码:
This is my Python code so far:
df_sub = df[:, {'Inflow': dt.sum(dt.f.Amount),
'Outflow': dt.sum(dt.f.Amount),
'Net': dt.sum(dt.f.Amount)},
dt.by('Account')]
我不知道如何包括流入和流出列的子集。有人可以帮忙吗?
I don't know how to include the subset for the inflow and outflow columns. Can anyone help?
这是所需的输出(使用R代码生成):
This is the desired output (generated with R code):
Account Inflow Outflow Net
1: Account 1 151 -32 119
2: Account 2 51 -226 -175
示例数据:
{'Account': ['Account 1', 'Account 1', 'Account 1', 'Account 1', 'Account 1', 'Account 1', 'Account 1', 'Account 1', 'Account 1', 'Account 2', 'Account 2', 'Account 2', 'Account 2', 'Account 2', 'Account 2', 'Account 2', 'Account 2', 'Account 2'], 'Amount': [34, 23, -23, -4, 34, 4, -3, 56, -2, 3, 5, 43, -67, -3, -78, -7, -4, -67]}
推荐答案
使用 ifelse 函数复制R代码:
from datatable import dt, f, by, ifelse
df[:, {"Inflow": dt.sum(ifelse(f.Amount > 0, f.Amount, None)),
"Outflow": dt.sum(ifelse(f.Amount < 0, f.Amount, None )),
"Net": dt.sum(f.Amount)},
by("Account")]
Account Inflow Outflow Net
0 Account1 151 −32 119
1 Account2 51 −226 −175
这篇关于Python数据表:sum,groupby,列< 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文