【问题标题】:python pandas selecting columns from a dataframe via a list of column namespython pandas通过列名列表从数据框中选择列
【发布时间】:2016-12-22 11:54:30
【问题描述】:

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

我一直在努力:

df_new = df[[list]]

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

但是我得到了错误:

TypeError: unhashable type: 'list'

对这个有帮助吗?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    你可以删除一个[]

    df_new = df[list]
    

    最好使用其他名称作为list,例如L:

    df_new = df[L]
    

    它看起来很有效,我尝试只简化它:

    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:]])
    

    【讨论】:

    • 已经试过了。但是我收到一个错误,列表中的名称“不在索引中”:S
    • 那么不匹配。您如何创建 listprint df.columns 是什么?
    • 我已经用下面的代码先接收所有的header名字,然后保存到header_names。然后我根据特定标准过滤标题名称。 header_names = list(df.columns.values) for x in header_names: y = x[-3:] if "_" in y: pass else: L.append(x)
    • 好的,请稍等。
    • 好的,我找到了问题所在。它与语法错误无关。您的建议很好,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    相关资源
    最近更新 更多