0

What is the best way to concatenate column or row in numpy?

I know of numpy.append and numpy.vstack.

for example, i have 3x5 array and 3x5 array

a = numpy.zeros((3,5))
b = numpy.ones((3,5))

If I want to concatenate a and b to make 3 x 10 array, i would do

a = numpy.hstack((a,b))

If I want to concatenate a and b to make 6 x 5 array, i would do

a = numpy.vstack((a,b))

is there a more efficient(more array-ish) syntax like in R?

1
  • You need to give us a better example, such as a couple of input arrays, and the desired output. Commented Jan 31, 2015 at 20:15

2 Answers 2

3

You can do shorthand like so:

import numpy as np

a = numpy.zeros((3,5))
b = numpy.ones((3,5))

# hstack equivalent
c = np.c_[a, b]

# vstack equivalent
d = np.r_[a, b]
Sign up to request clarification or add additional context in comments.

Comments

1

hstack and vstack both end up calling concatenate, which is a compiled function. So it's as efficient as can be.

In [76]: np.concatenate([a,b],1).shape
Out[76]: (3, 10)
In [77]: np.concatenate([a,b],0).shape
Out[77]: (6, 5)
In [79]: np.array([a,b]).shape
Out[79]: (2, 3, 5)

And np.array is the basic constructor, which normally adds a dimension. The input to all of these is a list, a list of arrays, lists, or numbers.

What is special about R syntax that makes more efficient or 'arrayish'?

1 Comment

I remember it wrong. R uses rbind and cbind. THank you!!

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.