1

Im calculating results for each rows in 2D-array.

import numpy as np
xyz = np.array([[1, 2, 100],[2, 5, 100]])
resultcolumn1 = (xyz[:,0]+xyz[:,1])*xyz[:,2]
>>array([300, 700])
>>type 'numpy.ndarray'>

But when I'm trying to add this resultvector to rest of the 2D-array as a column

print np.concatenate((xyz, resultcolumn1.T), axis=1)

I get this error:

ValueError: all the input arrays must have same number of dimensions.

Declaring the same vector with double brackets. Works:

resultcolumn2=np.array([[300, 700]])
>>>array([[300, 700]])
>>><type 'numpy.ndarray'>
np.concatenate((xyz, resultcolumn2.T), axis=1)
>>>[[  1   2 100 300]
    [  2   5 100 700]]

How do I change resultcolumn1 to match resultcolumn2? Also could this process be done in better fashion?

languitar
  • 6,554
  • 2
  • 37
  • 62
Johnes
  • 23
  • 3
  • 1
    Possible duplicate of [Python reshape list to ndim array](http://stackoverflow.com/questions/35432378/python-reshape-list-to-ndim-array) – languitar Mar 30 '17 at 12:37

1 Answers1

1

Simply add an extra dimension:

>>> np.concatenate((xyz, resultcolumn1.T[..., None]), axis=1)
array([[  1,   2, 100, 300],
       [  2,   5, 100, 700]])

Also, note that for a 1d array, .T (i.e. transpose) does nothing so you can simply drop it:

>>> np.concatenate((xyz, resultcolumn1[..., None]), axis=1)
array([[  1,   2, 100, 300],
       [  2,   5, 100, 700]])
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139