python - 有没有一种方法可以在 pandas/numpy 中使用升序逻辑进行前向填充?

标签 python pandas ffill

使用升序逻辑前向填充(无需遍历行)的最大胆的方法是什么?

输入:

import pandas as pd
import numpy as np

df = pd.DataFrame()

df['test'] = np.nan,np.nan,1,np.nan,np.nan,3,np.nan,np.nan,2,np.nan,6,np.nan,np.nan
df['desired_output'] = np.nan,np.nan,1,1,1,3,3,3,3,3,6,6,6

print (df)

输出:

    test  desired_output
0    NaN             NaN
1    NaN             NaN
2    1.0             1.0
3    NaN             1.0
4    NaN             1.0
5    3.0             3.0
6    NaN             3.0
7    NaN             3.0
8    2.0             3.0
9    NaN             3.0
10   6.0             6.0
11   NaN             6.0
12   NaN             6.0

在“测试”列中,连续 NaN 的数量是随机的。

在“desired_output”列中,尝试仅使用递增的值进行正向填充。此外,当遇到较低的值时(上面的第 8 行,值 = 2.0),它们将被当前较高的值覆盖。

有人可以帮忙吗?提前致谢。

最佳答案

你可以结合cummax选择累积最大值和 ffill替换 NaN:

df['desired_output'] = df['test'].cummax().ffill()

输出:

    test  desired_output
0    NaN             NaN
1    NaN             NaN
2    1.0             1.0
3    NaN             1.0
4    NaN             1.0
5    3.0             3.0
6    NaN             3.0
7    NaN             3.0
8    2.0             3.0
9    NaN             3.0
10   6.0             6.0
11   NaN             6.0
12   NaN             6.0

中级系列:

df['test'].cummax()

0     NaN
1     NaN
2     1.0
3     NaN
4     NaN
5     3.0
6     NaN
7     NaN
8     3.0
9     NaN
10    6.0
11    NaN
12    NaN
Name: test, dtype: float64

关于python - 有没有一种方法可以在 pandas/numpy 中使用升序逻辑进行前向填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72744525/

相关文章:

python - Pandas DataFrame 基于第一行值的条件前向填充

python - 值错误: Could not convert string to float: Reading from DictReader

python - 在 Jupyter Notebook 中居中 HTML 表格和文本

java - 如何减少GAE启动的前端实例数量?

python - 如何在 python 中为 excel 文件应用 if/else 逻辑? (日期)

python - 寻找一种加速 Pandas 合并的方法(或可能是另一种方法)

python - 将一列替换为属于两个不同数据框的另一列的值

python pandas如何通过其他数据框扩展数据框