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

标签 python pandas

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





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/

相关文章:

python - 使用 Bottledwater-pg,Python 消费者如何读取数据?

python - 将 Pandas 系列单元格转换为字符串和日期时间对象

python - 使用 numpy 将数据分组为时间相关集

python - 根据条件语句返回嵌套函数中的各种变量

python - 创建超链接以通过 python 访问多个 Excel 工作表

python - 编写一个简单的 "Rock Paper Scissors"游戏机器人

python - 在 OSX 10.11 (El Capitan) (系统完整性保护) 中安装 Scrapy 时出现 "OSError: [Errno 1] Operation not permitted"

python - 函数内的Python错误调用函数

python - 如何使用seaborn relplot绘制多个数据帧的数据

Python:将时间舍入到最接近的秒和分钟