I'm trying to write a values from other arrays without using for and ifs. Say we got multiple arrays, want to check condition and later assign values to new array. Better explained in code.
What I want to do so this for and ifs but in np.where way
import numpy as np
arr = np.array([np.nan, np.nan, 30, 60, 5, 10, 55])
up_arr = np.array([np.nan, np.nan, 100, 110, 120, 130, 140])
down_arr = np.array([np.nan, np.nan, 90, 100, 110, 120, 130])
result = np.full_like(arr, np.nan, dtype=float)
result2 = np.full_like(arr, np.nan, dtype=float)
for i in range(1, len(arr)):
if arr[i] >= 50:
if up_arr[i] < result[i - 1]:
result[i] = result[i - 1]
else:
result[i] = up_arr[i]
else:
if down_arr[i] > result[i - 1]:
result[i] = result[i - 1]
else:
result[i] = down_arr[i]
result2[i] = result[i - 2]
print(result)
print(result2)
Listing 1: For-if code
output is:
[ nan nan 90. 110. 110. 110. 140.]
[ nan nan nan nan 90. 110. 110.]
What I could do so far is given below:
result = [0]
result = np.where(arr>50.0,
np.where(up_arr<result[-1], result.append(result[-1]), up_arr),
np.where(down_arr>result[-1], result.append(result[-1]), down_arr))
print(result)
Listing 2: np.where code
output is
[nan nan None 110.0 None None 140.0]
I think my problem is trying to getting last number of result array and try to append it. In addition, I couldn't find a shift function as in pandas.Series/DataFrame.shift(), is there a defined function to backshift rows in array?
So, to be more clear, I want to get result of List 1 by using np.where function as in List 2. Is there a way to do it?
source https://stackoverflow.com/questions/75226666/how-to-assign-values-a-backshifted-array-inside-np-where
Comments
Post a Comment