我有一个数据框,其中以日期,销售和预算作为列名。我想删除日期列,但它给了我一个错误KeyError: "['Date'] not found in axis"
下面是我的代码:
df2 = df.copy() # make a copy of the dataframe object
df2.drop(columns = ['Date'], inplace=True) # drop the Date columns
所有列的数据类型
Date datetime64[ns]
Sales float64
Budget float64
PPV float64
SOPPV float64
dtype: object
完整的引用:
KeyError Traceback (most recent call last)
<ipython-input-81-22d4dafeb1cb> in <module>
----> 1 df2 = df.drop(columns = ['Date'], inplace=True)
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py in drop(self, labels, axis, index, columns, level, inplace, errors)
3995 level=level,
3996 inplace=inplace,
-> 3997 errors=errors,
3998 )
3999
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py in drop(self, labels, axis, index, columns, level, inplace, errors)
3934 for axis, labels in axes.items():
3935 if labels is not None:
-> 3936 obj = obj._drop_axis(labels, axis, level=level, errors=errors)
3937
3938 if inplace:
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py in _drop_axis(self, labels, axis, level, errors)
3968 new_axis = axis.drop(labels, level=level, errors=errors)
3969 else:
-> 3970 new_axis = axis.drop(labels, errors=errors)
3971 result = self.reindex(**{axis_name: new_axis})
3972
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in drop(self, labels, errors)
5016 if mask.any():
5017 if errors != "ignore":
-> 5018 raise KeyError(f"{labels[mask]} not found in axis")
5019 indexer = indexer[~mask]
5020 return self.delete(indexer)
KeyError: "['Date'] not found in axis"
答案 0 :(得分:0)
您可以尝试使用nan df2.dropna()
消除所有行,那么您认为可以删除它吗? df2.drop(['Date'])
答案 1 :(得分:0)
我相信您在Date
之前/之后还有一个空格。因此,您可以手动编辑列名称,也可以尝试:
df.drop(columns=['Date '],inplace=True)
或
df.drop(columns=[' Date'],inplace=True)