我正在寻找一种方法来进行修改后的pandas插值,以便不将超出限制的连续NaN值填充到数据帧中.

如果这是我开始使用的数据帧:

df = pd.DataFrame({'col1': [0, np.nan, np.nan, np.nan, 3, 4],
                   'col2': [np.nan, 1, 2, np.nan, 4, np.nan],
                   'col3': [4, np.nan, np.nan, 7, 10, 11]})

df
   col1  col2  col3
0   0.0   NaN   4.0
1   NaN   1.0   NaN
2   NaN   2.0   NaN
3   NaN   NaN   7.0
4   3.0   4.0  10.0
5   4.0   NaN  11.0

and I specify that I want to interpolate with a limit of two, with an inside limit area, as seen below: df.interpolate(method="linear", limit=2, limit_area="inside")
This is the result:

   col1  col2  col3
0   0.00   NaN   4.0
1   0.75   1.0   5.0
2   1.50   2.0   6.0
3    NaN   3.0   7.0
4   3.00   4.0  10.0
5   4.00   NaN  11.0

然而,我正在寻找另一种解决方案,以便只有当某一行中的某一特定列的极限NaN等于或小于时,才会发生插值填充.因此,我期望的结果如下所示:

   col1  col2  col3
0   0.00   NaN   4.0
1    NaN   1.0   5.0
2    NaN   2.0   6.0
3    NaN   3.0   7.0
4   3.00   4.0  10.0
5   4.00   NaN  11.0

第一列未填充,因为一行中有超过极限(2)个NAN.

推荐答案

我们可以只处理单个列,apply:

def interpolate(series, thresh=2):
    # where the nan values are
    nans = series.isna()

    # calculate the size of consecutive `nan`
    mask = nans.groupby([(~nans).cumsum(),nans]).transform('size') > thresh
    return series.interpolate(method='linear', limit_area='inside').mask(mask)

df.apply(interpolate)

注意:如果是,例如interpolate(df['col1']),那么mask将是:

0    False
1     True
2     True
3     True
4    False
5    False
Name: col1, dtype: bool

输出:

   col1  col2  col3
0   0.0   NaN   4.0
1   NaN   1.0   5.0
2   NaN   2.0   6.0
3   NaN   3.0   7.0
4   3.0   4.0  10.0
5   4.0   NaN  11.0

Python相关问答推荐

如何从在虚拟Python环境中运行的脚本中运行需要宿主Python环境的Shell脚本?

log 1 p numpy的意外行为

如何在给定的条件下使numpy数组的计算速度最快?

Godot:需要碰撞的对象的AdditionerBody2D或Area2D以及queue_free?

如何将多进程池声明为变量并将其导入到另一个Python文件

Pandas计数符合某些条件的特定列的数量

提取相关行的最快方法—pandas

如何在BeautifulSoup/CSS Select 器中处理regex?

pysnmp—lextudio使用next()和getCmd()生成器导致TypeError:tuple对象不是迭代器''

使用嵌套对象字段的Qdrant过滤

numpy数组和数组标量之间的不同行为

python的文件. truncate()意外地没有截断'

Python如何导入类的实例

如何在PYTHON中向单元测试S Side_Effect发送额外参数?

对包含JSON列的DataFrame进行分组

如何删除剪裁圆的对角线的外部部分

具有数值数组问题的递归矩阵构造(广播?)

使用BeautifulSoap库从Web获取表格时没有响应

通过PyTorch中的MIN函数传递渐变

抽象工厂模式与委托者模式组合时出现递归错误