4

I'm new to python and numpy (I'm more accustomed to R) and have been playing around with creating arrays and want to create a tall array, where the first column is just a range with custom increment, and the second column is a unif random between 0 and 1.

I have come up with the below, but it seems very clunky and not particularly readable. Are there more efficient ways of achieving the same result in one line?

import numpy as np

1stcol = np.array(np.arange(1,20,0.5), ndmin=2)
2ndcol = np.array(np.random.uniform(0,1,np.shape(d)[1]), ndmin=2)
tallmat = np.transpose(np.concatenate((d,e),axis=0))
1
  • or get rid of the extra dimension for the input arrays to get 1D arrays and use the shortcut np.c_[a, b] sometimes easier to remember than the *stack options in a pinch Commented Mar 15, 2017 at 14:47

2 Answers 2

3

Given the two columns that are to be stacked as the two columns to get the tall array, here are few approaches with np.vstack, np.row_stack and np.dstack -

np.vstack((d,e)).T
np.row_stack((d,e)).T
np.dstack((d,e))[0]

Alternatively, we could start off with 1D arrays and stack at the end with np.column_stack, like so -

d = np.arange(1,20,0.5)
e = np.random.uniform(0,1,np.shape(d)[1])
tallmat = np.column_stack((d,e))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, I wasn't aware of these - will try them out!
1

1stcol is not a valid variable name.

In terms of efficiency this is hard to beat.

In [159]: d = np.array(np.arange(1,20,0.5), ndmin=2)
     ...: e = np.array(np.random.uniform(0,1,np.shape(d)[1]), ndmin=2)
     ...: tallmat = np.transpose(np.concatenate((d,e),axis=0))

Simpler expressions for d and e are:

d = np.arange(1,20,0.5)[None,:]
e = np.random.uniform(0,1,d.shape)

You can construct the simpler 1d arrays

In [160]: a = np.arange(1,20,0.5)
     ...: b = np.random.uniform(0,1,np.shape(d)[1])

But any function that joins them will have to expand dimensions and/or transpose in one way other other. So the overall work will be similar. Your solution, while 'clunky', demonstrates a knowledge of the dimension issues required for concatenate.

With the 1d arrays, these all work

np.column_stack((a,b))
np.c_[a,b]
np.stack((a,b),axis=-1)
np.array((a,b).T

My simpler expressions for d and e suggest yet another construct - make the inputs (N,1) right from the start:

In [171]: d = np.arange(1,20,0.5)[:,None]
In [172]: e = np.random.uniform(0,1,d.shape)
In [173]: tallmat = np.concatenate((d,e), axis=1)

1 Comment

As someone new to the language, this the comprehensive analysis I was hoping for. Trying to get a sense of best practices etc. Thanks a lot!

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.