如何基于列拆分numpy数组? [英] How to split a numpy array based on a column?
本文介绍了如何基于列拆分numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个以下形式的数组:
[[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]]
我想基于第四列将该数组拆分为多个子数组.IE.我想要一个第四列等于1的子数组,另一个第四列等于2的子数组,依此类推.我事先不知道第四列中所有可能的值是什么. >
例如,对应于第四列的子数组为1:
[[1. 2. 3. 1. 3. 3. 4. 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. 3. 4.],[1.9 2.2 1. 1. 3. 3. 4.],[1.89 2.3 1. 1. 1. 3. 3. 4.]
解决方案
列出数组:
y = [x [x [:,3] == k]对于np.unique(x [:,3])中的k
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. ]]
解决方案
To make a list of arrays:
y = [x[x[:,3]==k] for k in np.unique(x[:,3])]
这篇关于如何基于列拆分numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文