10

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?

1 Answer 1

14

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}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @jezrael, this method is failing when I want to convert only 1 column. I get this error: AttributeError: 'float' object has no attribute 'to_json' Can you please consider this case and let me know how to do it?
@ShantanuJain It'll work if you put the one column into a list, like when you're passing a list of more than 1 columns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.