0

I have this problem in Python and I cannot figure out how I can do this. I have three arrays:

Two of the form:

array1 ([ 1,  2, 3])
array2 ([ 4,  5, 6])

and one of the form:

array3 ([ [1, 2, 3], [2, 3, 4], [3, 4, 5]])

What I want is an array from these two arrays which has three columns, in such a way, that the 2D array is in the center:

array  ([1, [1, 2, 3], 4],
        [2, [2, 3, 4], 5],
        [3, [3, 4, 5], 6])

I am able to join the first two arrays by using e.g. np.c_[array1, array2]. I can do np.c_[array1, array3, array2] as well, but then I get

array  ([1, 1, 2, 3, 4],
        [2, 2, 3, 4, 5],
        [3, 3, 4, 5, 6])

Any help is appreciated. Thanks.

4
  • You don't want to do this with numpy arrays. Jagged arrays are a bad idea. Commented May 1, 2019 at 18:36
  • This is for an exercise, so I don't have a choice. Any idea? Commented May 1, 2019 at 18:39
  • [list(el) for el in zip(array1, array3, array2)] Commented May 1, 2019 at 18:42
  • The desired display is flawed. It looks lilke a 3 element tuple, where the elements are lists that contain numbers and lists. The array word is just tacked on. It's not a valid array constructor or display, not even for object dtype. Commented May 1, 2019 at 20:24

1 Answer 1

1

This is a bad idea. Read up on how numpy stores data and you will understand that numpy is not meant to store jagged arrays with mixed data types.

That being said, all you are asking for is your three input elements zipped together. If you really want to store this data you could simply store it as a list, which would be preferable to an ndarray

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])

You can accomplish this with a list comprehension and zip

np.array([list(el) for el in zip(a, c, b)], dtype=object)

array([[1, array([1, 2, 3]), 4],
       [2, array([2, 3, 4]), 5],
       [3, array([3, 4, 5]), 6]], dtype=object)

You must specify a dtype of object since you are setting an array element with a sequence.

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

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.