Starts when the start
column is True
and ends when the end
column is True
.
The obtained result is assigned to the result
column.
Input:
import pandas as pd
import numpy as np
A = [6, 12, 21, 15, 18, 19, 13, 9, 10, 50]
cond1 = [False, True, False, False, False, False, True, False, False, False]
cond2 = [False, False, False, True, False, False, False, False, True, False]
df = pd.DataFrame({'A' : A, 'start' : cond1, 'end' : cond2})
Expected Output
A start end result
0 6 FALSE FALSE
1 12 TRUE FALSE
2 21 FALSE FALSE
3 15 FALSE TRUE 12
4 18 FALSE FALSE 12
5 19 FALSE FALSE 12
6 13 TRUE FALSE 12
7 9 FALSE FALSE 12
8 10 FALSE TRUE 9
9 50 FALSE FALSE 9
Index 3 calculates the minimum value from index 1 to index 3
Index 8 calculates the minimum value from index 6 to index 8
CodePudding user response:
We may need to create the groupby
key with cumsum
, then transform
the min
of each group and shift
it
df.loc[df.end,'new'] = (df.groupby([df['start'].cumsum(),df['end'].cumsum()]).
A.transform('min').shift())
df['new'] = df['new'].ffill()
df
Out[333]:
A start end new
0 6 False False NaN
1 12 True False NaN
2 21 False False NaN
3 15 False True 12.0
4 18 False False 12.0
5 19 False False 12.0
6 13 True False 12.0
7 9 False False 12.0
8 10 False True 9.0
9 50 False False 9.0
CodePudding user response:
Here is a simple algorithem to slove your problem
import pandas as pd
A=[6,12,21,15,18,19,13,9,10,50]
cond1=[False,True,False,False,False,False,True,False,False,False]
cond2=[False,False,False,True,False,False,False,False,True,False]
result=[]
numbers =[]
index=0
for i in A:
result.append("")
minimum=None;
while index<len(A):
if (cond1[index]):
while(not(cond2[index])):
numbers.append(A[index])
if (minimum != None):
result[index]=minimum
index = 1
minimum = min(numbers)
result[index]=minimum
numbers=[]
if(i==index):
index =1
else:
if (minimum != None):
result[index]=minimum
index =1
df=pd.DataFrame({'A':A,'start':cond1,'end':cond2,'result':result})
print(df)
OUTPUT
A start end result
0 6 False False
1 12 True False
2 21 False False
3 15 False True 12
4 18 False False 12
5 19 False False 12
6 13 True False 12
7 9 False False 12
8 10 False True 9
9 50 False False 9
Hope this will help you to get the result which you expected.