Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas apply value from a JSON into a dataframe

I have the following JSON file:

{"xx":1,"bb":2,"cc":3}

I want to add a column to a data frame by using the value from the JSON

My data frame

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df = pd.DataFrame([{"region": "xx"}, {"region": "xx"}, {"region": "cc"}])

So, using the column region, I want to add a column with the value of the column region on the data frame, in this case, the data frame will be something like this

[{"region": "xx", "value": 1}, {"region": "xx", "value": 1}, {"region": "cc", "value": 3}]

>Solution :

IIUC, you can call map

df['value'] = df['region'].map(d)
print(df)

  region  value
0     xx      1
1     xx      1
2     cc      3

print(df.to_dict('records'))

[{'region': 'xx', 'value': 1}, {'region': 'xx', 'value': 1}, {'region': 'cc', 'value': 3}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading