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()
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.
This question already has answers here:
Why does Python not perform type conversion when concatenating strings?
(8 answers)
Closed 6 months ago.
print ("hello"+"world)
or
print ("hello"
+"world")
would give the output as:
hello world
however, when I try to insert a variable (int) into the print functions along with 'str' using '+', there's an error. But, when I use ','s instead, it is designed to work. That is:
x=1
print("the value of 'x' is " + x + ".")
it shows the error
TypeError: can only concatenate str (not "int") to str
But when I use:
print("the value of 'x' is ",x,".")
I get the desired output.
I would like to know why is python designed this way, what is the meaning of using '+' in this context. Thankyou.
Edit: Thanks for the replies, the intent was because in Java + means to simply put together.
Treating this operation as “+ in print function” is the wrong mental model. There are two entirely separate operations here:
print which knows it needs to derive a string to display it,
+ which knows nothing about the followup usage of its result.
Functions (and by extension methods and operators) in Python are not return type polymorphic, which is a fancy way of saying functions do not know what output type is expected from them. Just because + is used to derive the argument to print does not tell it that a string is the desired result.
The operation :str + :int has no well defined output type. What is "1" + 1? Is it 2, is it "11", is it 11 or something else? There is no clear answer for these two types and Python thus consistently raises TypeError. Whether or not the result is eventually used in print is irrelevant.
In contrast, print serves to write a string-representation of its arguments to a stream. Every argument must eventually result in a string and be written to the stream. The operation print(:str, :int) does not need to concatenate a str and int - it can separately convert each to str and write it immediately.
print() is just a function and it was designed in a way that it accepts variable number of positional arguments and it internally convert them to str.
As you can see here at it's documentation:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False):
. . .
All non-keyword arguments are converted to strings like str() does and
written to the stream, separated by sep and followed by end. Both sep
and end must be strings; they can also be None, which means to use the
default values. If no objects are given, print() will just write end.
. . .
When you do print("the value of 'x' is ",x,".") you are passing 3 distinct arguments to the function which the function gets as objects. And they are converted to string as mentioned above.
However, in the line print("the value of 'x' is " + x + ".") you're trying to concatenate the values and pass as a SINGLE argument and since the concatenation operation isn't a valid operation (python doesn't have coercion like javascript does to convert unlike types amid operations), it fails before it ever reaches the print function.
I am having problems parsing a string to a function in python.
def logAppend(self, data):
print(data)
When I parse a string with a comma in the above code it returns the following.
TypeError: logAppend() takes exactly 2 arguments (3 given)
I am kinda new to Python, so please take it easy on me if I'm missing something simple here..
It's unclear what your string is, but if you're assuming it's (self, data), those two things are actually the variables for your function. Either could be calling a string, or more likely a list of strings, that are would be ['string1', 'string2'], for example.
Can anyone tell me whats wrong with this:
put(('%s%s.tar.gz' % config.SERVER_PROJECT_PATH, config.RELEASE))
TypeError: not enough arguments for format string
I just want insert two variables in to the string, is my syntax correct?
You need to put the two values in a tuple:
put('%s%s.tar.gz' % (config.SERVER_PROJECT_PATH, config.RELEASE))
otherwise Python sees this as two separate expressions to form a tuple, '%s%s.tar.gz' % config.SERVER_PROJECT_PATH and config.RELEASE.
The syntax is incorrect. The string formatting arguments must be a tuple. You are creating a tuple with the formatted string and the second formatting argument. Use this instead:
put("%s%s.tar.gz" % (config.SERVER_PROJECT_PATH, config.RELEASE))