Reputation: 198
I have a nd numpy array that emulates an 2d matrix in which each element is a column vector. I need to print the 2d array as it were a matrix.
Here is the code that creates the array:
Lx = 4
Ly = 4
f = 3
q = 10
pop = np.random.randint(q, size = (Lx, Ly, 1, f))
And the array looks like this:
[[[[3 3 6]]
[[5 2 2]]
[[6 0 2]]
[[5 8 8]]]
[[[7 8 2]]...
I need to see it as somehow this:
print(pop[0,0][0], pop[0,1][0], pop[0,2][0], pop[0,3][0])
print(pop[1,0][0], pop[1,1][0], pop[1,2][0], pop[1,3][0])
print(pop[2,0][0], pop[2,1][0], pop[2,2][0], pop[2,3][0])
print(pop[3,0][0], pop[3,1][0], pop[3,2][0], pop[3,3][0])
[2 9 2] [5 5 8] [4 9 3] [4 2 3]
[3 9 0] [6 4 0] [8 3 9] [6 4 1]
[4 8 9] [2 2 6] [1 3 8] [4 5 6]
[4 1 5] [8 0 9] [3 9 7] [4 4 3]
I can't use the print method of the example because the array can be much more larger. Ideally, it would be amazing to visualize it as in the image in this example:
Visualize 1D numpy array as 2D array with matplotlib
Thanks for all advice!
Upvotes: 0
Views: 636
Reputation: 23753
Nested four loop with the empty dimension removed:
In [46]: z = pop.reshape(tuple(d for d in pop.shape if d > 1))
In [47]: z.shape
Out[47]: (4, 4, 3)
In [48]: for x in z:
...: for y in x:
...: print(y, end=' ')
...: print()
...:
[4 0 3] [0 5 6] [7 4 2] [9 2 6]
[8 3 1] [0 8 8] [5 7 9] [3 1 5]
[4 9 9] [4 8 5] [0 8 7] [8 9 7]
[8 7 4] [4 7 5] [1 8 5] [4 3 0]
Or (using the same z
):
In [55]: n = z.shape[1]
In [56]: fmt = '{} ' * n
In [57]: for x in z:
...: print(fmt.format(*x))
...:
[4 0 3] [0 5 6] [7 4 2] [9 2 6]
[8 3 1] [0 8 8] [5 7 9] [3 1 5]
[4 9 9] [4 8 5] [0 8 7] [8 9 7]
[8 7 4] [4 7 5] [1 8 5] [4 3 0]
Upvotes: 1