重复数据帧中的行n次 [英] Repeat Rows in Data Frame n Times
本文介绍了重复数据帧中的行n次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑这样定义的数据框:
consider a data frame defined like so:
import Pandas as pd
test = pd.DataFrame({
'id' : ['a', 'b', 'c', 'd'],
'times' : [2, 3, 1, 5]
})
是否可以由此创建新的数据帧,其中每行重复times
次,使得结果如下所示:
Is it possible to create a new data frame from this in which each row is repeated times
times, such that the result looks like this:
>>> 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.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
这篇关于重复数据帧中的行n次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文