在数据帧中重复行n次[重复]

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

这个问题在这里已有答案:

考虑如下定义的数据框:

import Pandas as pd
test = pd.DataFrame({
    'id' : ['a', 'b', 'c', 'd'],
    'times' : [2, 3, 1, 5]
    })

是否有可能从中创建一个新的数据框,其中每行重复times次,这样结果如下所示:

>>> result
   id  times
0   a      2
1   a      2
2   b      3
3   b      3
4   b      3
5   c      1
6   d      5
7   d      5
8   d      5
9   d      5
10  d      5
python pandas
1个回答
6
投票

使用pd.DataFrame.locpd.Index.repeat的组合

test.loc[test.index.repeat(test.times)]

  id  times
0  a      2
0  a      2
1  b      3
1  b      3
1  b      3
2  c      1
3  d      5
3  d      5
3  d      5
3  d      5
3  d      5

要模仿您的确切输出,请使用reset_index

test.loc[test.index.repeat(test.times)].reset_index(drop=True)

   id  times
0   a      2
1   a      2
2   b      3
3   b      3
4   b      3
5   c      1
6   d      5
7   d      5
8   d      5
9   d      5
10  d      5
© www.soinside.com 2019 - 2024. All rights reserved.