简体   繁体   English

根据百分比水平拆分2D numpy数组

[英]Split 2D numpy array horizontally based on percentages

I want to be able to split 2D numpy horizontally into two splits (80% and 20%). 我希望能够将2D numpy 水平分割成两个分割(80%和20%)。 I have tried using np.vsplit() but it seems it is not made for such a case. 我已经尝试过使用np.vsplit()但似乎不适用于这种情况。 For instance, suppose I have the following matrix of size (6,3). 例如,假设我有以下大小的矩阵(6,3)。 I want to split it horizontally into 80% and 20% [roughly (5,3), (1,3)], so I tried something like this: 我想将它水平分割成80%和20%[大约(5,3),(1,3)],所以我尝试了这样的事情:

M = [[1,2,3],[4,5,6],[7,8,9], [10,11,12], [77,54,11], [424,78,98]]
M = np.asarray(M)
arr1 = np.vsplit(M, int(M.shape[0]* 0.8))[0]  # 80% of data goes to arr1
arr2 = np.vsplit(M, int(M.shape[0]* 0.2))[1]  # 20% of data goes to arr2

I know this try is incorrect but I can't fix it (actually still learning python). 我知道这个尝试是不正确的,但我无法解决它(实际上仍在学习python)。 Kindly if someone can help to modify this code. 如果有人可以帮助修改此代码。 Thank you 谢谢

You can do it like this using Indexing (or use train_test_split ): 你可以使用Indexing (或使用train_test_split )这样做:

M = [[1,2,3],[4,5,6],[7,8,9], [10,11,12], [77,54,11], [424,78,98]]
M = np.asarray(M)

split_horizontally_idx = int(M.shape[0]* 0.8) # integer for line selection (horizontal selection)

array1 = M[:split_horizontally_idx , :] # indexing/selection of the 80%
array2 = M[split_horizontally_idx: , :] # indexing/selection of the remaining 20% 

You can do it by slicing the list according to your wish. 您可以根据自己的意愿切片列表。

M = [[1,2,3],[4,5,6],[7,8,9], [10,11,12], [77,54,11], [424,78,98]]

M = np.asarray(M)

a80=M[:(round(0.8*len(M[:,2]))),:]
a20=M[:(round(0.2*len(M[:,2]))),:]
print(a80,"\n\n",a20)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM