首页 > 解决方案 > 具有正确列值时出现键错误

问题描述

我对编程比较陌生,我正在尝试执行我的一段代码以绘制值

我的代码:

import matplotlib.pyplot as plt
import pandas as pd

# set directory
df = pd.read_excel('Angle difference plot.xlsx', 'Sheet1')


# set plot
plt.plot(df['Angle'], df['RE Angle'])

# set label
plt.xlabel('calculated angle')
plt.ylabel('ground truth)')   
plt.title('angle accuracy plot')
plt.legend()

plt.show

当我执行上面的代码时,我得到以下错误:

 return self._engine.get_loc(key)
  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Angle'

有人能解释一下为什么我会看到这个错误吗?

我的 excel 文件如下所示:

在此处输入图像描述

很感谢任何形式的帮助

标签: pythonpandasdataframekeyerror

解决方案


修复列名

import pandas as pd
import matplotlib.pyplot as plt

# set directory
df = pd.read_excel('Angle difference plot.xlsx', 'Sheet1')

# clear whitespace from the beginning and end of the column names
df.columns = df.columns.str.strip()

# plot
plt.plot('Angle', 'RE Angle', data=df)

推荐阅读