我不确定为什么会在下面的示例代码中出现KeyError

2024-04-25 16:51:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在导入的CSV文件有一个名为“MED EXP DATE”的列。我在代码前面引用了同一列,没有问题。当我稍后引用它时,我得到一个键错误

import pandas as pd
df = pd.read_csv(r"C:\Users\Desktop\Air_Rally_Marketing\PILOT_BASIC.csv", low_memory=False, dtype={'UNIQUE ID': str, 'FIRST NAME': str,'LAST NAME': str, 'STREET 1': str, 'STREET 2': str, 'CITY': str, 'STATE': str, 'ZIP CODE': str, 'MED DATE': str, 'MED EXP DATE': str})
df.dropna(inplace = True)
df['EXP DATE LEN'] = df['MED EXP DATE'].apply(len) #creates a column to store the length of the column MED EXP DATE
print(df.head)

这是我收到的错误:

return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
  File "pandas\_libs\index.pyx", line 80, in pandas._libs.index.IndexEngine.get_value
  File "pandas\_libs\index.pyx", line 90, in pandas._libs.index.IndexEngine.get_value
  File "pandas\_libs\index.pyx", line 135, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index_class_helper.pxi", line 109, in pandas._libs.index.Int64Engine._check_type
KeyError: 'MED EXP DATE'

当我搜索此错误的含义时,我的理解是,这意味着我引用了一个找不到的密钥。我对此感到困惑,因为我在前一行中引用了“MED EXP DATE”,并且没有在那里得到关键错误


Tags: inpandasdfgetdateindexvalue错误
2条回答

这一点如下:

df = Right = df['MED EXP DATE'].str[-4:]

正在将df变量转换为一个系列,而不是一个数据帧。因此,当它到达apply语句时,它就不知道您所指的是什么

解决方案:使用双括号确保df仍然是一个数据帧

将df设置为系列

df = pd.DataFrame([{'a': 1, 'b': 2}, {'a': 1, 'b': 3}])
df = df['a']
type(df)
<class 'pandas.core.series.Series'>

将df保留为数据帧

df = pd.DataFrame([{'a': 1, 'b': 2}, {'a': 1, 'b': 3}])
df = df[['a']]
type(df)
<class 'pandas.core.frame.DataFrame'>

我认为错误在于这一行: 'df=Right=df['MED EXP DATE'].str[-4:' 为什么这里有两个赋值运算符(=)

相关问题 更多 >