Kunal Shah
Kunal Shah

Reputation: 614

Insert evenly spaced values to numpy array

I am trying to rewrite the following code,

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

Where

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...]

I am trying to make this into a one liner or just less lines of code (if the new solution is less efficient than the existing code then I will go back to the old way). So far I have tried using numpy insert

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

but that does not account for adding the values at the end of the array and I have to use two insert commands since I need to add two 0s at every feats+2 index.

Upvotes: 1

Views: 153

Answers (1)

user2357112
user2357112

Reputation: 280485

Reshape the two arrays to 22x8 and 22x6, and the operation simply becomes writing the second array into the first 6 columns of the first array and writing zeros into the other columns:

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

reshaped is a view of processed_feats, so writing data into reshaped writes through to processed_feats.

Upvotes: 2

Related Questions