3

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

Lucas
  • 49
  • 4

1 Answers1

5

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}
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 1
    @tlentali - thank you, I prefer `ast.literal_eval` - https://stackoverflow.com/a/1832957/2901002 – jezrael Sep 05 '22 at 12:57