On 6 April 2016 at 17:26, Heli <heml...@gmail.com> wrote: > > Thanks for your replies. I have a question in regard with my previous > question. I have a file that contains x,y,z and a value for that coordinate > on each line. Here I am giving an example of the file using a numpy array > called f. > > f=np.array([[1,1,1,1], > [1,1,2,2], > [1,1,3,3], > [1,2,1,4], > [1,2,2,5], ... > [3,2,3,24], > [3,3,1,25], > [3,3,2,26], > [3,3,3,27], > ]) > > then after tranposing f, I get the x,y and z coordinates: > f_tranpose=f.T > x=np.sort(np.unique(f_tranpose[0])) > y=np.sort(np.unique(f_tranpose[1])) > z=np.sort(np.unique(f_tranpose[2]))
You don't actually need to transpose the matrix to get a column as a 1D array: >>> a = np.array([[1,2,3],[4,5,6]]) >>> a array([[1, 2, 3], [4, 5, 6]]) >>> a[0] array([1, 2, 3]) >>> a[0,:] # 1st row array([1, 2, 3]) >>> a[:,0] # 1st column array([1, 4]) (Not that there's a correctness/performance difference or anything I just think that asking for the column is clearer than asking for the row of the transpose.) > Then I will create a 3D array to put the values inside. The only way I see to > do this is the following: > arr_size=x.size > val2=np.empty([3, 3,3]) > > for sub_arr in f: > idx = (np.abs(x-sub_arr[0])).argmin() > idy = (np.abs(y-sub_arr[1])).argmin() > idz = (np.abs(z-sub_arr[2])).argmin() > val2[idx,idy,idz]=sub_arr[3] > > I know that in the example above I could simple reshape f_tranpose[3] to a > three by three by three array, but in my real example the coordinates are not > in order and the only way I see to do this is by looping over the whole file > which takes a lot of time. So it's easy if the array is in order like your example? Why not sort the array into order then? I think lexsort will do what you want: http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.lexsort.html http://stackoverflow.com/questions/8153540/sort-a-numpy-array-like-a-table -- Oscar -- https://mail.python.org/mailman/listinfo/python-list