gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:17:11 26 4
gpt4 key购买 nike

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

我一直在努力:

df_new = df[[list]]

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

但是我得到了错误:

TypeError: unhashable type: 'list'

这方面有什么帮助吗?

最佳答案

你可以删除一个[]:

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)

列表理解:

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

关于python pandas 通过列名列表从数据框中选择列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38969267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com