Search code examples
pandasdataframedata-sciencedata-cleaning

Key Error Raise when trying to delete an existing column


RangeIndex: 381732 entries, 0 to 381731
Data columns (total 10 columns):
 #   Column           Non-Null Count   Dtype  
---  ------           --------------   -----  
 0   Unnamed: 0       381732 non-null  int64  
 1   tweet_id         378731 non-null  float64
 2   time             378731 non-null  object 
 3   tweet            378731 non-null  object 
 4   retweet_count    336647 non-null  float64
 5   Unnamed: 0.1     336647 non-null  float64
 6   User             3001 non-null    object 
 7   Date_Created     3001 non-null    object 
 8   Source of Tweet  3001 non-null    object 
 9   Tweet            3001 non-null    object 
dtypes: float64(3), int64(1), object(6)
memory usage: 29.1+ MB
df = df.drop(['Unnamed: 0','Unnamed: 0.1','User','Date_Created','Source of Tweet'],axis =1)
df.head()

i wrote this code to drop unwanted columns from my dataframe but i am encountering keyError not found in axis

KeyError: "['Unnamed: 0', 'Unnamed: 0.1', 'User', 'Date_Created', 'Source of Tweet'] not found in axis"

Solution

  • For debugging purpose, try:

    cols_to_drop = ['Unnamed: 0','Unnamed: 0.1','User','Date_Created','Source of Tweet']
    df = df[[col for col in df.columns if not col in cols_to_drop]]
    

    and check the remain columns using df.info()