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

如何替换DataFrame各列中最后一次出现的指定值?

解决方案

方法一:逐列遍历处理

逻辑直观,容易理解:

import pandas as pd

data1 = [[2,5,6,3,1],
         [2,2,5,4,2],
         [0,1,2,2,3],
         [6,2,1,0,9],
         [2,3,4,1,2]]
df = pd.DataFrame(data1)

# 遍历每一列
for col in df.columns:
    # 获取当前列中所有值为2的行索引
    target_indices = df[df[col] == 2].index
    # 如果该列存在值为2的行,替换最后一个
    if len(target_indices) > 0:
        df.loc[target_indices[-1], col] = 7

# 输出结果
print(df.values.tolist())

运行后会得到预期结果:

[[2,5,6,3,1],
 [2,2,5,4,2],
 [0,1,7,7,3],
 [6,7,1,0,9],
 [7,3,4,1,7]]

方法二:向量化处理(无循环,适合大数据集)

利用pandas向量化操作,效率更高:

import pandas as pd

data1 = [[2,5,6,3,1],
         [2,2,5,4,2],
         [0,1,2,2,3],
         [6,2,1,0,9],
         [2,3,4,1,2]]
df = pd.DataFrame(data1)

# 生成布尔矩阵,标记所有值为2的位置
is_two = df.eq(2)
# 对每列的2进行累加计数
cumulative_two = is_two.cumsum(axis=0)
# 获取每列中2的总数
max_two_count = cumulative_two.max(axis=0)
# 标记每列最后一个2的位置:是2,且累加计数等于总数
last_two_mask = is_two & (cumulative_two == max_two_count)

# 替换标记位置的值为7
df = df.mask(last_two_mask, 7)

print(df.values.tolist())

你之前代码的问题说明

  • df.last_valid_index()返回的是整个DataFrame最后一个非NA值的行索引(此处为4),和“最后一个2的位置”无关,条件逻辑错误。
  • 布尔数组和单一索引值做比较时会触发广播,生成的条件矩阵无法定位到正确位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 21:32:46