I am trying to create a numpy array using a pandas data frame. One column, named "repeat", in the data frame tells what value to repeat and the other column, named "times", tells how many times that value should be repeated.
Here is what I have tried:
import pandas as pd
import numpy as np
df = pd.DataFrame({'repeat': [1, 4, 3, 2], 'times': [2, 5, 4, 1]})
np.repeat(df['repeat'].values, df['times'])
However, this outputs the following:
array([1, 1, 4, 4, 4, 4, 4, 3, 3, 3, 3, 2])
This is what I want:
desired = np.array([[1, 1], [4, 4, 4, 4, 4], [3, 3, 3, 3], [2]])
array([list([1, 1]), list([4, 4, 4, 4, 4]), list([3, 3, 3, 3]), list([2])], dtype=object)
How can I repeat each value the corresponding number of times along the row efficiently? Is there a good numpy or pandas solution here?