numpy.log10 is a "ufunc", and the method Series.apply(func) has a special test for numpy ufuncs which makes test.apply(log10) equivalent to np.log10(test). This means test, a Pandas Series instance, is passed to log10. The data type of test is object, which means that the elements in test can be arbitrary Python objects. np.log10 doesn't know how to handle such a collection of objects (it doesn't "know" that those objects are, in fact, all np.float64 instances), so it attempts to dispatch the calculation to the individual elements in the Series. To do that, it expects the elements themselves to have a log10 method. That's when the error occurs: the elements in the Series (in this case, np.float64 instances) do not have a log10 method.
A couple alternative expression that should do what you want are np.log10(test.astype(np.float64)) or test.astype(np.float64).apply(np.log10). The essential part is that test.astype(np.float64) converts the data type of the Series object from object to np.float64.
numpy.log10 is a "ufunc", and the method Series.apply(func) has a special test for numpy ufuncs which makes test.apply(log10) equivalent to np.log10(test). This means test, a Pandas Series instance, is passed to log10. The data type of test is object, which means that the elements in test can be arbitrary Python objects. np.log10 doesn't know how to handle such a collection of objects (it doesn't "know" that those objects are, in fact, all np.float64 instances), so it attempts to dispatch the calculation to the individual elements in the Series. To do that, it expects the elements themselves to have a log10 method. That's when the error occurs: the elements in the Series (in this case, np.float64 instances) do not have a log10 method.
A couple alternative expression that should do what you want are np.log10(test.astype(np.float64)) or test.astype(np.float64).apply(np.log10). The essential part is that test.astype(np.float64) converts the data type of the Series object from object to np.float64.
I had a similar error message when using the standard deviation (np.std) instead of np.log10:
'AttributeError: 'numpy.float64' object has no attribute 'sqrt',
and this although I had previously converted the Pandas object X to a numpy array via np.asarray(X).
I could solve this problem by applying the above-mentioned solution:
X = pd.read_excel('file.xls')
Y = np.asarray(X).astype(np.float64)
Z = np.std(Y,axis=0)
python - Why isn't isnumeric working? - Stack Overflow
python - 'numpy.float64' object has no attribute 'apply' - Stack Overflow
Numpy.int64 object has no attribute 'quantile'
It helps to post a full stack trace, but based on what you’ve said it sounds like you’re trying to call the quantile function on a single integer, rather than the whole column
More on reddit.com[deleted by user]
What causes the 'numpy float64 object has no attribute isnull' error in Python?
How can I fix the 'numpy float64 object has no attribute isnull' error in Python?
What are some additional tips to avoid the 'numpy float64 object has no attribute isnull' error in Python?
I am trying to plot a .txt file of lines of the form: filename.txt date magnitude V098550.txt 362.0 3.34717962317 but I am getting the error "numpy.float64' object has no attribute 'replace'". Does anyone know if this is a syntax error with numpy, or how I can resolve my issue?
import numpy as np
import matplotlib.pyplot as plt
x, y = np.loadtxt ("condensed.txt", usecols=(1, 2),
delimiter=",", unpack=True)
for ii in range (len(x)): x[ii].replace('.txt', '.lc\n') jd, npmag = np.loadtxt ("/net/jovan/export/jovan/oelkerrj/Vela/rotation/Vela/"+x[ii], usecols= (1, 2), unpack=True)
plt.scatter (jd, npmag)
plt.xlabel ('Time')
plt.ylabel ('Mag')
plt.ylim ([max (npmag), min (npmag)])
plt.show() # aftertest comment this out
fileName = x[ii][:-3] + ".png"
plt.savefig(fileName)print "done"
No, str objects do not have an isnumeric method. isnumeric is only available for unicode objects. In other words:
>>> d = unicode('some string', 'utf-8')
>>> d.isnumeric()
False
>>> d = unicode('42', 'utf-8')
>>> d.isnumeric()
True
isnumeric() only works on Unicode strings. To define a string as Unicode you could change your string definitions like so:
In [4]:
s = u'This is my string'
isnum = s.isnumeric()
This will now store False.
Note: I also changed your variable name in case you imported the module string.
I have a column filled with ints however whenever I try to run the quantile function on this column I keep getting the above error. Also min and max functions are not returning correct values. Any suggestions
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
You are using the same variable name, du, for two distinct concepts (the container for all the valid du values, and each individual du value per iteration).
Change your code to du_values = [] and du_values.append(N[j + 1]) and it should work.
As an aside, there appears to be a typo in your code - you define the original array as NP, but later refer to it as N.
Note that since you did not provide any code, the code I am going to show you is not FOR you but code I have used and SOUNDS like you could easily adopt to to your needs.
# this will simulate 1000 different combinations of my portfolio
for x in range(1000):
weights = np.random.random(len(tickers))
weights /= np.sum(weights)
portfolio_returns.append(np.sum(weights * log_returns.mean()) * 250)
portfolio_volatilities.append(np.sqrt(np.dot(weights.T, np.dot(log_returns.cov() * 250, weights))))
What this code is doing is short is 1000x it is creating random numbers and weights for my data points, and then appending the result.The code won't be uniform as it is random, but if you really wanted uniform you could simply step through the increments. However I don't think you want uniform, but rather a large enough sample size to not have it be thrown off by outliers.
A way to compare the results would be something like this.
simple_return = (mydata / mydata.shift(1)) - 1
Comparing random samples should be pretty straightforard, so if you do need help follow up. And with numpy arrays you can also filter/remove items based on criteria.
Sorry if these do not answer exactly what you are wanting, but it should get you headed in the right direction.