猿问

使用numpy将基于二维数组的列拆分为python中的两个二维数组

我有一个由 19 行和 1280 列组成的二维数组。我想将它分成 2 个数组,由 19 行组成,70% 的列用于训练,30% 的列用于测试。这些列是随机选择的。我的代码在 python 中.请帮助我。谢谢



郎朗坤
浏览 334回答 1
1回答

潇潇雨雨

编辑为包括随机洗牌您可以使用slicing将数组切片为所需的形状并numpy.random.shuffle()获得随机数组索引。import numpy as npfrom copy import deepcopy# create example datanum_cols, num_rows = 10, 3arr = np.array([[f'{row}_{col}' for col in range(num_cols)] for row in range(num_rows)])# create a list of random indicesrandom_cols = list(range(arr.shape[1]))np.random.shuffle(random_cols)# calculate truncation index as 70% of total number of columnstruncation_index = int(arr.shape[1] * 0.7)# use arrray slicing to extract two sub_arraystrain_array = arr[:, random_cols[:truncation_index]]test_array = arr[:, random_cols[truncation_index:]]print(f'arr: \n{arr} \n')print(f'train array: \n{train_array} \n')print(f'test array: \n{test_array} \n')带输出arr: [['0_0' '0_1' '0_2' '0_3' '0_4' '0_5' '0_6' '0_7' '0_8' '0_9'] ['1_0' '1_1' '1_2' '1_3' '1_4' '1_5' '1_6' '1_7' '1_8' '1_9'] ['2_0' '2_1' '2_2' '2_3' '2_4' '2_5' '2_6' '2_7' '2_8' '2_9']] train array: [['0_5' '0_8' '0_0' '0_7' '0_6' '0_1' '0_4'] ['1_5' '1_8' '1_0' '1_7' '1_6' '1_1' '1_4'] ['2_5' '2_8' '2_0' '2_7' '2_6' '2_1' '2_4']] test array: [['0_3' '0_9' '0_2'] ['1_3' '1_9' '1_2'] ['2_3' '2_9' '2_2']]
随时随地看视频慕课网APP

相关分类

Python
我要回答