I'm looking to convert a 3d array (720,2800,3) into 3 distinct 2d arrays (3x 720,2800) that can be saved and called upon individually. Ideally, they would automatically be converted and named according to 3rd dimension, i.e the first slice would be 'arr1', second 'arr2', and third 'arr3' without naming each array individually. I'm extremely new to python and whatnot, so apologies if this is a stupid question.
Thanks
CodePudding user response:
If you start naming things like arr1, arr2, etc. it is a sure sign you should be using a collection of some kind, not individual variables. This is especially true if you are hoping for automated names. In your case, you can simply reshape (or possibly transpose depending on your exact requirements) your arrays so you can index them the way you want. Instead of arr1, arr2 you can use arr[0], arr[1]:
x = np.arange(5*4*3).reshape([5, 4, 3])
print(x.shape)
# (5, 4, 3)
arr = x.reshape(3, 5, 4)
print(arr[0].shape, arr[1].shape, arr[2].shape)
# (5, 4), (5, 4), (5, 4)
Numpy allows a lot of flexibility for reshaping and transposing, so you should be able to get any reorganization you want so long as the total number of elements doesn't change.
CodePudding user response:
You can use the exec function:
for ii in range(arr.shape[-1]):
exec(f"arr{ii 1} = arr[:,:,ii]")
However, I would recommend using a dictionary rather than creating multiple named variables:
myarrs = {}
for ii in range(arr.shape[-1]):
myarrs[ii 1] = arr[:,:,ii]
This will allow you to loop over the arrays, and allow you to avoid more exec calls in subsequent lines of code.
