noob
noob

Reputation: 3811

Drop multiple columns when column name has space pandas

I have a df

Col 1    Col 2    Col3  Col4
11         10      s     1
12         22      g     10

If I find the column names and Do

<<df.columns
>>Index(['Col 1', 'Col 2' , 'Col3', 'Col4'])

If I want to remove Col 1 and Col 2 from my df , then what to do:

df.drop(['Col 1, Col 2'], axis=1)

I am getting error:

KeyError: "['Col 1, Col 2'] not found in axis"

EDIT:

It works with below syntax

 df.drop(['Col 1', 'Col 2'], axis=1)

Upvotes: 2

Views: 618

Answers (1)

jezrael
jezrael

Reputation: 863226

If need remove columns with spaces:

df = df.loc[:, ~df.columns.str.contains('\s')]
print (df)
  Col3  Col4
0    s     1
1    g    10

But maybe space is not space, you can test it by ord, for space got 32:

a = [ord(x) for x in df.columns[0]]
print (a)
[67, 111, 108, 32, 49]

Upvotes: 2

Related Questions