Felix
Felix

Reputation: 139

Transpose Numpy Array (Vector)

a = np.array([0,1,2])
b = np.array([3,4,5,6,7])

...

c = np.dot(a,b)

I want to transpose b so I can calculate the dot product of a and b.

Upvotes: 1

Views: 480

Answers (4)

hpaulj
hpaulj

Reputation: 231355

Others have provided the outer and broadcasted solutions. Here's the dot one(s):

np.dot(a.reshape(3,1), b.reshape(1,5))    
a[:,None].dot(b[None,:])
a[None].T.dot( b[None])

Conceptually I think it's a bit of an overkill, but due to implementation details, it actually is fastest .

Upvotes: 0

iGian
iGian

Reputation: 11183

So with NumPy you could reshape swapping axes:

a = np.swapaxes([a], 1, 0)
# [[0]
#  [1]
#  [2]]

Then

print(a * b)

# [[ 0  0  0  0  0]
#  [ 3  4  5  6  7]
#  [ 6  8 10 12 14]]

Swapping b require to transpose the product, se here below.


Or usual NumPy reshape:

a = np.array([0,1,2])
b = np.array([3,4,5,6,7]).reshape(5,1)

print((a * b).T)

# [[ 0  0  0  0  0]
#  [ 3  4  5  6  7]
#  [ 6  8 10 12 14]]

Reshape is like b = np.array([ [bb] for bb in [3,4,5,6,7] ]) then b becomes:

# [[3]
#  [4]
#  [5]
#  [6]
#  [7]]


While reshaping a no need to transpose:

a = np.array([0,1,2]).reshape(3,1)
b = np.array([3,4,5,6,7])

print(a * b)

# [[ 0  0  0  0  0]
#  [ 3  4  5  6  7]
#  [ 6  8 10 12 14]]


Just out of curiosity, good old list comprehension:

a = [0,1,2]
b = [3,4,5,6,7]
print( [ [aa * bb for bb in b] for aa in a ] )

#=> [[0, 0, 0, 0, 0], [3, 4, 5, 6, 7], [6, 8, 10, 12, 14]]

Upvotes: 0

yatu
yatu

Reputation: 88226

Well for this what you want is the outer product of the two arrays. The function you want to use for this is np.outer, :

a = np.array([0,1,2])
b = np.array([3,4,5,6,7])

np.outer(a,b)

array([[ 0,  0,  0,  0,  0],
       [ 3,  4,  5,  6,  7],
       [ 6,  8, 10, 12, 14]])

Upvotes: 1

user8408080
user8408080

Reputation: 2468

You can use numpy's broadcasting for this:

import numpy as np

a = np.array([0,1,2])
b = np.array([3,4,5,6,7])


In [3]: a[:,None]*b
Out[3]: 
array([[ 0,  0,  0,  0,  0],
       [ 3,  4,  5,  6,  7],
       [ 6,  8, 10, 12, 14]])

This has nothing to do with a dot product, though. But in the comments you said, that you want this result.

You could also use the numpy function outer:

In [4]: np.outer(a, b)
Out[4]: 
array([[ 0,  0,  0,  0,  0],
       [ 3,  4,  5,  6,  7],
       [ 6,  8, 10, 12, 14]])

Upvotes: 5

Related Questions