Miguel Santos
Miguel Santos

Reputation: 2026

Remove pandas columns based on list

I have a list:

my_list = ['a', 'b']

and a pandas dataframe:

d = {'a': [1, 2], 'b': [3, 4], 'c': [1, 2], 'd': [3, 4]}
df = pd.DataFrame(data=d)

What can I do to remove the columns in df based on list my_list, in this case remove columns a and b

Upvotes: 9

Views: 14318

Answers (3)

user2110417
user2110417

Reputation:

You can select required columns as well:

cols_of_interest = ['c', 'd']
df = df[cols_of_interest]

if you have a range of columns to drop: for example 2 to 8, you can use:

df.drop(df.iloc[:,2:8].head(0).columns, axis=1) 

Upvotes: 1

denis_smyslov
denis_smyslov

Reputation: 887

This is a concise script using list comprehension: [df.pop(x) for x in my_list]

my_list = ['a', 'b']
d = {'a': [1, 2], 'b': [3, 4], 'c': [1, 2], 'd': [3, 4]}
df = pd.DataFrame(data=d)
print(df.to_markdown())
|    |   a |   b |   c |   d |
|---:|----:|----:|----:|----:|
|  0 |   1 |   3 |   1 |   3 |
|  1 |   2 |   4 |   2 |   4 |

[df.pop(x) for x in my_list]
print(df.to_markdown())
|    |   c |   d |
|---:|----:|----:|
|  0 |   1 |   3 |
|  1 |   2 |   4 |

Upvotes: 0

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

This is very simple:

df = df.drop(columns=my_list)

drop removes columns by specifying a list of column names

Upvotes: 15

Related Questions