Linfeng Li
Linfeng Li

Reputation: 25

Is there a better method to create such a numpy array?

I want a numpy array like this:

b = np.array([[1, 1, 1, 1, 1, 1], 
              [2, 2, 2, 2, 2, 2], 
              [3, 3, 3, 3, 3, 3], 
              [4, 4, 4, 4, 4, 4], 
              [5, 5, 5, 5, 5, 5], 
              [6, 6, 6, 6, 6, 6],
              [7, 7, 7, 7, 7, 7],
              [8, 8, 8, 8, 8, 8],
              [9, 9, 9, 9, 9, 9]])

Is there a faster way to create a NumPy array like this instead of typing them manually?

Upvotes: 0

Views: 54

Answers (5)

Caner Burc BASKAYA
Caner Burc BASKAYA

Reputation: 176

np.transpose(np.array(([np.arange(1,10)] * 6)))
  • np.arange(1,10) creates an numpy array from 1 to 9.
  • [] puts the array into a list.
  • *6 augments the array 6 times.
  • np.array() converts the resulting structure (list of arrays) to a numpy array
  • np.transpose() rotates the orientation of the numpy array to get vertical one.

Upvotes: 0

user8408080
user8408080

Reputation: 2468

You can do something like this:

>>> np.repeat(np.arange(1, 10).reshape(-1,1), 6, axis=1)
array([[1, 1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6, 6],
       [7, 7, 7, 7, 7, 7],
       [8, 8, 8, 8, 8, 8],
       [9, 9, 9, 9, 9, 9]])

Explanation:

  • np.arange(1, 10).reshape(-1,1) creates an array
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])
  • np.repeat(_, 6, axis=1) repeats this 6 times on the first (or second in human words) axis.

Upvotes: 1

keithpjolley
keithpjolley

Reputation: 2263

For any w*l size, convert a list of lists into an np.array like so:

w = 6
l = 9
[np.array([[1+i]*w for i in range(d)])
array([[1, 1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6, 6],
       [7, 7, 7, 7, 7, 7],
       [8, 8, 8, 8, 8, 8],
       [9, 9, 9, 9, 9, 9]])

Upvotes: 0

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95872

Another method is to use broadcasting:

>>> np.arange(1,10)[:,None] * np.ones(6, dtype=int)
array([[1, 1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6, 6],
       [7, 7, 7, 7, 7, 7],
       [8, 8, 8, 8, 8, 8],
       [9, 9, 9, 9, 9, 9]])

Upvotes: 1

LudvigH
LudvigH

Reputation: 4737

Yes. There are plenty of methods. This is one:

np.repeat(np.arange(1,10),6,axis=0).reshape(9,6)  

Upvotes: 1

Related Questions