python - 如何使 pandas 中的数据透视表表现得像 Excel 中的数据透视表?
问题描述
我正在尝试转置数据,聚合方法无关紧要,但数据是按值而不是日期分组的
代码:
import pandas as pd
d = {'date': ['2/21/2020', '2/21/2020','2/22/2020','2/22/2020','2/23/2020','2/23/2020'],
'name': ['James','John', 'James','John','James','John'],
'A':[1,2,3,4,5,6],
'B':[7,8,9,10,11,12],
'C':[13,14,15,16,17,18]}
df = pd.DataFrame(data=d)
df = pd.pivot_table (df, index ='name', columns='date', values=['A','B','C'])
df
我得到的输出:
我需要的
注意:在 Excel 中,数据透视表输入为(“日期”作为列/“名称”作为行/“A”、“B”和“C”作为值)
解决方案
您需要使用swaplevel
来切换 MultiIndex 列的顺序,以便日期在顶部,“A”、“B”、“C”在底部。然后,您还将对该索引进行排序。要将“A”替换为“A 的总和”,我使用该rename
方法在列前加上“Sum of A”。
new_df = (df.pivot_table(index ='name', columns='date', values=['A','B','C'])
.swaplevel(axis=1)
.sort_index(axis=1)
.rename(columns="Sum of {}".format, level=1)
)
print(new_df)
date 2/21/2020 2/22/2020 2/23/2020
Sum of A Sum of B Sum of C Sum of A Sum of B Sum of C Sum of A Sum of B Sum of C
name
James 1 7 13 3 9 15 5 11 17
John 2 8 14 4 10 16 6 12 18
推荐阅读
- python - 如何使用烧瓶将内容加载到 div 元素中
- python-3.x - Python3 意外的 to_bytes 返回值
- python - Spark:没有名为“编码”的模块
- bash - shell脚本中的可选变量
- python - 如何在无服务器框架中将外部 python 模块导入 AWS Lambda 函数?
- julia - 参数类型构造函数中“where”关键字的用途
- html - 强制本地 html 文件中的超链接打开关联的应用程序而不是下载
- python - 通过 CustomJS 更新轴范围时,分类轴上的矩形字形表现异常 - Bokeh
- php - 获取多维数组的值
- reactjs - 如何在 ReactJS 中通过上下文提供函数?