Search code examples
pythonpython-3.xnumpynumpy-ndarraynumpy-einsum

Numpy: multiplying (1/2)^k for each row of np.array for each array in a list


Suppose I have the following list of array

dat = [np.array([[1,2],[3,4]]), np.array([[5,6]]), np.array([[1,2],[7,8],[2,3]]), np.array([[1,2],[3,4]])]

Now, for each elements in the list, I want to multiply the row of the array with (1/2)^k where k is the (index + 1) for each row.

Take the first and third array in the list as example

for np.array([[1,2],[3,4]), it would becomes like
np.array([[0.5,1],[3/4,1])

for np.array([[1,2], [7,8], [2,3]]), it would becomes like
np.array([[0.5,1], [7/4,2], [1/4, 3/8])

so the final result would be like

newdat = [np.array([[0.5,1],[3/4,1]]), np.array([[5/2, 3]]), np.array([[1/2,  1],[7/4,2],[1/4,3/8]]), np.array([[0.5, 1], [3/4,1]])]

For what i have done is just using the for loop

for i in dat:
    n = i.shape[0]
    mul = (1/2)**np.arrange(1,n+1)
    i = i*mul[:,None]

is there any better way to do this?


Solution

  • No, unfortunately not. As you have a list of np.arrays with different shapes, only way to process that list is using a for loop. You could use list comprehension, but it is more or less the same thing. (It uses for loop)

    dat = [e * (1/2)**np.arange(1, e.shape[0]+1)[:,None] for e in dat]