Language: Python 3
Platform : Jupyter Notebook
I want to count the amount of messages sent by the same user at the same date and time in a dataframe. I tried to do it using a recursive function, following this example.
Define recursive function in Pandas dataframe
below is my attempt.
interaction = 0
for i, row in df.iterrows():
if ((df2['names'].iloc[i] == (df2['names'].iloc[i-1]) & (df2['time'].iloc[i] == df2['time'].iloc[i-1]) & (df2['date'].iloc[i]== df2['date'].iloc[i-1]))
interaction = interaction
else:
interaction = interaction+1
return interaction
but it returns this error,
File "<ipython-input-171-9670327f0e8e>", line 6
interaction = interaction
^
SyntaxError: invalid syntax
I am sorry that the question is so basic, but I am bummed. I've tried changing the variabel names, but it keeps returning the same error. when I changed it into return, like this,
interaction = 0
for i, row in df.iterrows():
if ((df2['names'].iloc[i] == (df2['names'].iloc[i-1]) & (df2['time'].iloc[i] == df2['time'].iloc[i-1]) & (df2['date'].iloc[i]== df2['date'].iloc[i-1]))
return interaction
else:
return (interaction+1)
return interaction
it returns this error.
File "<ipython-input-179-99d835a6b0e6>", line 5
return interaction
^
SyntaxError: invalid syntax
I deleted colon after in if after the condition because it's a syntax error as well.
thank you for your help.
Edit: this is the error if I included the colon
File "<ipython-input-184-041229eea329>", line 5
& (df2['date'].iloc[i]== df2['date'].iloc[i-1])):
^
SyntaxError: invalid syntax
You are missing : at the end of the if statement
Related
def car_type(m):
ar=0,br=0,cr=0
for i in m:
if i=='sedan':
ar+=1
if i=='SUV':
br+=1
if i=='hatchback':
cr+=1
l.append(ar)
l.append(br)
l.append(cr)
print(l)
Error:
File "<ipython-input-7-c1c0dab37c53>", line 2
ar=0,br=0,cr=0
^ SyntaxError: can't assign to literal
What is the issue here?
It's impossible to assign multiple variables in one line like you did.
Correct syntax for multiple assignments in one line:
ar, br, cr = 0, 0, 0
If you want to assign the same values, you can use the following syntax:
ar = br = cr= 0
or just break it down into multiple lines:
ar = 0
br = 0
cr = 0
Which version is better depends on the context and the meaning of the variables.
Trying to adapt a basic profiler for bash scripts, block of code below.
Can't figure out why profiling code with a "if branch" throws exception (for example when running this code with a duplicate file). From what I've traced, it somewhere creates an extra index value. My apologies if this is trivial as I'm new to Python, but any suggestions on where could be the issue or how to remedy it would be greatly appreciated
def collect_timings(profiled_line, i):
if i == len(results) - 1:
return [0] + profiled_line
timing = float(results[i+1][1].replace(".N", "")) - float(profiled_line[1].replace(".N", ""))
return [timing] + profiled_line
Error:
Traceback (most recent call last):
File "./profile", line 67, in <module>
main(sys.argv)
File "./profile", line 51, in main
profiling_time = map(collect_timings, results, range(len(results)))
File "./profile", line 24, in collect_timings
timing = float(results[i+1][1].replace(".N", "")) - float(profiled_line[1].replace(".N", ""))
IndexError: list index out of range
Found the answer, posting in case it proves useful for someone.
The issues was a with a output redirection:
echo "Found '$file' is a duplicate of '${filecksums[$cksum]}'" >&2
That got passed as a separate entry to results:
["Found 'txt2/0122file.bck' is a duplicate of 'txt2/0113file.txt'\n"]
No idea how to make the code run with redirects, but it's not necessary, so I'll just avoid it.
you say:
if i == len(results) - 1:
below you say :
timing = float(results[i+1][1].replace(".N", ""))
so you check if "i" show the last element of results array (i.e. results has 5 cells from 0 to 4 and you check if i == 4( len(results) == 5 in this case AND NOT 4) ) and then you say results[i+1] which in the example above is equal to results[5] which is out of bounds.
Maybe you meant results[i]?
I have a function in Python that returns 5 items (I didn't develop the function so I cannot change it). If I want to give meaningful names to the return values, it will be a long line and it will exceed the 80 characters per line recommendation. So I wrote it like this:
encoded_en,
forward_h_en, forward_c_en,
backward_h_en, backward_c_en = encoder(embedding)
But then, I faced the indentation error:
File "<ipython-input-28-5947292b462a>", line 20
forward_h_en, forward_c_en
^
IndentationError: unexpected indent
What is the proper way to deal with such cases?
Use parentheses:
(encoded_en,
forward_h_en, forward_c_en,
backward_h_en, backward_c_en) = range(5)
print(encoded_en) # 0
I have downloaded a data set in xml format from online webpage. I have extracted the values tag using beautifulsoup library of python. This gives me unicode values.
graphs = soup.graphs
c = 0
for q in graphs:
name = q['title']
data = {}
for r in graphs.contents[c]:
print float(str(unicode(r.string)))
data[r['xid']] = unicode(r.string)
c = c + 1
result[name] = [data[k] for k in key]
The Source is http://charts.realclearpolitics.com/charts/1171.xml
And I want to make r.string float type
So I did
print float(str(unicode(r.string)))
print float(unicode(r.string))
But I met this err
File "<ipython-input-142-cf14a8845443>", line 73
print float(unicode(r.string)))
^
SyntaxError: invalid syntax
How could i do?
First error is imbalanced round brackets.
print float(str(unicode(r.string))))
^ 4th here
Second error, check the value whether its None or not before making the operation. Otherwise you'll get error ValueError: could not convert string to float: None
So the fix will be:
if(r.string != None):
print float(str(unicode(r.string)))
The syntax error is because of unbalanced parentheses (remove one from right). r.string is probably None, hence the TypeError
My OS doesn't support Sage 5.4 so I'm stuck with 5.0 for now.
Defining this function registers no syntax errors in python, and I don't think it makes errors in Sage 5.4 (I'd appreciate confirmation if possible.) I'd like to know why it is failing in 5.0.
def num_matchings(G):
if min(G.degree_sequence())== 0 or G.num_edges()==0:
return 0
elif G.num_edges()==1:
if G.edges()[0][2] ==None:
return 1
else:
return G.edges()[0][2]
else:
H = copy(G)
K = copy(G)
e = G.edges()[0]
if e[2] ==None:
w=1
else:
w = e[2]
H.delete_edge(e)
K.delete_vertices([e[0],e[1]])
return num_matchings(H) + w*num_matchings(K)
The first error I get when I try to define is
File "<ipython console>", line 4
==Integer(1):
^
SyntaxError: invalid syntax
and they pile on after that. To my eye, the syntax looks fine.
I'm on Mac OS 10.5 with GCC 4.0.1.
Any help much appreciated.
[Aside: typo in .delete_vertives().]
Your syntax itself is fine. From the error message, though, it looks like you've simply copied and pasted code into the console. That will only work in certain very simple cases. You're also using tabs for indentation, which can cause a whole other set of headaches too. You should really switch to 4-space tabs instead.
If you want to insert code into a live console, you can use %paste (which copies from the clipboard if it can), or %cpaste instead.
For example, if I copy and paste your code, I get:
sage: def num_matchings(G):
....: if min(G.degree_sequence())== 0 or G.num_edges()==0:
....: return 0
....: elif G.num_edges()==1:
------------------------------------------------------------
File "<ipython console>", line 4
==Integer(1):
^
SyntaxError: invalid syntax
sage: if G.edges()[0][2] ==None:
....: return 1
------------------------------------------------------------
File "<ipython console>", line 2
SyntaxError: 'return' outside function (<ipython console>, line 2)
but if I use %cpaste with the 4-space equivalent (unfortunately %paste isn't working on my 5.4.1 install at the moment):
sage: %cpaste
Pasting code; enter '--' alone on the line to stop.
:
:def num_matchings(G):
: if min(G.degree_sequence())== 0 or G.num_edges()==0:
: return 0
[etc.]
: K.delete_vertices([e[0],e[1]])
: return num_matchings(H) + w*num_matchings(K)
:--
sage: num_matchings(graphs.LadderGraph(5))
8