簡體   English   中英

將唯一列值分組為 pandas dataframe 列中每個唯一值的總和

[英]Grouping unique column values to sum of each unique value in pandas dataframe column

我正在嘗試采用 pandas dataframe 並根據兩列對其進行分組,以獲得相應值列中每個唯一組合的總和。

Dataframe 看起來像這樣:

Charge Code  Billing Number  Amount
1250-001        500120        5000
1250-001        500120       -5000
1250-001        500220         300
1250-001        520320         400
1136-001        360220         700
1136-001        360220        -100
1207-001        070420         100
1207-001        070420         200
1207-001        070420         300
1207-001        070320         400
1090-001        900220         500

我想按 Charge code 和 Billing Number 列對 dataframe 進行分組,以獲得 Amount 列中值的總和。 如果總和最終為零,則不應包含在 dataframe 中。

所需的 dataframe 如下所示:

 Charge Code  Billing Number  Amount
  1250-001      500220         300
  1250-001      520320         400
  1136-001      360220         600
  1207-001      070420         600
  1207-001      070320         400
  1090-001      900220         500

我假設它應該看起來像:

df_Paid.groupby(level=0)['Charge Code','Billing Number'].sum()

使用解決方案:

df_Paid.groupby(['Charge Code','Billing Number'])['Amount'].sum().replace(0, np.nan).dropna()

返回:

Charge Code  Billing Number  Amount
  1250-001      500220         300
                520320         400
  1136-001      360220         600
  1207-001      070420         600
                070320         400
  1090-001      900220         500

當我嘗試使用谷歌 api 將其移動到谷歌表格時,這給了我以下錯誤:

IndexError: tuple index out of range

由於 Charge 代碼列中的 Charge 代碼行為空。

您可以將 0 替換為 NaN,然后刪除 NaN 值:

df_Paid.groupby(['Charge Code','Billing Number'])['Amount'].sum().replace(0, np.nan).dropna().reset_index()

您可以agg然后 loc values != 0

df_temp = df_Paid['Charge Code','Billing Number'].agg({'Amount': 'sum'}).reset_index()
df_Paid = df_temp.loc[df_temp['Amount'] != 0]

暫無
暫無

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

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