0

I have a CSV file which included some films info, and I want to remove column director and cast, but pandas told me KeyError.

Source Code:

import pandas as pd

if __name__ == '__main__':
    df = pd.read_csv(r'titles.csv', sep='\t')

    info = df.info

    # print(df.head())
    # print(df.tail())

    # print('dftypes: ', df.dtypes)

    # null = df.isnull().sum(axis=1)
    #
    # print(null)

    # df2=df.drop(['director'],axis=1)
    print(df.columns)
    df.drop(labels='director', axis=1)

Columns in csv file:

show_id, type, title, director, cast, country, date_added, release_year, rating, duration, listed_in, description

Error info:

KeyError: "['director'] not found in axis"

I have tried to drop like the follows:

df.drop(labels=['director', 'cast'], axis=1)

# or

df.drop(columns=['director', 'cast'])
vorbote
  • 33
  • 5
  • what is the result of *df.columns*? – Naveed Oct 19 '22 at 15:29
  • You need to assign back to df. df = df.drop(columns=['director', 'cast']) – Jason Baker Oct 19 '22 at 15:29
  • 1. `drop` is not `inplace`, 2. The separator is `, `(space after comma) – Ynjxsjmh Oct 19 '22 at 15:30
  • @Naveed The result is of df.columns is `Index(['show_id,type,title,director,cast,country,date_added,release_year,rating,duration,listed_in,description'], dtype='object')` – vorbote Oct 19 '22 at 15:31
  • 2
    you see, you only have one column here, note the quotes – Naveed Oct 19 '22 at 15:34
  • Can you [edit] to include a [mcve] with a sample of your input dataframe, like the output of `df.head()` so that we can better understand your problem? – G. Anderson Oct 19 '22 at 15:40
  • 1
    @Ynjxsjmh @jasonbaker neither `df=df.drop(...` or `inplace=True` would cause or prevent a `KeyError`, only affect the output – G. Anderson Oct 19 '22 at 15:43
  • @G.Anderson Have you checked my 2nd point? The separator of his csv is `, ` while he uses `\t`. – Ynjxsjmh Oct 19 '22 at 16:45
  • @Ynjxsjmh that's absolutely correct and the most likely cause of the issue, just wanted to point out that the first point is extraneous to the error in the question, since two people made it I didn't want the OP to get sidetracked into thinking that was related to the keyerror – G. Anderson Oct 19 '22 at 16:52

0 Answers0