首页 > 解决方案 > 删除 Numpy 数组部分的有效方法

问题描述

我正在使用以下格式的 numpy 功能数组

[[feat1_channel1,feat2_channel1...feat6_channel1,feat1_channel2,feat2_channel2...]](所以每个通道有 6 个特征,数组形状是 1 x (number channels*features_per_channel) 或 1 x total_features)

我正在尝试从特征数组中删除指定的通道,例如:删除通道 1 意味着删除与通道 1 关联的特征 1-6。

我目前的方法如下所示:

reshaped_features = current_feature.reshape((-1,num_feats))
desired_channels = np.delete(reshaped_features,excluded_channels,axis=0)
current_feature = desired_channels.reshape((1,-1))

我将数组重塑为 number_of_channels x number_of_features,删除与我要排除的通道对应的行,然后将具有所需变量的数组重塑为 1 x total_features 的原始格式。

这种方法的问题在于它极大地减慢了我的代码,因为这个过程完成了 1000 次,所以我想知道是否有任何关于如何加快速度或替代方法的建议?

例如,给定以下特征数组:

[[0,1,2,3,4,5,6,7,8,9,10,11...48,49,50,51,52,53]]

我重塑到以下:

[[0,1,2,3,4,5],
 [6,7,8,9,10,11],
 [12,13,14,15,16,17],
 .
 .
 .
 [48,49,50,51,52,53]]

并且,例如,如果我想删除前两个通道,那么结果输出应该是:

    [[12,13,14,15,16,17],
     .
     .
     .
     [48,49,50,51,52,53]]

最后:

[[12,13,14,15,16,17...48,49,50,51,52,53]]

标签: pythonnumpy

解决方案


我找到了一个不使用 np.delete() 的解决方案,它是减速的主要原因,建立了 msi_gerva 的答案。

我找到了我想继续使用列表组合的频道

all_chans = [1,2,3,4,5,6,7,8,9,10]

features_per_channel = 5 
my_data = np.arange(len(all_chans)*features_per_channel)

chan_to_exclude = [1,3,5]

channels_to_keep = [i for i in range(len(all_chans)) if i not in chan_to_exclude]

然后重塑阵列

reshaped =  my_data.reshape((-1,features_per_channel))

然后选择我想保留的频道

desired_data = reshaped[channels_to_keep]

最后重塑成想要的形状

final_data = desired_data.reshape((1,-1))

这些更改使代码比原始方法快约 2 倍。


推荐阅读