sourav khanna
sourav khanna

Reputation: 191

Convert Multiple pandas Column into json

My dataframe df is like:

col_1  col_2    col_3
A      Product  1
B      product  2
C      Offer    1
D      Product  1

What i want is to convert all this column to json with the condition that row of col_2 and col_1 should be key value pair. I have tried the following:

df['col_1_2'] = df.apply(lambda row: {row['col_2']:row['col_1']}, axis=1)
df['final_col']=df[['col_1_2','col_3']].to_dict('r')

My first row of df['final_col'] is:

{'col_1_2': {'product': A}, 'value': 1.0},

But what i want is :

{'product': A, 'value': 1.0}

Upvotes: 1

Views: 1228

Answers (1)

jezrael
jezrael

Reputation: 862511

Add missing key with value by col_3:

df['final_col'] = df.apply(lambda row: {row['col_2']:row['col_1'], 'value':row['col_3']},
                            axis=1)
print (df)
  col_1    col_2  col_3                     final_col
0     A  Product      1  {'Product': 'A', 'value': 1}
1     B  product      2  {'product': 'B', 'value': 2}
2     C    Offer      1    {'Offer': 'C', 'value': 1}
3     D  Product      1  {'Product': 'D', 'value': 1}

If need output in list:

L = [{b:a, 'value':c} for a,b,c in zip(df['col_1'], df['col_2'], df['col_3'])]
print (L)
[{'Product': 'A', 'value': 1}, 
 {'product': 'B', 'value': 2}, 
 {'Offer': 'C', 'value': 1}, 
 {'Product': 'D', 'value': 1}]

Or json:

import json
j = json.dumps([{b:a, 'value':c} for a,b,c in zip(df['col_1'], df['col_2'], df['col_3'])])
print (j)

[{"Product": "A", "value": 1}, 
 {"product": "B", "value": 2},
 {"Offer": "C", "value": 1}, 
 {"Product": "D", "value": 1}]

Upvotes: 3

Related Questions