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

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

问题描述:

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

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.

我一直在尝试:

df_new = df[[list]]

其中列表包含我要选择的所有列名称.

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

但是我得到了错误:

TypeError: unhashable type: 'list'

对此有什么帮助吗?

您可以删除一个[]:

df_new = df[list]

更好的方法是将其他名称用作list,例如L:

Also better is use other name as list, e.g. 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:

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