Have got input dataframe like below:
df
Store Item Space
11 Grape 0.125
11 Beans 0.0
12 Mango 0.25
13 Beetroot 0.375
13 Carrot 0.5
Need to expand given df
row w.r.t. 'Space
' column.
Values in 'Space
' column will always be in 1/8th term. E.g.: 0.125(1/8) equivalent to 1 Part among 8, 0.25 - 2 Part, 0.375 - 3 Part, 0.5 - 4 Part, 0.625 - 5 Part, 0.75 - 6 Part, 0.875 - 7 Part, 1.0 - 8 Part. So, rows in df
should be expand w.r.t. how many parts of 1/8 present for each 'Item
' in 'Space
' column. And if any 'Item
' holds 0
space that Item need to be dropped.
Expected Output:
Store Item Space
11 Grape 0.125
12 Mango 0.125
12 Mango 0.125
13 Beetroot 0.125
13 Beetroot 0.125
13 Beetroot 0.125
13 Carrot 0.125
13 Carrot 0.125
13 Carrot 0.125
13 Carrot 0.125
Any help appreciated. Thank You!
CodePudding user response:
You can use
eigth = 0.125
result = df['Item'].repeat(df['Space']/eigth).to_frame().assign(Space=eigth)
How to improve this line of code to include in any additional columns present in df and to include those as well? Question edited accordingly.
result = df.apply(pd.Series.repeat, repeats=df['Space']/eigth).assign(Space=eigth)