Python 在熊猫中删除多列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26347412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:22:30  来源:igfitidea点击:

Drop multiple columns in pandas

pythonpandas

提问by lukewitmer

I am trying to drop multiple columns (column 2 and 70 in my data set, indexed as 1 and 69 respectively) by index number in a pandas data frame with the following code:

我正在尝试使用以下代码在熊猫数据框中按索引号删除多列(数据集中的第 2 列和第 70 列,分别索引为 1 和 69):

df.drop([df.columns[[1, 69]]], axis=1, inplace=True)

I get the following error:

我收到以下错误:

TypeError: unhashable type: 'Index'

And in my code the [1, 69] is highlighted and says:

在我的代码中, [1, 69] 突出显示并说:

Expected type 'Integral', got 'list[int]' instead

The following code does what I want it to do successfully, but on two lines of repetitive code (first dropping col index 69, then 1, and order does matter because dropping earlier columns changes the index of later columns). I thought I could specify more than one column index simply as a list, but perhaps I have something wrong above?

下面的代码完成了我希望它成功完成的工作,但是在两行重复代码上(首先删除列索引 69,然后删除 1,并且顺序很重要,因为删除较早的列会更改较晚列的索引)。我以为我可以简单地将多个列索引指定为一个列表,但也许我上面有什么问题?

df.drop([df.columns[69]], axis=1, inplace=True)
df.drop([df.columns[1]], axis=1, inplace=True)

Is there a way that I can do this on one line similar to the first code snippet above?

有没有办法可以在类似于上面第一个代码片段的一行上执行此操作?

采纳答案by joris

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

您不需要将它包装在一个列表中[..],只需提供列索引的子选择:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

因为索引对象已经被视为类列表。

回答by Okroshiashvili

Try this

尝试这个

df.drop(df.iloc[:, 1:69], inplace=True, axis=1)

df.drop(df.iloc[:, 1:69], inplace=True, axis=1)

This works for me

这对我有用