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)
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With