如何在列表的间隔之间填充元素 [英] How to fill elements between intervals of a list

查看:77
本文介绍了如何在列表的间隔之间填充元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表:

list_1 = [np.NaN, np.NaN, 1, np.NaN, np.NaN, np.NaN, 0, np.NaN, 1, np.NaN, 0, 1, np.NaN, 0, np.NaN,  1, np.NaN]

因此,有些间隔以1开头,以0结束. 我如何替换这些间隔中的值,例如1?结果将如下所示:

So there are intervals that begin with 1 and end with 0. How can I replace the values in those intervals, say with 1? The outcome will look like this:

list_2 = [np.NaN, np.NaN, 1, 1, 1, 1, 0, np.NaN, 1, 1, 0, 1, 1, 0, np.NaN, 1, np.NaN]

在此示例中,我使用NaN,但是适用于任何值的通用解决方案也将很好

I use NaN in this example, but a generalized solution that can apply to any value will also be great

推荐答案

熊猫解决方案:

s = pd.Series(list_1)
s1 = s.eq(1)
s0 = s.eq(0)
m = (s1 | s0).where(s1.cumsum().ge(1),False).cumsum().mod(2).eq(1)
s.loc[m & s.isna()] = 1
print(s.tolist())
#[nan, nan, 1.0, 1.0, 1.0, 1.0, 0.0, nan, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, nan, 1.0, 1.0]


,但是如果只有10NaN,则可以:


but if there is only 1, 0 or NaN you can do:

s = pd.Series(list_1)
s.fillna(s.ffill().where(lambda x: x.eq(1))).tolist()

输出

[nan,
 nan,
 1.0,
 1.0,
 1.0,
 1.0,
 0.0,
 nan,
 1.0,
 1.0,
 0.0,
 1.0,
 1.0,
 0.0,
 nan,
 1.0,
 1.0]

这篇关于如何在列表的间隔之间填充元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆