如何解决如何使用grouby调整pandas中的小计列?
我正在使用数据框连接将数据框导出到 Excel。
然而,在加入数据框之后, 使用groupby计算小计时,执行下图。
索引列中有一个“小计”字样。
有什么办法可以把它移到代码列中并对索引进行排序吗?
这里的代码:
def subtotal(df__,str):
container = []
for key,group in df__.groupby(['key']):
group.loc['subtotal'] = group[['quantity','quantity2','quantity3']].sum()
container.append(group)
df_subtotal = pd.concat(container)
df_subtotal.loc['GrandTotal'] = df__[['quantity','quantity3']].sum()
print(df_subtotal)
return (df_subtotal.to_excel(writer,sheet_name=str))
解决方法
使用 np.where()
用 code
中的值填充 df.index
列中的 NaN。然后为 df.index
分配一个新的索引数组。
import numpy as np
df['code'] = np.where(df['code'].isna(),df.index,df['code'])
df.index = np.arange(1,len(df) + 1)
print(df)
code key product quntity1 quntity2 quntity3
1 cs01767 a apple-a 10 0 10.0
2 Subtotal NaN NaN 10 0 10.0
3 cs0000 b bannana-a 50 10 40.0
4 cs0000 b bannana-b 0 0 0.0
5 cs0000 b bannana-c 0 0 0.0
6 cs0000 b bannana-d 80 20 60.0
7 cs0000 b bannana-e 0 0 0.0
8 cs01048 b bannana-f 0 0 NaN
9 cs01048 b bannana-g 0 0 0.0
10 Subtotal NaN NaN 130 30 100.0
11 cs99999 c melon-a 50 10 40.0
12 cs99999 c melon-b 20 20 0.0
13 cs01188 c melon-c 10 0 10.0
14 Subtotal NaN NaN 80 30 50.0
15 GrandTotal NaN NaN 220 60 160.0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。