0

The following is a real-world problem in numPy reduced to the essentials, just with smaller dimensions.

Let's say I want to create an n-dimensional array all with dimensions (10, 10, 100):

all = np.empty((10, 10, 100))

I also have a 1d array data, simulated here as

data = np.arange(0, 100) 

for all i, j I now want to achieve that

all[i,j]=data

So I do:

all[:, :]=data

Of course that works.

But now I want to import data to all2 with shape (100, 10, 10). I could do that with

all2 = np.empty((100, 10, 10)) # new target to be populated
for i in range(100):
  for j in range(10):
    for k in range(10):
      all2[i, j, k]=data[i]

But is there an easier way to do this without looping? I would be surprised if it couldn't be done more elegantly, but I don't see how.

2
  • 1
    I'm not big on NumPy but you should have a look into the reshape functions, this may help! Commented Apr 18, 2024 at 8:41
  • 1
    all2[:] = data[:, None,None]. This puts a (100, 1,1) shape into the (100,10,10). Commented Apr 18, 2024 at 10:30

1 Answer 1

1

You can use transpose: all2.T[:] = data (note the second , : insn't necessary)

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

6 Comments

most easy. I would never have thought of that
You can also define directly all = np.tile(data, (10,10,1)) and all2 = np.tile(data, (10,10,1)).T although using all as variable name is a terrible idea...
as I told - this is only a boiled-down version of my original problem
@MichaelW: NumPy automatically fills in as many trailing :s as necessary.
Assignment to the transposed view is faster than the tile (or repeat) approach. But what about all3 with a (10,100,10) shape?
|

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.