我正在尝试获取一个熊猫数据框,并根据两列对其进行分组,以获取相应值列中每个唯一组合的总和。
数据框如下所示:
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 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
当我尝试使用Google API将其移动到Google表格时,出现以下错误:
IndexError: tuple index out of range
由于费用代码列中的费用代码行为空。
答案 0 :(得分:1)
您可以将NaN替换为0,然后删除NaN值:
df_Paid.groupby(['Charge Code','Billing Number'])['Amount'].sum().replace(0, np.nan).dropna().reset_index()
答案 1 :(得分:0)
您可以agg
然后找到values != 0
:
df_temp = df_Paid['Charge Code','Billing Number'].agg({'Amount': 'sum'}).reset_index()
df_Paid = df_temp.loc[df_temp['Amount'] != 0]