首页 > 解决方案 > 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()

标签: pythonpandasmatplotlib

解决方案


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 Noney : label, position or list of label, positions, default None分别。所以问题是以不正确的形式向方法发送参数。pandas.DataFrame.plot

数据帧绘图 API

如果是:

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()

在此处输入图像描述


推荐阅读