Reputation: 3
I am working with huge nested arrays which look something like this in structure:
import numpy as np
arr1 = np.array([[11, 12, 13],[21, 22, 23],[31, 32, 33]], dtype=complex)
arr2 = np.zeros([2, 2], dtype=object)
for i in range(2):
for j in range(2):
arr2[i,j] = arr1
arr2
array([[array([[11.+0.j, 12.+0.j, 13.+0.j],
[21.+0.j, 22.+0.j, 23.+0.j],
[31.+0.j, 32.+0.j, 33.+0.j]]),
array([[11.+0.j, 12.+0.j, 13.+0.j],
[21.+0.j, 22.+0.j, 23.+0.j],
[31.+0.j, 32.+0.j, 33.+0.j]])],
[array([[11.+0.j, 12.+0.j, 13.+0.j],
[21.+0.j, 22.+0.j, 23.+0.j],
[31.+0.j, 32.+0.j, 33.+0.j]]),
array([[11.+0.j, 12.+0.j, 13.+0.j],
[21.+0.j, 22.+0.j, 23.+0.j],
[31.+0.j, 32.+0.j, 33.+0.j]])]], dtype=object)
Now I want to create another array which only holds for example the 11 value of each sub array without using a loop. I know how to call the correct item. However, I cant figure out how to get the whole slice with every sub item. I thought I could use something like this to get every cell of the outer array and then specify the index of the inner array:
arr2[0, 0][0, 0]
(11+0j)
arr2[::][0, 0]
array([[11.+0.j, 12.+0.j, 13.+0.j],
[21.+0.j, 22.+0.j, 23.+0.j],
[31.+0.j, 32.+0.j, 33.+0.j]])
What I wish to create is something like this with the 11 element from every sub array:
arr3 = array([[11+0j], [11+0j], [11+0j], [11+0j]])
I tried different approaches but could not get to my desired output. What am I doing wrong? Thanks in advance!
Note: I could not find any existing topic around here. Further, this is my very first post here. If I did something wrong, just tell me for I am happy to learn how to behave here ;)
Upvotes: 0
Views: 166
Reputation: 117661
Don't use dtype=object
unless you 100% know what you're doing. As a beginner it is almost always the wrong answer.
What you want is this:
>>> arr1 = np.array([[11, 12, 13],[21, 22, 23],[31, 32, 33]], dtype=complex)
>>> arr2 = np.broadcast_to(arr1, (2, 2) + arr1.shape)
>>> arr2
array([[[[11.+0.j, 12.+0.j, 13.+0.j],
[21.+0.j, 22.+0.j, 23.+0.j],
[31.+0.j, 32.+0.j, 33.+0.j]],
[[11.+0.j, 12.+0.j, 13.+0.j],
[21.+0.j, 22.+0.j, 23.+0.j],
[31.+0.j, 32.+0.j, 33.+0.j]]],
[[[11.+0.j, 12.+0.j, 13.+0.j],
[21.+0.j, 22.+0.j, 23.+0.j],
[31.+0.j, 32.+0.j, 33.+0.j]],
[[11.+0.j, 12.+0.j, 13.+0.j],
[21.+0.j, 22.+0.j, 23.+0.j],
[31.+0.j, 32.+0.j, 33.+0.j]]]])
>>> arr2[:,:,0,0]
array([[11.+0.j, 11.+0.j],
[11.+0.j, 11.+0.j]])
Upvotes: 1