部分填充条件python



我有以下数据框架,我想应用bfill如下:

"百分比"1.02.03

根据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

填充DataFrame

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

最新更新