使用字典列表值选择pandas dataframe的列

2024-04-25 05:38:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我在字典中有列名,我想从数据帧中选择这些列。在

在下面的示例中,如何选择字典值“b”、“c”并将其保存到df1中?在

import pandas as pd
ds = {'cols': ['b', 'c']}
d = {'a': [2, 3], 'b': [3, 4], 'c': [4, 5]}
df_in = pd.DataFrame(data=d)
print(ds)
print(df_in)
df_out = df_in[[ds['cols']]]
print(df_out)

TypeError: unhashable type: 'list'


Tags: 数据inimport示例dataframepandasdf字典
2条回答

根据ref,只需要去掉一组括号。在

df_out = df_in[ds['cols']]

删除嵌套列表-[]

df_out = df_in[ds['cols']]
print(df_out)
   b  c
0  3  4
1  4  5

相关问题 更多 >