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

Aar*_*nDT 15 python dataframe pandas

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

我一直在努力做到:

df_new = df[[list]]
Run Code Online (Sandbox Code Playgroud)

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

但是我得到错误:

TypeError: unhashable type: 'list'
Run Code Online (Sandbox Code Playgroud)

对此有何帮助?

jez*_*ael 18

你可以删除一个[]:

df_new = df[list]
Run Code Online (Sandbox Code Playgroud)

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

df_new = df[L]
Run Code Online (Sandbox Code Playgroud)

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

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

List comprehension:

print ([x for x in df.columns if not "_" in x[-3:]])
Run Code Online (Sandbox Code Playgroud)

  • 已经尝试过了。但是我收到一个错误,即列表中的名称“不在索引中”:S (2认同)