You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Pandas中根据列值重复对应行

Pandas按指定次数重复行数据

原始数据

A        B
0    27.9     1.0
1    20.6     1.0
2    10.3     1.0
3     0.0     1.0
4   349.7     1.0
5   339.4     2.0
6   329.1     1.0
7   318.9     1.0

需求说明

当B列数值大于1时,将该行重复对应次数(例如B=2.0时,额外插入一行相同内容),期望输出如下:

A       B
0    27.9     1.0
1    20.6     1.0
2    10.3     1.0
3     0.0     1.0
4   349.7     1.0
5   339.4     2.0
6   339.4     2.0  --> 此处为插入的重复行
7   329.1     1.0
8   318.9     1.0

解决方案

使用Pandas的repeat方法可快速实现需求,代码如下:

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'A': [27.9, 20.6, 10.3, 0.0, 349.7, 339.4, 329.1, 318.9],
    'B': [1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0]
})

# 按B列的整数值重复行,然后重置索引
df_repeated = df.loc[df.index.repeat(df['B'].astype(int))].reset_index(drop=True)

print(df_repeated)

代码说明

  • df['B'].astype(int):将B列的浮点数转为整数,确保重复次数为整数类型
  • df.index.repeat(...):生成重复后的索引序列,每个索引的重复次数对应B列的数值
  • loc[...]:根据重复后的索引提取对应行数据
  • reset_index(drop=True):重置结果的索引,避免原索引重复导致的混乱

运行后即可得到符合预期的结果。

内容的提问来源于stack exchange,提问作者gvsa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 18:05:26