简体   繁体   中英

Dropping multiple columns in a pandas dataframe between two columns based on column names

A super simple question, for which I cannot find an answer.

I have a dataframe with 1000+ columns and cannot drop by column number, I do not know them. I want to drop all columns between two columns, based on their names.

foo = foo.drop(columns = ['columnWhatever233':'columnWhatever826']) 

does not work. I tried several other options, but do not see a simple solution. Thanks!

You can use .loc with column range. For example if you have this dataframe:

   A  B  C  D  E
0  1  3  3  6  0
1  2  2  4  9  1
2  3  1  5  8  4

Then to delete columns B to D :

df = df.drop(columns=df.loc[:, "B":"D"].columns)
print(df)

Prints:

   A  E
0  1  0
1  2  1
2  3  4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM