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

如何在Python中对DataFrame中Volume>1000的行拆分复制?

问题:处理DataFrame中Volume列大于1000的行

当前DataFrame状态

s_1w_1d_1w_2Volume
Source_1A1Dest_1A11800
Source_1A2Dest_1A2999
Source_1A3Dest_1A3850

期望处理结果

s_1w_1d_1w_2Volume
Source_1A1Dest_1A1900
Source_1A1Dest_1A1900
Source_1A2Dest_1A2999
Source_1A3Dest_1A3850

用户尝试的代码(存在语法错误):

for x in df:
   if x df["Volume"] >= 1000:
      print(df.loc[["s1","w_1", "d_1", "Volume"/2]] * 2

解决方案

通过pandas的布尔索引筛选目标行,修改数值后合并复制行即可实现需求,完整代码如下:

import pandas as pd

# 构造示例DataFrame
data = {
    's_1': ['Source_1', 'Source_1', 'Source_1'],
    'w_1': ['A1', 'A2', 'A3'],
    'd_1': ['Dest_1', 'Dest_1', 'Dest_1'],
    'w_2': ['A1', 'A2', 'A3'],
    'Volume': [1800, 999, 850]
}
df = pd.DataFrame(data)

# 筛选并处理Volume>1000的行:复制行+均分数值
high_volume = df[df['Volume'] > 1000].copy()
high_volume['Volume'] = high_volume['Volume'] / 2
processed_high = pd.concat([high_volume]*2, ignore_index=True)

# 保留无需处理的行
low_volume = df[df['Volume'] <= 1000].copy()

# 合并所有行并重置索引
result = pd.concat([processed_high, low_volume], ignore_index=True)
# 若需要保持原数据的行顺序,可添加排序
result = result.sort_index().reset_index(drop=True)

print(result)

代码说明

  1. 用布尔索引df['Volume'] > 1000筛选出需要处理的行,复制后将Volume值改为原值的一半
  2. 通过pd.concat([high_volume]*2)将修改后的行复制一次,得到两行均分后的数据
  3. 合并处理后的行与无需处理的行,最后重置索引保证索引连续

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 09:42:37