Try this instead,
print(
"{:.3f}% {} ({} sentences)".format(pcent, gender, nsents)
)
Refer the latest docs for more examples and check the Py version!
Answer from Aditya on Stack ExchangeTry this instead,
print(
"{:.3f}% {} ({} sentences)".format(pcent, gender, nsents)
)
Refer the latest docs for more examples and check the Py version!
You could also use {:.3%} instead of {:.3f}%.
It will transform the value into percentages automatically.
That means "{:.3%}".format(0.3) will print "30%" while you have to write "{:.3f}%".format(0.3 * 100) to get "30%" as well.
Videos
Probably there's something wrong with the input values for X and/or T. The function from the question works ok:
import numpy as np
from math import e
def sigmoid(X, T):
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])
print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))
Result:
[[15 16]
[ 5 10]]
[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]
[[ 0.99999969 0.99999989]
[ 0.99330715 0.9999546 ]]
Probably it's the dtype of your input arrays. Changing X to:
X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)
Gives:
Traceback (most recent call last):
File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
print sigmoid(X, T)
File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp
You convert type np.dot(X, T) to float32 like this:
z=np.array(np.dot(X, T),dtype=np.float32)
def sigmoid(X, T):
return (1.0 / (1.0 + np.exp(-z)))
Hopefully it will finally work!
Would you please check your function code. It's not like openerp function code.
Can you check this question link: How add a function in openERP 7?
def _invoiced_rate(self, cr, uid, ids, name, args, context):
amount_untaxed = 1
record_id=ids[0]
res={record_id: 0.0}
if amount_untaxed == 0:
res[record_id] = 100.0
else:
res[record_id] = 50.0
print (res)
return res
I had need to return result in the form of dictionary object. and key should be id of that record. Just replace My function
Credits need to go to Mr.Parth Gajjar @ http://help.openerp.com forum
The error points to this line:
df['content'] = df['content'].apply(lambda x: " ".join(x.lower() for x in x.split() \
if x not in stop_words))
split is being used here as a method of Python's built-in str class. Your error indicates one or more values in df['content'] is of type float. This could be because there is a null value, i.e. NaN, or a non-null float value.
One workaround, which will stringify floats, is to just apply str on x before using split:
df['content'] = df['content'].apply(lambda x: " ".join(x.lower() for x in str(x).split() \
if x not in stop_words))
Alternatively, and possibly a better solution, be explicit and use a named function with a try / except clause:
def converter(x):
try:
return ' '.join([x.lower() for x in str(x).split() if x not in stop_words])
except AttributeError:
return None # or some other value
df['content'] = df['content'].apply(converter)
Since pd.Series.apply is just a loop with overhead, you may find a list comprehension or map more efficient:
df['content'] = [converter(x) for x in df['content']]
df['content'] = list(map(converter, df['content']))
split() is a python method which is only applicable to strings. It seems that your column "content" not only contains strings but also other values like floats to which you cannot apply the .split() mehthod.
Try converting the values to a string by using str(x).split() or by converting the entire column to strings first, which would be more efficient. You do this as follows:
df['column_name'].astype(str)
As pointed out by warren-weckesser this can also happen if you use dtype object (and in fact this is likelier the issue you are facing):
>>> s = pd.Series([1.0], dtype='object')
>>> s
0 1
dtype: object
>>> np.log(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute 'log'
You can address this by setting the dtype to float explicitly:
>>> np.log(s.astype('float64'))
0 0.0
dtype: float64
In your case:
np.log(df['price'].astype('float'))
Note: You can have more control using to_numeric.
First/alternative answer:
You have a float variable np in scope.
The problem is that:
import numpy as np
np = 1
np.log
is perfectly valid python.
>>> import numpy as np
>>> np = 1.
>>> np.log
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute 'log'
The solution is not to use np are a variable name, or other popular import abbreviations pd or dt etc.
You can pick this kind of error up using a linter.
The problem is outside of the code that you posted. Your code works. At least if I assume that df is a dict. But I cannot assume anything else, because your question does not specify it.
import numpy as np
df = {'price': 10.0}
df['ln_price'] = np.log(df['price'])
print(df)
{'price': 10.0, 'ln_price': 2.3025850929940459}
The error is pretty clear. you are trying to replace characters in a float. x probably is a float. you might want to do str(x) which gets you
f["text"] = [str(x).replace(':',' ') for x in df["text"]]
but i can't see a situation where a float contains a :
In my opinion problem is missing value in column, so use pandas methods Series.str.replace or Series.replace instead list comprehension:
df["text"] = df["text"].str.replace(':',' ')
Or:
df["text"] = df["text"].str.replace(':',' ', regex=True)
Solution with list comprehension is possible, only need if-else statement for test strings:
df["text"] = [x.replace(':',' ') if isinstance(x, str) else x for x in df["text"]]
Sample:
df = pd.DataFrame({'text':['qq:ww','e:', np.nan]})
df["text"] = df["text"].str.replace(':',' ')
print (df)
text
0 qq ww
1 e
2 NaN
The answer is already provided in the comments by @mattdmo and @tdelaney:
NumPy 1.20 (release notes) deprecated
numpy.float,numpy.int, and similar aliases, causing them to issue a deprecation warningNumPy 1.24 (release notes) removed these aliases altogether, causing an error when they are used
In many cases you can simply replace the deprecated NumPy types by the equivalent Python built-in type, e.g., numpy.float becomes a "plain" Python float.
For detailed guidelines on how to deal with various deprecated types, have a closer look at the table and guideline in the release notes for 1.20:
...
To give a clear guideline for the vast majority of cases, for the types
bool,object,str(andunicode) using the plain version is shorter and clear, and generally a good replacement. Forfloatandcomplexyou can usefloat64andcomplex128if you wish to be more explicit about the precision.For
np.inta direct replacement withnp.int_orintis also good and will not change behavior, but the precision will continue to depend on the computer and operating system. If you want to be more explicit and review the current use, you have the following alternatives:
np.int64ornp.int32to specify the precision exactly. This ensures that results cannot depend on the computer or operating system.np.int_orint(the default), but be aware that it depends on the computer and operating system.- The C types:
np.cint(int),np.int_(long),np.longlong.np.intpwhich is 32bit on 32bit machines 64bit on 64bit machines. This can be the best type to use for indexing....
If you have dependencies that use the deprecated types, a quick workaround would be to roll back your NumPy version to 1.24 or less (as suggested in some of the other answers), while waiting for the dependency to catch up. Alternatively, you could create a patch yourself and open a pull request, or monkey patch the dependency in your own code.
In the 1.24 version:
The deprecation for the aliases np.object, np.bool, np.float, np.complex, np.str, and np.int is expired (introduces NumPy 1.20). Some of these will now give a FutureWarning in addition to raising an error since they will be mapped to the NumPy scalars in the future.
pip install "numpy<1.24" to work around it.
In [1]: import numpy as np
In [2]: np.__version__
Out[2]: '1.23.5'
In [3]: np.float(3)
<ipython-input-3-8262e04d58e1>:1: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
np.float(3)
Out[3]: 3.0
Don't use module name time as keyword here:
def timer(self, time):
if (time.time() - self.lastTime) > self.time:
self.lastTime = time.time()
return True
else:
return False
I guess this is the solution you are looking for:
def timer(self, timeVal):
if (timeVal - self.lastTime) > self.time:
self.lastTime = time.time()
return True
else:
return False
import time
class lastCycle(): def init(self): self.lastTime = time.time() self.time = 0.0
def timer(self, threshold):
if (time.time() - self.lastTime) > threshold:
self.lastTime = time.time()
return True
else:
return False
The reason of AttributeError: 'float' object has no attribute 'max' error is that with your code you are calling the max() function on every (float) items of your column, you can pass the max value of your column to the normalize function:
def normalize(x, col_max):
if x == -1:
return np.nan
else:
return x/col_max
And edit the norm1 column creation code as follow:
df['norm1'] = df['score1'].apply(lambda x: normalize(x, df['score1'].max()))
Another solution, using a function that takes a series as the input rather than a scalar:
import numpy as np
import pandas as pd
df = pd.DataFrame({'key' : [111, 222, 333, 444, 555, 666, 777, 888, 999],
'score1' : [-1, 0, 2, -1, 7, 0, 15, 0, 1],
'score2' : [2, 2, -1, 10, 0, 5, -1, 1, 0]})
df['norm1'] = df['score1'].replace(-1, np.nan)
def normalize_series(s):
return (s - s.min()) / (s.max() - s.min())
df['norm1'] = normalize_series(df['norm1'])
As already mentioned, your version isn't working because you are trying to find the max of a single number, not a series.
Clearly at some point you're calling lcd_string with something that's not a string, but a float. So, when it does this:
message = message.center(LCD_WIDTH," ")
… that fails, because float objects have no center method.
The fact that it's failing in the center case means it must be one of the places where you call lcd_string(<something>, 2). My first guess would be lcd_string(avgspeed,2), because avgspeed sure sounds like something that would be a float rather than a string.
(Now that you've posted the traceback, it tells you directly what I had to guess. The line that fails is exactly the one I said it would be, and the line that called it is exactly the one I suspected would be calling it. And this is why you should always look at the tracebacks, and paste them to your SO questions—otherwise, you have to scan the code and guess.)
The reason it seems to work if you replace that with just print message is that the print command automatically stringifies its arguments, so even if you pass it a float, it will print out that float.
If you want your lcd_string function to work the same way, you can do that pretty easily by adding one line to the start of it:
message = str(message)
Alternatively, change your code to never call lcd_string with anything else. So:
lcd_string(str(avgspeed), 2)
… or, if you want more control over the formatting, something like this:
lcd_string(format(avgspeed, '.2f'), 2)
Since any developer is bound to screw that up sometimes (at least I would, and you obviously would too), and you have a hard time debugging those screwups yourself, you might want to add a line at the top of the function to give you better error messages, like:
assert isinstance(message, str)
lcd_string requires it's first parameter to be a string
Check out this post:
lcd module raspberry pi