3

I have a numpy array of dimensions Nx8, with dtyp=boolean I want to convert it into a numpy 1-d array where each row is turned into a byte, by bin2dec

x = array([[ True,  True, False, False,  True,  True, False, False],
       [ False,  False, False, False,  True,  True, False, False],
       [ True,  False, False, False,  False,  False, False, False]], dtype=bool)

I'd like the output to be:

y = array([204 ,12, 128], dtype=uint8)
7
  • Im trying to encode each line into an integer Commented Oct 22, 2013 at 12:28
  • but whats up with the dimensions? (and how big is N going to be?) Commented Oct 22, 2013 at 12:30
  • what is the question exactly? X is a 3x8 array, i want to turn each line of 8 booleans into a single int, so the output would be a 1-d array of length 3 and dtype int8. N is potentially quite large, can be 10,000-20,000 Commented Oct 22, 2013 at 12:34
  • So where does the 204 come from? Commented Oct 22, 2013 at 12:36
  • 2
    This is actually an excellent question. I'm not sure why you're getting downvoted (other than mistyping int8 instead of uint8). Commented Oct 22, 2013 at 12:59

2 Answers 2

9
>>> np.packbits(np.uint8(x))
array([204,  12, 128], dtype=uint8)

How that?

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

1 Comment

I'd go with x.view(np.uint8), because I know for sure it doesn't copy any data. Other than that, +1.
1

I guess this will do:

import numpy
x = numpy.array([[ True,  True, False, False,  True,  True, False, False],
       [ False,  False, False, False,  True,  True, False, False],
       [ True,  False, False, False,  False,  False, False, False]], dtype=bool)
x2 = 1*x # makes True become 1 and False become 0
x3 = numpy.zeros((3), dtype = numpy.uint8) # change 3 to 20000 or whatever the length of your array is
for j in range(x2.shape[1]):
    x3 += x2[:,j]*(2**(7-j))
print x3
[204  12 128]

Tell me how long it takes for your long array, if it goes too slow, i will try to push the for-loop down to numpy to speed it up. (needs to be uint8 instead of int8, otherwise the result is [ -52 12 -128])

edit: should actually not be that slow, since the for-loop only runs 8 times (once per float)

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.