0

This is what I currently have:

import numpy as np

data = [0.2, 0.6, 0.3, 0.5]
vecs = np.reshape([np.arange(len(data)),data], (2, -1)).transpose()
vecs
array([[ 0.  ,  0.2],
       [ 1.  ,  0.6],
       [ 2.  ,  0.3],
       [ 3.  ,  0.5]])

This gives me the correct data as I want it, but it seems complex. Am I missing a trick?

1
  • 1
    You could use np.stack instead of reshaping and transposing? Commented Jul 30, 2020 at 9:45

2 Answers 2

2

You can simplify with np.stack and transpose:

data = np.array([0.2, 0.6, 0.3, 0.5])

np.stack([np.arange(len(data)), data], axis=1)
array([[0. , 0.2],
       [1. , 0.6],
       [2. , 0.3],
       [3. , 0.5]])

Timings -

a = np.random.random(10000)
%timeit np.stack([np.arange(len(a)), a], axis=1) 
# 26.3 µs ± 1.54 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit np.array([*enumerate(a)])
# 4.51 ms ± 156 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Sign up to request clarification or add additional context in comments.

8 Comments

I think you have one extra dimension.
Yup, just realized :) @arvin
Might I suggest the use of the axis keyword? I think it'll save you from having to do a transpose while also looking neater. Also, you can directly use range instead of np.arange, though I suppose it's a bit "hacky".
Thanks for that @arvin Forgot it had that arg. Not hacky, but why not just use np.arange? Numpy has then to cast to float anyways, so we're saving it from some work there
Timings show quite a difference @arvin . And as I say, range creates a range of integers, which would then have to be cast to float
|
2

You can try enumerate:

>>> np.array([*enumerate(data)])
array([[0. , 0.2],
       [1. , 0.6],
       [2. , 0.3],
       [3. , 0.5]])

6 Comments

Oh doh. That's very nice. But is it costly?
Given a choice between arange(len(data)) and enumerate I think enumerate would be much faster.
It turns out that it's actually quite a bit slower to utilize enumerate.
Yep, saw that. It seems like scaling issue for large arrays.
Right, I was basing my argument on range(len(data)) which returns an iterator rather than arange(len(data)).
|

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.