python - 带有参数“列”但没有列的每个类别的值的熊猫数据透视表
问题描述
我想应用 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
感谢您提前提供的所有建议和帮助。
解决方案
我认为您需要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
推荐阅读
- string - 将字符串转换为浮点数。列标题中有一个 % 符号
- c++ - 与已安装静态库链接的共享库的 automake Mingw 交叉编译问题
- visual-studio-code - 使用 WSL bash 作为带有 anaconda 的 vscode 终端
- java - java8方法引用,允许不兼容的返回类型
- javascript - google maps from DivPixelToLatLng 意外结果
- node.js - 如何使用 multer 从表单中获取上传文件的路径
- r - 参数不是数字或逻辑:用一个字符串列返回 NA
- ios - 在为 IOS 发布之前如何查看我的应用页面?
- google-maps - 找不到离子谷歌服务
- java - Java 高 CPU 线程 | JBOSS EAP 6.3 | 无法找到根本原因