Home > Mobile >  How to increase dimensions of a numpy arrray
How to increase dimensions of a numpy arrray

Time:10-19

so I got the following array:

a = []

for i in range(5):
    a.append(np.array(range(5)))
    
a = np.array(a)

array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])
               

I want to add an extra 'column' to the data, such that it looks like this:

array([[0, 1, 2, 3, 4, 5],
       [0, 1, 2, 3, 4, 5],
       [0, 1, 2, 3, 4, 5],
       [0, 1, 2, 3, 4, 5],
       [0, 1, 2, 3, 4, 5]])

However, the only way I can think of is like this, is there not a better way?

a = np.array([np.insert(i,5,5) for i in a])

CodePudding user response:

Here you go:

np.hstack([a, np.ones((5,1))*5])

Output:

array([[0., 1., 2., 3., 4., 5.],
       [0., 1., 2., 3., 4., 5.],
       [0., 1., 2., 3., 4., 5.],
       [0., 1., 2., 3., 4., 5.],
       [0., 1., 2., 3., 4., 5.]])

CodePudding user response:

Another possible way using some other numpy methods that might be useful to you in the future.

import numpy as np

# Creating initial grid.
X = np.arange(5)
a, yy = np.meshgrid(X, X, sparse=False)

# Create an array of n rpeating values; reshape it to (n, 1) dimensions.
newX = np.array([5] * 5).reshape((-1, 1))

# Append that sucker rowwise
np.append(a, newX, axis=1)
  • Related