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.)]
CodePudding user response:
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.
CodePudding user response:
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
.