1

I am trying to convert the below to integers

I have a variable p which is the below

array([0.09641092, 0.02070604, 0.21679783, ..., 0.06453979, 0.02907993, 0.12129478])

I want to convert the numbers based on a threshold

thres = 0.5

then convert

p1 = np.int(p > thres)

but i get the below error

TypeError: only size-1 arrays can be converted to Python scalars

3 Answers 3

1

You want to convert the type of the array. Accordingly, do this instead:

(p > thres).astype(np.int)
Sign up to request clarification or add additional context in comments.

Comments

1

np.int is just int, the normal Python built-in type. I think it's only even in the numpy namespace for backward compatibility. It's not a NumPy type, and you can't perform type conversion on arrays by calling it.

np.int_ is the NumPy type for the dtype int values get converted to by default, and it's the one used when you do something like some_array.astype(int). It corresponds to C long. np.int_, you can call to type-convert whole arrays:

>>> x = numpy.array([True, False, True])
>>> numpy.int_(x)
array([1, 0, 1])

but it's more usual to use astype:

>>> x.astype(int)
array([1, 0, 1])

Comments

-1
import numpy as np
a = np.array([0.09641092, 0.02070604, 0.21679783, 0.06453979, 0.02907993, 0.12129478])
t = 0.05
for i in range(len(a)):
if(a[i]>t):
    print(a[i])

output:

0.09641092
0.21679783
0.06453979
0.12129478

or

print(np.int(a[i]))

output:

0
0
0
0

1 Comment

I don't think that answers the question that OP (original poster) asked. They want to change all the values, not just select based on threshold.

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.