3

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)
1
  • 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. Commented Jun 18, 2019 at 18:51

2 Answers 2

5

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

1 Comment

one-linerized np.column_stack([*map(np.ravel, [*np.indices(np.shape(arr)), arr])])
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.

1 Comment

This still uses a for-loop though. Close but no cigar.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.