Reputation: 8234
I wrote the following script. I am expecting np_Xs
to be a np.int8
dtype. However, it is still np.float64
despite having declared np_Xs.astype( np.int8, copy=False )
.
from scipy.stats import norm
import numpy as np
from numpy.random import default_rng
np_samples = np.random.randint(0, 10, size=2)
print( 'np_samples' )
print( np_samples, np_samples.size, '\n' )
rg = default_rng()
np_p_all = rg.random( size=np_samples.sum() )
print( 'np_p_all' )
print( np_p_all, np_p_all.size, '\n' )
np_Xs = np.floor( norm.ppf( np_p_all, loc=15, scale=5.25 ) )
np_Xs.astype( np.int8, copy=False )
print( 'np_Xs' )
print( np_Xs, np_Xs.size, np_Xs.dtype, '\n' )
Output:
np_samples
[7 3] 2
np_p_all
[0.40001298 0.86285348 0.78885307 0.678035 0.08950794 0.15995076
0.19581122 0.29012991 0.30003468 0.89203236] 10
np_Xs
[13. 20. 19. 17. 7. 9. 10. 12. 12. 21.] 10 float64 #Why is np_Xs not a np.int8?
When I submitted the same commands via the idle terminal, np_Xs
does change to a np.int8
dtype (see below). Why did the script version of the same commands (i.e. the .astype( np.int8, copy=False )
command) not provide the correct/same output as the idle terminal version?
>>> a = np.array( [0.40001298, 0.86285348, 0.78885307, 0.678035, 0.08950794, 0.15995076, 0.19581122, 0.29012991, 0.30003468, 0.89203236] )
>>> a
array([0.40001298, 0.86285348, 0.78885307, 0.678035 , 0.08950794,
0.15995076, 0.19581122, 0.29012991, 0.30003468, 0.89203236])
>>> b = np.floor( norm.ppf( a, loc=15, scale=5.25 ) )
>>> b
array([13., 20., 19., 17., 7., 9., 10., 12., 12., 21.])
>>> b.astype( np.int8, copy=False )
array([13, 20, 19, 17, 7, 9, 10, 12, 12, 21], dtype=int8)
>>>
Also, I had tried explicitly declaring the dtype=np.int8
keyword in the np.floor()
ufunc in my script. However, it had issue too. May I know how to resolve the TypeError?
np_Xs = np.floor( norm.ppf( np_p_all, loc=15, scale=5.25 ), dtype=np.int8 )
TypeError: No loop matching the specified signature and casting was found for ufunc floor
Upvotes: 0
Views: 406
Reputation: 523
When you do np_Xs.astype( np.int8, copy=False)
, it returns the array so you have to catch it back in the variable like
np_Xs = np_Xs.astype( np.int8, copy=False)
Now even if copy=False
is set, it does not change the type inplace.
Upvotes: 2