Python 检索除一列以外的所有数据帧

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

Retrieve DataFrame of all but one specified column

pythonpandasdataframe

提问by user1802143

Is there a way to select all but one column in a pandas DataFrame object? I've seen ways to delete a column, but I don't want to do that.

有没有办法选择熊猫 DataFrame 对象中除一列之外的所有列?我已经看到了删除列的方法,但我不想这样做。

采纳答案by HYRY

use dropmethod:

使用drop方法:

df.drop(column_name, axis=1)

回答by EdChum

you can just select the columns you want without deleting or dropping:

您只需选择所需的列而无需删除或删除:

collist = ['col1', 'col2', 'col3']
df1 = df[collist]

Just pass a list of the columns you desire

只需传递您想要的列列表

You can also retrieve the list of columns and then select from that list

您还可以检索列列表,然后从该列表中进行选择

collist = df.columns.tolist()
# you can now select from this list any arbritrary range
df1 = df[collist[0:1]]
# or remove a column
collist.remove('col2')
# now select
df1 = df[collist]
# df1 will now only have 'col1' and 'col3'

回答by efajardo

You could use numpy to build a mask:

您可以使用 numpy 来构建掩码:

import numpy as np
columns = df.columns
mask = np.ones(columns.shape, dtype=bool)
i = 4 #The specified column that you don't want to show
mask[i] = 0
df[columns[mask]]

回答by lev

df.loc[:, df.columns != col]

where colis the name of the column to leave out.

哪里col是要省略的列的名称。

回答by pgalilea

df[ df.columns[df.columns!='not_this_column'] ]

回答by Ivan Calderon

Just as an option, you can select all columns but one (or many) using a list comprehension and df.loc method:

作为一种选择,您可以使用列表理解和 df.loc 方法选择除一个(或多个)之外的所有列:

select = [x for x in df.columns if x != "column_you_don't_want"]
df.loc[:, select]

In case you want to leave out more than one column you can try this:

如果您想省略多列,您可以尝试以下操作:

columns_dont_want = ["col1", "col2"]
select = [x for x in df.columns if x not in columns_dont_want]
df.loc[:, select]