根据列值创建附加行

问题描述 投票:0回答:2

我想根据列(index_end)中的数值扩展我的数据框。我的 df 看起来像这样:

项目 索引_结束
A 3
B 4
C 1

我希望将其扩展为 A 创建从 1 到 3 的行,为 B 创建从 1 到 4 的行,并创建分区索引。

项目 索引_结束 索引
A 3 1
A 3 2
A 3 3
B 4 1
B 4 2
B 4 3
B 4 4
C 1 1

在 Python/pandas 中寻找解决方案。谢谢!

python python-3.x pandas
2个回答
0
投票
import pandas as pd
df = pd.DataFrame({'item': ['A', 'B', 'C'], 'index_end': ['3', '4', '1']})
duplicate_rows = lambda value,iterate: sum([[str(v)]*int(i) for v,i in zip(value,iterate)],[])
custom_index = lambda old_index: sum([list(range(1,int(i)+1)) for i in old_index],[])

df2 = pd.DataFrame({'item': duplicate_rows(df.item,df.index_end), 'index_end': duplicate_rows(df.index_end,df.index_end), "index": custom_index(df.index_end)})

0
投票

组合

index.repeat
loc
groupby.cumcount

out = (df.loc[df.index.repeat(df['index_end'])]
         .assign(index=lambda x: x.groupby(level=0).cumcount().add(1))
      )
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.