[英]Concatenate several np arrays in python
I have several bumpy arrays and I want to concatenate them.我有几个凹凸不平的数组,我想连接它们。 I am using
np.concatenate((array1,array2),axis=1)
.我正在使用
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)
this function returns ([1,1,1]), I want it to return ([1,0,1,0,0,1,1,1,1]).这个函数返回([1,1,1]),我希望它返回([1,0,1,0,0,1,1,1,1])。 I tried to add the for loop inside the
np.concatenate
as such我尝试在
np.concatenate
添加 for 循环
xt =np.concatenate((for a in args: a),axis=1)
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
.我既不能使用 append 也不能使用扩展,因为我必须处理
numpy arrays
而不是lists
。 Can somebody help?有人可以帮忙吗?
Thanks in advance提前致谢
concatenate
can accept a sequence of array-likes, such as args
: 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])
By the way, although axis=1
works, the inputs are all 1-dimensional arrays (so they only have a 0-axis).顺便说一下,虽然
axis=1
有效,但输入都是一维数组(所以它们只有一个 0 轴)。 So it makes more sense to use axis=0
or omit axis
entirely since the default is axis=0
.因此,使用
axis=0
或完全省略axis
更有意义,因为默认值为axis=0
。
Do you need to use numpy?你需要使用numpy吗? Even if you do, you can convert numpy array to python list, run the following and covert back to numpy.array.
即使这样做,您也可以将 numpy 数组转换为 python 列表,运行以下命令并转换回 numpy.array。
Adding to lists in python will concatenate them...添加到 python 中的列表将连接它们......
x1=[1,0,1]
x2=[0,0,1]
x3=[1,1,1]
def conc_func(*args):
xt=args[0]
print(args)
for a in args[1:]:
xt+=a
print (xt)
return xt
xt=conc_func(x1,x2,x3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.