Lanc Lanc - 9 months ago 139
Python Question

How to split a numpy array based on a column?

I have an array of the form :

[[ 1. , 2., 3., 1., 3., 3., 4. ],
[ 1.3, 2.3, 3.3, 3., 3.3, 3.3, 4.3 ],
[ 1.2, 2.2, 3.2, 2., 3.2, 3.2, 4.2 ],
[ 1.1, 2.1, 1., 1., 3., 3., 4. ],
[ 1.3, 2.3, 3.5, 3., 3.3, 3.3, 4.3 ],
[ 1.2, 2.7, 3.2, 2., 3.2, 3.2, 4.2 ],
[ 1.3, 2.2, 1., 1., 3., 3., 4. ],
[ 1.3, 2.3, 3.6, 3., 3.3, 3.3, 4.3 ],
[ 1.2, 2.8, 3.2, 2., 3.2, 3.2, 4.2 ],
[ 1.4, 2.3, 1., 1., 3., 3., 4. ],
[ 1.3, 2.3, 3.7, 3., 3.3, 3.3, 4.3 ],
[ 1.2, 2.9, 3.2, 2., 3.2, 3.2, 4.2 ],
[ 1.5, 2.1, 1., 1., 3., 3., 4. ],
[ 1.89, 2.3, 3.5, 3., 3.3, 3.3, 4.3 ],
[ 1.2, 2.7, 3.2, 2., 3.2, 3.231, 4.2 ],
[ 1.9, 2.2, 1., 1., 3., 3., 4. ],
[ 1.3, 2.22, 3.6, 3., 3.3, 3.3, 4.3 ],
[ 1.2, 2.8, 3.2, 2., 3.66, 3.2, 4.2 ],
[ 1.89, 2.3, 1., 1., 3., 3., 4. ],
[ 1.3, 2.99, 3.7, 3., 3.3, 3.3, 4.3 ],
[ 1.2, 2.9, 3.2, 2., 3.34, 3.2, 4.2 ]]


I want to split this array into a number of subarrays based on the fourth column. I.e. I want one subarray whose fourth column is equal to 1, another one where the fourth column is equal to 2, etc. I do not know in advance what all possible values are there in fourth column.

For instance, the subarray corresponding to fourth column being 1 is :

[[ 1. 2. 3. 1. 3. 3. 4. ],
[ 1.1 2.1 1. 1. 3. 3. 4. ],
[ 1.3 2.2 1. 1. 3. 3. 4. ],
[ 1.4 2.3 1. 1. 3. 3. 4. ],
[ 1.5 2.1 1. 1. 3. 3. 4. ],
[ 1.9 2.2 1. 1. 3. 3. 4. ],
[ 1.89 2.3 1. 1. 3. 3. 4. ]]

Answer Source

To make a list of arrays:

y = [x[x[:,3]==k] for k in np.unique(x[:,3])]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download