Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If possible batch drop dataframe's columns with something like slice selection method?

Tags:

python

pandas

For next dataframe, I want to drop the columns c, d, e, f, g

    a   b   c   d   e   f   g   h   i   j
0   0   1   2   3   4   5   6   7   8   9
1   10  11  12  13  14  15  16  17  18  19

So I use next code:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(20).reshape(2, 10), columns=list('abcdefghij'))
df.drop(['c', 'd', 'e', 'f', 'g'], axis=1)

The problem is maybe my dataframe not just have so little columns, I may need to drop a lots of consecutive columns, so my question any way like 'c': 'g' could be possible for me to quick select the columns to drop?

like image 480
atline Avatar asked Apr 17 '26 19:04

atline


1 Answers

Use DataFrame.loc for select consecutive names of columns:

df = df.drop(df.loc[:, 'c':'g'].columns, axis=1)
print (df)
    a   b   h   i   j
0   0   1   7   8   9
1  10  11  17  18  19

Or use Index.isin:

c = df.loc[:, 'c':'g'].columns
df = df.loc[:, ~df.columns.isin(c)]

If possible multiple consecutive groups use Index.union for join values together, Index.isin, Index.difference or Index.drop:

c1 = df.loc[:, 'c':'g'].columns
c2 = df.loc[:, 'i':'j'].columns

df = df.loc[:, ~df.columns.isin(c1.union(c2))]
print (df)
    a   b   h
0   0   1   7
1  10  11  17

df = pd.DataFrame(np.arange(20).reshape(2, 10), columns=list('wbcdefghij'))
print (df)
    w   b   c   d   e   f   g   h   i   j
0   0   1   2   3   4   5   6   7   8   9
1  10  11  12  13  14  15  16  17  18  19

c1 = df.loc[:, 'c':'g'].columns
c2 = df.loc[:, 'i':'j'].columns

#possible change order of columns, because function difference sorting
df1 = df[df.columns.difference(c1.union(c2))]
print (df1)
    b   h   w
0   1   7   0
1  11  17  10

#ordering is not changed
df2 = df[df.columns.drop(c1.union(c2))]
print (df2)
    w   b   h
0   0   1   7
1  10  11  17
like image 193
jezrael Avatar answered Apr 20 '26 08:04

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!