Reputation: 6197
I have a row of ints that I would like to add as a column to a 2D matrix of floats. So when combined, the first column would be the column of ints, the second column would be the first column of the 2D matrix, and the last column would be the last column of the matrix.
I tried isolating the issue to just 1 row but I still can't get it to work. Here is the most minimal example
tee = np.array( [[ 0.3322441, -0.34410527, -0.1462533 , 0.35244817, -0.3557416, -0.3362794 ], [ 0.9750831, -0.24571404 , 0.12960567, 0.14683421 ,0.00650549, -0.21060513]] )
zeros = np.array([0])
all_data = np.hstack((zeros, tee))
output
ValueError Traceback (most recent call last)
<ipython-input-34-02aa17f12182> in <module>()
----> 1 all_data = np.hstack((zeros, tee))
/usr/local/lib/python3.6/dist-packages/numpy/core/shape_base.py in hstack(tup)
336 # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
337 if arrs and arrs[0].ndim == 1:
--> 338 return _nx.concatenate(arrs, 0)
339 else:
340 return _nx.concatenate(arrs, 1)
ValueError: all the input arrays must have same number of dimensions
Desired output
print(all_data)
[[0],[ 0.3322441, -0.34410527, -0.1462533 , 0.35244817, -0.3557416, -0.3362794 ], [ 0.9750831, -0.24571404 , 0.12960567, 0.14683421 ,0.00650549, -0.21060513]]
Upvotes: 0
Views: 167
Reputation: 833
You can use np.column_stack
:
all_data = np.column_stack(([0]*len(tee),tee))
This would yield the following output:
print (all_data)
array([[ 0. , 0.3322441 , -0.34410527, -0.1462533 , 0.35244817,
-0.3557416 , -0.3362794 ],
[ 0. , 0.9750831 , -0.24571404, 0.12960567, 0.14683421,
0.00650549, -0.21060513]])
The reason your method did not work is because you are trying to prepend a column of one element to a 2D array of vertical axis length 2. However, the above method converts your integers to floats. If this is undesired, you may want to look into a list of lists which can be created as:
all_data = [[0]]+tee.tolist()
which yields the output:
print (all_data)
[[0],
[0.3322441, -0.34410527, -0.1462533, 0.35244817, -0.3557416, -0.3362794],
[0.9750831, -0.24571404, 0.12960567, 0.14683421, 0.00650549, -0.21060513]]
Upvotes: 1
Reputation: 712
The only way to mix data types in a NumPy array is to use the datatype: np.object
. This can be done implicitly like this:
all_data = np.asarray((zeros, *tee))
or explicitly like this:
all_data = np.asarray((zeros, *tee), dtype=np.object)
Upvotes: 1