Compare each value in B
column with the first value in A
column until it is greater than it, then set the expected
column to true.
Then compare the value of A
column with the expected
column that is true until B
column value is greater than it,then set the expected
column to true.
Input:
import pandas as pd A=[20,13,15,25,24,13,14,19,13,11] B=[12,15,31,13,16,19,15,16,25,21] df=pd.DataFrame({'A':A,'B':B})
Expected Output
A B expected 0 20 12 1 13 15 2 15 31 TRUE 3 25 13 4 24 16 TRUE 5 13 19 6 14 15 7 19 16 8 13 25 TRUE 9 11 21 TRUE
Advertisement
Answer
You must use a custom function with a loop:
def compare(A, B): x = A[0] out = [] for a,b in zip(A,B): if b>x: out.append(True) x = a else: out.append(False) return out df['compare'] = compare(df['A'], df['B'])
output:
A B compare 0 20 12 False 1 13 15 False 2 15 31 True 3 25 13 False 4 24 16 True 5 13 19 False 6 14 15 False 7 19 16 False 8 13 25 True 9 11 21 True