Reputation: 343
I would like to extract matrix A (4,4) into matrix b (7,4).
Below matrix :
>>> Matrix_A = numpy.array([[[10,1.5,-3.8,8.0],[20,10.2,5.2,6.7],[30,0.5,-6.2,-7.1],[40,-0.7,-0.6,-0.5]]])
>>> Matrix_A
array([[[ 10. , 1.5, -3.8, 8. ],
[ 20. , 10.2, 5.2, 6.7],
[ 30. , 0.5, -6.2, -7.1],
[ 40. , -0.7, -0.6, -0.5]]])
>>> Matrix_B = numpy.array([[[10,2.7,4.8,-5.8],[15,-1.4,-6.4,8.1],[20,12.4,-7.1,4.9],[25,-1.5,6.2,-4.8],[30,-6.8,0.47,3.8],[35,5.4,-4.8,10.5],[40,16.2,5.7,-8.3]]])
>>> Matrix_B
array([[[ 10. , 2.7 , 4.8 , -5.8 ],
[ 15. , -1.4 , -6.4 , 8.1 ],
[ 20. , 12.4 , -7.1 , 4.9 ],
[ 25. , -1.5 , 6.2 , -4.8 ],
[ 30. , -6.8 , 0.47, 3.8 ],
[ 35. , 5.4 , -4.8 , 10.5 ],
[ 40. , 16.2 , 5.7 , -8.3 ]]])
The result I would like is :
>>> Matrix_A_extract_from_Matrix_B
array([[[ 10. , 2.7 , 4.8 , -5.8 ],
[ 20. , 12.4 , -7.1 , 4.9 ],
[ 30. , -6.8 , 0.47, 3.8 ],
[ 40. , 16.2 , 5.7 , -8.3 ]]])
And if it is possible I would like to get a matrix R containing the rest as you can see below :
>>> Matrix_R
array([[[ 15. , -1.4, -6.4, 8.1],
[ 25. , -1.5, 6.2, -4.8],
[ 35. , 5.4, -4.8, 10.5]]])
The main goal is to compare Matrix_A and Matrix_A_extract_from_Matrix_B.
My real problem is to compare matrix with thousands of lines, Matrix_A et Matrix B it is just an example to simplify the problem.
Thanks a lot for your help.
Upvotes: 0
Views: 110
Reputation: 107347
First off all since your arrays ar 3d arrays you should squeeze the size to convert them to 2d arrays for the ease of computation.
In [27]: Matrix_A = np.squeeze(Matrix_A)
In [28]: Matrix_B = np.squeeze(Matrix_B)
Then you can use np.in1d
to find the indices of the common first columns and extract them with a simple indexing:
In [29]: Matrix_B[np.in1d(Matrix_B[:, 0],Matrix_A[:, 0])]
Out[29]:
array([[ 10. , 2.7 , 4.8 , -5.8 ],
[ 20. , 12.4 , -7.1 , 4.9 ],
[ 30. , -6.8 , 0.47, 3.8 ],
[ 40. , 16.2 , 5.7 , -8.3 ]])
In [30]: Matrix_B[np.logical_not(np.in1d(Matrix_B[:, 0],Matrix_A[:, 0]))]
Out[30]:
array([[ 15. , -1.4, -6.4, 8.1],
[ 25. , -1.5, 6.2, -4.8],
[ 35. , 5.4, -4.8, 10.5]])
Upvotes: 1