[英]How to Pivot table in Pandas
I'm trying to write code for pivot table using pandas,我正在尝试使用 pandas 为 pivot 表编写代码,
Here is my sample excel file.这是我的样本 excel 文件。
Name Owner Role Can Edit Can Read Can Delete Can download
John Julan Role1 Yes No No No
Ricard Julan Role2 No Yes No No
Sam Hannah Role2 No No Yes No
Julia Hannah Role1 No No No Yes
Katie Julan Role2 No Yes No Yes
and output should be like this:和 output 应该是这样的:
Here's my code这是我的代码
import pandas as pd
import numpy as np
df = pd.read_excel('pivot.xlsx')
table = pd.pivot_table(df, values=['Can Edit','Can Read','Can Delete','Can download'], index=['Owner'],columns=['Role'], aggfunc=np.sum)
But i don't get desired results但我没有得到想要的结果
You almost had it but you forgot "Name" in the index:你几乎拥有它但你忘记了索引中的“名称”:
pd.pivot_table(df, index=['Name', 'Owner'], columns=['Role'],
values=['Can Edit','Can Read','Can Delete','Can download'],
aggfunc=np.sum)
Note that you do not need to specify the values if all the other columns are used:请注意,如果使用所有其他列,则无需指定值:
pd.pivot_table(df, index=['Name', 'Owner'], columns=['Role'], aggfunc=np.sum)
output: output:
Can Delete Can Edit Can Read Can download
Role Role1 Role2 Role1 Role2 Role1 Role2 Role1 Role2
Name Owner
John Julan No NaN Yes NaN No NaN No NaN
Julia Hannah No NaN No NaN No NaN Yes NaN
Katie Julan NaN No NaN No NaN Yes NaN Yes
Ricard Julan NaN No NaN No NaN Yes NaN No
Sam Hannah NaN Yes NaN No NaN No NaN No
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.