How to remove column with number as index name?

Viewed 85

I have the following dataframe:

enter image description here

I tried to drop the data of -1 column by using

df = df.drop(columns=['-1'])

However, it is giving me the following error:

enter image description here

I was able to drop the column if the column name is some language character using this similar coding script, but not a number. What am I doing wrong?

3 Answers

You can test real columns names by converting them to list:

print (df.columns.tolist())

I think you need droping number -1 instead string '-1':

df = df.drop(columns=[-1])

Or another solution with same ouput:

df = df.drop(-1, axis=1)

EDIT:

If need select all columns without first use DataFrame.iloc for select by position, first : means select all rows and second 1: all columns with omit first:

df = df.iloc[:, 1:]

If you are just trying to remove the first column, another approach that would be independent of the column name is this:

df = df[df.columns[1:]]

you can do it simply by using the following code:

first check the name of the column by using following:

df.columns

then if the output is like:

Index(['-1', '0'], dtype='object')

use drop command to delete the column

df.drop(['-1'], axis =1, inplace = True)

guess this should help for future as well

Related