just asked a question about multiplying matrices and that can be found here, I have one more question though about multiplying matrices. Say I have the following matrices:
matrix_a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix_b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
How could I get a result like this:
[[1, 4, 9], [16, 25, 36], [49, 64, 81]]
...so that each element is basically being multiplied by the single corresponding element of the other array. Does anyone know how to do that?
Thanks guys!
You could express the element-wise product (and matrix product) using list comprehensions, zip, and the * argument-unpacking operator:
matrix_a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix_b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
elementwise_product = [[ai*bi for ai, bi in zip(*rows)]
for rows in zip(matrix_a, matrix_b)]
print(elementwise_product)
# [[1, 4, 9], [16, 25, 36], [49, 64, 81]]
matrix_product = [[sum([ai*bi for ai, bi in zip(row_a, col_b)])
for col_b in zip(*matrix_b)]
for row_a in matrix_a]
print(matrix_product)
# [[30, 36, 42], [66, 81, 96], [102, 126, 150]]
The numpy package provides an array object that can do both element-wise and matrix-wise calculations:
import numpy as np
matrix_a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix_b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix_a*matrix_b
np.dot(matrix_a, matrix_b)
This outputs:
array([[ 1, 4, 9],
[16, 25, 36],
[49, 64, 81]])
array([[ 30, 36, 42],
[ 66, 81, 96],
[102, 126, 150]])
Numpy is available using pip install numpy or by using one of the numerical python distributions such as anaconda or pythonxy.
Since those lists are equal, you can just multiply it with itself. Here is a slightly verbose way to iterate the matrix and store the result in a new one.
matrix = [[1,2,3],[4,5,6],[7,8,9]]
result_matrix = [[],[],[]]
print (matrix)
for i in range(0, len(matrix)):
for j in range(0,len(matrix[i])):
result_matrix[i].append(matrix[i][j] * matrix[i][j])
print (result_matrix)
Ouput
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 4, 9], [16, 25, 36], [49, 64, 81]]
Related
I have the following list, let's call it R:
[(array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]),
array([100, 101, 102])),
(array([[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]),
array([103, 104, 105]))]
I want to be able to delete columns of R in a for loop, based on an index i. For example, if i = 3, the 3rd column should be deleted, which should result in the following new, say R1:
[(array([[1, 2],
[4, 5],
[7, 8]]),
array([100, 101])),
(array([[10, 11],
[13, 14],
[16, 17]]),
array([103, 104]))]
I have zero experience with handling such multi dimensional arrays, so I am unsure how to use numpy.delete(). My actual list R is pretty big, so I would appreciate if someone can suggest how to go about the loop.
You can use np.delete with col==2 and axis=-1.
# if your 'list' be like below as you say in the question :
print(lst)
# [
# array([[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]]),
# array([100, 101, 102]),
# array([[10, 11, 12],
# [13, 14, 15],
# [16, 17, 18]]),
# array([103, 104, 105])
# ]
for idx, l in enumerate(lst):
lst[idx] = np.delete(l, 2, axis=-1)
print(lst)
Output:
[
array([[1, 2],
[4, 5],
[7, 8]]),
array([100, 101]),
array([[10, 11],
[13, 14],
[16, 17]]),
array([103, 104])
]
Creating input array like in the question:
import numpy as np
lst = [[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[100, 101, 102],
[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]],
[103, 104, 105]
]
lst = [np.array(l) for l in lst]
Update base comment, If you have a tuple of np.array in your list, you can try like below:
lst = [
(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), np.array([100, 101, 102])),
(np.array([[10, 11, 12], [13, 14, 15], [16, 17, 18]]), np.array([103, 104, 105]))
]
for idx, tpl in enumerate(lst):
lst[idx] = tuple(np.delete(l, 2, axis=-1) for l in tpl)
print(lst)
Output:
[
(array([[1, 2],
[4, 5],
[7, 8]]),
array([100, 101])
),
(array([[10, 11],
[13, 14],
[16, 17]]),
array([103, 104]))
]
I'm new to numpy and I'm currently working on a modeling project for which I have to perform some calculations based on two different data sources. However until now I haven't managed to figure out how I could multiply all the individual values to each other:
I have two data frames
One 2D-dataframe:
df1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
One 1D-dataframe:
df2 = np.array([1, 2, 3, 4, 5])
I would like to multiply all the individual values within the first dataframe (df1) separately with all the values that are stored within the second dataframe in order to create a data cube / new 3D-dataframe that has the shape 5x3x3:
df3 = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[2, 4, 6], [8, 10, 12], [14, 16, 18]], ..... ])
I tried different methods but every time I failed to obtain something that looks like df3.
x = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
y = np.array([1, 2, 3, 4, 5])
z = y
for i in range(len(z)):
z.iloc[i] = x
for i in range(0, 5):
for j in range(0, 3):
for k in range(0, 3):
z.iloc[i, j, k] = y.iloc[i] * x.iloc[j, k]
print(z)
Could someone help me out with some example code? Thank you!
Try this:
df1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df2 = np.array([1, 2, 3, 4, 5])
df3 = df1 * df2[:, None, None]
Output:
>>> df3
array([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[ 2, 4, 6],
[ 8, 10, 12],
[14, 16, 18]],
[[ 3, 6, 9],
[12, 15, 18],
[21, 24, 27]],
[[ 4, 8, 12],
[16, 20, 24],
[28, 32, 36]],
[[ 5, 10, 15],
[20, 25, 30],
[35, 40, 45]]])
Say I want to do a lot of matrix multiplications in Numpy; what is the fastest way?
For concreteness, say this is the problem: I have two long lists of matrices, and I want to elementwise multiply them together. That is, I have
[a_1, a_2, a_3, ..., a_N]
and
[b_1, b_2, b_3, ..., b_N],
where each a_i, b_i is an nxn matrix (n is small, say n=2), and N is large (say N = 100000), and I want to find the matrix products a_1 * b_1, a_2 * b_2, ...
What is the fastest way to do this using Python and Numpy/Scipy?
some options are:
with a for loop--this is slow since Python loops are slow.
putting the small matrices into two NxN block diagonal matrices A and B--this will result in having to multiply a much bigger matrix than needed.
using vectorize-- this is easiest to code, but isn't any faster than a for loop.
You already can multiply 3D arrays, simply put your list of arrays into numpy arrays, e.g.,
A = np.array([a_1, a_2, ..., a_N])
B = np.array([b_1, b_2, ..., b_N])
Then multiply A # B (# is the matrix multiplication operator). Here's an example using two "lists" of 3x3 arrays:
In [1]: import numpy as np
In [2]: x = np.random.randint(0, 9, (2, 3, 3))
In [3]: y = np.random.randint(0, 9, (2, 3, 3))
In [4]: x
Out[4]:
array([[[0, 4, 8],
[2, 5, 5],
[3, 0, 5]],
[[7, 6, 1],
[7, 0, 7],
[5, 2, 8]]])
In [5]: y
Out[5]:
array([[[7, 2, 6],
[6, 1, 4],
[6, 8, 5]],
[[8, 5, 4],
[8, 2, 7],
[3, 7, 0]]])
In [7]: x # y
Out[7]:
array([[[ 72, 68, 56],
[ 74, 49, 57],
[ 51, 46, 43]],
[[107, 54, 70],
[ 77, 84, 28],
[ 80, 85, 34]]])
To demonstrate that all this does is the product of each matrix at the corresponding index:
In [8]: x[0]
Out[8]:
array([[0, 4, 8],
[2, 5, 5],
[3, 0, 5]])
In [9]: y[0]
Out[9]:
array([[7, 2, 6],
[6, 1, 4],
[6, 8, 5]])
In [10]: x[0] # y[0]
Out[10]:
array([[72, 68, 56],
[74, 49, 57],
[51, 46, 43]])
In [11]: (x # y)[0]
Out[11]:
array([[72, 68, 56],
[74, 49, 57],
[51, 46, 43]])
Just use numpy.matmul or # like usual, it's a ufunc and can do broadcasting, just not on array elements but matrix subarrays. In your case, you just need to stack your (n,m) matrices in a (N,n,m) numpy array and your (m,p) matrices in a (N,m,p) numpy array.
m = np.array([[1, 3], [2,4]])
m
Out[12]:
array([[1, 3],
[2, 4]])
m # m
Out[13]:
array([[ 7, 15],
[10, 22]])
stackedm = np.stack([m,m,m])
stackedm
Out[15]:
array([[[1, 3],
[2, 4]],
[[1, 3],
[2, 4]],
[[1, 3],
[2, 4]]])
stackedm # stackedm
Out[16]:
array([[[ 7, 15],
[10, 22]],
[[ 7, 15],
[10, 22]],
[[ 7, 15],
[10, 22]]])
I have an mxn A matrix and an nxr B matrix that I want to multiply in a specific way to get an mxr matrix. I want to multiply every element in the ith column of A as a scalar to the ith row of B and the sum the n matrices
For example
a = [[0, 1, 2],
[3, 4, 5],
b = [[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]]
The product would be
a*b = [[0, 0, 0, 0], + [[4, 5, 6, 7], + [[16, 18, 20, 22], = [[20, 23, 26, 29],
[0, 3, 6, 9]] [16, 20, 24, 28]] [40, 45, 50, 55]] [56, 68, 80, 92]]
I can't use any loops so I'm pretty sure I have to use broadcasting but I don't know how. Any help is appreciated
Your input matrices are of shape (2, 3) and (3, 4) respectively and the result you want is of shape (2, 4).
What you need is just a dot product of your two matrices as
a = np.array([[0, 1, 2],
[3, 4, 5]])
b = np.array([[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]])
print (np.dot(a,b))
# array([[20, 23, 26, 29],
# [56, 68, 80, 92]])
I want to make a new list of lists when the value in the 3rd column is of the highest 10%.
My list of lists currently look like this:
[[1, -1, 10, 0]]
[[2, 1, 20, 5]]
[[3, 2, 15, 10], [4, 2, 85, 10], [5, 2, 90, 10]]
[[6, 3, 75, 11], [7, 4, 78, 11], [8, 5, 80, 11]]
[[9, 6, 13, 14]]
[[10, 7, 50, 17]]
[[11, 8, 70, 30], [12, 8, 95, 30], [13, 8, 90, 30]].....
I was thinking of something along the lines of:
M1 = max(row1)[2] (maximum value from the 3rd column)
if row1[i][2] >= M1*(0.1):
newrow1.append()
Any help would be greatly appreciated!! Thanks in advance
You can use list comprehension:
[item for item in l if item[2]>10]