numpy - Returns the value of the array when the condition was true on the n -th most recent occurrence -
i have defined function
result = valuewhen(condition, array)
which returns value of array
when condition
true
on recent occurrence:
import pandas pd pd1 = pd.series([0,0,1,1,0,0,1,0,1,0,0,0,1]) pd2 = pd.series([1,2,3,4,5,6,7,8,9,10,11,12,13]) def valuewhen(a1, a2): res = pd.series(index=a1.index) res.loc[a1 == 1] = a2 res = res.ffill().fillna(0) return res result = valuewhen(pd1, pd2)
example:
result = valuewhen(array1, array2) array1 array2 result 0 1 0 0 2 0 1 3 3 1 4 4 0 5 4 0 6 4 1 7 7 0 8 7 1 9 9 0 10 9 0 11 9 0 12 9 1 13 13
now want return value of array
when condition
true
on n
th recent occurrence:
result = valuewhen(condition, array[, n]) #[if missing n=1]
example:
result = valuewhen(array1, array2, 1) result2 = valuewhen(array1, array2, 2) array1 array2 result result2 0 1 0 0 0 2 0 0 1 3 3 0 1 4 4 3 0 5 4 3 0 6 4 3 1 7 7 4 0 8 7 4 1 9 9 7 0 10 9 7 0 11 9 7 0 12 9 7 1 13 13 9
what pythonic way add parameter n
function?