Issue
I have bi-dimensional array, like that:
f_vars = np.array([[0,4],
[0,2],
[3,-1],
[3,4],
[1,-1]])
I am trying to replace some of the elements based on few conditions, as follow: if an element is equal to -1: leave it as is, if it is less then given variable (for example 2): increase by 1. If it is equal to 2, make it 0. If it is between two given variables (for example 2 and 4), leave it as is. If it is equal to the second variable, make it 0. If it is higher than the second variable: decrease with one.
So far I have tried the following cycle:
for i in np.nditer(f_vars):
if i < 2: f_vars[i] = f_vars[i]+1
print(f_vars)
This is only the beginning of my cycle, but the result is quite unexpected:
[[ 3 7]
[ 0 2]
[ 3 -1]
[ 3 4]
[ 2 0]]
It is modifying only the first and the last element for some reason, and the modification is not by adding 1, but quite different.
Any advice will be highly appreciated.
Solution
Using logical indexing:
f_vars[f_vars < 2] += 1
will give you:
[[1 4]
[1 2]
[3 0]
[3 4]
[2 0]]
as expected. You can continue in the same manner for applying more conditionals. You might make use of np.logical_and
to achieve multiple conditions. Take care of the order you apply the conditions and if you find it confusing, an if-elif-else
statement would be the easiest. The np.nditer
indexing is done like this:
for x in np.nditer(f_vars,op_flags = ['readwrite']):
if x == -1:
continue
elif x < 2:
x[...] += 1
So, you have to set op_flags = ['readwrite']
and index through the i[...]
syntax.
Answered By - AboAmmar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.