0

Total beginner on Python here, and all I want to do is add a column of 1s to a matrix, and I cannot seem to accomplish it. I wanted the new column to be the first one of the matrix. What I have tried:

import numpy as np

a = np.random.random((4, 4))

for i in range(len(a)):
  a[i] = [1] + a[i]

But apparently that just adds 1 to every element in my matrix. I am using Python3

  • This question might be duplicated but the answer is `np.hstack((np.ones((len(a), 1)), a))` – titipata May 12 '17 at 18:42
  • see this question: http://stackoverflow.com/questions/8486294/how-to-add-an-extra-column-to-an-numpy-array :) – titipata May 12 '17 at 18:44
  • 1
    Thank you for the answer, I had seen the question you linked but I had not seen the answer containing the code you just posted. I had seen another answer and wasn't able to apply it. – Philipe Atela May 12 '17 at 19:37

1 Answers1

0
import numpy as np
a = np.random.random((4, 4))
b = np.ones((len(a), 1), dtype=float)
print np.hstack([b,a])

You can brush your skills by following this tutorial

Amey Kumar Samala
  • 904
  • 1
  • 7
  • 20