如何在 Pandas 中调整 table

How to Pivot table in Pandas

我正在尝试使用 pandas、

为枢轴 table 编写代码

这是我的示例 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

输出应该是这样的:

这是我的代码

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)

但我没有得到想要的结果

您几乎已经找到了,但您在索引中忘记了“姓名”:

pd.pivot_table(df, index=['Name', 'Owner'], columns=['Role'],
               values=['Can Edit','Can Read','Can Delete','Can download'],
               aggfunc=np.sum)

请注意,如果使用了所有其他列,则无需指定值:

pd.pivot_table(df, index=['Name', 'Owner'], columns=['Role'], aggfunc=np.sum)

输出:

              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