0

I have the code below, which works, but I want a list of integers only. How do I get python to only append the integer, and not the (array) portion?

import numpy as np
import matplotlib.pyplot as p

icp4 = np.loadtxt(icp4_img)
ptm = np.loadtxt(ptm_img)

inside, outside = [], []

with np.nditer(icp4, op_flags=['readwrite']) as icp_it, np.nditer(ptm, op_flags=['readonly']) as ptm_it:
    for icp, ptm in zip(icp_it, ptm_it):
        if icp[...] > 800:
            icp[...] = 1
        else:
            icp[...] = 0
        if np.all(icp > 0):
            inside.append(ptm)
        else:
            outside.append(ptm)

p.imshow(icp4, interpolation='nearest', cmap='gray')
p.show()
print(insdie)
>>>[array(435.), array(945.), array(761.)]
1
  • adding the if ptm.shape == () does not change the output Commented May 2, 2022 at 14:00

2 Answers 2

1

It appears that each ptm is a scalar array.

To obtain the scalar equivalent of a scalar array ptm, use ptm.item() (documentation).

So instead of appending ptm to inside, try appending ptm.item().

Alternatively, appending float(ptm) should accomplish the same task. If this needs to be an integer, append int(ptm) instead.

Remark

To obtain the scalar equivalent of a scalar array, one used to be able to use numpy.asscalar(). However, that function is now deprecated. The documentation says to use the item() method instead.

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

Comments

0

If I understand properly what you are trying to do, you just need to append ptm[0] (i.e the first - and only - integer of the array ptm) instead of ptm.

2 Comments

This returns the error: IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed
Indeed, I did not notice it was a 0-dimensional array. Appending int(ptm) should work.

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.