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

如何基于另一列设置Pandas中bfill的填充限制?

实现动态行级限制的向后填充(bfill)

pandas原生的bfill()方法的limit参数仅支持全局固定值,无法直接将另一列的对应行值作为动态填充限制。但可以通过自定义逻辑实现你的需求,具体步骤如下:

1. 构造原始DataFrame

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'amount': [28, 40, 30, np.nan, np.nan, np.nan, np.nan, 30, 50, np.nan, np.nan, np.nan, 30, np.nan],
    'bfilllimit': [6, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 2, 0]
})

2. 自定义动态填充逻辑

核心思路是遍历所有非NaN的amount值,以该行的bfilllimit为限制,向前填充对应数量的NaN:

# 获取所有amount列非空值的索引
non_nan_indices = df[df['amount'].notna()].index

for idx in non_nan_indices:
    fill_limit = df.loc[idx, 'bfilllimit']
    # 跳过限制为0或负数的情况
    if fill_limit <= 0:
        continue
    # 计算需要填充的索引范围:从当前索引向前推fill_limit个位置
    fill_start = max(0, idx - fill_limit)
    fill_range = pd.RangeIndex(fill_start, idx)
    # 仅填充该范围内amount为NaN的行
    mask = df.loc[fill_range, 'amount'].isna()
    df.loc[fill_range[mask], 'amount'] = df.loc[idx, 'amount']

3. 查看结果

执行上述代码后,输出的DataFrame与你的预期一致:

amount  bfilllimit
0     28.0           6
1     40.0           0
2     30.0           0
3      NaN           0
4     30.0           0
5     30.0           0
6     30.0           0
7     30.0           3
8     50.0           0
9      NaN           0
10    30.0           0
11    30.0           0
12    30.0           2
13     NaN           0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 15:30:59