在 pandas 中放置多列 [英] Drop multiple columns in pandas

查看:61
本文介绍了在 pandas 中放置多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

我收到以下错误:

TypeError: unhashable type: 'Index'

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

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

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

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

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?

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?

推荐答案

您无需使用[..]将其包装在列表中,只需提供列索引的子选择即可:

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.

这篇关于在 pandas 中放置多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆