I have a list like this:
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]
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]
I use NaN
in this example, but a generalized solution that can apply to any value will also be great
Conclusion An Interval is all the numbers between two given numbers. Showing if the beginning and end number are included is important There are three main ways to show intervals: Inequalities, The Number Line and Interval Notation.
First, sort the given list. Initialize previous_number and range_start with first element. Start a loop and check if the next number is additive of the previous number, If yes, Initialize this number to previous number otherwise yield the new interval starting with range_start and ending with previous_number.
In "Interval Notation" we just write the beginning and ending numbers of the interval, and use: With the Number Line we draw a thick line to show the values we are including, and: That means up to and including $10.
We can have two (or more) intervals. We used a "U" to mean Union (the joining together of two sets ). Note: be careful with inequalities like that one. 2 ≥ x > 3 wrong! and greater than 3 at the same time). We just saw how to join two sets using "Union" (and the symbol ∪ ). There is also "Intersection" which means "has to be in both".
Pandas solution:
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]
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()
output
[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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With