0

I have a 3D nested list constructed like this:

[[[1,1],[2,1],[2,2],[1,2]],[[-1,-1],[-2,-1],[-2,-2],[-1,-2]]]

and I want to concat to that [[0,0]] to get this result:

[[[1,1],[2,1],[2,2],[1,2]],[[-1,-1],[-2,-1],[-2,-2],[-1,-2]],[[0,0]]]

I tried to use numpy.append and column_stack methods, but it complains about dimension mismatch. How to do that right?

3
  • 1
    Is this a numpy.array or a built-in list? Commented Jun 6, 2021 at 11:30
  • if it's a list then a.append([[0,0]]) should work. Commented Jun 6, 2021 at 11:34
  • you can't do this in numpy but possible in list with append method. Commented Jun 6, 2021 at 11:46

2 Answers 2

1

The problem is that once you have a numpy array with shape (2, 4, 2), you cannot really append another array with shape (1, 1, 2) unless you treat lists as objects (i.e. you are appending an element to an array of size 2 so that in the end you have an array of size 3).

If you have a numpy array of list objects you won't be able to benefit from most of the functionality provided by numpy so perhaps explain in a bit more detail what exactly you are trying to achieve here.

>>> a = np.array([[[1,1],[2,1],[2,2],[1,2]],[[-1,-1],[-2,-1],[-2,-2],[-1,-2]]])
>>> b = np.array([[[0, 0]]])
>>> a.shape, b.shape
((2, 4, 2), (1, 1, 2))
>>> c = np.array(a.tolist() + b.tolist())
>>> c
array([list([[1, 1], [2, 1], [2, 2], [1, 2]]),
       list([[-1, -1], [-2, -1], [-2, -2], [-1, -2]]), list([[0, 0]])],
      dtype=object)
>>> c.shape
(3,)
>>> c.tolist()
[[[1, 1], [2, 1], [2, 2], [1, 2]],
 [[-1, -1], [-2, -1], [-2, -2], [-1, -2]],
 [[0, 0]]]

The last value is the list you seem to be looking for. You don't have to go through this process with numpy to get it and can simply append as others have suggested.

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

2 Comments

[[1,1],[2,1],[2,2],[1,2]] and [[-1,-1],[-2,-1],[-2,-2],[-1,-2]] are coordinates of rectangles vertices and [[0,0]] is a point's coordinates, which I want to add to array which has rectangles (for later processing)
numpy is designed to help you work with vectors, matrices, tensors etc. it allows you to perform all kinds of manipulations, however, you cannot have "rows" that are incomplete so you probably want to work with pure lists, and simply append your point to the list of previous "shapes"
0

guess what, I can just use default append function; I didn't know that function is not returning the new array

1 Comment

Yes, be careful about using numpy functions. If you start with a list, and want a list result, using numpy is often slower, and possibly wrong.

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.