Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas -- How to get Series to dict

Tags:

python

pandas

now I have this Series:

us    2
br    1
be    3
dtype: int64

so How get I can a list. as follows:

[ { "country": "us", "value": 2},
  { "country": "br", "value": 1},
  { "country": "be", "value": 3}
]

thanks

like image 583
xingyuan jiang Avatar asked Mar 08 '23 11:03

xingyuan jiang


1 Answers

Create DataFrame first and then use DataFrame.to_dict:

print (s.rename_axis('country').reset_index(name='value').to_dict('records'))
[{'value': 2, 'country': 'us'}, {'value': 1, 'country': 'br'}, {'value': 3, 'country': 'be'}]

DataFrame by constructor:

print (pd.DataFrame({'country':s.index, 'value':s.values}).to_dict('records'))
[{'value': 2, 'country': 'us'}, {'value': 1, 'country': 'br'}, {'value': 3, 'country': 'be'}]

Another solution with list comprehension:

d = [dict(country=x[0], value=x[1]) for x in s.items()]
print (d)
[{'value': 2, 'country': 'us'}, {'value': 1, 'country': 'br'}, {'value': 3, 'country': 'be'}]

Similar solution from piRSquared deleted answer with Series.items:

d = [dict(country=k, value=v) for k, v in s.items()]
like image 178
jezrael Avatar answered Mar 10 '23 23:03

jezrael