【问题标题】:Pivot table in python (Sum of values in column)python中的数据透视表(列中的值总和)
【发布时间】:2020-04-06 21:41:37
【问题描述】:

我在生成数据透视表时遇到了一些问题。我尝试用 Python 来做到这一点。 现在我有测试表了:

表 1

我想做这样的表格:

表 2

我写了代码,但仍然有两列,但没有总和。

import pandas as pd
import numpy as np


table = pd.read_excel('test.xlsx',0)
print(table.head())
print(pd.pivot_table(table,values=["A","B","C","D","E","F","G"],columns=[np.sum]))

【问题讨论】:

    标签: python pandas numpy dataframe pivot-table


    【解决方案1】:

    您应该Transpose 数据框,然后对列求和(axis=1)。

    类似这样的:

    In [384]: table                                                                                                                                                                                                
    Out[384]: 
       A  B  C
    0  1  2  4
    1  1  3  2
    
    In [386]: table.T.sum(axis=1)                                                                                                                                                                                  
    Out[386]: 
    A    2
    B    5
    C    6
    dtype: int64
    

    OP 评论后更新答案:

    如果您只想对某些列求和,请执行以下操作:

    In [468]: df                                                                                                                                                                                                
    Out[468]: 
       A  B  C  D  E  F  G
    0  1  2  4  5  6  5  6
    1  2  3  2  1  2  3  4
    
    In [469]: df[['C','D','E','F']]                                                                                                                                                                             
    Out[469]: 
       C  D  E  F
    0  4  5  6  5
    1  2  1  2  3
    
    In [471]: df[['C','D','E','F']].T.sum(axis=1)                                                                                                                                                               
    Out[471]: 
    C    6
    D    6
    E    8
    F    8
    dtype: int64
    

    【讨论】:

    • 如果我只想要 C - F 列的总和并且只打印这些列怎么办?
    • @KamilStępniewski 检查我更新的答案。另外,接受答案。
    猜你喜欢
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    相关资源
    最近更新 更多