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)
Related
For two-dimensaol array, according Guide to numpy
The two-styles of memory layout for arrays are connected through the transpose operation. Thus, if A is a (contiguous) C-style array, then the same block memory can be used to represent AT as a (contiguous) Fortran-style array. This kindof undorctondina non ho ucoful mhon trrina to orn mmonnina of Fortron
In three dimensional matrix
A = np.arange(6).reshape([1,2,3])
we can view A as a 1 by 1 block matrix, which means A has one entry, and that entry is a matrix with two rows and three columns.
So we can iteratively take the transpose according to the rules above.
My question is:
A= np.arange(6).reshape([1,2,3])
B = A.transpose(1,2,0)
In this case, how does it work. Is there a rule that can tell me how the elements of B are arranged
I have read about concatenate. But, did not see the function taking a single list as input.It must have two lists as input.
Consider the following statement in a program that I want to execute
row = np.concatenate(row, 1)
What is concatenate doing here? It is taking only one list named row.
Probably you have seen it most often used like this:
c = np.concatenate([a, b])
but you can of course also do:
ab = [a, b]
c = np.concatenate(ab)
Look at row before and after concatenating to see what is going on.
The first argument of np.concatenate is supposed to be a sequence of objects (think vectors or matrices). The second argument is the axis along which the concatenation is to be performed. See help(np.concatenate) for the full docstring.
For your command to be valid, the objects in the row sequence must have at least a 0th and a 1st dimension. This would typically be a matrix, but the name row is suggestive of a set of row vectors that have dimension [0, d].
If you concatenate n vectors of shape [0, d] along the 1st dimension, this will result in an object of shape [0, n*d]. Which is a very long row vector.
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.
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)
Is there any neat way to check is numpy array surrounded by zeros.
Example:
[[0,0,0,0],
[0,1,2,0],
[0,0,0,0]]
I know I can iterate it element wise to find out but I wonder is there any nice trick we can use here. The numpy array is of floats, n x m of arbitrary size.
Any ideas are welcome.
You can use numpy.any() to test if there is any non-zero element in numpy array.
Now, to test if a 2D array is surrounded by zeroes, you can get first and last columns as well as first and last rows and test if any of those contains a non-zero number.
def zero_surrounded(array):
return not (array[0,:].any() or array[-1,:].any() or array[:,0].any() or array[:,-1].any())
We can check this by constructing two submatrices:
A[[0,-1]] the first and the last row, including the first and last column; and
A[1:-1,[0,-1]] the first and last column, excluding the first and last row.
All the values of these matrices should be equal to zero, so we can use:
if np.all(A[[0,-1]] == 0) and np.all(A[1:-1,[0,-1]] == 0):
# ...
pass
This works for an arbitrary 2d-array, but not for arrays with arbitrary depth. We can however use a trick for that as well.
For an arbitrary matrix, we can use:
def surrounded_zero_dim(a):
n = a.ndim
sel = ([0,-1],)
sli = (slice(1,-1),)
return all(np.all(a[sli*i+sel] == 0) for i in range(n))
Using the slice is strictly speaking not necessary, but it prevents checking certain values twice.
Not the fastest, but perhaps the shortest (and hence a "neat") way of doing it:
surrounded = np.sum(a[1:-1, 1:-1]**2) == np.sum(a**2)
print(surrounded) # True
Here, a is the array.
This compares the sum of all squared elements to the sum of all squared elements except for those on the boundary. If we left out the squaring, cases where positive and negative boundary values add up to zero would produce the wrong answer.