Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何返回NumPy数组中的某些列项?_Python_Python 3.x_Numpy - Fatal编程技术网

Python 如何返回NumPy数组中的某些列项?

Python 如何返回NumPy数组中的某些列项?,python,python-3.x,numpy,Python,Python 3.x,Numpy,我想在2DNumPy数组中打印一些项目 例如: a = [[1, 2, 3, 4], [5, 6, 7, 8]] a = numpy.array(a) 我的问题是: 如何仅返回(1和2)?以及(5和6) 如何将维度保持为[2,2] 以下是: a[:, [0, 1]] 将仅选择前两列(索引为0和1)。结果将是: array([[1, 2], [5, 6]]) 以下是: a[:, [0, 1]] 将仅选择前两列(索引为0和1)。结果将是: array([[1, 2]

我想在
2D
NumPy
数组中打印一些项目

例如:

a = [[1, 2, 3, 4],
     [5, 6, 7, 8]]

a = numpy.array(a)
我的问题是:

  • 如何仅返回
    (1和2)
    ?以及
    (5和6)
  • 如何将维度保持为
    [2,2]
  • 以下是:

    a[:, [0, 1]]
    
    将仅选择前两列(索引为0和1)。结果将是:

    array([[1, 2],
           [5, 6]])
    
    以下是:

    a[:, [0, 1]]
    
    将仅选择前两列(索引为0和1)。结果将是:

    array([[1, 2],
           [5, 6]])
    

    可以使用切片来获取numpy阵列的必要部分。 要获得1和2,需要选择0的行和前两列,即

    >>> a[0, 0:2]
    array([1, 2])
    
    5和6的情况也一样

    >>> a[1, 0:2]
    array([5, 6])
    
    您还可以选择2x2子阵列,例如

    >>> a[:,0:2]
    array([[1, 2],
           [5, 6]])
    

    可以使用切片来获取numpy阵列的必要部分。 要获得1和2,需要选择0的行和前两列,即

    >>> a[0, 0:2]
    array([1, 2])
    
    5和6的情况也一样

    >>> a[1, 0:2]
    array([5, 6])
    
    您还可以选择2x2子阵列,例如

    >>> a[:,0:2]
    array([[1, 2],
           [5, 6]])
    
    你可以这样做

    In [44]: a[:, :2]
    Out[44]: 
    array([[1, 2],
           [5, 6]])
    
    你可以这样做

    In [44]: a[:, :2]
    Out[44]: 
    array([[1, 2],
           [5, 6]])
    

    谢谢,但是,如果有很多列,比如100,我只想先返回51,我该怎么办?像其他答案一样:
    a[,:51]
    谢谢,但是,如果有很多列,比如100,我只想先返回51,我该怎么办?像其他答案一样:
    a[,:51]