Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Inserting slice of array objects into different slice
#1
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?
Quote
#2
Shouldn't it be: a = np.zeros((2,), dtype=np.object)

(2) is an int, (2,) is s tuple
Quote
#3
(Mar-31-2020, 06:52 PM)deanhystad Wrote: Shouldn't it be: a = np.zeros((2,), dtype=np.object)

(2) is an int, (2,) is s tuple

No, it shouldn't.
Quote
#4
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.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Quote
#5
(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.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  slice per group Progressive 3 814 Jul-20-2019, 06:52 AM
Last Post: scidam
  TypeError: '(slice(None, None, None), 0)' is an invalid key zaki424160 1 5,027 Jul-17-2019, 11:53 PM
Last Post: scidam
  Melt or Slice Grin 0 746 Jun-24-2018, 06:02 PM
Last Post: Grin

Forum Jump:


Users browsing this thread: 1 Guest(s)