Inserting slice of array objects into different slice - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Inserting slice of array objects into different slice (/thread-25445.html) |
Inserting slice of array objects into different slice - ThemePark - Mar-30-2020 Suppose I have the following code: import numpy as np a=np.zeros((2),dtype=np.object) b=np.array([[11],[13]]) a[0]=b[0] a[1]=b[1] print(a)This gives me the wanted result of "[array([11]) array([13])]". But if I have a big array, it's too tedious to add a line for each index. So I wanna do it in some way like this: a[0:2]=b[0:2]But that gives me the error "ValueError: could not broadcast input array from shape (2,1) into shape (2)". So how do I have to write that one line to accomplish the same as the code at the beginning? RE: Inserting slice of array objects into different slice - deanhystad - Mar-31-2020 Shouldn't it be: a = np.zeros((2,), dtype=np.object) (2) is an int, (2,) is s tuple RE: Inserting slice of array objects into different slice - ThemePark - Mar-31-2020 (Mar-31-2020, 06:52 PM)deanhystad Wrote: Shouldn't it be: a = np.zeros((2,), dtype=np.object) No, it shouldn't. RE: Inserting slice of array objects into different slice - perfringo - Apr-01-2020 The problem is exactly described in error message: you can't broadcast shape 2,1 into shape 2. array([0, 0], dtype=object) # a array([[11], # b [13]])Before any advice it would be good to know what is the objective i.e. what do you want to accomplish. RE: Inserting slice of array objects into different slice - ThemePark - Apr-01-2020 (Apr-01-2020, 04:35 AM)perfringo Wrote: The problem is exactly described in error message: you can't broadcast shape 2,1 into shape 2.But it obviously doesn't describe a solution, and a ton of research hasn't led me any nearer on a solution. (Apr-01-2020, 04:35 AM)perfringo Wrote: Before any advice it would be good to know what is the objective i.e. what do you want to accomplish.The exact same result that I said I got in the first post, but without having to do it one by one. It's fine with an array of a size 2, but what if I had a size 10, 1000 or even higher? Then part of my code would look like this: a[0]=b[0] a[1]=b[1] a[2]=b[2] a[3]=b[3] a[4]=b[4] a[5]=b[5] ... a[997]=b[997] a[998]=b[998] a[999]=b[999]But there must be an easier way of doing this, using slicing, or list comprehension perhaps. And that's what I can't figure out how to do. |