How to raise the power of each array in a 2d numpy array to a power of each element in a 1d numpy array in Python?

Viewed 151

I have a numpy array filled with arrays and I want to raise each array to the power of corresponding elements in another array. To better show what I want to do here's an example:

a = np.array([2,2,2,2]) 
b = np.array([1,2,3,4])
c = np.ones((4,4))*a

The output that i'm trying to get is:

print(c[0]**b[0],c[1]**b[1],c[2]**b[2],c[3]**b[3])

Which would be: [2. 2. 2. 2.] [4. 4. 4. 4.] [8. 8. 8. 8.] [16. 16. 16. 16.]

But I'm trying to do this without using loops, I've tried this:

np.power(c,b)

But this is the result: [[ 2. 4. 8. 16.] [ 2. 4. 8. 16.] [ 2. 4. 8. 16.] [ 2. 4. 8. 16.]]

I've been looking online for some sort of solution for this problem, but I could not find anything or at least I could not phrase it properly enough to find it.

1 Answers

You need to be aware of broadcasting rules, which line up dimensions on the right. Two arrays of shapes

4, 4
   4

A do not give what you want. But the following will:

4, 4
4, 1

You can add a unit dimension like this:

c**b[:, None,]

or

c**b.reshape(-1, 1)

or any number of other ways.

Related