NumPy Array Conversion - python

I'm new to python and I'm trying to convert a (m,n,1) multidimensional array to (m,n) in a fast way, how can I go about it?
Also given a (m,n,k) array how can I split it to k (m,n) arrays? (each of the k members belongs to a different array)

To reshape array a you can use a.reshape(m,n).
To split array a along the depth dimension, you can use numpy.dsplit(a, a.shape[2]).
https://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html
https://docs.scipy.org/doc/numpy/reference/generated/numpy.dsplit.html#numpy.dsplit

To reshape a NumPy Array arr with shape (m, n, 1) to the shape (m, n) simply use:
arr = arr.reshape(m, n)
You can get a list of (m, n)-shaped arrays out of a (m, n, k) shaped array arr_k by:
array_list = [arr_k[:, :, i] for i in range(arr_k.shape[2])]

Related

Numpy kron applied to multiple matrices in different axes

I have a numpy array (called op_rot) with shape (N, P, 2, 2), with N and P generic integers.
I want to obtain a numpy array with shape (P, 2**N, 2**N), where I applied np.kron to all the N (2,2) matrices.
I managed to arrive at this solution which I believe gives me the desired result:
op = []
for j in range(P):
op.append(reduce(np.kron,op_rot[:,j]))
op = np.array(op)
Is there a way to vectorize this process avoiding the for loop?

Slice multidimensional numpy array from max in a given axis

I have a 3-dimensional array a of shape (n, m, l). I extract one column j from it's last axis and compute the maximum index along the first axis like follows:
sub = a[:, :, j] # shape (n, m)
wheremax = np.argmax(sub, axis=0) # this have a shape of m
Now I'd like to slice the original array a to get all the information based on the index where the column j is maximal. I.e. I'd like an numpythonic way to do the following using array broadcasting or numpy functions:
new_arr = np.zeros((m, l))
for i, idx in enumerate(wheremax):
new_arr[i, :] = a[idx, i, :]
a = new_arr
Is there one?
As #hpaulj mentionned in the comments, using a[wheremax, np.arange(m)] did the trick.

Why does numpy.insert convert an (N, 1) array to an (N,) array?

I have a numpy array with size (N,1). When I insert a value somewhere into the array using numpy.insert, it results in an (N,) array. This later causes problems when subtracting an (N,1) array from an (N,) array.
Example:
#Random (4 x 1) array
a = np.random.rand(4,1)
#Insert a number. This results in a (4,) array
b = np.insert(a,0,10)
#Some other (5 x 1) array
c = np.random.rand(5,1)
#Because c is (5,1) and b is (5,), this subtraction is not element by
#element and results in a (5,5) array.
d = b - c
Two questions:
Why does "insert" decrease the dimensions of the array?
Why does subtracting a (5,) array from a (5,1) array result in a (5,5) array rather than an element-wise subtraction?
From the numpy.insert docs:
axis : int, optional
Axis along which to insert values. If axis is None then arr is flattened first.
You didn't specify an axis, so insert flattened the array as the first step. As for how the subtraction works, that's broadcasting.

Delete 2d subarray from 3d array in numpy

In numpy I have a 3d array and I would ike to remove some of the 2d subarrays. Think about it like this:
r = range(27)
arr = np.reshape(r, (3,3,3))
del = [[0,1,2],[0,0,2]]
flatSeam = np.ravel_multi_index(del, arr.shape)
arr = np.delete(arr, flatSeam)
So at the end I would like to have an array of the shape (3,2,3) without the elements 00, 10, 22 from the original array. My problem is that I acn not use ravel_multi_index for this, because my indices are 2d and the array shape is 3d, so the wrong indices are calculated (the code above also does not execute because the indices array and the shape have to be the same size).
Do you have any ideas how I can achieve this?
Here's an approach using advanced-indexing -
# arr: Input array, rm_idx : 2-row list/array of indices to be removed
m,n,p = arr.shape
mask = np.asarray(rm_idx[1])[:,None] != np.arange(n)
out = arr[np.arange(m)[:,None],np.where(mask)[1].reshape(m,-1)]
Alternatively, with boolean-indexing -
out = arr.reshape(-1,p)[mask.ravel()].reshape(m,-1,p)
A bit less memory-intensive approach as we try to avoid creating 2D mask -
vmask = ~np.in1d(np.arange(m*n),rm_idx[1] + n*np.arange(m))
out = arr.reshape(-1,p)[vmask].reshape(m,-1,p)

Multiply a 1d array x 2d array python

I have a 2d array and a 1d array and I need to multiply each element in the 1d array x each element in the 2d array columns. It's basically a matrix multiplication but numpy won't allow matrix multiplication because of the 1d array. This is because matrices are inherently 2d in numpy. How can I get around this problem? This is an example of what I want:
FrMtx = np.zeros(shape=(24,24)) #2d array
elem = np.zeros(24, dtype=float) #1d array
Result = np.zeros(shape=(24,24), dtype=float) #2d array to store results
some_loop to increment i:
some_other_loop to increment j:
Result[i][j] = (FrMtx[i][j] x elem[j])
Numerous efforts have given me errors such as arrays used as indices must be of integer or boolean type
Due to the NumPy broadcasting rules, a simple
Result = FrMtx * elem
Will give the desired result.
You should be able to just multiply your arrays together, but its not immediately obvious what 'direction' the arrays will be multiplied since the matrix is square. To be more explicit about which axes are being multiplied, I find it is helpful to always multiply arrays that have the same number of dimensions.
For example, to multiply the columns:
mtx = np.zeros(shape=(5,7))
col = np.zeros(shape=(5,))
result = mtx * col.reshape((5, 1))
By reshaping col to (5,1), we guarantee that axis 0 of mtx is multiplied against axis 0 of col. To multiply rows:
mtx = np.zeros(shape=(5,7))
row = np.zeros(shape=(7,))
result = mtx * row.reshape((1, 7))
This guarantees that axis 1 in mtx is multiplied by axis 0 in row.

Categories

Resources