0

I have a nested JSON like below. I want to convert it into a pandas dataframe. As part of that, I also need to parse the weight value only. I don't need the unit.

I also want the number values converted from string to numeric.

Any help would be appreciated. I'm relatively new to python. Thank you.

JSON Example:

{'id': '123', 'name': 'joe', 'weight': {'number': '100', 'unit': 'lbs'}, 
'gender': 'male'}

Sample output below:

id     name    weight    gender
123    joe     100       male

3 Answers 3

1

use " from pandas.io.json import json_normalize ".

id     name    weight.number  weight.unit  gender
123    joe     100              lbs        male
Sign up to request clarification or add additional context in comments.

Comments

0

if you want to discard the weight unit, just flatten the json:

temp = {'id': '123', 'name': 'joe', 'weight': {'number': '100', 'unit': 'lbs'}, 'gender': 'male'}
temp['weight'] = temp['weight']['number']

then turn it into a dataframe:

pd.DataFrame(temp)

Comments

0

Something like this should do the trick:

json_data = [{'id': '123', 'name': 'joe', 'weight': {'number': '100', 'unit': 'lbs'}, 'gender': 'male'}]
# convert the data to a DataFrame
df = pd.DataFrame.from_records(json_data)
# conver id to an int
df['id'] = df['id'].apply(int)
# get the 'number' field of weight and convert it to an int
df['weight'] = df['weight'].apply(lambda x: int(x['number']))
df

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.