Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas dataFrame create single json column of multiple columns value

In python pandas dataFrame i wanted create single json column of multiple columns value.

Assuming following dataFrame:
Example:

| -   | col1 | col2 | col3 | col4|
| 1   | abc  | def  | ghi  |  8  |
| 2   | xab  | xcd  | xef  |  9  |

This is the result i want.

|     |col1 | json_col|br
|1    | abc |   {"col2":"def","col3":"ghi","col4":8}|
|2    | xab |   {"col2":"xcd","col3":"xef","col4":9}|

How can i create the single column(json type) of selected columns?

like image 293
NHD Avatar asked Jun 07 '17 13:06

NHD


1 Answers

You can use apply with to_json, last remove columns by drop:

cols = ['col2','col3','col4']
df['json_col'] = df[cols].apply(lambda x: x.to_json(), axis=1)
df = df.drop(cols, axis=1)
print (df)
   - col1                              json_col
0  1  abc  {"col2":"def","col3":"ghi","col4":8}
1  2  xab  {"col2":"xcd","col3":"xef","col4":9}
like image 82
jezrael Avatar answered Oct 18 '22 09:10

jezrael