I've got a value that is of the type:
'pandas._libs.tslibs.timestamps.Timestamp'
but I want to convert it into:
'int'
Simply using int() doesn't work and gives me the following error message:
int() argument must be a string, a bytes-like object or a number, not 'Timestamp'
Edit: to be clear, I only want the type to change to integral. However I want the number to stay the same.
You should use the class (pandas._libs.tslibs.timestamps.Timestamp) methods. pandas._libs.tslibs.timestamps.Timestamp.timestamp() returns the timestamp, however it is a float instead of an int.
Related
I encountered the error
'>' not supported between instances of 'str' and 'int'
while trying to print the below lines in Pandas dataframe
print (survey_df_clean.shape)
print (survey_df_clean[survey_df_clean['text']>30].shape)
Should I try to convert them to int and how would that work in this statement?
First make sure that all value of survey_df_clean['text'] is the same, if you want to convert as numeric, do this :
survey_df_clean['text'] = pd.to_numeric(survey_df_clean['text'])
Then do this
survey_df_clean.loc[survey_df_clean['text']>30].shape
This message suggests, that you try to compare a string object (str) with an integer (int).
The expression
survey_df_clean['text']
will probably return a string. Therefore, you cannot directly compare it with the number 30. If you want to compare the length of the entry, you can use the pandas.Series.str.len() operation as you can see here.
If this field should actuallty contain an integer, you can use this method (pandas.to_numeric) to cast it from str to int.
survey_df_clean['text'] might have NAN or str values in it some where.
to find out :
survey_df_clean['text'].isnull().sum()
if they are,first take care of them then apply
print (survey_df_clean[survey_df_clean['text']>30].shape)
I had the same error message when trying to use that conditional. What intrigued me was that the same command had run correctly on another notebook.
The difference was in how I read the csv file. This was the troublesome one:
df=pd.read_csv('data.csv')
And when I put the decimal argument it worked:
df=pd.read_csv('data.csv', decimal=',')
Obviously, it'll depend on how your data is organized. ;)
This is because values in 'text' column are of type str and you are comparing str with int.
You can do a quick check for getting type of 'text' column.
print(type(survey_df_clean['text'][:1][0]))
For comparing you can do as following
survey_df_clean[survey_df_clean['text'].astype(int)>30]
I am a newbie to programming and I recently came across this error. I am working on the Space Analysis dataset from Kaggle and the Price column is a panda series. I tried using astype() to convert it into float and int which was working fine a while ago but now it shows me the Value error. When the astype() is removed the TypeError: '<' not supported between instances of 'str' and 'int' occurs.
df_money = df_.groupby(["Organisation"])["Price"].sum().reset_index()
df_money["Price"] = df_money["Price"].astype('float')
df_money = df_money[df_money["Price"]>0]
df_money.head()
Error was:
ValueError: invalid literal for int() with base 10: '48.5200.048.5200.0200.0200.037.0200.037.0200.0200.037.0200.0200.037.0200.0200.037.0200.037.0200.0200.0200.037.0200.0200.037.0200.037.0200.0200.0200.0200.037.0200.0200.0200.0200.037.0200.0200.037.0200
This means some record in your Price column likely has a string with the literal value "48.5200.048.5200.0200.0200.037.0200.037.0200.0200.037.0200.0200.037.0200.0200.037.0200.037.0200.0200.0200.037.0200.0200.037.0200.037.0200.0200.0200.0200.037.0200.0200.0200.0200.037.0200.0200.037.0200"
This string format cannot be naively converted to a number, and thus the conversion fails.
Later you do a comparison between that column and > 0. Python, while dynamic, is still strongly typed, meaning that you can only usually compare values of the same type. A string isn't a number and cannot be compared to a number, hence the TypeError if the Pricing column contains strings.
To resolve your issue, you will have to somehow convert your long string to something that can be converted to a number. You can typically only convert something with a single decimal separator. For example, float("48.5200") will work, but float("48.5200.048") won't.
I believe your groupby.sum() is probably creating this long string. Convert the Price column to a float before doing the groupby operation.
Here I'am trying to build a simple calculator using tkinter and I have used some number images as buttons,i want only numbers and mathematical characters to be entered in entry box,but when i press the number button i get AttributeError: 'int' object has no attribute 'isnumeric' error, I didn't get the solution for this problem:
here is my code and below code is function for tkinter button:
def press(n):
new=value.get()
if new=="Can't divide by zero" or new=="Can't perform operation":
new=''
if n.isnumeric() or n=='+' or n=='-' or n=='*' or n=='/' or n=='%' or n=='.':
new+=str(n)
value.set(new)
The python isnumeric() method expects a string and checks if the characters in the string are numeric. If you're already passing n into def press(n) as an integer there is no reason to check if it's numeric and it's expecting a string which is why you get the AttributeError: 'int' object has no attribute 'isnumeric'. Your input should be a string, not an int literal.
The python isnumeric() method expects a string and checks if the characters in the string are numeric
as bpiekars said, and you can try:
str(n).isnumeric()
In my python server code, I am getting all arguments as strings. I am unaware of the original type of the argument.
For example,
if the actual value is integer 10, the argument received is string value '10'
if the actual value is string "apple". The argument received is unchanged string 'apple'
if the actual value is float 10.0 , the argument received is string value '10.0'
What is the best way to detect the right type of the argument and cast them back to 'int' in the first example, 'string' in the second example, 'float' in the third example?
Ideally, you want to fix the client code so it doesn't throw away type information in the first place. Or, if you can't do that, you at least want to know what the rule is for how these strings are generated, so you can work out how to reverse the rule.
But if neither of those is possible, and you need to guess, one possibility is something like this:
def parseval(s):
try:
return int(s)
except ValueError:
pass
try:
return float(s)
except ValueError:
pass
return s
This will treat anything that could be a valid int as an int, anything that can't be a valid int but could be a valid float as a float, and anything else as a str.
In the special case where the output comes from just calling repr or str in Python, you may want this:
import ast
def parseval(s):
try:
return ast.literal_eval(s)
except ValueError:
return s
This will convert any Python literal, or any collection display made up of literals and other collection displays made up of etc. recursively, to the original value, but leave anything else as itself. (If you know the client is using repr rather than str, you should leave off the try/except. But if it's using str, this works, because it relies on the fact that, for every kind of literal but strings, the str is interpretable as a repr.)
However, note that this makes it impossible to, e.g., send the string "10" to your server.
can someone tell me what is wrong with this code...
def format_money_value(num):
return u'{0:.2f}'.format(num)
It gives me the following error:
Unknown format code 'f' for object of type 'unicode'
I'm running Django 1.5
Thank you
In your case num is a unicode string, which does not support the f format modifier:
>>> '{0:.2f}'.format(u"5.0")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'f' for object of type 'unicode'
You can fix the error making the conversion to float yourself:
>>> '{0:.2f}'.format(float(u"5.0"))
'5.00'
As pointed out by mgilson when you do '{0:.2f}'.format(num), the format method of the strings calls num.__format__(".2f"). This results in an error for str or unicode, because they don't know how to handle this format specifier. Note that the meaning of f is left as an implementation for the object. For numeric types it means to convert the number to a floating point string representation, but other objects may have different conventions.
If you used the % formatting operator the behaviour is different, because in that case %f calls __float__ directly to obtain a floating point representation of the object.
Which means that when using %-style formatting f does have a specific meaning, which is to convert to a floating point string representation.
what .format() do
str.format method calls __format__() method of related type. That means
<type>.__format__(<value>, <spec>)
above method accepts the same type argument as first value, and accepts a suitable spec type
as second one. Like,
str.__format__('1', 's')
int.__format__(1, 'f')
float.__format__(1.00, 'f')
str.__format__ accepts any type that is derived from str type, like str or unicode. Spec value must be a valid formatter that is usable of that type. Following will raise an error
str.__format__('1', 'f')
ValueError: Unknown format code 'f' for object of type 'str'
since floating point formatting is not a suitable format type fot string. Likewise following will raise an error too
float.__format__(1.00, 's')
ValueError: Unknown format code 's' for object of type 'float'
since float is a numeric type and can not formatted as a string. But following are all valid:
float.__format__(1.00, 'g')
float.__format__(1.00, 'f')
similarly following will raise an exception
float.__format__(1.00, 'd')
ValueError: Unknown format code 'd' for object of type 'float'
since formatting a float point to a decimal value will cause precision values to be lost. But formatting an int to float will not cause a such thing, so it is a valid conversion:
int.__format__(1, 'f')
So .format() is limeted to specs that is available to the related formatting type. You must parse your value as #Bakuriu defined:
'{0:.2f}'.format(float(u"5.0"))
The scenario where you are re-formatting a string (unicode or otherwise) as a float string is not very safe. You should first convert the string to a numeric representation and only if that succeeds should you format it as a string again. You are not in control of the data that comes into your program so you should be sure to validate it coming in.
If you choose to leave it as a string you can use this:
return u"{:.2f}".format(num) if num.isnumeric() else u"{}".format(num)
If you have already converted the string into a numeric format, you can adjust your formatter like this:
return u"{:.2f}".format(num) if isinstance(num, NumberTypes) else u"{}".format(num)
I've faced a similar problem as the OP, when num was a numerical answer returned by one of my libraries, whose implementation detais got forgotten:
>>> num
-4132.56528214700
>>> u'{0:.4g}'.format(num)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'g' for object of type 'unicode'
I was really puzzled because num behaved like a float but after testing #Bakuriu 's solution, I've found out it wasn't a float:
>>> type(num)
<class 'sympy.core.numbers.Float'>
So #Bakuriu 's solution was right on target for my case:
>>> u'{0:.4g}'.format(float(num))
u'-4133'
Therefore, the error can be due to types that display/calculate like but aren't really floats.