Python 在数据帧中重复行n次
考虑这样定义的数据帧:Python 在数据帧中重复行n次,python,pandas,Python,Pandas,考虑这样定义的数据帧: import pandas as pd test = pd.DataFrame({ 'id' : ['a', 'b', 'c', 'd'], 'times' : [2, 3, 1, 5] }) 是否可以在此基础上创建一个新的数据帧,其中每行重复次次,结果如下所示: >>> result id times 0 a 2 1 a 2 2 b 3 3 b 3 4 b
import pandas as pd
test = pd.DataFrame({
'id' : ['a', 'b', 'c', 'd'],
'times' : [2, 3, 1, 5]
})
是否可以在此基础上创建一个新的数据帧,其中每行重复次
次,结果如下所示:
>>> 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
使用和的组合
要模拟您的精确输出,请使用
reset\u 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
这很公平。我想我的问题是:这可能吗?目前正在摸索
test.index
和test.iloc[x]
尝试。谢谢。@MrT现场,这是个骗局
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