sh37211
sh37211

Reputation: 1523

Converting array of ints to binary in Python3: "TypeError: only integer scalar arrays can be converted?"

this is not a duplicate question as far as I can tell. I will list related-but-different questions below.

Here's the code I'm trying to run, to convert an array of ints to binary as a single vectorized operation:

import numpy as np

a = np.array([1,2,3,4],dtype=int)
b = bin(a)

----> 4 b = bin(a)

TypeError: only integer scalar arrays can be converted to a scalar index

...Um... I am literally operating on an "integer scalar array". (And changing dtype=int to something like dtype=np.int64 has no effect.)

I realize could do do this with a loop (Python 2 question), or as a list comprehension (I understand that bin produces strings), so...this post is more a question of: Why can't I do it as a single vectorized operation, and why that error message? It seems so inappropriate in this case. Any thoughts?

Related but non-dup questions: here, here, here, and here, and here.

The docs for bin read "Convert an integer number..." suggesting that arrays are just not allowed, and it's a Python function not a numpy function. (Ok, so then list comprehension or loop it is -- these just seem to be slow and I'm hoping for something fast). But then why the error message about integer scalar arrays?

Thanks.

Upvotes: 2

Views: 392

Answers (1)

Nk03
Nk03

Reputation: 14949

You need to map the function to every element of the numpy array -

import numpy as np
a = np.array([1,2,3,4],dtype=int)
b = np.array(list(map(bin,a)))

Additionally, you can check-out this link - Most efficient way to map function over numpy array

Upvotes: 1

Related Questions