last day (15 days later) » 

2:30 PM
0
A: convert list of dictionaries to one row in dataframe using python pandas

perlimport pandas as pd import json with open('test.json') as f: content = f.read().replace('U',',')[::-1].replace(',', '', 1)[::-1] content = '[{}]'.format(content) l = json.loads(content) d = [{k1+k2:v2 for k1,v1 in x.items() for k2,v2 in v1.items()} for x in l] df = pd.DataFrame(d, colu...

 
getting error unicode object has no items
 
Are you using the same original file as in the previous question?
 
yes i am using same orginal file
 
I've included the one that I'm using (test.json), yours is the same, right?
 
Yes just i am replaced these d = [{k1+k2: v2 for k2,v2 in v1.items()} for x in l for k1,v1 in x.items()] old line to this d = [{k1+k2:v2 for k1,v1 in x.items() for k2,v2 in v1.items()} for x in l]
 
2:30 PM
OK, so better try using the whole block from my answer to make sure we don't miss any changes. For me it works, so if the file is the same, it should be fine
 
same error after copying
 
What is the print(l) output?
 
[{"D":{ "1":"66", "2":"77", "3":"3" },"A":{ "11":"166", "12":"177", "13":"13" }}, {"X":{ "2":"5", "3":"4"}}, {"E":{ "4":"55", "6":"33"}}] this is the output of printing l
 
Looks good, so now print([{k1+k2:v2 for k1,v1 in x.items() for k2,v2 in v1.items()} for x in l])
Did you manage to get the output?
 
getting in one row but the headers are not in order
they are coming different manner
not in sequential order
 
3:16 PM
OK, let's try to go line by line, it's very odd because it works fine for me
So let's just run the following:
import pandas as pd
import json

with open('test.json') as f:
content = f.read().replace('U',',')[::-1].replace(',', '', 1)[::-1]
content = '[{}]'.format(content)

l = json.loads(content)
d = [{k1+k2:v2 for k1,v1 in x.items() for k2,v2 in v1.items()} for x in l]
---
And then check the output of `d`
I'm getting:
[{'D1': '66', 'D2': '77', 'D3': '3', 'A11': '166', 'A12': '177', 'A13': '13'},
{'X2': '5', 'X3': '4'},
{'E4': '55', 'E6': '33'}]
Do you have the same?
If yes, then after this once again run [k for x in d for k in x.keys()] and share the output
I'm getting:
['D1', 'D2', 'D3', 'A11', 'A12', 'A13', 'X2', 'X3', 'E4', 'E6']
 

last day (15 days later) »