0

I am trying to create an array of binary strings each exactly 16 bits long.

I have declared an empty string array which holds up to 20 characters for each element:

bin_array = np.empty(len(dat_array), dtype="S20")

Then I assign each element using this loop:

for i in range(len(dat_array)):
binary = bin(dat_array[i])
if len(binary) < 18:
    number_of_zeros = 18 - len(binary)
    zeros = ""
    for i in range(number_of_zeros):
        zeros = zeros + "0"
    binary = "0b" + zeros + binary[2:]
bin_array[i] = binary
print bin_array[i]

at this stage, print bin_array[i] gives me every element entirely correctly, but once I am outside of the loop and check my array:

print bin_array

some elements have apparently changed to error messages and it returns something like this:

'0b1011000011010101' '0b1100000000110011' '0b1101000101101010' 
'0b1110000000101001' '0b1111000100011111' 'ject that raises an ' 
'ImportError if ctype' 's is not available.\n' '\n        Raises\n  
 ' '    ------\n        I' 'mportError\n         ' '   If ctypes is 

not ' 'available.\n\n ' '0b1000000000110100' '0b1001000101110100' '0b1010000000011111'

How can it be that each element when assigned by the for loop is exactly correct, but inside the array, some elements (and only some!) produce errors?

Alternatively if I use an empty python list, and use the for loop to .append each element, everything works fine. But I would still like to know why this is happening in numpy.

edit: when initializing values in a predefined list of len(dat_array) using the same for loop, some elements are also failing to initialize, so it seems like this is not a numpy array issue...

0

2 Answers 2

1

The problem is that you've used i as the index in both the inner and outer for loops. You can change the inner index to k, say or simply eliminate the inner loop and use zeros = number_of_zeros * "0"

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

Comments

0

You are using the same index i for your inner and outer loop, which is causing you your indexing into the numpy array to get corrupted. You should use a different index variable:

    for j in range(number_of_zeros):
        zeros = zeros + "0"

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.