Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill elements between intervals of a list

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

like image 242
NonSleeper Avatar asked Apr 18 '20 16:04

NonSleeper


People also ask

What is an interval?

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.

How do you find the interval between two numbers in Python?

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.

How do you include $10 in interval notation?

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.

How many intervals can you have in math?

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".


1 Answers

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]
like image 194
ansev Avatar answered Sep 25 '22 18:09

ansev