4

I have an array:

arr = [
  ['00', '01', '02'],
  ['10', '11', '12'],
]

I want to reshape this array considering its indices:

reshaped = [
  [0, 0, '00'],
  [0, 1, '01'],
  [0, 2, '02'],
  [1, 0, '10'],
  [1, 1, '11'],
  [1, 2, '12'],
]

Is there a numpy or pandas way to do that? Or do I have to do the good old for?

for x, arr_x in enumerate(arr):
    for y, val in enumerate(arr_x):
        print(x, y, val)
Gustavo Lopes
  • 3,794
  • 4
  • 17
  • 57
  • 1
    Do you need to keep the mix of integers and strings? A 'normal' numpy array will use one or the other, not the mix. As shown you are using lists and list notation. – hpaulj Jun 18 '19 at 18:51

2 Answers2

6

You can use np.indices to get the indices and then stitch everything together...

arr = np.array(arr)
i, j = np.indices(arr.shape)
np.concatenate([i.reshape(-1, 1), j.reshape(-1, 1), arr.reshape(-1, 1)], axis=1)
Gerges
  • 6,269
  • 2
  • 22
  • 44
1

I would use numpy.ndenumerate for that purpose, following way:

import numpy as np
arr = np.array([['00', '01', '02'],['10', '11', '12']])
output = [[*inx,x] for inx,x in np.ndenumerate(arr)]
print(*output,sep='\n') # print sublists in separate lines to enhance readibility

Output:

[0, 0, '00']
[0, 1, '01']
[0, 2, '02']
[1, 0, '10']
[1, 1, '11']
[1, 2, '12']

As side note: this action is not reshaping, as reshaping mean movement of elements, as output contain more cells it is impossible to do it with just reshaping.

Daweo
  • 31,313
  • 3
  • 12
  • 25