📜  如何按列访问 NumPy 数组

📅  最后修改于: 2022-05-13 01:55:34.179000             🧑  作者: Mango

如何按列访问 NumPy 数组

可以通过索引来实现通过特定 Column 索引访问基于NumPy的数组。让我们详细讨论一下。

NumPy 遵循基于标准 0 的索引。

NumPy 中的行和列类似于Python列表

例子:

Given array : 1 13 6
              9  4 7
              19 16 2

Input: print(NumPy_array_name[ :,2])

# printing 2nd column
Output: [6 7 2]

Input: x =  NumPy_array_name[ :,1]
       print(x)

# storing 1st column into variable x
Output:  [13 4 16]

方法 #1:使用切片进行选择

Python3
# Python code to select row and column
# in NumPy
 
import numpy as np
 
array = [[1, 13, 6], [9, 4, 7], [19, 16, 2]]
 
# defining array
arr = np.array(array)
 
print('printing array as it is')
print(arr)
 
print('printing 0th row')
print(arr[0, :])
 
print('printing 2nd column')
print(arr[:, 2])
 
# multiple columns or rows can be selected as well
print('selecting 0th and 1st row simultaneously')
print(arr[:,[0,1]])


Python3
# program to select row and column
# in numpy using ellipsis
 
import numpy as np
 
# defining array
array = [[1, 13, 6], [9, 4, 7], [19, 16, 2]]
 
# converting to numpy array
arr = np.array(array)
 
print('printing array as it is')
print(arr)
 
print('selecting 0th column')
print(arr[..., 0])
 
print('selecting 1st row')
print(arr[1, ...])


输出 :

printing array as it is
[[ 1 13  6]
 [ 9  4  7]
 [19 16  2]]
printing 0th row
[ 1 13  6]
printing 2nd column
[6 7 2]
selecting 0th and 1st row simultaneously
[[ 1 13]
 [ 9  4]
 [19 16]]

方法#2:使用省略号

注意:这不是一种非常实用的方法,但必须尽可能多地了解。

Python3

# program to select row and column
# in numpy using ellipsis
 
import numpy as np
 
# defining array
array = [[1, 13, 6], [9, 4, 7], [19, 16, 2]]
 
# converting to numpy array
arr = np.array(array)
 
print('printing array as it is')
print(arr)
 
print('selecting 0th column')
print(arr[..., 0])
 
print('selecting 1st row')
print(arr[1, ...])

输出 :

printing array as it is
[[ 1 13  6]
 [ 9  4  7]
 [19 16  2]]
selecting 0th column
[ 1  9 19]
selecting 1st row
[9 4 7]