Konchog
Konchog

Reputation: 2188

Pythonic/Numpy way of converting a 1D array into 2D vector array of indexed values

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?

Upvotes: 0

Views: 55

Answers (2)

yatu
yatu

Reputation: 88226

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)

Upvotes: 2

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You can try enumerate:

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

Upvotes: 2

Related Questions