[英]How to Pivot table in Pandas
我正在嘗試使用 pandas 為 pivot 表編寫代碼,
這是我的樣本 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
和 output 應該是這樣的:
這是我的代碼
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)
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.