3

My data is as follows:

d = [{'id':1, 'a':10, 'b':10}, {"id":2,"a":20, "b":20}]  

The result I want is as follows:

res = [{'id': 1, 'prop': 'a', 'value': 10},
 {'id': 1, 'prop': 'b', 'value': 10},
 {'id': 2, 'prop': 'a', 'value': 20},
 {'id': 2, 'prop': 'b', 'value': 20}]

Since each row has two properties I want to split each row having the same id but different property and the corresponding value to that property

I am using iterrows as

import pandas as pd
df = pd.DataFrame(d)
l = []
for _, r in df.iterrows(): 
    for p in ['a','b']: 
        l.append({'id':r.id, 'prop':p, 'value':r[p]})

I get what I want but what I wish to know is whether there is any way to use purely pandas command to achieve my goal

0

2 Answers 2

2

use pd.melt then use to_json with orient=records

convert string json to proper list format using json.loads

import json
d = [{'id':1, 'a':10, 'b':10}, {"id":2,"a":20, "b":20}]

df = pd.DataFrame(d)

res = pd.melt(df,id_vars=['id'],value_vars=['a','b'],var_name='prop')

json_res= json.loads(res.to_json(orient='records'))
[{"id":1,"prop":"a","value":10},{"id":2,"prop":"a","value":20},{"id":1,"prop":"b","value":10},{"id":2,"prop":"b","value":20}]
Sign up to request clarification or add additional context in comments.

Comments

2

Create DataFrame by constructor, then use DataFrame.melt and last DataFrame.to_dict with parameter r for records:

df = pd.DataFrame(d)

#melt all columns without id
df1 = df.melt('id', var_name='prop')
#if necessary specify columns
#df1 = df.melt('id', var_name='prop', value_vars=['a','b'])

res = df1.to_dict('r')
print (res)
[{'id': 1, 'prop': 'a', 'value': 10}, {'id': 2, 'prop': 'a', 'value': 20}, 
 {'id': 1, 'prop': 'b', 'value': 10}, {'id': 2, 'prop': 'b', 'value': 20}]

print (type(res))
<class 'list'>

Comments

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.