0

I have two 2d numpy arrays like

array2D_1 = np.arange(9).reshape(3,3)
array2D_2 = np.arange(10,19).reshape(3,3)

Is it possible to append the second array to the first as just one column?

To concat two numpy arrays I have tryed the following function:

def _concat_two_features(self, array2D_1, array2D_2):
    return np.concatenate((array2D_1, array2D_2), axis=1)

and also

def _append_two_features(self, array2D_1, array2D_2):
        return np.append((array2D_1, array2D_2), axis=1)

Both result in the same array

array([[ 0,  1,  2, 10, 11, 12],
       [ 3,  4,  5, 13, 14, 15],
       [ 6,  7,  8, 16, 17, 18]])

What I would like to have is:

array([[ 0,  1,  2, [10, 11, 12]],
       [ 3,  4,  5, [13, 14, 15]],
       [ 6,  7,  8, [16, 17, 18]]])

I also tried something like this:

np.concatenate((array2D_1,[array2D_2]),axis=1)

But this doesn't the operation eather.

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 3 dimension(s)

Thanks in advance

6
  • just curious... why do you want that? Commented Sep 8, 2021 at 14:41
  • With axis, np.append just does concatenate. Look at its code Commented Sep 8, 2021 at 14:43
  • @some_name.py I have a multi dimensional feature which need to be considered as single value Commented Sep 8, 2021 at 14:49
  • @hpaulj what do you want to say? the output shows your answer already Commented Sep 8, 2021 at 14:49
  • What you seek is not a multidimensional numeric array. concatenate can't do it. Commented Sep 8, 2021 at 14:53

2 Answers 2

2

Does this help?

import numpy as np

array2D_1 = np.arange(9).reshape(3,3)
array2D_2 = np.arange(10,19).reshape(3,3)

out = np.empty(shape=(3,4),dtype=np.object)
out[:,:3] = array2D_1

out[:,3] = list(array2D_2)

Output:

array([[0, 1, 2, array([10, 11, 12])],
       [3, 4, 5, array([13, 14, 15])],
       [6, 7, 8, array([16, 17, 18])]], dtype=object)
Sign up to request clarification or add additional context in comments.

1 Comment

This is quiet perfect! Thx
1

OK, there is a way to use concatenate, but you have to work with object dtype arrays. This can't be done with numeric arrays.

In [6]: x=np.empty(array2D_2.shape[0],object); x[:]=list(array2D_2);
In [7]: x
Out[7]: 
array([array([10, 11, 12]), array([13, 14, 15]), array([16, 17, 18])],
      dtype=object)
In [8]: np.concatenate((array2D_1.astype(object), x[:,None]), axis=1)
Out[8]: 
array([[0, 1, 2, array([10, 11, 12])],
       [3, 4, 5, array([13, 14, 15])],
       [6, 7, 8, array([16, 17, 18])]], dtype=object)

1 Comment

Thx, great idea. However, I will accept the solution that was proposed preveously, since it is more readable

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.