Search code examples
python-3.xpandasdictionarysklearn-pandas

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


I have a dictionary object,

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

Based on that,

I desire to get output object as pandas series or array as,

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

Even if elements in output series are not in order that is fine, but should reflect same count as of value for its respective key element in input dictionary.


Solution

  • use np.repeat

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