I have a matrix A
with 3 columns that looks something like, but much larger:
[[10 15 1.0]
[21 13 1.0]
[9 14 0.0]
[14 24 1.0]
[21 31 0.0]
...]
I want to create two separate matrices: one that contains all of the data with the third column=0.0, and another with all the data with the third column=1.0. So essentially splitting the data by the values 0.0 or 1.0 in the third column.
To split a list into n parts in Python, use the numpy. array_split() function. The np. split() function splits the array into multiple sub-arrays.
You can add lists as matrices in Python.
If you're using Numpy, first find the rows where the third column has your desired value, then extract the rows using indexing.
Demo
>>> import numpy
>>> A = numpy.array([[1, 0, 1],
[2, 0, 1],
[3, 0, 0],
[4, 0, 0],
[5, 0, 0]])
>>> A1 = A[A[:, 2] == 1, :] # extract all rows with the third column 1
>>> A0 = A[A[:, 2] == 0, :] # extract all rows with the third column 0
>>> A0
array([[3, 0, 0],
[4, 0, 0],
[5, 0, 0]])
>>> A1
array([[1, 0, 1],
[2, 0, 1]])
>>> a
array([[ 10., 15., 1.],
[ 21., 13., 1.],
[ 9., 14., 0.],
[ 14., 24., 1.],
[ 21., 31., 0.]])
>>> a[np.where(a[:,-1])]
array([[ 10., 15., 1.],
[ 21., 13., 1.],
[ 14., 24., 1.]])
>>> a[np.where(~a[:,-1].astype(bool))]
array([[ 9., 14., 0.],
[ 21., 31., 0.]])
Here's how we'd separate the matrix using list comprehensions, there's no need to import additional libraries. First, one matrix that contains all of the data with the third column is 0.0
:
[x for x in matrix if x[2] == 0.0]
And another matrix with all the data that relates to when the third column is 1.0
:
[x for x in matrix if x[2] == 1.0]
For example:
matrix = [[10, 15, 1.0],
[21, 13, 1.0],
[ 9, 14, 0.0],
[14, 24, 1.0],
[21, 31, 0.0]]
[x for x in matrix if x[2] == 0.0]
=> [[ 9, 14, 0.0],
[21, 31, 0.0]]
[x for x in matrix if x[2] == 1.0]
=> [[10, 15, 1.0],
[21, 13, 1.0],
[14, 24, 1.0]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With