【问题标题】:Numpy append list to array without merging themNumpy 将列表附加到数组而不合并它们
【发布时间】:2020-09-05 10:31:23
【问题描述】:

有一个空数组

x = numpy.empty(0)

还有两个这样的列表

l1 = [1, 2, 3]
l2 = [4, 5, 6]

如何将列表添加到空数组中,使其变成这样

np.array([[1, 2, 3], [4, 5, 6])

而不是

np.array([1, 2, 3, 4, 5, 6])

当我使用时会发生什么

x = np.append(x, l1)
x = np.append(x, l2)

【问题讨论】:

  • 你可以简单地做x = np.array([l1, l2]),如果你需要经常追加,我建议将它追加到列表中,然后在需要时转换为数组。 np.appendlist.append 贵。
  • 你的用例是什么,你为什么首先定义x = numpy.empty(0)
  • FWIW,如果你想使用np.append,代码将是:x = np.empty((0,3));x = np.append(x, [l1], axis=0);x = np.append(x, [l2], axis=0)
  • 你没有仔细阅读append文档。够了!

标签: python python-3.x numpy numpy-ndarray


【解决方案1】:

首先将列表转换为 numpy 数组以更灵活地工作

from numpy import *
l1 = [1, 2, 3]
l2 = [4, 5, 6]
l1_np = asarray(l1)
l2_np = asarray(l2)
l = concatenate([l1_np,l2_np])

【讨论】:

    【解决方案2】:
    import numpy as np
    
    x = []
    l1 = [1, 2, 3]
    l2 = [4, 5, 6]
    
    x.append(l1)
    x.append(l2)
    
    x = np.array(x)
    print(x)
    

    【讨论】:

      【解决方案3】:

      只需使用np.vstack垂直顺序堆叠数组:

      l1 = [1, 2, 3]
      l2 = [4, 5, 6]
      
      
      x = np.vstack([l1, l2])
      print(x)
      

      这个结果:

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

      【讨论】:

        【解决方案4】:

        您可以使用 reshape 来帮助自动执行附加操作

        l1 = np.array([1, 2, 3])
        l2 = np.array([4, 5, 6])
        l=np.concatenate([l1,l2])
        l.reshape((2,3))
        

        输出:

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

        【讨论】:

          猜你喜欢
          • 2021-02-21
          • 1970-01-01
          • 1970-01-01
          • 2018-08-24
          • 1970-01-01
          • 1970-01-01
          • 2019-08-26
          • 2023-04-05
          • 1970-01-01
          相关资源
          最近更新 更多