[Tutor] finding a maximum between the absolute difference of several columns
Andre' Walker-Loud
walksloud at gmail.com
Fri Feb 17 07:38:04 CET 2012
Hi Elaina,
> Vhel_fdiff3=[]
> for i in xrange(len(Vmatch3_1)):
> Vhel_fdiff3.append(max([abs(Vmatch3_1[i] - Vmatch3_2[i]),abs(Vmatch3_1[i] - Vmatch3_3[i]),abs(Vmatch3_3[i] - Vmatch3_2[i])]))
>
> #print Vhel_fdiff3
> #appending writes a list, but numpy which makes the with_ work needs an array
> Vhel_fdiff3=array(Vhel_fdiff3)
You can skip making the list and directly make a numpy array.
"""
import numpy as np
...
Vhel_fdiff3 = np.zeros_like(Vmatch3_1)
for i in xrange(len(Vmatch3_1):
Vhel_fdiff3[i] = max(abs(Vmatch3_1[i] - Vmatch3_2[i]),abs(Vmatch3_1[i] - Vmatch3_3[i]),abs(Vmatch3_3[i] - Vmatch3_2[i]))
"""
But, more importantly, you can do it all in numpy - have a read about the "max" function
http://scipy.org/Numpy_Example_List#head-7918c09eea00e59ec399064e7d5e1e672d242f60
Given an 2-dimensional array, you can find the max for each row or each column by specifying which axis you want to compare against. Almost surely, the built in numpy function will be faster than your loop - even if you precompile it by importing your functions in another file. You can do something like
"""
import numpy as np
Vhel_fdiff3 = np.array([abs(Vmatch3_1 - Vmatch3_2), abs(Vmatch3_1 - Vmatch3_3), abs(Vmatch3_3 - Vmatch3_2)]) #create an array of the absolute values of the differences of each pair of data
# Vhel_fdiff3 is a 2D array
# the first index runs over the three pairs of differences
# the second index runs over the elements of each pair
# to get the maximum difference, you want to compare over the first axis (0)
your_answer = Vhel_fdiff3.max(axis=0)
"""
but you may not want the abs value of the differences, but to actually keep the differences, depending on which one has the maximum abs difference - that would require a little more coding.
Andre
More information about the Tutor
mailing list