python - Pandas df.plot() 抛出 KeyError
问题描述
大编辑:如果我从 read_csv 函数中删除 index_col = 1,则不会抛出此错误。留下这个问题是因为我很好奇为什么会发生这种情况。
我有以下 CSV:
Agency Division Expenditures ($000,000)
NYPD OPERATIONS 3331
NYPD EXECUTIVE MANAGEMENT 489.4
NYPD SCHOOL SAFETY 279.6
NYPD ADMINISTRATION-PERSONNEL 263.9
当我用以下方式绘制它时:
data.plot(x='Division',y='Expenditures ($000,000)')
我被抛出:
KeyError: 'Division'
我很困惑,因为我的索引被命名为“Division”,那么为什么会抛出这个错误呢?使用 data.plot(kind='bar') 给了我一个合理的情节,但我在按其键调用此列时遇到问题。
完整代码如下:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
NYPD_data = "D:/CSVs/NYPD_Spending.csv"
data = pd.read_csv(NYPD_data, index_col = 1)
plt.figure(1, figsize=(10,10))
plt.xlabel('NYPD Division')
data.plot(x='Division', y='Expenditures ($000,000)')
plt.show()
解决方案
data = {'Agency': {0: 'NYPD', 1: 'NYPD', 2: 'NYPD', 3: 'NYPD'},
'Division': {0: 'OPERATIONS',
1: 'EXECUTIVE MANAGEMENT',
2: 'SCHOOL SAFETY',
3: 'ADMINISTRATION-PERSONNEL'},
'Expenditures ($000,000)': {0: 3331.0, 1: 489.4, 2: 279.6, 3: 263.9}}
df = pd.DataFrame.from_dict(data)
plt.figure(figsize=(10, 10))
plt.plot(df['Division'], df['Expenditures ($000,000)'])
plt.xticks(rotation='30')
plt.xlabel('NYPD Division')
plt.show()
产生情节:
df.plot('Division', 'Expenditures ($000,000)')
df.plot(x='Division', y='Expenditures ($000,000)')
不工作:
df.plot(x=df['Division'], y=['Expenditures ($000,000)'])
这不起作用,因为源已由df.plot
. x
&y
应该是x : label or position, default None
和y : label, position or list of label, positions, default None
分别。所以问题是以不正确的形式向方法发送参数。pandas.DataFrame.plot
如果是:
df = pd.read_csv('Book1.csv', index_col=1)
df =
Agency Expenditures ($000,000)
Division
OPERATIONS NYPD 3331.0
EXECUTIVE MANAGEMENT NYPD 489.4
SCHOOL SAFETY NYPD 279.6
ADMINISTRATION-PERSONNEL NYPD 263.9
请注意,Division
现在是索引,不再是列,因此x = 'Division'
无法使用。
df.plot()
推荐阅读
- tensorflow - 使用生成器时,model.evaluate() 随步数的变化而变化很大
- php - CakePHP 2.X - 关于 HasMany 关系的几个问题
- python - 将 Python XML ElementTree 输出写入 CSV
- netlogo - 计算 NetLogo 中的相异指数
- redis - 将 redisearch 与 openresty 一起使用
- android - FireBase 实时数据库
- powerbi - 计算列:不同的 id# 应返回第一个日期并忽略其他日期
- python - 在 Linux 中从 python 脚本运行 .m 文件
- database - Power BI - TopN + Others 来自两个表的数据
- c# - 如何在 Common Data Service 上创建自定义行业加速器?