簡體   English   中英

Python 數據表:sum、groupby、column < 0

[英]Python datatable: sum, groupby, column < 0

嗨,我正在努力將一些 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]}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM