Python Numpy-附加三个数组以形成矩阵或3D数组 [英] Python Numpy - attach three arrays to form a matrix or 3D array

查看:213
本文介绍了Python Numpy-附加三个数组以形成矩阵或3D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的简单代码段

一切都是一个numpy数组.我也欢迎使用列表进行操作.

Everything is a numpy array. I welcome manipulation using lists too.

a = [1,2,3,4,5]
b = [3,2,2,2,8]

c = ['test1', 'test2', 'test3','test4','test5']

预期结果:

d = [ 1, 2, 3, 4, 5; 
      3, 2, 2, 2, 8;
      'test1','test2', 'test3', 'test4','test5' ]

OR

 d = [ 1  3   'test1';
       2   2    'test2';
       3   2   'test3';
        4   2   'test4';
        5   8    'test5']

使用numpy.concat

推荐答案

亚当的答案也是正确的,但是在指定期望的确切形状(垂直堆叠的行)方面,您需要查看

Adam's answer using numpy.concat is also correct, but in terms of specifying the exact shape you are expecting — rows stacked vertically — you'll want to look at numpy.vstack:

>>> import numpy as np
>>> np.vstack([a, b, c])
array([['1', '2', '3', '4', '5'],
       ['3', '2', '2', '2', '8'],
       ['test1', 'test2', 'test3', 'test4', 'test5']], 
        dtype='<U21')

无论哪种方式,这里都有一个陷阱:由于您单独的数组(int64int64<U5)都被放在一起了,所以新数组将自动使用限制最小的类型,在这种情况下为unicode类型.

There's a catch here either way you do it: since your separate arrays (int64, int64, <U5) are all being put together, the new array will automatically use the least restrictive type, which in this case is the unicode type.

另请参阅:numpy.hstack.

这篇关于Python Numpy-附加三个数组以形成矩阵或3D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆