I have a dataframe with multiple columns some of which are lists. I would like to apply a function on each row that essentially expands each row into n rows (n changes for each row) after some data manipulations on the lists.
A simplified version of this can be seen here:
df = pd.DataFrame({'id':[0,1],'value':[[0,1,2],[3,4]]}).set_index('id')
def func(x):
v = np.array(x['value'])
return pd.Series([v,v**2],index=['value','value_2'])
My desired output is:
id value value_2
0 0 0 0
1 0 1 1
2 0 2 4
3 1 3 9
4 1 4 16
If I apply the function I get an output with the same number of rows as the original dataframe which I then need to reshape:
df.apply(func,axis=1)
value value_2
id
0 [0, 1, 2] [0, 1, 4]
1 [3, 4] [9, 16]
Is there a way to get the desired outcome without needing to reshape after applying the function?