Skip to main content
 首页 » 编程设计

python之使用 pandas 过滤 excel 数据时出现 KeyError

2024年10月01日1098°冷暖

我正在尝试在 Python 中读取和过滤 excel 数据。我使用了下面的代码:

import pandas as pd 
import numpy as np 
df = pd.read_excel('file.xlsx')  
df['apples'] = (pd.cut(df['apples'],bins=[-np.inf,2,5,np.inf],labels=['WOW','ok','BOB'])) 
print(df) 

This is my excel file

但是 KeyError: 'apples' 发生了。你对我如何解决这个问题有什么建议吗?

请您参考如下方法:

2 行的标题存在问题,因此默认情况下 DataFrame 的列由第一行创建。

因此需要通过以下方式跳过第一行:

df = pd.read_excel('file.xlsx', skiprows=1) 

或者:

df = pd.read_excel('file.xlsx', header=1)