How to delete all columns in DataFrame except certain ones?

In [48]: df.drop(df.columns.difference(['a','b']), 1, inplace=True)
Out[48]:
   a  b
0  1  2
1  4  3
2  8  9

or:

In [55]: df = df.loc[:, df.columns.intersection(['a','b'])]

In [56]: df
Out[56]:
   a  b
0  1  2
1  4  3
2  8  9

PS please be aware that the most idiomatic Pandas way to do that was already proposed by @Wen:

df = df[['a','b']]

or

df = df.loc[:, ['a','b']]

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)