Home > Software design >  Deleting the Unnamed columns in the data frame generates errors
Deleting the Unnamed columns in the data frame generates errors

Time:11-02

I want to delete the Unnamed columns in the following data frame df (to download from enter image description here

print(df.columns)

Out:

Index([       'Code',        'Area',          2002,  'Unnamed: 3',
                2003,  'Unnamed: 5',          2004,  'Unnamed: 7',
                2005,  'Unnamed: 9',          2006],
      dtype='object')

Can someone help? Thanks.

I have tried several methods and I get errors, eg.:

  • Solution 1:

    df.loc[:, ~df.columns.str.contains('^Unnamed')]

Out:

`TypeError: bad operand type for unary ~: 'Index'`
  • Solution 2:

    remove_cols = [col for col in df.columns if 'Unnamed' in col] df.drop(remove_cols, axis='columns', inplace=True)

Out:

`TypeError: argument of type 'int' is not iterable`
  • Solution 3:

    df.drop(df.columns[df.columns.str.contains('Unnamed',case = False)],axis = 1, inplace = True)

Out:

ValueError: Cannot mask with non-boolean array containing NA / NaN values

df.columns.str.contains('^Unnamed')

Out:

Index([False, False,   nan,  True,   nan,  True,   nan,  True,   nan,  True,
         nan,  True,   nan,  True,   nan,  True,   nan,  True,   nan,  True,
         nan,  True,   nan,  True,   nan,  True,   nan,  True,   nan,  True,
         nan,  True,   nan,  True,   nan,  True,   nan,  True,   nan,  True,
         nan,  True],
      dtype='object')

CodePudding user response:

This is one way to solve your problem.

cols = [col for col in df.columns.values if 'Unnamed' not in col]
df = df[cols]

CodePudding user response:

The only code I've found so far that solves this problem:

df.drop(df.filter(regex="Unname"), axis=1, inplace=True)

  • Related