How to create a 2-D numpy array from a 1-D array?

I have a numpy array:

import numpy as np
A = np.array([1,2])

I want to make n-copy of both elements in a 2-D numpy array, e.g.

B=[[1,1,1,1],[2,2,2,2]] # 4 copies of each element of A into a separate array

How can i do this?

+4
source share
3 answers

Use np.repeatand then change the form -

np.repeat(A,4).reshape(-1,4)

That which reshape(-1,4)basically stores the number of columns 4, but -1indicates it calculates the number of rows based on the total size of the array to be resized. Thus, for this sample, as it np.repeat(A,4).sizeis 8, it assigns the 8/4 = 2number of rows. Thus, it converts np.repeat(A,4)to an array of 2Dforms (2,4).

np.repeat A 2D None/np.newaxis -

np.repeat(A[:,None],4,axis=1)

np.tile -

np.tile(A[:,None],4)
+3

, 1 s:

>>> import numpy as np
>>> A=np.array([1,2])
>>> A[:, np.newaxis] * np.ones(4, int)
array([[1, 1, 1, 1],
       [2, 2, 2, 2]])

, broadcast_to (, ):

>>> np.broadcast_to(A[:, None], [A.shape[0], 4])
array([[1, 1, 1, 1],
       [2, 2, 2, 2]])
+1

You can use matrix multiplication with an array (properly formed) of 1s and then transpose the final array.

import numpy as np

A = np.array([1, 2])

n = 4
B = np.ones((n, 1))
out = (A*B).T

You can also use np.vstackand then move the array.

out = np.vstack((A,)*n).T
+1
source

Source: https://habr.com/ru/post/1672759/


All Articles