【问题标题】:Python datatable: sum, groupby, column < 0Python 数据表:sum、groupby、column < 0
【发布时间】:2020-10-09 20:10:37
【问题描述】:

您好,我正在努力将一些 R 代码转换为 Python 代码。

这是我的 R 代码:

  df_sum <- df[, .(
    Inflow = sum(subset(Amount, Amount>0)),
    Outflow = sum(subset(Amount, Amount<0)),
    Net = sum(Amount)
  ), by = Account]

到目前为止,这是我的 Python 代码:

df_sub = df[:, {'Inflow': dt.sum(dt.f.Amount),
                'Outflow': dt.sum(dt.f.Amount),
                'Net': dt.sum(dt.f.Amount)},
         dt.by('Account')]

我不知道如何包含流入和流出列的子集。有人可以帮忙吗?

这是所需的输出(使用 R 代码生成):

     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]}

【问题讨论】:

  • 嗨,彼得。您能否也分享一些示例数据。谢谢
  • 我会尽快发布示例数据
  • 如何打印df的方式复制粘贴到这里,可以直接使用?
  • 嗯。以与粘贴所需输出相同的方式粘贴它。如果你有它作为数据表,你可以做frame.to_dict()并粘贴字典

标签: python r group-by datatable py-datatable


【解决方案1】:

使用 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

【讨论】:

  • 运行这个会导致 SyntaxError: invalid syntax
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
相关资源
最近更新 更多