3

I am newbie in Python. I think I'm looking for something easy, but can't find. I have an numpy binary array, e.g.:

 [1,0,1,1,0,0,0,1,1,1,1,0]

And I want to do 2 things:

  1. Join (?) all elements into one number, so result will be:

    x=101100011110
    
  2. Next want to converse it into binary, so:

    xx=2846
    

I have an algorithm to do 2., but I don't know how to do 1. I can do it using loop, but is it possible to do it using numpy, without loop? My array will be huge, so I need the best option.

0

3 Answers 3

2
>>> int(''.join(map(str, [1,0,1,1,0,0,0,1,1,1,1,0])))
101100011110

Or with a little numpy:

>>> int(''.join(np.array([1,0,1,1,0,0,0,1,1,1,1,0]).astype('|S1')))
101100011110
Sign up to request clarification or add additional context in comments.

Comments

1

I like @timgeb's answer, but if you're sure you want to use numpy calculations directly, you could do something like this:

x = np.array([1,0,1,1,0,0,0,1,1,1,1,0])
exponents = np.arange(len(x))[::-1]
powers = 10**exponents
result = sum(powers * x)

In [12]: result
Out[12]: 101100011110

As pointed out by @Magellan88 in the comments, if you set powers=2**exponents you can get from 0 to your second part of the question in one sweep.

3 Comments

the powers should probably be 2**exponents, but other than that I would agree
That's if you want to get straight to binary from the initial array. It's a good point! I added a note on that to the answer.
I came to an old answer of yours in order to get away with the off-topic comment hat I love your avatar.
0

Since you don't want loop in first task then you can go with map method , I just wanted to show you can also try this :

import numpy as np
array=np.array([1,0,1,1,0,0,0,1,1,1,1,0])

int_con=str(array).replace(',','').replace(' ','').replace('[','').replace(']','')

print("Joined {}".format(int_con))

bin_to_de=0

for digit in int_con:
    bin_to_de=bin_to_de*2+int(digit)

print("Decimal conversion {}".format(bin_to_de))

output:

Joined 101100011110
Decimal conversion 2846

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.