使用python计算唯一值并按频率缩放

时间:2017-09-16 21:08:49

标签: python data-processing

我自己有一个看起来像这样的数据集:

[
    {'A':'0'},
    {'B':'0'}, 
    {'C':'1'}
]

我希望将其变换为一个如下所示的数据集:

[
    {'0':'2'},
    {'1':'1'}
]

基本上任务是计算值,

以及每个唯一值

在数据结构中创建新条目

对于每个唯一条目(再次,基于值)

增加相应的条目,

基本上,任务是统计我们已经看到的唯一值,并根据表达值的次数进行放大。

在python中最有效,最有效的方法是什么?

我一直在尝试使用计数器,但迄今为止没有太大的成功,因为我的基础数据结构似乎不兼容,代码库看起来像这样:

dict_hash_gas = list()
for line in inpt:
    resource = json.loads(line)
    dict_hash_gas.append({resource['first']:resource['second']})

和这样的数据集:

{"first":"A","second":"0","third":"2"} 
{"first":"B","second":"0","third":"2"} 
{"first":"C","second":"1","third":"2"} 

2 个答案:

答案 0 :(得分:1)

result = dict()

for name, value in input.items():
    result.update({value: result.get(value, 0) + 1})

答案 1 :(得分:1)

您可以非常轻松地使用Counter

>>> data = [
...     {'A':'0'},
...     {'B':'0'},
...     {'C':'1'}
... ]
>>> import collections
>>> counts = collections.Counter(v for d in data for v in d.values())
>>> counts
Counter({'0': 2, '1': 1})

现在,要获得您想要的最终列表,只需:

>>> [{k:v} for k,v in counts.items()]
[{'0': 2}, {'1': 1}]

虽然,我不知道为什么你会想要这样的列表,但我只能假设一些基于REST的API期望这种格式的某些JSON ......

相关问题