gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:57:39 25 4
gpt4 key购买 nike

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

我一直在尝试做:

df_new = df[[list]]

其中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)
List comprehension:
print ([x for x in df.columns if not "_" in x[-3:]])

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

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