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?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With