Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas – how to reduce each row to a json column?

Let’s say we have the following df:

| col_a| col_b |
| -----| ----- |
| 1    | a     |
| 2    | b     |

And we want to reduce all rows to JSONs representing all columns row-wise:

|    json_representation        |
| ------------------------------| 
| {'col_a': 1, 'col_b': 'a'}    | 
| {'col_a': 2, 'col_b': 'b'}    |

Dicts are also good, since converting them to JSON strings is simple.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am aiming for a solution where there is no need to know every column name, so answers here (up to the moment I am asking), are not the solution I am looking for.

How
Thanks.

>Solution :

here is one way to do it

use apply and convert the row using to_json

df.apply(lambda x: x.to_json( ), axis=1)


0    {"col_a":1,"col_b":"a"}
1    {"col_a":2,"col_b":"b"}
dtype: object
df['json']=df.apply(lambda x: x.to_json( ), axis=1)
df
col_a   col_b   json
0   1   a   {"col_a":1,"col_b":"a"}
1   2   b   {"col_a":2,"col_b":"b"}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading