在一个数组中连接多个 numpy 数组? [英] concatenate multiple numpy arrays in one array?
本文介绍了在一个数组中连接多个 numpy 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有很多 numpy 数组:
a = ([1,2,3,4,5])b = ([2,3,4,5,6])c = ([3,4,5,6,7])
我想生成一个新的二维数组:
d = ([[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7]])
我应该编码什么?我试过用过:
d = np.concatenate((a,b),axis=0)d = np.concatenate((d,c),axis=0)
它返回:
d = ([1,2,3,4,5,2,3,4,5,6,3,4,5,6,7])
解决方案
正如评论中提到的,你可以使用 np.array
函数:
一般情况下,您希望基于not-yet-existing"维度进行堆叠,您也可以使用 np.stack
:
Assume I have many numpy array:
a = ([1,2,3,4,5])
b = ([2,3,4,5,6])
c = ([3,4,5,6,7])
and I want to generate a new 2-D array:
d = ([[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7]])
What should I code? I tried used:
d = np.concatenate((a,b),axis=0)
d = np.concatenate((d,c),axis=0)
It returns:
d = ([1,2,3,4,5,2,3,4,5,6,3,4,5,6,7])
解决方案
As mentioned in the comments you could just use the np.array
function:
>>> import numpy as np
>>> a = ([1,2,3,4,5])
>>> b = ([2,3,4,5,6])
>>> c = ([3,4,5,6,7])
>>> np.array([a, b, c])
array([[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7]])
In the general case that you want to stack based on a "not-yet-existing" dimension, you can also use np.stack
:
>>> np.stack([a, b, c], axis=0)
array([[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7]])
>>> np.stack([a, b, c], axis=1) # not what you want, this is only to show what is possible
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
[5, 6, 7]])
这篇关于在一个数组中连接多个 numpy 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文