将均匀间隔的值插入numpy数组

时间:2020-07-01 22:13:44

标签: python numpy

我正在尝试重写以下代码,

processed_feats[0, 0::feats+2] = current_feats[0, 0::feats]
processed_feats[0, 1::feats+2] = current_feats[0, 1::feats]
processed_feats[0, 2::feats+2] = current_feats[0, 2::feats]
processed_feats[0, 3::feats+2] = current_feats[0, 3::feats]
processed_feats[0, 4::feats+2] = current_feats[0, 4::feats]
processed_feats[0, 5::feats+2] = current_feats[0, 5::feats]
processed_feats[0, 6::feats+2] = 0
processed_feats[0, 7::feats+2] = 0

哪里

feats = 6
current_feats is a (1,132) numpy array

and the size of processed_feats should be (1,176) and 
have the following format [feat1_1,feat2_1...feat6_1,0,0,feat1_2,feat2_2...]

我试图将其变成一行或更少的代码行(如果新解决方案的效率低于现有代码,那么我将回到旧方法)。到目前为止,我已经尝试使用numpy insert

processed_feats = np.insert(current_feats,range(6,len(current_feats[0]),feats+2),0)

但是这并不能说明在数组末尾添加值的原因,我必须使用两个插入命令,因为我需要在每个专长+2索引处添加两个0。

1 个答案:

答案 0 :(得分:2)

将两个数组重塑为22x8和22x6,操作简单地变成将第二个数组写入第一个数组的前6列,并将零写入其他列:

reshaped = processed_feats.reshape((22, 8))
reshaped[:, :6] = current_feats.reshape((22, 6))
reshaped[:, 6:] = 0

reshapedprocessed_feats的视图,因此将数据写入reshaped会写入processed_feats