【发布时间】: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