通过将字典作为输入形成 pandas 系列元素,其中值表示该字典中键的频率

Form pandas series of elements by taking dictionary as a input wherein value indicates frequency of key in that dictionary

我有一个字典对象,

z = {"a":3, "b":2, "c":5}

基于此,

我希望将输出对象作为 pandas 系列或数组作为,

array(["a", "a", "a", "b", "b", "c", "c", "c", "c", "c"])

即使输出序列中的元素未按顺序排列也没关系,但应该反映与输入字典中相应关键元素的值相同的计数。

这是一种解决方案:

z = {"a":3, "b":2, "c":5}
list=[]
for i in z: list += [i]*z[i]

print(list)

['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'c', 'c']

使用np.repeat

import numpy as np

np.repeat(*zip(*z.items()))
#array(['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'c', 'c'], dtype='<U1')