问题描述
我有几个凹凸不平的数组,我想将它们连接起来.我正在使用 np.concatenate((array1,array2),axis=1)
.我现在的问题是我想让数组的数量参数化,我写了这个函数
I have several bumpy arrays and I want to concatenate them. I am using np.concatenate((array1,array2),axis=1)
. My problem now is that I want to make the number of arrays parametrizable, I wrote this function
x1=np.array([1,0,1])
x2=np.array([0,0,1])
x3=np.array([1,1,1])
def conc_func(*args):
xt=[]
for a in args:
xt=np.concatenate(a,axis=1)
print xt
return xt
xt=conc_func(x1,x2,x3)
这个函数返回([1,1,1]),我希望它返回([1,0,1,0,0,1,1,1,1]).我尝试在 np.concatenate
中添加 for 循环,例如
this function returns ([1,1,1]), I want it to return ([1,0,1,0,0,1,1,1,1]). I tried to add the for loop inside the np.concatenate
as such
xt =np.concatenate((for a in args: a),axis=1)
但我收到一个语法错误.我既不能使用 append 也不能使用扩展,因为我必须处理 numpy 数组
而不是 lists
.有人可以帮忙吗?
but I am getting a syntax error. I can't used neither append nor extend because I have to deal with numpy arrays
and not lists
. Can somebody help?
提前致谢
推荐答案
concatenate
可以接受类似数组的序列,例如 args
:
In [11]: args = (x1, x2, x3)
In [12]: xt = np.concatenate(args)
In [13]: xt
Out[13]: array([1, 0, 1, 0, 0, 1, 1, 1, 1])
顺便说一下,虽然 axis=1
有效,但输入都是一维数组(所以它们只有一个 0 轴).因此,使用 axis=0
或完全省略 axis
更有意义,因为默认值为 axis=0
.
By the way, although axis=1
works, the inputs are all 1-dimensional arrays (so they only have a 0-axis). So it makes more sense to use axis=0
or omit axis
entirely since the default is axis=0
.
这篇关于在python中连接几个np数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!