Reputation: 395
I have a dataframe that has date, sales, and budget as column names. I want to drop the date column but it gives me an error KeyError: "['Date'] not found in axis"
Below is my code:
df2 = df.copy() # make a copy of the dataframe object
df2.drop(columns = ['Date'], inplace=True) # drop the Date columns
The Datatype of all columns
Date datetime64[ns]
Sales float64
Budget float64
PPV float64
SOPPV float64
dtype: object
The full Trackback:
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"
Upvotes: 1
Views: 6203
Reputation: 3594
I believe you have an additional space before/after the Date
. So, either you can edit the column name manually or you can try:
df.drop(columns=['Date '],inplace=True)
Or
df.drop(columns=[' Date'],inplace=True)
Upvotes: 1
Reputation: 108
You could try and eliminate all lines with nan df2.dropna()
then you I think you can drop it? df2.drop(['Date'])
Upvotes: 0