1

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?

2
  • What happens if the rows are not sorted? For example if the first row is [3, 2, 1]? Commented Nov 10, 2021 at 17:40
  • actually I just need the x position of each element, so the result would be the same Commented Nov 10, 2021 at 17:43

1 Answer 1

2

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]]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.