简体   繁体   English

从熊猫数据框中删除大量列

[英]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?假设我有一个包含 100 多列的数据框,我将如何删除最后 15 列?

Is there a better way than typing: df.drop([column1,column2,...,column15]) ?有没有比输入更好的方法: 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] ?有没有办法像[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:正如@fillbranden 在评论中提到的,我应该向您展示如何删除最后 15 列:

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:在这种情况下,我使用以下方法删除了最后 5 列:

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:如果您不知道特定的列索引,请删除最后 X 列:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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