python - 如何解决 Pandas 中 CategoricalIndex 列的问题?

标签 python pandas

我正在处理芝加哥的犯罪数据,并希望汇总每个地区/社区的前 5 名犯罪。但是,我的代码有效,但我在数据框列中得到了不需要的索引和 CategoricalIndex 类型列,这使我无法访问特定列以进行进一步的数据操作。

我做了什么:

crimes_2012 = pd.read_csv('Chicago_Crimes_2012_to_2017.csv', sep=',', error_bad_lines=False)
df=crimes_2012[['Primary Type', 'Location Description', 'Community Area']]
crime_catg = df.groupby(['Community Name', 'Primary Type'])['Primary Type'].count().unstack()
crime_catg = crime_catg[['THEFT','BATTERY', 'CRIMINAL DAMAGE', 'NARCOTICS', 'ASSAULT']]
crime_catg = crime_catg.dropna()

这是我当前需要改进的输出:

enter image description here

这是我的尝试:

当我尝试下面的代码时,我仍然没有得到新的索引,并且索引名称在输出数据框中显示得很奇怪。为什么?如何解决这个问题?任何想法?谢谢

enter image description here

即使我尝试重新索引数据框,它也终究没有获得新索引。

crime_catg.reindex(inplace=True, drop=True)

有解决这个问题的想法吗?有什么想法吗?

最佳答案

有几种方法可以解决这个问题。

1) 保留 CategoricalIndex 类型并使用 .add_categories 方法更新有效类别,例如修复您的 .reindex 问题:

crime_catg.columns = crime_catg.columns.add_categories(['Community Name'])

2) 转换为 pandas.Index:

crime_catg.columns = pd.Index(list(crime_catg.columns))

关于python - 如何解决 Pandas 中 CategoricalIndex 列的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55749399/

相关文章:

python - 全局计数器线程在 python 中安全吗?

Python - 将日期戳添加到文本文件

javascript - 如何使用 python 或 javascript 在 <canvas> 元素中抓取数据?

python - Python 中 Pandas 数据帧的 if 语句

python - 如何从 pandas 系列中的字符串中删除正则表达式捕获组的第一个实例?

python - 在 Linux Python/pip 上构建 cyrus-sasl 后无法看到 sasl.h 文件

python - 如何使用 argparse 在 python 中添加多个参数选项?

python - 优化条件 while 循环

python - tensorflow 错误 : Invalid argument: shape must be a vector

python - Pandas 将年份列转换为日期列