3

I tried to transform JSON data into a dataframe with the following code:

import json
l = []
for line in open('data.json', 'r'):
    l.append(json.loads(line))

df = pd.DataFrame(l)
df.parameters.head(1))

l looks like this :

{"user_id":0,"client":"35.181","parameters":[{"key":"from","value":"9.204444;45.486389"},{"key":"to","value":"200"},{"key":"with","value":"Train"},

And df looks like this :

user_id  client    ...   parameters
0        30112     ...   [{'key': 'from', 'value': '9.29''}, {'key': 'to', 'value': '200'}, {'key': 'with', 'value': 'Train'}]
1        30113     ...   [{'key': 'from', 'value': '9.20''}, {'key': 'to', 'value': '30'}, {'key': 'with', 'value': 'Car'}]

And I would like to be able to break the parameters column into 3 distinct columns which would be: from, to, with.

user_id  client  error  ...   from   to   with
0        30112    yes   ...   9.29   200  Train
1        30113    NaN   ...   9.20   30   Car

Could you help me, please?

2
  • This question lacks clarity. Show l, show the df you get, show the df you want. If l is large reduce its size as much as possible. Commented Feb 28, 2022 at 11:03
  • 1
    Thanks for your comment, I made the changes to make it clearer Commented Feb 28, 2022 at 11:30

2 Answers 2

3

Use list comprehension with DataFrame constructor:

m = df['parameters'].notna()
df1 = pd.DataFrame([{y['key']: y['value'] for y in x} for x in df.pop('parameters').dropna()], 
                    index=df.index[m])

df = df.join(df1)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, but it gives the error "'float' object is not iterable", while the type of the parameters column is not float but object
@Alex - seems some missing values, can you add .dropna() ?
2
    import json
    import pandas as pd
    with open('refactory.json') as f:
    data = json.load(f)
    print(data)
    df = pd.read_json('refactory.json')
    df

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.