0

I have some 3-dimensional array and I want to take from each array the value at the same position and then copy it into an array with the name of the position.

E.g I have three 2x2x2 array and I want to take the value at position (1,1,1) of each of those matrices and copy it into an array called 111array. This array then should contain three values The same should be done for all values and all positions in a matrix

I have a for loop which iterates over all values in one array. But I dont know how to save the result to an array in a correct way, that the array name displays the position number.

My first array is called b.

for i in range(b.shape[0]):
    for j in range(b.shape[1]):
        for k in range(b.shape[2]):
            print(b[i,j,k])

Looking for help!

3 Answers3

2

Looks like someone else beat me to an answer, but here is another way of doing it. I used a dictionary to corral all the arrays and return it from a function.

import numpy as np

b = np.array([0, 1, 2, 3, 4, 5, 6, 7])
b = np.reshape(b, (2, 2, 2))
print(b, type(b))
# [[[0 1],
#   [2 3]],
#  [[4 5],
#   [6 7]]] <class 'numpy.ndarray'>

def myfunc(arr):
    for i in range(b.shape[0]):
        for j in range(b.shape[1]):
            for k in range(b.shape[2]):
                # Create a new array name from string parts.
                name = "arr"+str(i)+str(j)+str(k)
                print(name, b[i, j, k])  
                # Example: 'arr000', 0.
                # Add a new key-value pair to the dictionary.
                mydict.update({name: b[i,j,k]}) 
    return(mydict)

mydict = {}
result = myfunc(b)
print(result)
# {'arr000': 0, 'arr001': 1, 'arr010': 2, 'arr011': 3, 'arr100': 4, 
#  'arr101': 5, 'arr110': 6, 'arr111': 7}

# You would need to unpack the dictionary to use the arrays separately.
# use "mydict.keys()" to get all array names.
# "for key in keys" to loop through all array names. 
# mydict['arr000'] will return the value 0.

Your question tags "numpy" but does not use it in your code snippet. If you are trying to stick with numpy, there is another method called "structured data array". It's similar to a dictionary in that "name" and "value" can be stored as paired sets in a numpy array. This keeps numpy's efficient memory management and fast calculation (C optimization). This matters if you are working with large datasets.

Also if working with numpy, there may be a way to use the index values in variable names.

Later, I will think of examples for both and update my answer if possible.

Jennifer Yoon
  • 791
  • 5
  • 10
0

See if this is what you want. This is based on your example.

import numpy as np
from itertools import product


a = np.arange(8).reshape(2,2,2)
b = a + 1
c = a + 2

indices = product(range(2), repeat=3)
all_arrays = []
for i in indices:
    suffix = ''.join(map(str,i))
    array_name = 'array'+suffix

    value = np.array([a[i],b[i],c[i]])
    exec(array_name+'= value')
    exec(f'all_arrays.append({array_name})')

for name in all_arrays:
    print(name)
print('\n')
print(all_arrays)
print('\n')
print(array111)
print('\n')
print(array101)

Output:

[0 1 2]
[1 2 3]
[2 3 4]
[3 4 5]
[4 5 6]
[5 6 7]
[6 7 8]
[7 8 9]

[array([0, 1, 2]), array([1, 2, 3]), array([2, 3, 4]), array([3, 4, 5]), array([4, 5, 6]), array([5, 6, 7]), array([6, 7, 8]), array([7, 8, 9])]

[7 8 9]

[5 6 7]
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
0

As others have pointed out, this seems like a weird request. But just for fun, here's a shorter solution:

In [1]: import numpy as np
   ...: A = np.arange(8).reshape((2,2,2))
   ...: B = 10*A
   ...: C = 100*A

In [2]: A
Out[2]:
array([[[0, 1],
        [2, 3]],

       [[4, 5],
        [6, 7]]])

In [3]: D = np.concatenate((A[None], B[None], C[None]))
   ...: for (a,b,c) in np.ndindex((2,2,2)):
   ...:     locals()[f'array{a}{b}{c}'] = D[:,a,b,c]
   ...:

In [4]: array000
Out[4]: array([0, 0, 0])

In [5]: array001
Out[5]: array([  1,  10, 100])

In [6]: array010
Out[6]: array([  2,  20, 200])

In [7]: array011
Out[7]: array([  3,  30, 300])

In [8]: array100
Out[8]: array([  4,  40, 400])

In [9]: array101
Out[9]: array([  5,  50, 500])

In [10]: array110
Out[10]: array([  6,  60, 600])

In [11]: array111
Out[11]: array([  7,  70, 700])
Stuart Berg
  • 17,026
  • 12
  • 67
  • 99