simonalexander2005
simonalexander2005

Reputation: 4577

numpy dot on 1D and 2D array

I am trying to understand what happens in the following python code:

import numpy as np

numberList1 = [1,2,3]
numberList2 = [[4,5,6],[7,8,9]]

result = np.dot(numberList2, numberList1)

# Converting iterator to set
resultSet = set(result)
print(resultSet)

Output:

{32, 50}

I can see that it is multiplying each element in numberList1 by the element in the same position in each array within numberList2 - so {1*4 + 2*5 + 3*6 = 32},{1*7+2*8+3*9 = 50}.

But, if I change the arrays to:

numberList1 = [1,1,1]
numberList2 = [[2,2,2],[3,3,3]]

Then the output I see is

{9, 6}

Which is the wrong way around...

and, if I change it to:

numberList1 = [1,1,1]
numberList2 = [[2,2,2],[2,2,2]]

Then the output I see is just

{6}

From the documentation:

If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.

I am not enough of a mathematician to understand quite what this is telling me; or why the order of the outputs swaps around sometimes.

Upvotes: 3

Views: 923

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46921

a set is an unordered data type - and it will remove your duplicates. np.dot does not return an iterator (as mentioned in your code) but an np.ndarray which will be in the order you expect:

import numpy as np

numberList1 = [1, 2, 3]
numberList2 = [[4, 5, 6], [7, 8, 9]]

result = np.dot(numberList2, numberList1)
# [32 50]
# <class 'numpy.ndarray'>

# numberList1 = [1, 1, 1]
# numberList2 = [[2, 2, 2], [3, 3, 3]]
# -> [6 9]

Upvotes: 1

Related Questions