I have a matrix called POS which has form (10,132) and I need to average those first 10 elements in such a way that my averaged matrix has the form of (1,132)
I have tried doing
means = pos.mean (axis = 1)
or
menas = np.mean(pos)
but the result in the first case is a matrix of (10,) and in the second it is a simple number
i expect the ouput a matrix of shape (1,132)
The solution is to specify the correct axis and use keepdims=True which is noted by several commenters (If you add your answer I will delete mine).
This can be done with either pos.mean(axis = 0,keepdims=True) or np.mean(pos,axis=0,keepdims=True)
Related
In order to modify the value of a particular vertical line in the image, i want to extract the 3-band vertical line of the image.
When I was a two dimensional array, I extracted the vertical lines with the following code:
vertical_line = array[:,[1]]
I tried to use this code in a 3d array image but it failed.
#image shape(b,g,r) (100,100,3)
# my try
vertical_line_try_1 = image[:,[1]][3]#result => [[255,255,255]]
vertical_line_try_2 = image[:,[1][3]]#result => IndexError: list index out of range
vertical_line_try_3 = image[:,[1],[3]]#result => IndexError: index 3 is out of bounds for axis 2 with size 3
How can I extract the vertical lines of three bands at once without writing a loop?
When you index with a slice the corresponding dimension is kept (since you get a possible stridded range of values). On the other hand, when you index with a single number that dimension disappears.
Ex:
a = np.random.randn(4,5)
# Let's get the third column in the matrix
print(a[:, 2].shape) # prints `(4,)` -> we get a vector
print(a[:, 2:3].shape) # prints `(4,1)` -> we keep the result as a column matrix
From your two dimensional example it seems you are using advanced indexing just as a way to keep the dimension. If that is true, using a slice containing a single element as I have shown is cleaner (my opinion) and faster (tested with %timeit in IPython).
Now, back to your question. It looks like you want to extract all values whose index of the second dimension is equal to 1, similar to the red part in the figure below.
If that is the case, then just use either image[:,1, :] (or just image[:,1]) if you to get the values as a matrix, or image[:,1:2, :] if you want a 3D array.
It is also useful to understand what your failed attempts were actually doing.
image[:,[1]][3]: This is actually two indexing operations in the same line.
First, image[:,[1]] would return a 100x1x3 array, and then the second indexing with [3] would take the fourth line. Since this second indexing is a regular one (not a fancy and not a slice), then the indexed dimension disappears and you get a 1x3 array in the end
image[:,[1][3]]: This one I'm not really sure what it is doing
image[:,[1],[3]]: This means "take all values from the first dimension, but only the ones from the second index of the first dimension and the fourth index of the third dimension. Since the third dimension only has "size" 3, then trying to get the fourth index results in the out of bound error.
Title kinda says it all, I'm trying to make two new matrices after using numpy.split, so:
#A is some mxn matrix
numfolds=5
folds = numpy.split(A,numfolds)
#now folds is 5 equalish subarrays which can be called out
#subarray1 is the second fold (the second fifth of A along axis=0 by default)
subarray1 = folds[2]
#numpy.delete does not get rid of the second subarray in A
arrayWithoutSubArray1 = numpy.concatenate(numpy.delete(folds[2]))
How do a make a matrix which is all but one subarray in A, in this example. I'd rather not use loops. Thanks in advance.
(Posted on behalf of the OP).
The solution is to do the delete outside of the concatenate and index properly.
#A is some mxn matrix
numfolds=5
folds = numpy.split(A,numfolds)
#now folds is 5 equalish subarrays which can be called out
#subarray1 is the second fold (the second fifth of A along axis=0 by default)
subarray1 = folds[2]
#numpy.delete does not get rid of the second subarray in A
arrayWithoutSubArray1 = numpy.delete(folds,2,0)
arrayWithoutSubArray1 = numpy.concatenate(arrayWithoutSubArray1)
I have an array of 3 dimensional vectors. The dimension of the array is arbitrary: it could be a single (N×3), double (M×N×3), triple (K×M×N×3) etc. I need to operate on two components of the vector while preserving the other dimensions.
For example, if I know it is three dimensionsional, I could do the following:
R = numpy.arctan2(A[:,:,:,1], A[:,:,:,0])
which gives me a three dimensional array of scalar values.
Now, to be able to do this on arbitrary number of dimensions. I need to slice over all other dimensions except the the last. So far, I'm able to do it with this:
s = [numpy.s_[:]] * (len(A.shape)-1)
R = numpy.arctan2(A[s+[1]], A[s+[0]])
which works even for single vectors. Is there a more numpythonic way of achieving the above?
I found an even nicer way. This here works for me
R = numpy.arctan2(A[...,1],A[...,0])
I have a list of np.array, mya = [a0,...,an] (all of which have the same shape and dtype). Say ai has the shape ai = array[xi0,xi1,..,xim]. I want to get
[max((a[i] for a in mya)) for i in range(m)]
. For example, let x=np.array([3,4,5]), y=np.array([2,50,-1]) and z=np.array([30,0,3]) then for mya = [x,y,z], I want [30,50,5] (or np.array equivalent).
Giving m by m=len(mya[0]), my code above does work, but it seems way too tedious. What are the suggested ways to achieve this?
In numpy, numpy.amax(myarray) give you the maximum of myarray. If you look for the maximum of each list/array of first dimmension, you can set also the axis you want. In this case, it should be:
x=np.array([3,4,5])
y=np.array([2,50,-1])
z=np.array([30,0,3])
mya = [x,y,z]
maximum = np.amax(mya, axis=0)
# maximum will store a list as [maximumofx, maximumofy, maximumofz] -> [30,50,5]
See docs
As #Ruben_Bermudez suggested, np.amax was just what I was looking for.
np.amax, scipy documentation provided here, accepts an array-like data as input and returns "the maximum of an array or maximum along an axis." Among its optional parameters is axis, which specifies the axis along which to find maximum.
By default, input is flattened, so
np.amax(mya) # => 50
Specifying axis=0
np.amax(mya,axis=0) # np.array([30,50,5])
and this was what I wanted.
Sorry for the mess.
I'm using Numpy and have a 7x12x12 matrix whose values I would like to populate in 12x12 chunks, 7 different times. Suppose I have these 12x12 matrices:
first_Matrix
second_Matrix
third_Matrix
... (etc)
seventh_Matrix = first_Matrix + second_Matrix + third_Matrix...
that I'd like to add to:
grand_Matrix
How can I do this? I assume there is a better way than loops that map the coordinates from one matrix to the next, and if there's not, could someone please write out the code for mapping first_Matrix into the first 12x12 element of grand_Matrix?
grand_Matrix[0,...] = first_Matrix
grand_Matrix[1,...] = second_Matrix
and so on.
Anyway, as #Lattyware commented, it is a bad design to have extra names for so many such homogenous objects.
If you have a list of 12x12 matrices:
grand_Matrix = np.vstack(m[None,...] for m in matrices)
None adds a new dimension to each matrix and stacks them along this dimension.