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

Time:09-06

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

CodePudding user response:

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}
  • Related