首页 > 解决方案 > 带有条件python的部分填充

问题描述

我有以下要应用 bfill 的数据框,如下所示:

'数量' '百分比'
1.0 20
2.0 10
3.0 50
4.0 10
5.0 10

我想按照百分比列中的百分比在金额列中填充 Nan,即,如果相应的百分比为 50,则在数字之前填充 50% 的 Nan(部分填充)。例如,值为 3.0 的金额占 50 的百分比,因此在 4 个 Nan 条目中,只有 50% 将被填充。

拟议产出:

'数量' '百分比'
1.0 20
2.0 10
3.0
3.0
3.0 50
4.0 10
5.0 10

请帮忙。

标签: pythonpandasfillna

解决方案


根据NaNs创建组

df['group_id'] = df.amount.where(df.amount.isna(), 1).cumsum().bfill()

创建填充函数

def custom_fill(x):

    # Calculate number of rows to be filled
    max_fill_rows = math.floor(x.iloc[-1, 1] * (x.shape[0] - 1) / 100)

    # Fill only if number of rows to fill is not zero
    return x.bfill(limit=max_fill_rows) if max_fill_rows else x

填充数据框

df.groupby('group_id').apply(custom_fill)

输出

   amount  percentage group_id
0     NaN         NaN      1.0
1     1.0        20.0      1.0
2     2.0        10.0      2.0
3     NaN         NaN      3.0
4     NaN         NaN      3.0
5     3.0        50.0      3.0
6     3.0        50.0      3.0
7     3.0        50.0      3.0
8     4.0        10.0      4.0
9     NaN         NaN      5.0
10    5.0        10.0      5.0

PS:别忘了导入需要的库

import math

推荐阅读