python运行报错 KeyError: “[‘…’] not in index”

我在使用python指定列读取xlsx数据时遇到这个报错,具体原因不知。

这个错误通常表示你正在尝试访问一个不存在的索引或列。为了解决这个错误,你应该检查正在使用的代码并确定是否存在以下情况之一:

  1. 索引或列名错误: 检查是否在 DataFrame 中具有正确的索引或列名,可以通过 df.columns 或 df.index 属性来验证。
  2. 数据缺失:检查是否存在数据缺失导致无法访问某些索引或列,可以通过 df.isnull().sum() 来检查缺失数据量,并考虑进行填充、删除或者插值等操作。
  3. 数据类型问题:检查索引或列是否是您期望的数据类型。例如,如果您正在使用字符串索引,则确认它们在数据帧中是否被正确地设置为对象类型而不是整数类型。

针对这个报错,我的解决方式主要是,尝试下重置索引。

df = df .reindex(columns=columns)      #索引重置

索引重置后发现问题得以解决。

源码如下:

import pandas as pd
pd.set_option('display.max_columns', None)                               #显示所有列
pd.set_option('display.unicode.ambiguous_as_wide', True)                 #设置各列对齐
pd.set_option('display.unicode.east_asian_width', True)         
pd.set_option('display.width', 180)                                      #设置打印宽度
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']    #解决中文乱码
import matplotlib.colors as mcolors

src_df = pd.read_excel('./data4.xlsx', sheet_name='淘宝201805')
print('原始数据集:')
print(src_df.head(20))

columns = ['买家会员名','买家支付宝账号','买家应付货款','买家实际支付金额','订单状态','收货人姓名','收货地址','联系手机','订单创建时间','订单付款时间','宝贝标题','宝贝种类','订单备注','宝贝总数量','类别','图书编号']
src_df = src_df.reindex(columns=columns)      #索引重置
print('\n选择需要读入的列:')
df = src_df[columns]
print(df.head(20))

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年8月17日
下一篇 2023年8月17日

相关推荐