对熊猫枢轴的时间序列中某一天的所有值求和

问题描述 投票:0回答:2

如何计算pd透视图中时间序列中某一天的所有值的总和?我的熊猫轴看起来像这样:

       Date    2019-10-01         2019-10-02          2019-10-03       ....          2019-12-01 
Hospital_name                                                         

Hospital1          12                 15                  16           ....              12                                                              
Hospital2          10                 17                  14           ....              12 
Hospital3          15                 20                  12           ....              12 

而且我想像这样旋转:

       Date    2019-10-01         2019-10-02           2019-10-03      ....          2019-12-01 

Sum                37                 52                   42          ....               36                                               

我的数据类型是:

type(df.columns[0])
out: str
type(df.columns[1])
out: pandas._libs.tslibs.timestamps.Timestamp

感谢您的帮助!

python pandas dataframe pivot-table
2个回答
0
投票

sum是您的朋友在这里,如评论中所述。使用虚拟df:

              2019-10-01 2019-10-02 2019-10-03
Hospital_name       John       Maya      Robin
h1                    12         12         42
h2                    15         55         13
h3                    14         42         22

您只需忽略第一行并使用sum

df.loc[df.index!='Hospital_name'].sum()

2019-10-01     41.0
2019-10-02    109.0
2019-10-03     77.0
dtype: float64

编辑:看来您有多索引列。您可以使用以下方法删除它:

df.columns = df.columns.droplevel()

(从this answer中获取)


0
投票
new_df = df.transpose()
new_df["Total"] = df[0:].sum()
df = new_df.transpose()

new_df分配为df,但转置版本new_df["Total"] = df[0:].sum()添加总计列df = new_df.transpose()将表恢复为原先的位置

为了获得更好的体验,您始终可以在Jupyter笔记本或实验室中尝试每行以查看会发生什么。并且如果您对答案满意,请将其标记为接受

谢谢

© www.soinside.com 2019 - 2024. All rights reserved.