Pandas apply value from a JSON into a dataframe

Question:

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

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}]
Asked By: Rodrigo

||

Answers:

I think what you want is this:

df['value'] = df['region'].apply(my_dict.get)
>>> df
  region  value
0     xx      1
1     xx      1
2     cc      3

series.apply creates a new series with the results of the function you pass it, so for the first row it will run my_dict.get('xx') and so on.

Answered By: nielsrolf

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}]
Answered By: Ynjxsjmh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.