Pandas 删除索引类型列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32327566/
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-09-13 23:50:31  来源:igfitidea点击:

Pandas drop index type columns

pythonpandas

提问by Gilaztdinov Rustam

I want to drop multiple columns from pandas.DataFrameand can't do it.

我想删除多个列pandas.DataFrame,但不能这样做。

In [10]: object_columns = X.select_dtypes(['object']).columns

In [10]: type(object_columns)

Out[10]: pandas.core.index.Index

In [11]: X = X.drop(object_columns, inplace=True, axis=1)

ValueError: labels ['VAR_0001' 'VAR_0005' 'VAR_0044' 'VAR_0073'] not contained in axis

I change code and it doesn't help:

我更改了代码,但没有帮助:

In [12]: X = X.drop(X[object_columns], inplace=True, axis=1)

KeyError: "['VAR_0001' 'VAR_0005' 'VAR_0044' 'VAR_0073'] not in index"

Can anybody explain what I doing wrong?

谁能解释我做错了什么?

回答by EdChum

You need to do X.drop(object_columns, inplace=True, axis=1)

你需要做 X.drop(object_columns, inplace=True, axis=1)

by passing inplace=Trueit operates on the object and returns nothing so you shouldn't be assigning it back, see the docs.

通过传递inplace=True它对对象进行操作并且不返回任何内容,因此您不应该将其分配回来,请参阅文档

So you don't need:

所以你不需要:

X = X.drop(object_columns, inplace=True, axis=1)

just

只是

X.drop(object_columns, inplace=True, axis=1)

if you passed inplace=Falsewhich is the default:

如果你通过inplace=False这是默认值:

X = X.drop(object_columns, inplace=False, axis=1)

then it would have worked

那么它会起作用

回答by Okroshiashvili

You can try the following

您可以尝试以下操作

If you want to remove "Index" column use

如果要删除“索引”列,请使用

X.reset_index()

X.reset_index()

here removed index column will be added as a new column.

这里删除的索引列将作为新列添加。

If you want to just delete index columns use

如果您只想删除索引列,请使用

X.reset_index(drop=True)

X.reset_index(drop=True)

If you just want to drop some columns but not only one use the following

如果您只想删除一些列而不是仅删除一个列,请使用以下内容

X.drop(['list of column names, seperated by comma'], inplace=True, axis=1)

X.drop(['list of column names, seperated by comma'], inplace=True, axis=1)