16

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)

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)

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?

Thanks in advance

1
  • 1
    concatenate takes a list of arrays (or tuple), It isn't restricted to a tuple of 2. And giving it just one array is usually wrong. (for a in args: a) is the wrong syntax for a list comprehension. Commented Jun 21, 2015 at 2:18

3 Answers 3

32

concatenate can accept a sequence of array-likes, such as 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). So it makes more sense to use axis=0 or omit axis entirely since the default is axis=0.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use functools.reduce along with np.append

from functools import reduce
reduce(np.append, [x1,x2,x3])

which gives

array([1, 0, 1, 0, 0, 1, 1, 1, 1])

Comments

0

Do you need to use numpy? Even if you do, you can convert numpy array to python list, run the following and covert back to numpy.array.

Adding to lists in python will concatenate them...

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.