I'm trying to write an array of values within two nested loops over another ndarray with at the corresponding position. Enumerate does not work, because of the increments.
For example:
#Base np.array
basearray =np.array([[10, 20, 30, 40, 50],
[15, 16, 17, 18, 19],
[25, 26, 27, 28, 29],
[35, 36, 37, 38, 39]])
resulting_array=np.zeros((4,4))
#nested for loops with increments
for x in basearray[::2]:
for y in x[::2]:
#the magic happens here
#result I am trying to achieve:
resulting_array = [['result', 0, 'result', 0, 'result'],
[0, 0, 0, 0, 0],
['result', 0, 'result', 0, 'result'],
[0, 0, 0, 0, 0]]
How can I solve that?
Very best and thank you in advance
Christian
CodePudding user response:
If you are intialising zeroes in the form of list the desired output can be achievable
Code:-
import numpy as np
basearray=np.array([[10, 20, 30, 40, 50],
[15, 16, 17, 18, 19],
[25, 26, 27, 28, 29],
[35, 36, 37, 38, 39]])
resulting_array1=([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
for lis in range(0,len(basearray)-1,2):
for y in range(0,len(basearray[0]),2):
resulting_array1[lis][y]='result'
print(resulting_array1)
Output:-
[['result', 0, 'result', 0, 'result'], [0, 0, 0, 0, 0], ['result', 0, 'result', 0, 'result'], [0, 0, 0, 0, 0]]
Points to remember:-
(1) The elements of a NumPy array must all be of the same type. you can not change integer type to string type result
Code:-2 Using np array
import numpy as np
basearray=np.array([[10, 20, 30, 40, 50],
[15, 16, 17, 18, 19],
[25, 26, 27, 28, 29],
[35, 36, 37, 38, 39]])
resulting_array2=np.array([['0 ', '0', '0 ', '0', '0 '],
['0', '0', '0', '0', '0'],
['0 ', '0', '0 ', '0', '0 '],
['0', '0', '0', '0', '0']])
for lis in range(0,len(basearray)-1,2):
for y in range(0,len(basearray[0]),2):
resulting_array2[lis][y]='result'
print(resulting_array2)
Output:-
[['result' '0' 'result' '0' 'result']
['0' '0' '0' '0' '0']
['result' '0' 'result' '0' 'result']
['0' '0' '0' '0' '0']]
Note you have to give spaces in 0 when initialising..!
i.e if you give two spaces with 0 it will return only res
so to return result you have to write 0 with 4 spaces to print result
CodePudding user response:
If I understood correctly, one approach is to do:
import numpy as np
basearray = np.array([[10, 20, 30, 40, 50],
[15, 16, 17, 18, 19],
[25, 26, 27, 28, 29],
[35, 36, 37, 38, 39]])
resulting_array = np.zeros((4, 5))
resulting_array[::2, ::2] = basearray[::2, ::2]
print(resulting_array)
Output
[[10. 0. 30. 0. 50.]
[ 0. 0. 0. 0. 0.]
[25. 0. 27. 0. 29.]
[ 0. 0. 0. 0. 0.]]