【问题标题】:KeyError: 'x' keeps stopping my code from workingKeyError: 'x' 不断阻止我的代码工作
【发布时间】:2023-03-06 07:21:01
【问题描述】:

我正在为我的大学课程做一些统计作业,但由于某种原因,我不断收到 KeyError: 'x' 我不确定这意味着什么或如何更改它以使代码正常工作。它说它与 pandas 库有关(文件“pandas_libs\index_class_helper.pxi”,第 109 行,在 pandas._libs.index.Int64Engine._check_type)。

这是我使用的代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

array = np.loadtxt(r'C:\Users\Tim\Desktop\University\Statistics\Body-Data.csv', skiprows = 1, delimiter=',' )
print('questions a), b) and c) \n', array)

sorted_array = array[np.argsort(array[:,1])]
print('question d) \n', sorted_array)

print("median: \n")
median = np.median(sorted_array, axis = 0)
print(median)

print("mean: \n")
mean = np.mean(sorted_array, axis = 0)
print(mean)

print("standard deviation: \n")
standard_deviation = np.std(sorted_array, axis = 0)
print(standard_deviation)

print("variance: \n")
variance = (standard_deviation)**2
print(variance)

print("covariance: \n")
covariance = np.cov(sorted_array)
print(covariance)

print("Correlation matrix: \n")
df = pd.DataFrame(sorted_array)
CorrMatrix = df.corr()
print(CorrMatrix)

print("Absolute relative fequency: \n")
data1 = np.ravel(sorted_array).T
dg = pd.Series(data1).value_counts()
print(dg)

print("Histogram in plot section of Spyder editor: \n")
fig, axes = plt.subplots(ncols=len(df.columns), figsize=(10,5))
for col, ax in zip(df, axes):
    df[col].value_counts().sort_index().plot.bar(ax=ax, title=col)
plt.tight_layout()    
plt.show()
    
df.plot()    
df.plot(kind='scatter',x='x',y='y') 

【问题讨论】:

  • 检查x是否出现在df.columns的输出中
  • "说和pandas库有关" 首先请阅读meta.stackoverflow.com/questions/359146/…。然后,尝试追溯并诊断错误的逻辑。例如,查看代码中发生的最后一件事的堆栈跟踪。想想KeyError 实际上是什么(提示:Error 由字典中缺少的Key 引起)以及为什么会发生这种情况(pandas 正试图在字典中查找内容;你能想哪个?)
  • 您可以尝试的其他有用的事情是阅读文档,并回忆您对相关代码的意图。例如,在这里您想绘制数据框中的数据,使用 x 轴的 x 列(因此 x='x'),是吗?那么,数据框实际上是否有该列?
  • 即使我在创建数据框后立即运行代码,我仍然遇到同样的问题。我认为因为我在散点图中指定了“x”,所以它会起作用。
  • @AnuragDabas 的第一条评论可能是正确的。更详细地说,您的最后一行是df.plot(kind='scatter',x='x',y='y')x='x' 部分试图在您的 DataFrame 中选择一列,而您可能没有名为 'x' 的列。 (如果您发布了minimal reproducible example,您会更快地得到答案,因为没有数据,我们不知道全貌。)

标签: python pandas dataframe numpy statistics


【解决方案1】:

让我们做一个简单的数据框:

In [305]: df2=pd.DataFrame(np.arange(12).reshape(4,3),columns=['a','b','c'])
In [306]: df2
Out[306]: 
   a   b   c
0  0   1   2
1  3   4   5
2  6   7   8
3  9  10  11
In [307]: df2.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   a       4 non-null      int64
 1   b       4 non-null      int64
 2   c       4 non-null      int64
dtypes: int64(3)
memory usage: 224.0 bytes

如果我像你一样使用plot,但使用列名,我会得到一个图:

In [308]: df2.plot(kind='scatter', x='a',y='b')
Out[308]: <AxesSubplot:xlabel='a', ylabel='b'>

但是,如果我使用通用的 xy,就像我认为的那样,认为你正在指定轴标签或类似的东西,我会得到你的错误。

In [309]: df2.plot(kind='scatter', x='x',y='y')
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/pandas/core/indexes/base.py", line 3080, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas/_libs/index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 4562, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'x'

The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "<ipython-input-309-89538e1b65fa>", line 1, in <module>
    df2.plot(kind='scatter', x='x',y='y')
  File "/usr/local/lib/python3.8/dist-packages/pandas/plotting/_core.py", line 900, in __call__
    return plot_backend.plot(data, x=x, y=y, kind=kind, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/pandas/plotting/_matplotlib/__init__.py", line 61, in plot
    plot_obj.generate()
  File "/usr/local/lib/python3.8/dist-packages/pandas/plotting/_matplotlib/core.py", line 280, in generate
    self._make_plot()
  File "/usr/local/lib/python3.8/dist-packages/pandas/plotting/_matplotlib/core.py", line 1042, in _make_plot
    data[x].values,
  File "/usr/local/lib/python3.8/dist-packages/pandas/core/frame.py", line 3024, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/usr/local/lib/python3.8/dist-packages/pandas/core/indexes/base.py", line 3082, in get_loc
    raise KeyError(key) from err
KeyError: 'x'

我包含了完整的traceback,您也应该这样做。

在关键错误之前,它使用self.columns.get_loc(key)

查看数据框的columns

In [310]: df2.columns
Out[310]: Index(['a', 'b', 'c'], dtype='object')

get_loc 适用于有效名称:

In [312]: df2.columns.get_loc('b')
Out[312]: 1

但因无效而失败:

In [313]: df2.columns.get_loc('x')
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/pandas/core/indexes/base.py", line 3080, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas/_libs/index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 4562, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'x'

The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "<ipython-input-313-537e5b0cd441>", line 1, in <module>
    df2.columns.get_loc('x')
  File "/usr/local/lib/python3.8/dist-packages/pandas/core/indexes/base.py", line 3082, in get_loc
    raise KeyError(key) from err
KeyError: 'x'

我展示所有这些细节是因为你需要学会在错误消息中寻找这样的线索。对于基本的 Python dict,KeyError 意味着您尝试获取不存在的条目。在pandas 中,列通常由名称标识,KeyError 类似——您正在寻找一个不存在的列名称。

我承认df.plot 的文档对于xy 参数的含义有些模糊。

x : label or position, default None
    Only used if data is a DataFrame.
y : label, position or list of label, positions, default None
    Allows plotting of one column versus another. Only used if data is a DataFrame.

有一个单独的xlabel 参数。

【讨论】:

  • 非常感谢您的帮助!我真的很感激。
【解决方案2】:

请检查您的 df.columns 输出中是否存在 x。

KeyError 通常意味着密钥不存在于 df 中。

【讨论】:

    猜你喜欢
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多