pandas 重复数据帧中的行 n 次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49074021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:15:21 来源:igfitidea点击:
Repeat Rows in Data Frame n Times
提问by 93i7hdjb
consider a data frame defined like so:
考虑一个像这样定义的数据框:
import Pandas as pd
test = pd.DataFrame({
'id' : ['a', 'b', 'c', 'd'],
'times' : [2, 3, 1, 5]
})
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:
是否可以从中创建一个新的数据框,其中每一行都重复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
回答by piRSquared
Use a combination of pd.DataFrame.loc
and pd.Index.repeat
使用的组合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
To mimic your exact output, use reset_index
要模仿您的确切输出,请使用 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