简体   繁体   English

将Series转换为熊猫词典列表

[英]Convert Series to list of dictionaries in pandas

I have a Series of the form ["A","B","B","C","A"] . 我有一个["A","B","B","C","A"]

I am counting the frequency of each unique element using pandas.Series.value_counts which also returns a Series: ["A":2,"B":2,"C":1] 我正在使用pandas.Series.value_counts计数每个唯一元素的频率,这还会返回一个Series: ["A":2,"B":2,"C":1]

I want to convert this Series into a list of dictionaries [{A:2},{B:2},{C:1}] . 我想将此系列转换为字典[{A:2},{B:2},{C:1}] However, neither to_dict nor to_records is giving me the desired result. 但是, to_dictto_records都没有给我想要的结果。 What's an alternative? 有什么选择?

I don't think any type-conversion method in Pandas for Series or DataFrames will produce exactly the output you're after. 我认为Pandas for Series或DataFrames中的任何类型转换方法都不会产生您想要的输出。

You might simply have to adjust the result of to_dict() with a list comprehension: 您可能只需要使用列表理解来调整to_dict()的结果:

>>> counts = pd.value_counts(series).to_dict()
>>> [{u: v} for (u, v) in counts.iteritems()]
[{'A': 2}, {'C': 1}, {'B': 2}]

you need counter 你需要counter

>>> from collections import Counter
>>> [ {x:y} for x,y in Counter(["A","B","B","C","A"]).items() ]
[{'A': 2}, {'C': 1}, {'B': 2}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM