Python:以 1/8 的形式扩展具有特定列值的数据框行

Python: Expand dataframe rows with specific column value in terms of 1/8th

有如下输入数据框:

df

Store   Item        Space
11      Grape       0.125
11      Beans       0.0
12      Mango       0.25
13      Beetroot    0.375
13      Carrot      0.5

需要扩展给定 df 行 w.r.t。 'Space' 列。 “Space”列中的值将始终为第 1/8 项。 例如:0.125(1/8)相当于8份中的1份,0.25-2份,0.375-3份,0.5-4份,0.625-5份,0.75-6份, 0.875 - 7 份,1.0 - 8 份。因此,df 中的行应该展开 w.r.t。 “Space”列中每个“Item”存在多少 1/8 的部分。如果任何 'Item' 持有 0 space 则需要删除该项目。

预期输出:

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

感谢任何帮助。谢谢!

您可以使用

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)