简体   繁体   中英

Dropping lots of columns from a pandas dataframe

Say I have a data frame with 100+ columns, how would I go about dropping, say, the last 15 columns?

Is there a better way than typing: df.drop([column1,column2,...,column15]) ? I have to input the names of all of the columns here. Is there not a way I can sort of slice, like something like [column1 : column15] ?

If you know the indexes of the columns you want to drop you could use

df.drop(df.columns[15:30], axis=1)

As mentioned in the comment by @fillbranden I should have shown you how to delete the last 15 columns with:

df.drop(df.columns[-15:], axis=1)

从数据框中删除最后 15 列:

df = df.iloc[:, :-15]

Try this code with the made up dataframe:

df = pd.DataFrame(np.random.randint(0,100, size= (100, 15)), columns=list('ABCDEFGHIJKLMNO'))

In this case I dropped the last 5 columns using:

df.drop(df.iloc[:,10:15], inplace=True, axis=1)
print(df)

在此处输入图片说明

As long as you can easily use your column index, this should work for your purposes.

Drop the last X columns if you don't know the specific column indexes:

cols = list(range(-1, -10, -1)) # Drop last 10 columns

df.drop(df.columns[cols], axis = 1)

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