代码之家  ›  专栏  ›  技术社区  ›  Majoris

如何在NumPy中附加到数组而不使数组变平?

  •  0
  • Majoris  · 技术社区  · 2 年前

    如何在NumPy中附加两个数组而不进行扁平化? 我试着改变轴。

    >>> h = np.array([])
    >>> g = np.array([2,4])
    >>> i = np.array([6,9])
    >>> np.append(h,g)
    array([2., 4.])
    >>> h = np.append(h,g)
    >>> h
    array([2., 4.])
    >>> np.append(h,i)
    array([2., 4., 6., 9.])
    >>> np.append(h,i, axis=0)
    array([2., 4., 6., 9.])
    >>> np.append(h,i, axis=1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/opt/homebrew/lib/python3.11/site-packages/numpy/lib/function_base.py", line 5617, in append
        return concatenate((arr, values), axis=axis)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    numpy.exceptions.AxisError: axis 1 is out of bounds for array of dimension 1
    >>> 
    

    应为-

    h = [[2,4],[6,9]]

    1 回复  |  直到 2 年前
        1
  •  0
  •   shaik moeed    2 年前

    尝试使用 np.vstack ,

    np.vstack((h, i))
    

    输出:

    np.array([[2,4],[6,9]])