python - 带有条件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 |
请帮忙。
解决方案
根据NaN
s创建组
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
推荐阅读
- r - 如何为一组图添加一个常见的 y 和 x 标签,以及在 R 中为该排列的几列添加一个标签?
- python - 使用 BeautifulSoup 解析获取的 html 内容
- raku - Raku .hyper() 和 .race() 示例不起作用
- google-analytics - 延迟的 bigquery 事件会出现在哪里?
- reactjs - 如何使用反应和打字稿修复错误“无法调用可能未定义的对象”?
- r - 如何在文本文件的数据操作期间过滤日期?
- python - Tkinter 窗口字体在拉伸窗口时动态扩展
- regex - 如何在正则表达式提取期间处理可能的不同顺序的 HTML (img) 元素属性?
- google-cloud-platform - Skaffold vs Spinnaker
- flutter - Flutter 的图像选择器未在应用程序发布中打开图库