I have this dataframe:
In[1]df = pd.DataFrame([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]])
In[2]df
Out[2]:
0 1 2 3 4
0 1 2 3 4 5
1 6 7 8 9 10
2 11 12 13 14 15
3 16 17 18 19 20
4 21 22 23 24 25
I need to achieve this:
- for every rows in my dataframe,
- if 2 or more values within any 3 consecutive cells is greater than 10,
- then the last of that 3 cells should be marked as True.
The resulting dataframe df1 should be same size with True of False in it based on the above stated criteria:
In[3]df1
Out[3]:
0 1 2 3 4
0 NaN NaN False False False
1 NaN NaN False False False
2 NaN NaN True True True
3 NaN NaN True True True
4 NaN NaN True True True
- df1.iloc[0,1] is NaN bacause in that cell, only two numbers were given but needed atleast 3 numbers to do the test.
- df1.iloc[1,3] is False since none in [7,8,9] is greater than 10
- df1.iloc[3,4] is True since 2 or more in [18,19,20] is greater than 10
I figured dataframe.rolling.apply() with a function might be the solution, but how exactly?
Use
sum
on a boolean dataframe.You can nail down the exact requested output by masking where na.
You need -
Output
Explanation
breaks it down to taking 3 columns at a time for every row -
Checks for each element in the list of tuples and then outputs
True
if all the elements in the tuple are greater than 10Concatenating
[np.nan, np.nan]
to match your output. Hope that helps.You are right that using
rolling()
is the way to go. However, you must keep in mind sincerolling()
replaces the value at end of the window with the new value, so you can not just mark the window withTrue
you will also getFalse
whenever the condition is not applicableHere is the code that uses your sample dataframe and performs the desired transformation:
now, defining a function that takes a window as an argument and returns whether the condition is satisfied
I have hardcoded the threshold as 10. So if in any window the numbers of values greater than 10 are greater than or equal to 2 than the last value is replaced by 1 (denoting True), else it is replaced by -1(denoting False).
If you want to keep threshold parameters as variables, then have a look at this answer to pass them as arguments.
Now applying the function on rolling window, using window size as 3, axis 1 and additionally if you don't want NaN then you can also set min_periods to 1 in the arguments.
produces the output as