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

在Pandas中为列批量填充指定行值并移除含-1的行

Pandas分组赋值与行过滤实现方案

原始数据

import pandas as pd

df = pd.DataFrame({
    "col_1": [1,1,1,-1,2,2,2,-1],
    "col_2": [2,2,2,-1,3,3,3,-1],
    "col_3": [0,0,0,10,0,0,0,20]
})

需求说明

将col_1和col_2均为-1的行对应的col_3值,赋值给该行上方同组的所有行的col_3;随后移除所有col_1或col_2包含-1的行,得到目标结果。

解决方案

这里提供两种简洁的实现方式:

方法一:分组标识+transform批量赋值

# 1. 创建分组标识:遇到col_1=-1时分组号递增,前面的行归为同一组
df['group'] = (df['col_1'] == -1).cumsum()

# 2. 每个分组取最后一行(即标记行)的col_3值,批量赋值给组内所有行
df['col_3'] = df.groupby('group')['col_3'].transform(lambda x: x.iloc[-1])

# 3. 过滤掉含-1的行,并删除临时分组列
result_df = df[~((df['col_1'] == -1) | (df['col_2'] == -1))].drop('group', axis=1)

方法二:填充法简化操作

# 1. 将标记行(col_1=-1)的col_3值保留,其余行设为NaN,再向前填充
df['col_3'] = df['col_3'].where(df['col_1'] == -1).ffill()

# 2. 过滤掉含-1的行,重置索引
result_df = df[~((df['col_1'] == -1) | (df['col_2'] == -1))].reset_index(drop=True)

最终结果

执行上述任意一种方法后,result_df的输出如下:

print(result_df)
#    col_1  col_2  col_3
# 0      1      2     10
# 1      1      2     10
# 2      1      2     10
# 3      2      3     20
# 4      2      3     20
# 5      2      3     20

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:25:44