提取numpy数组Python中列的特定范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35593994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract Specific RANGE of columns in numpy array Python
提问by mfathirirhas
I have an array :
我有一个数组:
e = np.array([[ 0, 1, 2, 3, 5, 6, 7, 8],
[ 4, 5, 6, 7, 5, 3, 2, 5],
[ 8, 9, 10, 11, 4, 5, 3, 5]])
I want to extract array by its columns in RANGE, if I want to take column in range 1 until 5, It will return
我想按 RANGE 中的列提取数组,如果我想取范围 1 到 5 中的列,它将返回
e = np.array([[ 1, 2, 3, 5, ],
[ 5, 6, 7, 5, ],
[ 9, 10, 11, 4, ]])
How to solve it? Thanks
如何解决?谢谢
采纳答案by whbb
You can just use e[:, 1:5] to retrive what you want.
您可以使用 e[:, 1:5] 来检索您想要的内容。
In [1]: import numpy as np
In [2]: e = np.array([[ 0, 1, 2, 3, 5, 6, 7, 8],
...: [ 4, 5, 6, 7, 5, 3, 2, 5],
...: [ 8, 9, 10, 11, 4, 5, 3, 5]])
In [3]: e[:, 1:5]
Out[3]:
array([[ 1, 2, 3, 5],
[ 5, 6, 7, 5],
[ 9, 10, 11, 4]])
https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
回答by netskink
Numpy row and column indices start counting at 0.
Numpy 行和列索引从 0 开始计数。
The rows are specified first and then the column with a comma to separate the row from column.
首先指定行,然后指定列,用逗号分隔行与列。
The ":" (colon) is used to shortcut all rows or all columns when it is used alone.
“:”(冒号)在单独使用时用于对所有行或所有列进行快捷方式。
When the row or column specifier has a range, then the ":" is paired with numbers that specify the inclusive start range and the exclusive end range.
当行或列说明符具有范围时,“:”与指定包含的开始范围和不包含的结束范围的数字配对。
For example
例如
import numpy as np
np_array = np.array( [ [ 1, 2, 3, ],
[ 4, 5, 6, ],
[ 7, 8, 9 ] ] )
first_row = np_array[0,:]
first_row
output: array([1, 2, 3])
last_column = np_array[:,2]
last_column
output: array([3, 6, 9])
first_two_vals = np_array[0,0:2]
first_two_vals
output: array([1, 2])