Home > Back-end >  change dictionary to dictionary series
change dictionary to dictionary series

Time:07-21

I have a column

index data
1    {'data': '123'}
2    {'data': '123'}
3    {"data": "123"}

I need to change data column to

index data
1    {'data': '123'}
2    {'data': '123'}
3    {'data': '123'}

The difference is line with index 3 Thank you for your help

CodePudding user response:

Use list comprehension with if-else for convert strings to dictionaries:

import ast

df = pd.DataFrame({'data':[{'data': '123'}, {'data': '123'},  '{"data":"123"}']})
    

df['data'] = [ast.literal_eval(x) if isinstance(x, str) else x for x in df.data]
print (df)
              data
0  {'data': '123'}
1  {'data': '123'}
2  {'data': '123'}

import json

df['data'] = [json.loads(x) if isinstance(x, str) else x for x in df.data]
print (df)
              data
0  {'data': '123'}
1  {'data': '123'}
2  {'data': '123'}
  • Related