Transform square matrix into 1D array with NumPy - python

Let's say I have a square matrix with 20 lines and 20 columns. Using NumPy, what should I do to transform this matrix into a 1D array with a single line and 400 columns (that is, 20.20 = 400, all in one line)?
So far, I've tried:
1) array = np.ravel(matrix)
2) array = np.squeeze(np.asarray(matrix))
But when I print array, it's still a square matrix.

Use the reshape method:
array = matrix.reshape((1,400)).
This works for both Numpy Array and Matrix types.
UPDATE: As sacul noted, matrix.reshape(-1) is more general in terms of dimensions.

Related

How to reshape a 1d array to a 3d array with diffrerent size of 2d arrays?

I want to reshape this array: np.array(np.arange(15)) to a 3d array that is built from a 3x3 array and a 3x2 array.
I've tried to do it with the reshape method but it didn't work.
I thought that maybe reshape can get a number of tuples maybe.
a=np.array(np.arange(15)).reshape(1,((3,2),(3,3)))
but I then I saw it cant.
How can I reshape it then? is there a nice way?
a multidimensional array can't have dimensions with different size.
but if you want a tuple you will need to split the array in 2 parts, the first that match in size with the 3x3 array and the second that match the 3x2, at this point you'll have 2 one dimensional array, then reshape them
arr1 = arr1.reshape((3,3))
arr2 = arr2.reshape((3,2))
tuple = arr1, arr2

Transpose a 1-dimensional array in Numpy without casting to matrix

My goal is to to turn a row vector into a column vector and vice versa. The documentation for numpy.ndarray.transpose says:
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a matrix object.)
However, when I try this:
my_array = np.array([1,2,3])
my_array_T = np.transpose(np.matrix(myArray))
I do get the wanted result, albeit in matrix form (matrix([[66],[640],[44]])), but I also get this warning:
PendingDeprecationWarning: the matrix subclass is not the recommended way to represent matrices or deal with linear algebra (see https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html). Please adjust your code to use regular ndarray.
my_array_T = np.transpose(np.matrix(my_array))
How can I properly transpose an ndarray then?
A 1D array is itself once transposed, contrary to Matlab where a 1D array doesn't exist and is at least 2D.
What you want is to reshape it:
my_array.reshape(-1, 1)
Or:
my_array.reshape(1, -1)
Depending on what kind of vector you want (column or row vector).
The -1 is a broadcast-like, using all possible elements, and the 1 creates the second required dimension.
If your array is my_array and you want to convert it to a column vector you can do:
my_array.reshape(-1, 1)
For a row vector you can use
my_array.reshape(1, -1)
Both of these can also be transposed and that would work as expected.
IIUC, use reshape
my_array.reshape(my_array.size, -1)

Fastest way to mask rows of a 2D numpy array given a boolean vector of same length?

I have a numpy boolean vector of shape 1 x N, and an 2d array with shape 160 x N. What is a fast way of subsetting the columns of the 2d array such that for each index of the boolean vector that has True in it, the column is kept, and for each index of the boolean vector that has False in it, the column is discarded?
If you call the vector mask and the array features, i've found the following to be far too slow: np.array([f[mask] for f in features])
Is there a better way? I feel like there has to be, right?
You can try this,
new_array = 2d_array[:,bool_array==True]
So depending on the axes you can select which one you want to remove. In case you get a 1-d array, then you can just reshape it and get the required array. This method will be faster also.

filtering a 3D numpy array according to 2D numpy array

I have a 2D numpy array with the shape (3024, 4032).
I have a 3D numpy array with the shape (3024, 4032, 3).
2D numpy array is filled with 0s and 1s.
3D numpy array is filled with values between 0 and 255.
By looking at the 2D array values, I want to change the values in 3D array. If a value in 2D array is 0, I will change the all 3 pixel values in 3D array into 0 along the last axes. If a value in 2D array is 1, I won't change it.
I have checked this question, How to filter a numpy array with another array's values, but it applies for 2 arrays which have same dimensions. In my case, dimensions are different.
How the filtering is applied in two arrays, with same size on 2 dimensions, but not size on the last dimension?
Ok, I'll answer this to highlight one pecularity regarding "missing" dimensions. Lets' assume a.shape==(5,4,3) and b.shape==(5,4)
When indexing, existing dimensions are left aligned which is why #Divakar's solution a[b == 0] = 0 works.
When broadcasting, existing dimensions are right aligned which is why #InvaderZim's a*b does not work. What you need to do is a*b[..., None] which inserts a broadcastable dimension at the right
I think this one is very simple:
If a is a 3D array (a.shape == (5, 4, 3)) filled with values, and b is a 2D array (b.shape == (5, 4)) filled with 1 and 0, then reshape b and multiply them:
a = a * b.reshape(5, 4, 1)
Numpy will automatically expand the arrays as needed.

how to convert a 2D numpy array to a 2D numpy matrix by changing shape

I have been struggling with changing a 2D numpy array to a 2D numpy matrix. I know that I can use numpy.asmatrix(x) to change array x into a matrix, however, the size for the matrix is not the size I wish to have. For example, I want to have a numpy.matrix((2,10)). It is easier for me to use two separate numpy.arrays to form each rows of the matrix. then I used numpy.append to put these two arrays into a matrix. However, when I use numpy.asmatrix to make this 2d array into a 2d matrix, the size is not the same size as my matrix (my desired matrix should have a size of 2*10 but when I change arrays to matrix, the size is 1*2). Does anybody know how I can change size of this asmatrix to my desired size?
code (a and b are two numpy.matrix with size of (1*10)):
m=10
c=sorted(random.sample(range(m),2))
n1=numpy.array([a[0:c[0]],b[c[0]:c[1]],a[c[1]:]])
n2=numpy.array([b[0:c[0]],a[c[0]:c[1]],b[c[1]:]])
n3=numpy.append(n1,n2)
n3=numpy.asmatrix(n3)
n1 and n2 are each arrays with shape 3 and n3 is matrix with shape 6. I want n3 to be a matrix with size 2*10
Thanks

Categories