1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

OP's code also works when sizes are not multiples of 6 / 8.
@PaulPanzer: Are you talking about the feats != 6 case, or are you talking about what happens when the sizes of the arrays aren't multiples of feats and feats+2?
The latter. Even if this particular user won't need it others may.
Thank you for your response! I just tested the time and this solution is more efficient as well. added a reshape at the end to put it back into the desired form and it was still faster
@KunalShah: You don't need the final reshape. processed_feats already has the correct data and shape by the end of this code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.