Home > OS >  Python Numpy Calculate with Prior Value -- No Loop
Python Numpy Calculate with Prior Value -- No Loop

Time:10-30

I'm looking for a vectorized solution that doesn't use a loop. The 2nd column is equal to the average of the prior value in the 2nd column and the current value in the 1st column. The exception is the first row. And it's the only value we start with so we must calculate as we go.

I can solve this with a loop but that's not helpful to my question.

starting array
[[ 1.  2.  3.]
 [ 4. nan nan]
 [ 7. nan nan]
 [ 8. nan nan]]
-------
populate 2nd column
[[1.  2.  3. ]
 [4.  3.  nan]
 [7.  5.  nan]
 [8.  6.5 nan]]

    a = np.asarray([[1,2,3],[4,np.nan,np.nan],[7, np.nan, np.nan], [8, np.nan, np.nan]])
    print("starting array")
    print(a)
    a[1:,1] = a[1:,0]*.5   a[0:-1,1]*.5
    a[1:,1] = a[1:,0]*.5   a[0:-1,1]*.5
    a[1:,1] = a[1:,0]*.5   a[0:-1,1]*.5
    print("-------")
    print("populate 2nd column")
    print(a)

CodePudding user response:

You can try this:

import numpy as np

# first column of the array
col1 = np.array([1, 4, 7, 8])
# first value of the second column
top2 = 2

# compute the second column
N = len(col1)
weights = 0.5**np.arange(1, N)
col2 = np.r_[top2, np.convolve(col1[1:], weights)[:N-1]   top2 * weights]
print(col2)

This gives:

[2.  3.  5.  6.5]
  • Related