【问题标题】:Python converting lists into 2D numpy arrayPython将列表转换为二维numpy数组
【发布时间】:2016-03-13 22:38:05
【问题描述】:

我有一些列表要转换为二维 numpy 数组。

list1 = [ 2, 7 , 8 , 5]
list2 = [18 ,29, 44,33]
list3 = [2.3, 4.6, 8.9, 7.7]

我想要的numpy数组是:

[[  2.   18.    2.3]
 [  7.   29.    4.6]
 [  8.   44.    8.9]
 [  5.   33.    7.7]]

我可以通过将列表中的单个项目直接键入 numpy 数组表达式作为np.array(([2,18,2.3], [7,29, 4.6], [8,44,8.9], [5,33,7.7]), dtype=float) 来获得。

但我希望能够将列表转换为所需的 numpy 数组。

【问题讨论】:

    标签: python list numpy


    【解决方案1】:

    一种方法是创建您的numpy 数组,然后使用转置函数将其转换为您想要的输出:

    import numpy as np
    
    list1 = [ 2, 7 , 8 , 5]
    list2 = [18 ,29, 44,33]
    list3 = [2.3, 4.6, 8.9, 7.7]
    
    arr = np.array([list1, list2, list3])
    arr = arr.T
    print(arr)
    

    输出

    [[  2.   18.    2.3]
     [  7.   29.    4.6]
     [  8.   44.    8.9]
     [  5.   33.    7.7]]
    

    【讨论】:

      【解决方案2】:

      你可以直接使用np.transpose

      np.transpose([list1, list2, list3])
      

      这会将您的列表列表转换为 numpy 数组,然后将其转置(将行更改为列,将列更改为行):

      array([[  2. ,  18. ,   2.3],
             [  7. ,  29. ,   4.6],
             [  8. ,  44. ,   8.9],
             [  5. ,  33. ,   7.7]])
      

      【讨论】:

      • 任何用于创建反向尺寸重复transpose
      【解决方案3】:

      你也可以像这样使用zip函数

      In [1]: import numpy as np
      
      In [2]: list1 = [ 2, 7 , 8 , 5]
      
      In [3]: list2 = [18 ,29, 44,33]
      
      In [4]: list3 = [2.3, 4.6, 8.9, 7.7]
      
      In [5]: np.array(zip(list1,list2,list3))
      Out[5]: 
      array([[  2. ,  18. ,   2.3],
             [  7. ,  29. ,   4.6],
             [  8. ,  44. ,   8.9],
             [  5. ,  33. ,   7.7]])
      

      【讨论】:

        猜你喜欢
        • 2011-12-04
        • 2014-10-13
        • 2015-08-18
        • 1970-01-01
        • 2021-05-13
        • 2019-05-05
        • 2022-06-17
        • 1970-01-01
        • 2021-08-28
        相关资源
        最近更新 更多