这个问题在这里已经有了答案:
Replicating rows in a pandas data frame by a column value
(4 个回答)
3年前关闭。
考虑一个像这样定义的数据框:
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
最佳答案
使用 pd.DataFrame.loc
的组合和 pd.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
关于python - 重复数据帧中的行 n 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49074021/