0

I need to pad a numpy array at the start of the array if it is not 8 bits long.
For example:

If I have an array which is [1 0 0] it should be [0 0 0 0 0 1 0 0].
However, if it is already [1 0 0 0 0 0 0 0] (8 bits long), I do not have to do anything with it.


Thanks

2 Answers 2

3

Use numpy.pad in constant mode with a pad_width (8-len(a), 0) which pads 8-len(a) zeros to the left, and nothing to the right:

a = [1, 0, 0]

np.pad(a, (8-len(a), 0), 'constant')
# array([0, 0, 0, 0, 0, 1, 0, 0])
Sign up to request clarification or add additional context in comments.

Comments

0

First, calculate the width you need to pad. Then make an array with zeros of the calculated width. After that, concatenate this array with your original array. Check the code snippet below:

pad_width = 8 - length_of_your_array
pad_array = np.zeros(pad_width)
desired_array = np.concatenate((pad_array, your_array))

Comments

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.