I have a variable called fab, and a Django queryset. As follows,
fab = self.request.GET.get('fab')
and my queryset,
queryset_df = Table1.objects.filter(Q(fab=int(fab)) | Q(fab=int(0+fab))).values_list('masks').distinct()
As seen I want to append a zero in front of the fab in my Q, because sometimes the fab comes as a integer value and sometimes with a 0 infront. When I tried to add by +, it returned me an error like, unsupported operand type(s) for +: 'int' and 'unicode'. Any idea why? Thanks in advance.
You should cast the 0 to unicode or string before concatenating.
fab = "0" + fab
You can not concatenate a unicode variable with an integer, you can also not concatenate strings with integers or floats, so you need to convert one to the correct type.
It sounds like your logic is wrong somewhere,
You are either trying to force an integer into a CharField or you are trying to force a string into an IntegerField. If its the former you're always going to struggle with having to cast values to get the correct results and if its the latter the leading 0 is pointless.
You should try to use the correct field type, it will even help with your model's validation.
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 get this error from python when I try to run my program does anyone know how to fix it.
ops.append(i+".)"+names[i]+"'s Living Quarters\n")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
ops is a array for choices.
names is a array with names to be made in to the ops array with a number for printing.
i is a increasing number for the choice number.
sorry if there have been other questions like this, I couldn't find a solution
You'll need to convert your integer to a string before you can concatenate it. You can do this with str(i).
Or you can accomplish your append line with f-strings, like so:
ops.append(f"{i}.) {names[i]}'s Living Quarters\n")
ops.append(str(i)+".)"+str(names[i])+"'s Living Quarters\n")
Should work!
str(VARIABLE) converts the VARIABLE into STR(String)
You can use an integer in a string by either converting the integer to a string using
str(variable), or by formatting it in the string using F-strings.
String formatting example:
stringName = f"Number: {integer_variable}"
Which can also be used for other variable types and is a bit more readable than concatenating a ton of variables to strings using +
There's lots of fun ways to format strings in Python. I tend to prefer string.format just because of the flexibility.
ops = "{}{}.) {}'s Living Quarters\n".format(ops, i, names[i])
Ideally, you'd include the formatting for ops in there as well, but since I didn't have the code you used to generate it , I just showed you the closest I could.
I have a panel for 5 years. Each person [aa_cod_fiscm] declares his income [cc_red_lrd] each year. I am trying to have a difference of declaration between each year and the previous one [difprev]. My code is
data["difprev"]= data.groupby(data.aa_cod_fiscm % 5).cc_red_lrd.diff()
All the variables are integers, but I get the following error
TypeError: not all arguments converted during string formatting
I don't know why. Can you help me , please?
I think your issue is that the % is being evaluated as a formatter rather than a mod function because data.aa_cod_fiscm is evaluating as a str object. Maybe this is how it is stored in that attribute? You could try casting it to an int.
try this:
data["difprev"]= data.groupby(int(data.aa_cod_fiscm) % 5).cc_red_lrd.diff()
Let's assume I have a variable tmp that is of type bytes and contains zeros and ones. I want to replace the value of the fifth position within tmp by setting an explicit value (e.g. 1).
I wonder what is a clean way to replace individual bits within an object (tmp) that has type 'Bytes'. I would like to set it directly. My attempt does not work. Help in understanding the problem in my approach would highly be appreciated.
print(tmp) # -> b'00101001'
print(type(tmp)) # -> <class 'bytes'>
tmp[3] = 1 # Expected b'00111001' but actually got TypeError: 'bytes' object does not support item assignment
Is there a function like set_bit_in(tmp, position, bit_value)?
A bytes object is an immutable object in python, you can index it an iterate it though.
You can turn it into a bytearray though, and that would be the easiest way to go about it
Or what you can do is, for example, turn it into a list, then change the value, as follows:
tmp_list = list(bin(tmp)[2:])
tmp_list[3] = '1'
The first two characters are stripped ([2:]) because they are always '0b', of course that is optional.
Also a bytesis a string representation of a byte (hence immutable), thus the assignment you want to make is = '1' not = 1
If turning to a list, then back, is not the way you wanna go you can also just copy the string representation and change the one element you wanna change.
Alternatively you can perform bitwise operations (on the int itself), if you feel comfortable with working with binaries
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.