pandas 从熊猫数据框中选择除列列表之外的所有内容

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

Select everything but a list of columns from pandas dataframe

pythonpandas

提问by Mohamed Ali JAMAOUI

Is it possible to select the negation of a given list from pandas dataframe?. For instance, say I have the following dataframe

是否可以从 Pandas 数据框中选择给定列表的否定?例如,假设我有以下数据框

T1_V2  T1_V3 T1_V4 T1_V5 T1_V6 T1_V7 T1_V8
1     15      3      2     N     B     N         
4     16     14      5     H     B     N            
1     10     10      5     N     K     N  

and I want to get out all columns but column T1_V6. I would normally do that this way:

我想取出除 T1_V6 列之外的所有列。我通常会这样做:

df = df[["T1_V2","T1_V3","T1_V4","T1_V5","T1_V7","T1_V8"]]

My question is on whether there is a way to this the other way around, something like this

我的问题是是否有办法做到这一点,就像这样

df = df[!["T1_V6"]]

回答by Pekka

Do:

做:

df[df.columns.difference(["T1_V6"])]

Notes from comments:

评论中的注释:

  • This will sort the columns. If you don't want to sort call differencewith sort=False

  • The differencewon't raise error if the dropped column name doesn't exist. If you want to raise error in case the column doesn't exist then use drop as suggested in other answers: df.drop(["T1_V6"])`

  • 这将对列进行排序。如果你不想排序呼叫differencesort=False

  • difference如果删除的列名称不存在,则不会引发错误。如果您想在列不存在的情况下引发错误,请按照其他答案中的建议使用 drop:df.drop(["T1_V6"])`

回答by joris

For completeness, you can also easily use dropfor this:

为了完整起见,您还可以轻松地使用drop

df.drop(["T1_V6"], axis=1)

回答by yesemsanthoshkumar

I would suggest using DataFrame.drop()

我建议使用 DataFrame.drop()

columns_to _exclude = ['T1_V6']
old_dataframe = #Has all columns
new_dataframe = old_data_frame.drop(columns_to_exclude, axis = 1)

You could use inplace to make changes to the original dataframe itself

您可以使用就地更改原始数据帧本身

old_dataframe.drop(columns_to_exclude, axis = 1, inplace = True)
#old_dataframe is changed

回答by Or Duan

You need to use List Comprehensions:

您需要使用列表理解

[col for col in df.columns if col != 'T1_V6']