gpt4 book ai didi

python - 重复数据帧中的行 n 次

转载 作者:行者123 更新时间:2023-12-03 21:27:38 25 4
gpt4 key购买 nike

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





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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com