简体   繁体   English

Pandas pd.pivot_table 给出了一个 KeyError

[英]Pandas pd.pivot_table gives a KeyError

I have a df dataframe with 4 columns 'year' , 'cath1' , 'cath2' and 'cath3' and 2000 entries corresponding to products, with corresponding year of production, and a value in each 3 categories.我有一个df数据'cath1' ,其中包含 4 列'year''cath1''cath2''cath3'以及与产品对应的 2000 个条目,具有相应的生产年份,以及每 3 个类别中的一个值。

I would like to create another dataframe with the same 3 category columns and compute the average value of all products for each specific year in each of these categories.我想创建另一个具有相同 3 个类别列的数据框,并计算每个类别中每个特定年份的所有产品的平均值。

I tried with the following code but it does not work.我尝试使用以下代码,但它不起作用。

df1=pd.pivot_table(df,index=['year'],values=['0','1','2'],aggfunc=np.mean)
Exception has occurred: KeyError '0'

Your code is correct but you need to use the column name in the values.您的代码是正确的,但您需要在值中使用列名。

df_pivot = pd.pivot_table(df, index=['year'], values=['cath1', 'cath2','cath3'],
                          aggfunc=np.mean)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM