Home > Blockchain >  numpy array position of each element along one axis
numpy array position of each element along one axis

Time:11-11

I've got a numpy 2D array, let's say

a = np.arange(1,7).reshape(2,3)
array([[1, 2, 3],
       [4, 5, 6]])

and I'd like to have an array with the position of each element of this array along one axis like so:

array([[0, 1, 2],
       [0, 1, 2]])

I need this for the arguments to matplotlib.pyplot's bar3d. Is there a simple way to do this?

CodePudding user response:

Use np.tile:

import numpy as np

a = np.arange(1,7).reshape(2,3)

n_rows, n_cols = a.shape
res = np.tile(np.arange(n_cols), (n_rows, 1))
print(res)

Output

[[0 1 2]
 [0 1 2]]
  • Related