现在我有了这个系列:
us 2
br 1
be 3
dtype: int64
所以我怎么能得到一个列表。如下:
[ { "country": "us", "value": 2},
{ "country": "br", "value": 1},
{ "country": "be", "value": 3}
]
谢谢
最佳答案
先创建DataFrame
,然后使用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
构造函数:
print (pd.DataFrame({'country':s.index, 'value':s.values}).to_dict('records'))
[{'value': 2, 'country': 'us'}, {'value': 1, 'country': 'br'}, {'value': 3, 'country': 'be'}]
另一种列表理解
的解决方案:
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'}]
piRSquared 的类似解决方案删除了 Series.items
的答案:
d = [dict(country=k, value=v) for k, v in s.items()]
关于python - pandas -- 如何让 Series 听写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45452935/