Im trying to find the largest difference between i and j in a series where i cannot be before j. Is there an efficient way to do this in pandas:
x = [1, 2, 5, 4, 2, 4, 2, 1, 7]
largest_change = 0for i in range(len(x)):for j in range(i+1, len(x)):change = x[i] - x[j]print(x[i], x[j], change)if change > largest_change:largest_change = change
The output would just be the value, in this case 4 from 5 to 1.
Try numpy broadcast with np.triu
and max
arr = np.array(x)
np.triu(arr[:,None] - arr)array([[ 0, -1, -4, -3, -1, -3, -1, 0, -6],[ 0, 0, -3, -2, 0, -2, 0, 1, -5],[ 0, 0, 0, 1, 3, 1, 3, 4, -2],[ 0, 0, 0, 0, 2, 0, 2, 3, -3],[ 0, 0, 0, 0, 0, -2, 0, 1, -5],[ 0, 0, 0, 0, 0, 0, 2, 3, -3],[ 0, 0, 0, 0, 0, 0, 0, 1, -5],[ 0, 0, 0, 0, 0, 0, 0, 0, -6],[ 0, 0, 0, 0, 0, 0, 0, 0, 0]])np.triu(arr[:,None] - arr).max()Out[758]: 4