Home > Blockchain >  How to split df with a column of dictionary need to split all its values and keys into respective co
How to split df with a column of dictionary need to split all its values and keys into respective co

Time:02-11

{'labels': ['travel', 'dancing', 'cooking'],
'scores': [0.9938651323318481, 0.0032737774308770895, 0.002861034357920289],
'sequence': 'one day I will see the world'} 

i have this a df['prediction'] column i want to split this result into three different column as df['travel'],df['dancing'],df['cooking'] and their respective scores i am sorry if the question is not appropriaterequired result

required result

CodePudding user response:

you can edit your data as a list of dicts and each dict is row data and at the end, you can you set_index you select the index

import pandas as pd

list_t = [{
    "travel":0.9938651323318481,
    "dancing": 0.0032737774308770895,
    "cooking":0.002861034357920289,
    "sequence":'one day I will see the world'
}]

df = pd.DataFrame(list_t)
df.set_index("sequence")
#output
                                  travel    dancing     cooking
sequence            
one day I will see the world    0.993865    0.003274    0.002861

CodePudding user response:

What you can do is iterate over this dict and make another dictionary

say s is the source dictionary and x is the new dictionary that you want

x = {}
x['sequence']=s['sequence']
for i, l in enumerate(s['labels']):
  x[l] = s['scores'][i]

This should solve your problem.

  • Related