2

I want to add column of ones to 5x5 matrix on at 0 index. np.append() is working but i search another way.

import numpy as np
arr = np.array(range(25)).reshape(5,5)
ones = np.ones((arr.shape[0],1))
arr_with_ones = np.append(ones, arr, axis=1)
print(arr_with_ones)

3 Answers3

2

You will not need to predefine a ones array. You can use numpy.insert function directly:

arr = np.array(range(25)).reshape(5,5)
arr_with_ones = np.insert(arr, 0, 1, axis=1)

np.insert(arr, 0, 1, axis=1) inserts value=1 in index 0 along axis=1(which is columns in 2D array) of array arr.

output:

[[ 1  0  1  2  3  4]
 [ 1  5  6  7  8  9]
 [ 1 10 11 12 13 14]
 [ 1 15 16 17 18 19]
 [ 1 20 21 22 23 24]]
Ehsan
  • 12,072
  • 2
  • 20
  • 33
0

U Can try like this:

import numpy as np
arr = np.array(range(25)).reshape(5,5)
ones = np.ones((arr.shape[0],1))
arr_with_ones = np.c_[ones, arr]
PandaO
  • 86
  • 3
0

You can try the np.hstack((ones,arr)) function as well.