简体   繁体   中英

Select columns of pandas dataframe using a dictionary list value

I have column names in a dictionary and would like to select those columns from a dataframe.

In the example below, how do I select dictionary values 'b', 'c' and save it in to 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'

Remove nested list - [] :

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

根据ref ,只需要放一套括号即可。

df_out = df_in[ds['cols']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM