5

I currently have a numpy multi-dimensional array (of type float) and a numpy column array (of type int). I want to combine the two into a mutli-dimensional numpy array.

import numpy

>> dates.shape
(1251,)
>> data.shape
(1251,10)
>> test = numpy.hstack((dates, data))
ValueError: all the input arrays must have same number of dimensions

To show that the types of the arrays are different:

>> type(dates[0])
<type 'numpy.int64'>
>> type(data[0,0])
<type 'numpy.float64'>
5
  • I'm showing numpy.dstack as stacking along the 3rd axis. I want to take a 1251, 10 (in this case) and turn it into a 1251, 11, are you suggesting that i would use dstack for that? Commented Dec 31, 2011 at 3:09
  • Ah ok sorry thought you wanted a 1251,1251,10 Commented Dec 31, 2011 at 3:12
  • Short of using an object array, you can't do this. Numpy arrays can, by definition, only contain a single type. So the only alternative is to cast the integer array to floating point, then stack them. Commented Dec 31, 2011 at 3:17
  • I believe a 1-D numpy array is treated as a row vector, not a column vector. I recall tripping over this recently as my intuition is that 1-D arrays should be column vectors :) Have you tried dates.shape = (1251,1)? Commented Dec 31, 2011 at 3:40
  • Thanks, that actually allows me to changes things more cleanly when I pre-allocate. I had: m,n = data.shape dates = numpy.empty(shape = temp.shape) now I can just make it dates = numpy.empty(shape = (m,1)) (because the number of dates must equal the number of rows of the date vector) and everything works fine. Commented Dec 31, 2011 at 3:49

3 Answers 3

11
import numpy as np

np.column_stack((dates, data))

The types are cast automatically to the most precise, so your int array will be converted to float.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much Griffith, this certainly did the trick, much appreciated, I was hoping to not have to cast the floats to get back to ordinals, but it'll work just fine, thanks again!
If you like my answer give me a vote and check it as the correct one ;)
1

The types don't matter, you should reshape dates to be (1251, 1) before using hstack.

Ps. The ints will be cast to float.

Comments

0

test = numpy.hstack((dates[:,numpy.newaxis], data))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.