简体   繁体   中英

Convert list of dictionaries with one element to single dictionary in pandas DataFrame

I found many different solutions for doing so for single case but not for pandas Series. I would like to change this

    col1
0   [{'a':2, 'b':3, 'c':9}]
1   [{'a':1, 'b':0, 'c':8}]
2   [{'a':4, 'b': 5, 'c':12}]
3   [{'a':3, 'b':6, 'c':11}]

into

    col1
0   {'a':2, 'b':3, 'c':9}
1   {'a':1, 'b':0, 'c':8}
2   {'a':4, 'b': 5, 'c':12}
3   {'a':3, 'b':6, 'c':11}

Thanks

If there is one element list select by indexing for remove [] :

df['col'] = df['col'].str[0]

If values are strings repr of dicts:

import ast

df['col'] = df['col'].apply(ast.literal_eval).str[0]
print (df)
                         col
0   {'a': 2, 'b': 3, 'c': 9}
1   {'a': 1, 'b': 0, 'c': 8}
2  {'a': 4, 'b': 5, 'c': 12}
3  {'a': 3, 'b': 6, 'c': 11}

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