python pandas通过列名列表从数据框中选择列

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

python pandas selecting columns from a dataframe via a list of column names

pythonpandasdataframe

提问by AaronDT

I have a dataframe with a lot of columns in it. Now I want to select only certain columns. I have saved all the names of the columns that I want to select into a Python list and now I want to filter my dataframe according to this list.

我有一个包含很多列的数据框。现在我只想选择某些列。我已将要选择的列的所有名称保存到 Python 列表中,现在我想根据此列表过滤我的数据框。

I've been trying to do:

我一直在尝试做:

df_new = df[[list]]

where list includes all the column names that I want to select.

其中 list 包括我要选择的所有列名称。

However I get the error:

但是我收到错误:

TypeError: unhashable type: 'list'

Any help on this one?

对此有任何帮助吗?

回答by jezrael

You can remove one []:

您可以删除一个[]

df_new = df[list]

Also better is use other name as list, e.g. L:

更好的是使用其他名称作为list,例如L

df_new = df[L]

It look like working, I try only simplify it:

它看起来像工作,我只是尝试简化它:

L = []
for x in df.columns: 
    if not "_" in x[-3:]: 
        L.append(x) 
print (L)


List comprehension:

List comprehension

print ([x for x in df.columns if not "_" in x[-3:]])