1

I have a 500x2 matrix which has been filled using numpy.random.rand.

The output looks like this (but obviously a larger version):

 [ -3.28460744e+00  -4.29156493e-02]
 [ -1.90772015e-01  -9.17618367e-01]
 [ -2.41166994e+00  -3.76661496e+00]
 [ -2.43169366e+00  -6.31493375e-01]
 [ -1.48902305e+00  -9.78215901e-01]
 [ -3.11016192e+00  -1.87178962e+00]
 [ -3.72070031e+00  -1.66956850e+00]

I want to append 1 to the end of each row so that each line would look like this:

[ -3.72070031e+00  -1.66956850e+00  1]

Is this possible? I've been trying to use numpy.append() but struggling to work out what should be used.

Any help would be much appreciated!

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
calvin2011
  • 317
  • 3
  • 9

1 Answers1

5
a = np.ones((4,2)) * 2
>>> a
array([[ 2.,  2.],
       [ 2.,  2.],
       [ 2.,  2.],
       [ 2.,  2.]])

Numpy.concatenate documentation: The arrays must have the same shape, except in the dimension corresponding to axis ... along which the arrays will be joined.

>>> a.shape
(4, 2)

You want to concatenate along the second axis so make an array of ones that has a shape of (4,1) - use values from a.shape to do this.

b = np.ones((a.shape[0], 1))

>>> b.shape
(4, 1)
>>> b
array([[ 1.],
       [ 1.],
       [ 1.],
       [ 1.]])

Now you can concatenate

z = np.concatenate((a,b), axis = 1)

>>> z
array([[ 2.,  2.,  1.],
       [ 2.,  2.,  1.],
       [ 2.,  2.,  1.],
       [ 2.,  2.,  1.]])

Or use hstack

>>> np.hstack((a,b))
array([[ 2.,  2.,  1.],
       [ 2.,  2.,  1.],
       [ 2.,  2.,  1.],
       [ 2.,  2.,  1.]])
wwii
  • 23,232
  • 7
  • 37
  • 77