我已经定义了一个函数
result = valuewhen(condition, array)
在最近一次出现array
为condition
时返回True
的值:
import pandas as 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)
示例:
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
现在,我希望在最近array
次condition
True
为n
时返回result = ValueWhen(condition, array[, n]) #[if missing n=1]
的值:
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
示例:
n
将参数{{1}}添加到此函数的最Pythonic方法是什么?