Python KeyError: 'None of [Int64Index([...], dtype='int64')] are in the [columns]' 错误解析及解决方法

在使用 Python 进行数据分析,特别是使用 Pandas DataFrame 和机器学习算法时,你可能会遇到 KeyError: 'None of [Int64Index([...], dtype='int64')] are in the [columns]' 错误。这个错误通常发生在你尝试访问 DataFrame 中不存在的列时。

错误分析:

这个错误提示意味着你正在尝试使用一个整数索引列表 (Int64Index) 来访问 DataFrame 的列,但这些索引值在 DataFrame 的列名中并不存在。

**错误示例:**pythonimport pandas as pd

data = {'A': [1, 2, 3], 'B': [4, 5, 6]}df = pd.DataFrame(data)

尝试使用整数索引访问列,会导致 KeyErrorcenters = df[[16, 27, 19]]

解决方法:

  1. 检查数据类型: 确保你尝试访问的数据是 Pandas DataFrame 类型。如果不是,则需要将其转换为 DataFrame。2. 确认列名: 仔细检查你要访问的列名是否存在于 DataFrame 中。你可以使用 df.columns 查看所有列名。3. 使用正确的索引方式: * 使用列名: 使用列名访问 DataFrame 的列,例如 df['A']。 * 使用整数索引访问行: 如果你想使用整数索引,请确保使用 .iloc 属性来访问行,例如 df.iloc[[16, 27, 19]]。 * 使用切片: 使用切片来选择多行或多列,例如 df[10:20]。4. 检查代码逻辑: 检查你的代码逻辑,确保你没有在其他地方修改 DataFrame 的结构,导致列名发生变化。

**代码示例:**pythonimport pandas as pdimport numpy as np

class MyKmeans: def init(self, k, n=100): self.k = k self.n = n

def fit(self, x, centers=None):        if centers is None:            # 使用随机索引选择初始中心点            idx = np.random.choice(len(x), size=self.k, replace=False)             centers = x[idx]

    # ... 其他代码 ...

示例数据data = {'feature1': [1, 2, 3, 4, 5], 'feature2': [6, 7, 8, 9, 10]}df = pd.DataFrame(data)

m = MyKmeans(3)

选择正确的特征列points_set, centers = m.fit(df[['feature1', 'feature2']].values)

... 其他代码 ...

通过仔细检查你的代码,并使用正确的索引方式访问 DataFrame 的列,你可以避免 'KeyError: 'None of [Int64Index([...], dtype='int64')] are in the [columns]' 错误。

Python KeyError:

原文地址: https://www.cveoy.top/t/topic/f0iV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录