Use .astype.
>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1., 2., 3., 4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])
See the documentation for more options.
Answer from kennytm on Stack OverflowUse .astype.
>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1., 2., 3., 4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])
See the documentation for more options.
While astype is probably the "best" option there are several other ways to convert it to an integer array. I'm using this arr in the following examples:
>>> import numpy as np
>>> arr = np.array([1,2,3,4], dtype=float)
>>> arr
array([ 1., 2., 3., 4.])
The int* functions from NumPy
>>> np.int64(arr)
array([1, 2, 3, 4])
>>> np.int_(arr)
array([1, 2, 3, 4])
The NumPy *array functions themselves:
>>> np.array(arr, dtype=int)
array([1, 2, 3, 4])
>>> np.asarray(arr, dtype=int)
array([1, 2, 3, 4])
>>> np.asanyarray(arr, dtype=int)
array([1, 2, 3, 4])
The astype method (that was already mentioned but for completeness sake):
>>> arr.astype(int)
array([1, 2, 3, 4])
Note that passing int as dtype to astype or array will default to a default integer type that depends on your platform. For example on Windows it will be int32, on 64bit Linux with 64bit Python it's int64. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy types like np.int32 or np.int64.
python - convert number from numpy.float64 to integer - Stack Overflow
Converting numpy dtypes to native python types - Stack Overflow
python - Convert numpy.float64 to integer - Stack Overflow
'numpy.float64' object cannot be interpreted as an integer
Use val.item() to convert most NumPy values to a native Python type:
import numpy as np
# for example, numpy.float32 -> python float
val = np.float32(0)
pyval = val.item()
print(type(pyval)) # <class 'float'>
# and similar...
type(np.float64(0).item()) # <class 'float'>
type(np.uint32(0).item()) # <class 'int'>
type(np.int16(0).item()) # <class 'int'>
type(np.cfloat(0).item()) # <class 'complex'>
type(np.datetime64(0, 'D').item()) # <class 'datetime.date'>
type(np.datetime64('2001-01-01 00:00:00').item()) # <class 'datetime.datetime'>
type(np.timedelta64(0, 'D').item()) # <class 'datetime.timedelta'>
...
(A related method np.asscalar(val) was deprecated with 1.16, and removed with 1.23).
For the curious, to build a table of conversions of NumPy array scalars for your system:
for name in dir(np):
obj = getattr(np, name)
if hasattr(obj, 'dtype'):
try:
if 'time' in name:
npn = obj(0, 'D')
else:
npn = obj(0)
nat = npn.item()
print('{0} ({1!r}) -> {2}'.format(name, npn.dtype.char, type(nat)))
except:
pass
There are a few NumPy types that have no native Python equivalent on some systems, including: clongdouble, clongfloat, complex192, complex256, float128, longcomplex, longdouble and longfloat. These need to be converted to their nearest NumPy equivalent before using .item().
If you want to convert (numpy.array OR numpy scalar OR native type OR numpy.darray) TO native type you can simply do :
converted_value = getattr(value, "tolist", lambda: value)()
tolist will convert your scalar or array to python native type. The default lambda function takes care of the case where value is already native.
I am trying to do a spectral flux analysis of an .wav input signal and I am getting this error and I don't know how to fix it. The code is:
! The errors are fixed now and the solutions are added as comments. Thank you all for the help ^
import numpy as np
from numpy.lib import stride_tricks
def stft(sig, frameSize, overlapFac=0.5, window=np.hanning):
from numpy.lib import stride_tricks
win = window(frameSize)
hopSize = int(frameSize - np.floor(overlapFac * frameSize))
# zeros at beginning (thus center of 1st window should be for sample nr. 0)
samples = np.append(np.zeros(np.floor(frameSize/2.0)), sig)
#fix error:samples = np.append(np.zeros(int(np.floor(frameSize/2.0))), sig)
# cols for windowing
#fix error:cols = int(np.ceil( (len(samples) - frameSize) /float(hopSize))+1)
cols = np.ceil( (len(samples) - frameSize) / float(hopSize)) + 1
# zeros at end (thus samples can be fully covered by frames)
samples = np.append(samples, np.zeros(frameSize))
frames = stride_tricks.as_strided(samples, shape=(cols, frameSize), strides=(samples.strides[0]*hopSize, samples.strides[0])).copy()
frames *= win
return np.fft.rfft(frames)spectral flux function:
def spectral_Flux(wavedata, window_size, sample_rate):
# convert to frequency domain
magnitude_spectrum = stft(wavedata, window_size)
timebins, freqbins = np.shape(magnitude_spectrum)
# when do these blocks begin (time in seconds)?
timestamps = (np.arange(0,timebins - 1) * (timebins / float(sample_rate)))
sf = np.sqrt(np.sum(np.diff(np.abs(magnitude_spectrum))**2, axis=1)) / freqbins
return sf[1:] #, np.asarray(timestamps)
the Error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-157-54c4d632ffbf> in <module>
----> 1 sFlux=spectral_Flux(data,512,fs)
<ipython-input-156-f14509755e4e> in spectral_Flux(wavedata, window_size, sample_rate)
1 def spectral_Flux(wavedata, window_size, sample_rate):
2 # convert to frequency domain
----> 3 magnitude_spectrum = stft(wavedata, window_size)
4 timebins, freqbins = np.shape(magnitude_spectrum)
5
<ipython-input-155-b145f5690a25> in stft(sig, frameSize, overlapFac, window)
11
12 # zeros at beginning (thus center of 1st window should be for sample nr. 0)
---> 13 samples = np.append(np.zeros(np.floor(frameSize/2.0)), sig)
14 # cols for windowing
15 cols = np.ceil( (len(samples) - frameSize) / float(hopSize)) + 1
TypeError: 'numpy.float64' object cannot be interpreted as an integerThe seccond error:
TypeError Traceback (most recent call last)
<ipython-input-193-54c4d632ffbf> in <module>
----> 1 sFlux=spectral_Flux(data,512,fs)
<ipython-input-192-f14509755e4e> in spectral_Flux(wavedata, window_size, sample_rate)
1 def spectral_Flux(wavedata, window_size, sample_rate):
2 # convert to frequency domain
----> 3 magnitude_spectrum = stft(wavedata, window_size)
4 timebins, freqbins = np.shape(magnitude_spectrum)
5
<ipython-input-191-0ee2f8ea37ed> in stft(sig, frameSize, overlapFac, window)
17 samples = np.append(samples, np.zeros(frameSize))
18
---> 19 frames = stride_tricks.as_strided(samples, shape=(cols, frameSize), strides=(samples.strides[0]*hopSize, samples.strides[0])).copy()
20 frames *= win
21
C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\stride_tricks.py in as_strided(x, shape, strides, subok, writeable)
99 interface['strides'] = tuple(strides)
100
--> 101 array = np.asarray(DummyArray(interface, base=x))
102 # The route via `__interface__` does not preserve structured
103 # dtypes. Since dtype should remain unchanged, we set it explicitly.
C:\ProgramData\Anaconda3\lib\site-packages\numpy\core\_asarray.py in asarray(a, dtype, order)
81
82 """
---> 83 return array(a, dtype, copy=False, order=order)
84
85
TypeError: 'numpy.float64' object cannot be interpreted as an integer
z_as_int64 = numpy.int64(z)
It's that simple. Make sure you have a good reason, though - there are a few good reasons to do this, but most of the time, you can just use a regular int directly.
import numpy as np
z = 3
z = np.dtype('int64').type(z)
print(type(z))
outputs:
<class 'numpy.int64'>
But i support Juliens question in his comment.