简体   繁体   中英

How to Print a specific column in a 3D Matrix using numpy Python

I have a problem with printing a column in a numpy 3D Matrix. Here is a simplified version of the problem:

import numpy as np
Matrix = np.zeros(((10,9,3))) # Creates a 10 x 9 x 3 3D matrix
Matrix[2][2][6] = 578
# I want to print Matrix[2][x][6] for x in range(9)
# the purpose of this is that I want to get all the Values in Matrix[2][x][6]

Much appreciated if you guys can help me out. Thanks in advance.

Slicing would work:

a = np.zeros((10, 9, 3))
a[6, 2, 2] = 578
for x in a[6, :, 2]:
    print(x)

Output:

0.0
0.0
578.0
0.0
0.0
0.0
0.0
0.0
0.0

Not sure if Numpy supports this, but you can do it with normal lists this way:

If you have three lists a = [1,2,3] , b = [4,5,6] , and c = [7,8,9] , you can get the second dimension [2,5,8] for example by doing

list(zip(a,b,c))[1]

EDIT:

Turns out this is pretty simple in Numpy. According to this thread you can just do:

Matrix[:,1]

No sure if this is what you want. Here is demo:

In [1]: x = np.random.randint(0, 20, size=(4, 5, 3))

In [2]: x
Out[2]: 
array([[[ 5, 13,  9],
        [ 8, 16,  5],
        [15, 17,  1],
        [ 6, 14,  5],
        [11, 13,  9]],

       [[ 5,  8,  0],
        [ 8, 15,  5],
        [ 9,  2, 13],
        [18,  4, 14],
        [ 8,  3, 13]],

       [[ 3,  7,  4],
        [15, 11,  6],
        [ 7,  8, 14],
        [12,  8, 18],
        [ 4,  2,  8]],

       [[10,  1, 16],
        [ 5,  2,  1],
        [11, 12, 13],
        [11,  9,  1],
        [14,  5,  1]]])

In [4]: x[:, 2, :]
Out[4]: 
array([[15, 17,  1],
       [ 9,  2, 13],
       [ 7,  8, 14],
       [11, 12, 13]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM