微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用grouby调整pandas中的小计列?

如何解决如何使用grouby调整pandas中的小计列?

我正在使用数据框连接将数据框导出到 Excel。

然而,在加入数据框之后, 使用groupby计算小计时,执行下图。

索引列中有一个“小计”字样。

enter image description here

有什么办法可以把它移到代码列中并对索引进行排序吗?

enter image description here

这里的代码

    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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?