首页 > 解决方案 > 带有参数“列”但没有列的每个类别的值的熊猫数据透视表

问题描述

我想应用 pd.pivot_table() 来获取列“类别”的每个类别值的数量。

这里,数据集的基本信息如下:

df.info()
Data columns (total 3 columns):
location                                   2270 non-null object
time                               2270 non-null object
categories    2270 non-null object
dtypes: object(3)

我的代码:

table=pd.pivot_table(df,values=['categories'],
                     index=['location','time'],
                     columns=['categories'],
                     aggfunc='count',fill_value=0)
table.head()

预期结果是:

location    time    Cat1 Cat2
L1      Jan-2020    5   1
L1      Feb-2020    2   1
L2      Jan-2019    4   3
L2      Feb-2020    5   0

但我的结果是:

    location      time  
    L1      Jan-2020    
    L1      Feb-2020    
    L2      Jan-2019    
    L2      Feb-2020    

我尝试通过输入以下示例的数据来创建简单的数据框,然后我可以获得预期的结果。但是如果我从 csv 文件导入我的整个数据框,它就会失败。

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html

感谢您提前提供的所有建议和帮助。

标签: pythonpandaspivot

解决方案


我认为您需要GroupBy.size计数功能,并且values应该省略参数:

table=pd.pivot_table(df,
                     index=['location','time'],
                     columns=['categories'],
                     aggfunc='size',fill_value=0)
print (table.head())
categories         Cat1  Cat2
location time                
L1       Feb-2020     2     1
         Jan-2020     5     1
L2       Feb-2020     5     0
         Jan-2019     4     3

推荐阅读