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

如何用前一个非零值加1填充Pandas DataFrame的末尾零值?

Pandas DataFrame末尾零值填充方案

针对你提出的需求——保留开头零值,用最后一个非零值加1填充末尾连续零值,可以通过以下步骤实现:

代码实现

import pandas as pd

# 构造示例DataFrame(替换为你的实际数据)
df = pd.DataFrame({'target_col': [0, 1, 1, 2, 2, 3, 4, 5, 5, 0, 0, 0]})

# 获取最后一个非零元素的值和其索引
last_non_zero_val = df['target_col'].loc[df['target_col'] != 0].iloc[-1]
last_non_zero_idx = df['target_col'].loc[df['target_col'] != 0].index[-1]

# 对末尾的零值进行填充
df.loc[last_non_zero_idx + 1:, 'target_col'] = last_non_zero_val + 1

# 输出结果
print(df['target_col'])

逻辑说明

  1. 筛选出列中所有非零元素,提取最后一个非零值及其所在的索引位置;
  2. 从该索引的下一位开始,将后续所有零值替换为「最后非零值 + 1」;
  3. 开头的零值因为位于最后非零值之前,不会被修改,自然保留。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 04:27:02