0

I know in R there is a rbind function:

list = c(1,2,3)
blah = NULL
blah = rbind(blah,list)

How would I replicate this in python? I know you could possible write:

a = NULL
b= array([1,2,3])
for i in range(100):
 a = np.vstack((a,b))

but I am not sure what to write in the a=NULL spot. I am essentially looping and adding rows to a table. What's the most efficient way to do this?

1
  • Do you know the size a priori? Commented Mar 27, 2013 at 21:50

2 Answers 2

1

In numpy, things will be more efficient if you first pre-allocate space and then loop to fill that space than if you dynamically create successively larger arrays. If, for instance, the size is 500, you would:

a = np.empty((500, b.shape[0]))

Then, loop and enter values as needed:

for i in range(500):
    a[i,:] = ...

Note that if you really just want to repeat b 500 times, you can just do:

In [1]: import numpy as np

In [2]: b = np.array([1,2,3])

In [3]: a = np.empty((500, b.shape[0]))

In [4]: a[:] = b

In [5]: a[0,:] == b
Out[5]: array([ True,  True,  True], dtype=bool)
Sign up to request clarification or add additional context in comments.

4 Comments

I write a = np.empty((500, 500)) and loop and set a[1,:] =b but get an error saying output operand requires a reduction
edited to make the 2nd part more clear, though Ophion's answer is better if you're really just trying to copy an array X times.
nvm i just did a[i,:] = b.reshape(,500)
what is b.shape? If it is asking for a reduction, that's likely because b.shape != (a.shape[1],)
1

To answer your question exactly

a = []
b= np.array([1,2,3])
for i in xrange(100):
  a.append(b)
a = np.vstack( tuple(a) )

The tuple function casts an iterable (in this case a list) as a tuple object, and np.vstack takes a tuple of numpy arrays as argument.

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.