How to concatenate using numpy?

Viewed 269

I have two array, the first one is (n rows, 6 columns), say X:

[[ 0.2    7.7   -6.2   0.4  9.6  -2.4]
 [ 0.1    7.2   -6.3   0.4  9.5  -2.1]
 [ 0.02   7.9   -5.8   0.2  9.1  -3.5]
 ...
 [-3.6    7.9   -5.3  -0.7  9.4  -0.4]
 [-1.2    8.8   -4.1  -0.4  9.8   0.9]
 [-1.2    9.6    1.2  -1.0  9.8   1.6]]

the second one is (n elements), say Y:

[100. 101. 102. 103. 100. 100. 100. 100. 100. 100. 100. 100. 100. 100.
 100. 100. 100. 100. 100. 100. 100. 101. 101. 101. 101. 101. 101. 101.
 ...
 105. 105. 105. 105. 105. 105. 105. 105. 105. 105. 105. 105. 105. 105.
 105. 107. 108. 109.]

I want to have a third c array(n rows, 7 columns) like that, say Z:

[[ 0.2    7.7   -6.2   0.4  9.6  -2.4  100.]
 [ 0.1    7.2   -6.3   0.4  9.5  -2.1  101.]
 [ 0.02   7.9   -5.8   0.2  9.1  -3.5  102.]
 ...
 [-3.6    7.9   -5.3  -0.7  9.4  -0.4  107.]
 [-1.2    8.8   -4.1  -0.4  9.8   0.9  108.]
 [-1.2    9.6    1.2  -1.0  9.8   1.6  109.]]

I have this code to do it:

import numpy as np

Y.resize((2, 1))
Z = np.concatenate((X, Y), axis=1)

But i got this error message:

Y.resize((2, 1))
ValueError: resize only works on single-segment arrays

Can anyone help me to fix this please?

2 Answers

Easiest way to do it is:

Z = np.hstack((X,Y[:,None]))

Y[:,None] adds a dimension to Y and hstack stacks them horizontally.

Example:

X=np.ones((3,6))
#[[1. 1. 1. 1. 1. 1.]
# [1. 1. 1. 1. 1. 1.]
# [1. 1. 1. 1. 1. 1.]]
Y = np.zeros(3)
#[0. 0. 0.]

Z:

[[1. 1. 1. 1. 1. 1. 0.]
 [1. 1. 1. 1. 1. 1. 0.]
 [1. 1. 1. 1. 1. 1. 0.]]

Your error is on the shape of your arrays. X shape is (n, 7) while Y shape is (n, ). Try changing Y shape to (n, 1) and concatenate along axis = 1. Here is a small example.

import numpy as np

X = np.array([[1, 2, 5],
              [3, 4, 6]])
Y = np.array([[7, 8]]).reshape(2, 1)
Z = np.concatenate((X, Y), axis=1)

Good luck

Related