Home > Software design >  Pandas store a json into a pandas column
Pandas store a json into a pandas column

Time:04-30

I have a pandas dataframe like this

data = {"Name": ["Tom", "nick", "kish", "jack"], "Age": [20, 21, 19, 18]}                                   
                                                                                                             
df1 = pd.DataFrame(data)                                                                                     
                                                                                                             
df1.to_json(orient="records", lines=True)                                                                    
'{"Name":"Tom","Age":20}\n{"Name":"nick","Age":21}\n{"Name":"kish","Age":19}\n{"Name":"jack","Age":18}\n' 

I would like to store the json into a column and have an output like this.

    Name  Age       json
0    Tom   20       {"Name":"Tom","Age":20}
1   nick   21       {"Name":"nick","Age":21}
2   kish   19       {"Name":"kish","Age":19}
3   jack   18       {"Name":"jack","Age":18}

CodePudding user response:

Use split by new line with remove trailing values:

df1['new'] = df1.to_json(orient="records", lines=True).strip().split('\n')

Or if need dictionary:

df1['new'] = df1.to_dict(orient="records")   
print (df1)
   Name  Age                          new
0   Tom   20   {'Name': 'Tom', 'Age': 20}
1  nick   21  {'Name': 'nick', 'Age': 21}
2  kish   19  {'Name': 'kish', 'Age': 19}
3  jack   18  {'Name': 'jack', 'Age': 18}
  • Related