![](/img/trans.png)
[英]Pandas df.pivot() and pd.pivot_table() with multiple indexes
[英]Pandas pd.pivot_table gives a KeyError
我有一個df
數據'cath1'
,其中包含 4 列'year'
、 'cath1'
、 'cath2'
和'cath3'
以及與產品對應的 2000 個條目,具有相應的生產年份,以及每 3 個類別中的一個值。
我想創建另一個具有相同 3 個類別列的數據框,並計算每個類別中每個特定年份的所有產品的平均值。
我嘗試使用以下代碼,但它不起作用。
df1=pd.pivot_table(df,index=['year'],values=['0','1','2'],aggfunc=np.mean)
Exception has occurred: KeyError '0'
您的代碼是正確的,但您需要在值中使用列名。
df_pivot = pd.pivot_table(df, index=['year'], values=['cath1', 'cath2','cath3'],
aggfunc=np.mean)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.