【问题标题】:how to combine two arrays of different types and put them as a list如何组合两个不同类型的数组并将它们作为列表
【发布时间】:2019-08-01 10:14:09
【问题描述】:

我有如下两个 numpy 数组

A = [1,2,3,1,2,3,1,2,3] #integers
B = ['xx','xx','xx','yy','yy','yy','zz','zz''zz'] #strings

我想合并并存储为一个列表,例如:

AB_list = [[1,'xx'],[2,'xx'],[3,'xx'],[1,'yy'],[2,'yy'],[3,'yy'],[1,'zz'],[2,'zz'],[3,'zz'],]

有人可以帮忙吗?

【问题讨论】:

  • 看看zip函数。

标签: python-3.x list numpy


【解决方案1】:

像这样使用列表理解和 zip 迭代器的东西应该可以工作:

A = np.array([1,2,3,1,2,3,1,2,3]) #integers
B = np.array(['xx','xx','xx','yy','yy','yy','zz','zz','zz'])
[ [a,b] for a,b in zip(A,B) ]
Out[29]: 
[[1, 'xx'],
 [2, 'xx'],
 [3, 'xx'],
 [1, 'yy'],
 [2, 'yy'],
 [3, 'yy'],
 [1, 'zz'],
 [2, 'zz'],
 [3, 'zz']]

【讨论】:

    【解决方案2】:

    首先,您的列表“B”中缺少一个逗号

    B = ['xx','xx','xx','yy','yy','yy','zz','zz','zz']
    

    修复后,你可以使用 column_stack 得到想要的结果

    import numpy as np    
    A = [1,2,3,1,2,3,1,2,3]
    B = ['xx','xx','xx','yy','yy','yy','zz','zz','zz']
    
    np.column_stack((A, B))
    

    输出:

    array([['1', 'xx'],
           ['2', 'xx'],
           ['3', 'xx'],
           ['1', 'yy'],
           ['2', 'yy'],
           ['3', 'yy'],
           ['1', 'zz'],
           ['2', 'zz'],
           ['3', 'zz']], dtype='<U21')
    

    【讨论】:

    • 这是不正确的,因为它改变了整数的类型
    • 同意,错过了。 @talonmies 解决方案效果很好
    猜你喜欢
    • 2021-12-15
    • 2020-02-20
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多