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.
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"}