title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Text file manipulation - insert a newline character after the first two characters in a line
38,573,769
<p>I have a text file that looks like this:</p> <pre><code>XX number number number XY number number number ... XN number number number </code></pre> <p>XX, XY etc have either 1 or 2 characters and the numbers can be either positive or negative, it doesn't really matter. What I would like to figure out (but I can't, f...
0
2016-07-25T17:12:55Z
38,573,834
<p><a href="https://docs.python.org/2/library/stdtypes.html#str.replace" rel="nofollow"><code>str.replace()</code></a> seems like a good choice, espcially if you want to modify every single line.</p> <pre><code>with open('input.txt') as input_file: with open('output.txt', 'w') as output_file: for line in i...
2
2016-07-25T17:16:47Z
[ "python", "file" ]
Text file manipulation - insert a newline character after the first two characters in a line
38,573,769
<p>I have a text file that looks like this:</p> <pre><code>XX number number number XY number number number ... XN number number number </code></pre> <p>XX, XY etc have either 1 or 2 characters and the numbers can be either positive or negative, it doesn't really matter. What I would like to figure out (but I can't, f...
0
2016-07-25T17:12:55Z
38,573,890
<pre><code>import re with open('input.txt') as input_file: with open('output.txt', 'w') as output_file: for line in input_file: splitter = re.search("\d", line).start() output_file.write(line[:splitter].strip() + "\n") output_file.write(line[splitte...
0
2016-07-25T17:20:39Z
[ "python", "file" ]
Biopython/EMBOSS WindowsError [Error 2]
38,573,775
<p>I am trying to locally align a set of around 100, very long (>8000 sequence) sequences using the biopython wrapper for EMBOSS.</p> <p>Essentially I need to locally align each sequence in my fasta file against every other sequence in that fasta file. Thus far I have tried to run the very basic code below:</p> <pre>...
1
2016-07-25T17:13:09Z
38,576,236
<p>can you try absolute paths for seq_fname1, seq_fname2 as well? Also, i hope you are trying this out in elevated command prompt</p> <p>Moving it to answer from comments :)</p>
0
2016-07-25T19:49:55Z
[ "python", "biopython", "emboss" ]
Python Email attachment loses end-of-newline "\n"
38,573,786
<p>My python script (as the following) can send a ".txt" attachment, but unfortunately the received attachment lost the "\n", so all lines are together which ruined my column format. Can anyone please give me a help? Thanks a lot!</p> <pre><code>msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] ...
0
2016-07-25T17:13:42Z
38,578,940
<pre><code>import smtplib import io sender = 'from@fromdomain.com' receivers = ['to@todomain.com'] file = io.open('newfile.txt', 'r') message = file.readlines() try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print("Successfully sent email") except Exception: pri...
0
2016-07-25T23:34:55Z
[ "python", "email", "format", "attachment" ]
Python Email attachment loses end-of-newline "\n"
38,573,786
<p>My python script (as the following) can send a ".txt" attachment, but unfortunately the received attachment lost the "\n", so all lines are together which ruined my column format. Can anyone please give me a help? Thanks a lot!</p> <pre><code>msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] ...
0
2016-07-25T17:13:42Z
38,624,360
<p>Thanks to @gixxer's hint. It is the format problem of the txt file itself. The end-of-line character in the original txt is "\n" which works well on Unix system, but not on Windows. Windows uses "\r\n" instead. So I just add "\r\n" to the end of each line in the original file, and then it works.</p>
0
2016-07-27T22:39:58Z
[ "python", "email", "format", "attachment" ]
How to assert that a type equals a given value
38,573,862
<p>I am writing a test for a method and I want to validate that the method returns a specific type. However, when I try this I get an error. </p> <pre><code>def search_emails(mail): data = mail.uid('search') raw_email = data[0][1] return raw_email </code></pre> <p>The type(raw_email) is: <code>&lt;class 'by...
0
2016-07-25T17:18:49Z
38,573,929
<p>You need to use isinstance, its a built in function for type checking</p> <pre><code>def test_search_emails_returns_bytes(): result = email_handler.search_emails(mail) assert isinstance(result, bytes) </code></pre>
1
2016-07-25T17:23:11Z
[ "python", "python-3.x", "py.test" ]
How to assert that a type equals a given value
38,573,862
<p>I am writing a test for a method and I want to validate that the method returns a specific type. However, when I try this I get an error. </p> <pre><code>def search_emails(mail): data = mail.uid('search') raw_email = data[0][1] return raw_email </code></pre> <p>The type(raw_email) is: <code>&lt;class 'by...
0
2016-07-25T17:18:49Z
38,574,776
<p>If you want to check that something is specifically of a class, isinstance won't do, because that will return True even if it is a derived class, not exactly the class you want to check against. You can get the type as a string like this:</p> <pre><code>def decide_type(raw_prop): """Returns the name of a type o...
1
2016-07-25T18:15:02Z
[ "python", "python-3.x", "py.test" ]
How to assert that a type equals a given value
38,573,862
<p>I am writing a test for a method and I want to validate that the method returns a specific type. However, when I try this I get an error. </p> <pre><code>def search_emails(mail): data = mail.uid('search') raw_email = data[0][1] return raw_email </code></pre> <p>The type(raw_email) is: <code>&lt;class 'by...
0
2016-07-25T17:18:49Z
38,575,275
<p>You can use the <code>is</code> operator to check that a variable is of a specific type</p> <pre><code>my_var = 'hello world' assert type(my_var) is str </code></pre>
1
2016-07-25T18:44:45Z
[ "python", "python-3.x", "py.test" ]
Generate XML files based on rows in CSV
38,573,991
<p>I have a CSV and would like generate an <strong>XML file based on each row in the CSV</strong>. Right now it creates an XML file but only with the <strong>last row in the CSV</strong>. How can I modify this script to generate an XML file for EACH row. And ideally have <strong>the filename based on the Column: "Fi...
0
2016-07-25T17:27:17Z
38,579,395
<p>You set the value of Root here:</p> <pre><code>for row in csv.DictReader(f): root = Element('gmd:MD_Metadata') tree = ElementTree(root) filename = row.items()[7] # where 7 is the column your interested in for k, v in row.items(): child = SubElement(root, k) child.text = v re...
0
2016-07-26T00:35:09Z
[ "python", "xml", "python-2.7", "csv", "elementtree" ]
Generate XML files based on rows in CSV
38,573,991
<p>I have a CSV and would like generate an <strong>XML file based on each row in the CSV</strong>. Right now it creates an XML file but only with the <strong>last row in the CSV</strong>. How can I modify this script to generate an XML file for EACH row. And ideally have <strong>the filename based on the Column: "Fi...
0
2016-07-25T17:27:17Z
38,581,021
<p>You only want to create the <code>csv.DictReader()</code> class once, rather than for each iteration of your loop.</p> <p>Similarly, you only want to create your <code>root</code> XML element once.</p> <p>Finally, the order of the items returned from <code>row.items()</code> is arbitrary, and not reflective of the...
0
2016-07-26T04:27:59Z
[ "python", "xml", "python-2.7", "csv", "elementtree" ]
Given 3 dicts of varying size, how would I find the intersections and values?
38,574,001
<p>I looked up intersections of dictionaries, and tried to use the set library, but couldn't figure out how to show the values and not just pull out the keys to work with them, so I'm hoping for some help. I've got three dictionaries of random length:</p> <pre><code>dict_a= {1: 488, 2: 336, 3: 315, 4: 291, 5: 275} di...
1
2016-07-25T17:27:46Z
38,574,578
<pre><code> lst = [dict_a,dict_b,dict_c] total_intersect_key = set(dict_a) &amp; set(dict_b) &amp; set(dict_c) total_intersect = { k:[ item[k] for item in lst ] for k in total_intersect_key} </code></pre> <p>output:</p> <pre><code>{1: [488, 61, 1.15], 2: [336, 0, 0.11]} </code></pre> <p>for other question...
1
2016-07-25T18:03:19Z
[ "python", "dictionary" ]
Given 3 dicts of varying size, how would I find the intersections and values?
38,574,001
<p>I looked up intersections of dictionaries, and tried to use the set library, but couldn't figure out how to show the values and not just pull out the keys to work with them, so I'm hoping for some help. I've got three dictionaries of random length:</p> <pre><code>dict_a= {1: 488, 2: 336, 3: 315, 4: 291, 5: 275} di...
1
2016-07-25T17:27:46Z
38,575,140
<p>I hope this might help</p> <pre><code>dict_a= {1: 488, 2: 336, 3: 315, 4: 291, 5: 275} a = set(dict_a) dict_b={2: 0, 3: 33, 1: 61, 5: 90, 15: 58} b = set( dict_b) dict_c= {1: 1.15, 9: 0, 2: 0.11, 15: 0.86, 19: 0.008, 20: 1834} c = set( dict_c ) a_intersect_b = a &amp; b a_intersect_c = a &amp; c b_intersect_c ...
0
2016-07-25T18:36:49Z
[ "python", "dictionary" ]
OOP techniques with Python GUI (PySide) elements
38,574,025
<p><strong>Objective:</strong> create a line item object that contains a textbox for a label, value, and value units in PySide.</p> <p><strong>Background:</strong> I am creating a control panel for a device that is run off of a Raspberry Pi using Python PySide (QtPython) to handle the GUI. I am using the grid layout, ...
1
2016-07-25T17:29:24Z
38,597,031
<p>You just need a <code>QWidget</code> subclass to act as a container for the other widgets. Its structure will be very similar to a normal form - the main difference is that it will end up as a child widget of another form, rather than as a top-level window.</p> <pre><code>class LineItem(QWidget): def __init__(s...
1
2016-07-26T18:09:41Z
[ "python", "python-2.7", "class", "pyside", "encapsulation" ]
Unable to get data in form of list in django jquery
38,574,036
<p>here is the script</p> <pre><code>var size = []; var formdata = new FormData(); $("input[name='size']:checked").each(function() { size.push($(this).val()); }); formdata.append('size[]' , size) $.ajax({ type: "POST", data: formdata, url : "{% url 'data_entry' %}...
0
2016-07-25T17:30:13Z
38,574,060
<p>You can split your string using the <code>split()</code> method:</p> <pre><code>size = [u'L,M,S'] size = size[0].split(',') # [u'L', u'M', u'S'] </code></pre>
1
2016-07-25T17:31:58Z
[ "jquery", "python", "django" ]
Django logout makes trouble with the error : Reverse for 'logout' with arguments '()' and keyword arguments '{}' not found
38,574,057
<p>My error is below : </p> <blockquote> <p>Reverse for 'logout' with arguments '()' and keyword arguments '{}' not found</p> </blockquote> <p>My 'urls.py' is below :</p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',HomeView.as_view(), name='home'), url(r'^about/$',AboutView.as_view(), na...
0
2016-07-25T17:31:37Z
38,574,184
<p>You have a comma in the regex that shouldn't be there. Replace </p> <pre><code>url(r'^logout/$,', views.logoutView, name='logout'), </code></pre> <p>with</p> <pre><code>url(r'^logout/$', views.logoutView, name='logout'), </code></pre>
2
2016-07-25T17:39:32Z
[ "python", "django", "django-urls" ]
Should I use `__setattr__`, a property or...?
38,574,070
<p>I have an object with two attributes, <code>file_path</code> and <code>save_path</code>. Unless <code>save_path</code> is explicitly set, I want it to have the same value as <code>file_path</code>.</p> <p>I <em>think</em> the way to do this is with <code>__setattr__</code>, with something like the following:</p> <...
4
2016-07-25T17:32:41Z
38,574,167
<p>First, the easiest way to do this would be with a property:</p> <pre><code>class Class(object): def __init__(self, ...): self._save_path = None ... @property def save_path(self): if self._save_path is None: return self.file_path else: return self._...
9
2016-07-25T17:38:40Z
[ "python" ]
Should I use `__setattr__`, a property or...?
38,574,070
<p>I have an object with two attributes, <code>file_path</code> and <code>save_path</code>. Unless <code>save_path</code> is explicitly set, I want it to have the same value as <code>file_path</code>.</p> <p>I <em>think</em> the way to do this is with <code>__setattr__</code>, with something like the following:</p> <...
4
2016-07-25T17:32:41Z
38,574,220
<p>Use <code>super</code>!</p> <pre><code>class Class: def __init__(self): self.save_path = None self.file_path = None ...
1
2016-07-25T17:41:44Z
[ "python" ]
Should I use `__setattr__`, a property or...?
38,574,070
<p>I have an object with two attributes, <code>file_path</code> and <code>save_path</code>. Unless <code>save_path</code> is explicitly set, I want it to have the same value as <code>file_path</code>.</p> <p>I <em>think</em> the way to do this is with <code>__setattr__</code>, with something like the following:</p> <...
4
2016-07-25T17:32:41Z
38,574,269
<p>this looks kind of unpythonic. You can just use attributes. Three lines of code:</p> <pre><code>&gt;&gt;&gt; class Class: ... def __init__(self, file_path, save_path=None): ... self.file_path=file_path ... self.save_path = save_path or file_path ... &gt;&gt;&gt; c = Class('file') &gt;&gt;&gt;...
3
2016-07-25T17:44:28Z
[ "python" ]
OneHotEncoded features causing error when input to Classifier
38,574,222
<p>I’m trying to prepare data for input to a Decision Tree and Multinomial Naïve Bayes Classifier.</p> <p>This is what my data looks like (pandas dataframe)</p> <pre><code>Label Feat1 Feat2 Feat3 Feat4 0 1 3 2 1 1 0 1 1 2 2 2 2 1 1 3 3 ...
0
2016-07-25T17:41:46Z
38,587,625
<p>First, you have to swap <code>chk</code> and <code>Y</code> consider <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.cross_val_score.html" rel="nofollow"><code>cross_val_score</code></a> documentation. Next, you didn't specify what is <code>Y</code> so I hope it's a 1d-array. And t...
1
2016-07-26T10:39:54Z
[ "python", "pandas", "machine-learning", "scikit-learn", "categorical-data" ]
Using Stanford nlp's sentiment engine with python parser?
38,574,254
<p>I am working on a project where I am planning to use the <a href="http://nlp.stanford.edu/sentiment/" rel="nofollow">Stanford's sentiment analysis model</a> to do my sentiment analysis. </p> <p>I have tried NLTK's stanford parser but couldn't get the sentiment analysis module in it. Can anyone point me to that modu...
0
2016-07-25T17:43:32Z
38,609,385
<p>(from same question <a href="http://stackoverflow.com/questions/32879532/stanford-nlp-for-python">here</a> )</p> <hr> <p>I am facing the same problem : maybe a solution with <a href="https://github.com/e5c/stanford_corenlp_py" rel="nofollow">stanford_corenlp_py</a> that uses <code>Py4j</code> as pointed out by @ro...
0
2016-07-27T09:45:13Z
[ "python", "nltk", "stanford-nlp", "sentiment-analysis" ]
How to align entry and label in the same row within a scrollable frame?
38,574,314
<p>My code is using a vertical scrolled frame (from <a href="http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame" rel="nofollow">here</a>). Currently "Name:Ryan", and the entry box are not aligned in the same row. I wanted to align the entry box and the label so they are on the same column, and I messed around wi...
0
2016-07-25T17:47:01Z
38,574,567
<p>Try creating intermediate frames in which to hold each row, like so:</p> <pre><code>class SampleApp(Tk): def __init__(self, *args, **kwargs): root = Tk.__init__(self, *args, **kwargs) self.label = Label(text="Choose the info to exclude (if any) on the \n left." "...
1
2016-07-25T18:02:45Z
[ "python", "python-3.x", "tkinter" ]
How to align entry and label in the same row within a scrollable frame?
38,574,314
<p>My code is using a vertical scrolled frame (from <a href="http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame" rel="nofollow">here</a>). Currently "Name:Ryan", and the entry box are not aligned in the same row. I wanted to align the entry box and the label so they are on the same column, and I messed around wi...
0
2016-07-25T17:47:01Z
38,575,515
<p>If you want to lay things out in a grid, your best choice is to use <code>grid</code> rather than <code>pack</code>.</p> <p>For example:</p> <pre><code>self.frame2.interior.grid_columnconfigure(1, weight=1) for i in range(10): resource.append(Entry(self.frame2.interior, width=3)) label.append(Label(self.f...
2
2016-07-25T18:58:25Z
[ "python", "python-3.x", "tkinter" ]
Close main Tkinter window binding a key
38,574,355
<p>I do not understand why this code does not work:</p> <pre><code>import tkinter class Application (): def__init__(self): self.master = tkinter.Tk() self.master.bind("&lt;Enter&gt;", self.quit) self.master.mainloop() def quit (self): self.master.destroy() my_app = Application(...
0
2016-07-25T17:49:57Z
38,574,757
<p>Simply add another variable to the quit method ("i","n",etc.), when you bind an event to a method, the method must be able to handle said event as a parameter.</p> <pre><code>import tkinter class Application (): def __ init __ (self): self.master = tkinter.Tk() self.master.bind("&lt;Enter&gt;",...
1
2016-07-25T18:13:41Z
[ "python", "tkinter" ]
Using Regex to match numbers on rows of different size in Python
38,574,364
<p>I have a file that contain positive and negative numbers in row of different sizes. I am trying to extract the numbers using regex.However, it is skips some rows as below.</p> <p>Part of the Input file:</p> <pre><code>. . . ...s -- -0.28096 -0.27907 -0.27770 -0.27730 -0.27573 ...s -- -0.27149 -0.27076 -0...
1
2016-07-25T17:50:14Z
38,574,455
<p>Don't use regex.</p> <pre><code>import io text = ''' ...s -- -0.28096 -0.27907 -0.27770 -0.27730 -0.27573 ...s -- -0.27149 -0.27076 -0.27036 -0.26883 -0.26794 ...s -- -0.26114 -0.26098 0.25950 -0.25891...
0
2016-07-25T17:55:51Z
[ "python", "regex", "matching" ]
Using Regex to match numbers on rows of different size in Python
38,574,364
<p>I have a file that contain positive and negative numbers in row of different sizes. I am trying to extract the numbers using regex.However, it is skips some rows as below.</p> <p>Part of the Input file:</p> <pre><code>. . . ...s -- -0.28096 -0.27907 -0.27770 -0.27730 -0.27573 ...s -- -0.27149 -0.27076 -0...
1
2016-07-25T17:50:14Z
38,574,498
<p>Your regex only allows negative numbers, and it also requires at least 5 numbers in a line.</p> <p>Try <code>(?&lt;=s\s\S\S\s)(\s\s[- ]\d+\.\d+)+</code>.</p>
0
2016-07-25T17:58:10Z
[ "python", "regex", "matching" ]
What does this daemonize method do?
38,574,461
<p>I was looking around on GitHub, when I stumbled across this method called <code>daemonize()</code> in a reverse shell example. <sup><a href="https://gist.github.com/gdamjan/3025923" rel="nofollow">source</a></sup></p> <p>What I don't quite understand is what it does in this context, wouldn't running this code from ...
0
2016-07-25T17:56:08Z
38,574,525
<p>Have a look at <a href="https://en.wikipedia.org/wiki/Orphan_process" rel="nofollow">Orphan Processes</a> and <a href="https://en.wikipedia.org/wiki/Daemon_%28computer_software%29" rel="nofollow">Daemon Process</a>. A process without a parent becomes a child of init (pid 1). </p> <p>When it comes time to shut down ...
1
2016-07-25T18:00:21Z
[ "python" ]
What does this daemonize method do?
38,574,461
<p>I was looking around on GitHub, when I stumbled across this method called <code>daemonize()</code> in a reverse shell example. <sup><a href="https://gist.github.com/gdamjan/3025923" rel="nofollow">source</a></sup></p> <p>What I don't quite understand is what it does in this context, wouldn't running this code from ...
0
2016-07-25T17:56:08Z
38,574,840
<p>A background process - running <code>python2.7 &lt;file&gt;.py</code> with the <code>&amp;</code> signal - is not the same thing as a true daemon process. </p> <p>A true daemon process:</p> <ul> <li>Runs in the background. This also happens if you use <code>&amp;</code>, and is where the similarity ends.</li> <li>...
1
2016-07-25T18:18:34Z
[ "python" ]
Loop for imputation
38,574,471
<p>I make an imutation for a single variable &amp; return it to the same variable</p> <pre><code>X = pd.DataFrame(df, columns=['a']) imp = Imputer(missing_values='NaN', strategy='median', axis=0) X = imp.fit_transform(X) df['a'] = X </code></pre> <p>However I have many variables &amp; want to use loop like this</p> ...
0
2016-07-25T17:56:44Z
38,574,805
<p>A DataFrame iterates over it's columns names so k == 'a' in this instance rather than the first column. You could implement it with</p> <pre><code>f = df[[a, b, c, d, e]] for k in f: X = df[k] imp = Imputer(missing_values='NaN', strategy='median', axis=0) X = imp.fit_transform(X) df[k] = X </code></...
1
2016-07-25T18:16:33Z
[ "python", "loops", "dataframe", "imputation" ]
Loop for imputation
38,574,471
<p>I make an imutation for a single variable &amp; return it to the same variable</p> <pre><code>X = pd.DataFrame(df, columns=['a']) imp = Imputer(missing_values='NaN', strategy='median', axis=0) X = imp.fit_transform(X) df['a'] = X </code></pre> <p>However I have many variables &amp; want to use loop like this</p> ...
0
2016-07-25T17:56:44Z
38,575,262
<pre><code>for k in f: X = pd.DataFrame(df, columns=[k]) imp = Imputer(missing_values='NaN', strategy='median', axis=0) X = imp.fit_transform(X) df[k] = X </code></pre>
0
2016-07-25T18:43:55Z
[ "python", "loops", "dataframe", "imputation" ]
Comparing tuple contents with int in python
38,574,474
<pre><code>a = [(0, "Hello"), (1,"My"), (3, "Is"), (2, "Name"), (4, "Jacob")] </code></pre> <p>This is an example of a list, but when I try to this this it doesn't work:</p> <pre><code>if time &lt; a[3]: print ("You did it!") </code></pre> <p>The problem is that I can't apparently compare a tuple with an int, bu...
0
2016-07-25T17:56:55Z
38,574,505
<p>This?</p> <pre><code>if time &lt; a[3][0]: # ^ print ("You did it!") </code></pre> <p>You can index the tuple the same way you did with the list.</p>
4
2016-07-25T17:58:39Z
[ "python", "list" ]
trying to display data from database, only getting blank page
38,574,562
<p>I'm trying to display some data from a data base. Here's the template:</p> <pre><code>&lt;ul&gt; {% for post in latest_post %} &lt;li&gt;{{ post.id }} : {{ post.post_body }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre> <p>Here's the subview:</p> <pre><code>def success(request): latest_post = mod...
0
2016-07-25T18:02:21Z
38,574,590
<p>You need to call the <code>all</code> method of your model:</p> <pre><code>latest_post = models.Post.objects.all() # ^^^^^ </code></pre> <p>If you intend to return a non-all result, then you should use <code>filter</code>.</p> <p>Read more about <a href="https://docs.djangoproject....
0
2016-07-25T18:03:41Z
[ "python", "django", "python-3.x", "django-templates" ]
py2exe converted script does not run win32com.client correctly
38,574,582
<p>I have seen a couple posts related to my issue on other sites, but nothing worked. To make a long story short, my program importa win32com.client to access Microsoft Word. I create a standalone executable using py2exe and every time the user selects the option to open MS Word I get a KeyError. Below is the code whic...
0
2016-07-25T18:03:23Z
38,588,974
<p>OKAY! So for some reason the library.zip file that py2exe creates after being run does not allow for modules like win32com.client to import into the program. Why? I really do not know I am a noob at this stuff. Anyway the following solution works VERY well, as if I initially had no problem at all. This is what shoul...
0
2016-07-26T11:42:37Z
[ "python", "python-2.7", "py2exe", "win32com", "keyerror" ]
Flatten nested pandas dataframe
38,574,596
<p>I'm wondering how to flatten the nested pandas dataframe as demonstrated in the picture attached. <a href="http://i.stack.imgur.com/7UR1f.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/7UR1f.jpg" alt="enter image description here"></a></p> <p>The nested attribute is given by 'data' field. In short: I have a...
3
2016-07-25T18:04:04Z
38,574,693
<p>Try this:</p> <pre><code>pd.concat([df.data.apply(pd.Series), df.drop('data', axis=1)], axis=1) </code></pre>
4
2016-07-25T18:10:13Z
[ "python", "pandas", "dataframe" ]
How to filter a pandas series with a datetime index on the quarter and year
38,574,618
<p>I have a Series, called 'scores', with a datetime index. </p> <p>I wish to subset it by <code>quarter</code> and <code>year</code><br> pseudocode: <code>series.loc['q2 of 2013']</code></p> <p>Attempts so far:<br> <code>s.dt.quarter</code></p> <blockquote> <p>AttributeError: Can only use .dt accessor with dateti...
1
2016-07-25T18:05:40Z
38,574,816
<p>If you know the the year and quarter, say Q2 2013, then you can do this:</p> <pre><code>s['2013-04':'2013-06'] </code></pre> <p>Wrap it up into a function:</p> <pre><code>qmap = pd.DataFrame([ ('01', '03'), ('04', '06'), ('07', '09'), ('10', '12') ], list('1234'), list('se')).T def get_quarter(df, ye...
1
2016-07-25T18:17:12Z
[ "python", "datetime", "pandas", "datetimeindex" ]
How to filter a pandas series with a datetime index on the quarter and year
38,574,618
<p>I have a Series, called 'scores', with a datetime index. </p> <p>I wish to subset it by <code>quarter</code> and <code>year</code><br> pseudocode: <code>series.loc['q2 of 2013']</code></p> <p>Attempts so far:<br> <code>s.dt.quarter</code></p> <blockquote> <p>AttributeError: Can only use .dt accessor with dateti...
1
2016-07-25T18:05:40Z
38,574,988
<pre><code>import numpy as np import pandas as pd index = pd.date_range('2013-01-01', freq='M', periods=12) s = pd.Series(np.random.rand(12), index=index) print(s) # 2013-01-31 0.820672 # 2013-02-28 0.994890 # 2013-03-31 0.928376 # 2013-04-30 0.848532 # 2013-05-31 0.122263 # 2013-06-30 0.305741 # 20...
1
2016-07-25T18:27:38Z
[ "python", "datetime", "pandas", "datetimeindex" ]
How to filter a pandas series with a datetime index on the quarter and year
38,574,618
<p>I have a Series, called 'scores', with a datetime index. </p> <p>I wish to subset it by <code>quarter</code> and <code>year</code><br> pseudocode: <code>series.loc['q2 of 2013']</code></p> <p>Attempts so far:<br> <code>s.dt.quarter</code></p> <blockquote> <p>AttributeError: Can only use .dt accessor with dateti...
1
2016-07-25T18:05:40Z
38,575,104
<p>Suppose you have a dataframe like this:</p> <pre><code>sa Out[28]: 0 1970-01-31 1 1970-02-28 2 1970-03-31 3 1970-04-30 4 1970-05-31 5 1970-06-30 6 1970-07-31 7 1970-08-31 8 1970-09-30 9 1970-10-31 10 1970-11-30 11 1970-12-31 12 </code></pre> <p>If the index is datetime then you c...
1
2016-07-25T18:34:40Z
[ "python", "datetime", "pandas", "datetimeindex" ]
webbrowser not opening new windows
38,574,629
<p>I just got a new job working remotely and I have to start my day by opening a bunch of pages and logging into them. I would love to automate this process as it can be kind of tedious. I would like to leave my personal browsing window alone and open a new window with all of the pages I need. Here is the gist of wh...
0
2016-07-25T18:06:20Z
38,574,953
<p>I don't have Chrome installed, but there seem to be multiple problems:</p> <ol> <li>According to the docs, <code>webbrowser.get</code> expects the name of the browser, not the path.</li> <li>You should save the return value of <code>webbrowser.get()</code> and use it to open the remaining urls.</li> </ol> <p></p> ...
0
2016-07-25T18:25:22Z
[ "python", "python-webbrowser" ]
HTML and Python?
38,574,659
<p>I have a website design that I can turn into HTML that needs Python integration. Everything in the design is static except one part that has a table of values that needs to be updated every 15 minutes. I have my Python code ready to do this, but I have no idea how to combine Python and HTML. </p> <p>My website will...
-1
2016-07-25T18:08:14Z
38,575,045
<p>Check this out: <a href="https://pypi.python.org/pypi/html" rel="nofollow">https://pypi.python.org/pypi/html</a></p> <p>I found it useful.</p> <p>Or you can start using Flask for your task. <a href="http://flask.pocoo.org/" rel="nofollow">Flask</a></p>
0
2016-07-25T18:31:02Z
[ "python", "html", "python-2.7" ]
sleep while querying VirusTotal?
38,574,662
<p>I would like to use the VirusTotal API to check hash values against the VirusTotal database, but the VirusTotal public API limits the requests to 4 per minute. The section of my code that compares my list of hash values (hash_list) against the database is as follows:</p> <pre><code>url = "https://www.virustotal.co...
0
2016-07-25T18:08:21Z
38,574,788
<pre><code>import time /code/ time.sleep(15) </code></pre> <p>Should work. Just add the <code>time.sleep()</code> snippet to the block to cause a delay. </p>
0
2016-07-25T18:15:35Z
[ "python", "wait", "sleep" ]
How do I use Flask Migrate to create a SIMILAR TO constraint?
38,574,713
<p>I would like to build a constraint on status, using flask migrate. Status does not yet exist. </p> <p>my model includes this line:</p> <pre><code>status = db.Column(db.String(120), unique=False) </code></pre> <p>I would like to add the following constraint on status in addition to create status:</p> <pre><code>A...
1
2016-07-25T18:11:23Z
38,579,072
<p>You can write SQL in your migration scripts. See <a href="http://alembic.zzzcomputing.com/en/latest/ops.html#alembic.operations.Operations.execute" rel="nofollow">http://alembic.zzzcomputing.com/en/latest/ops.html#alembic.operations.Operations.execute</a>.</p> <p>Side note: Flask-Migrate is just a wrapper to Alembi...
1
2016-07-25T23:51:38Z
[ "python", "flask", "flask-migrate" ]
Split the string when alphabet is found next to a number using regex Python
38,574,795
<p>I have a string like this</p> <pre><code>string = "3,197Working age population" </code></pre> <p>I want to break the string such that when number 3,197 ends and Working age population starts using regex or any other efficient method. In short I need only 3,197</p>
-3
2016-07-25T18:16:08Z
38,574,949
<p>You may have a look at <a href="https://docs.python.org/3.4/library/itertools.html#itertools.takewhile" rel="nofollow"><code>itertools.takewhile</code></a>:</p> <pre><code>from itertools import takewhile string = "3,197Working age population" r = ''.join(takewhile(lambda x: not x.isalpha(), string)) print(r) # '3,...
0
2016-07-25T18:25:18Z
[ "python", "regex" ]
Create child of str (or int or float or tuple) that accepts kwargs
38,574,834
<p>I need a class that behaves like a string but also takes additional <code>kwargs</code>. Therefor I subclass <code>str</code>: </p> <pre><code>class Child(str): def __init__(self, x, **kwargs): # some code ... pass inst = Child('a', y=2) print(inst) </code></pre> <p>This however raises: </p>...
4
2016-07-25T18:18:18Z
38,575,015
<p>You need to override <code>__new__</code> in this case, not <code>__init__</code>:</p> <pre><code>&gt;&gt;&gt; class Child(str): ... def __new__(cls, s, **kwargs): ... inst = str.__new__(cls, s) ... inst.__dict__.update(kwargs) ... return inst ... &gt;&gt;&gt; c = Child("foo") &gt;&gt;&gt; c.up...
7
2016-07-25T18:29:26Z
[ "python", "python-3.x", "parent-child", "subclass", "kwargs" ]
How can I jump to next page in Scrapy
38,574,869
<p>I'm trying to scrape the results from <a href="https://www.class-central.com/courses/recentlyAdded" rel="nofollow">here</a> using scrapy. The problem is that not all of the classes appear on the page until the 'load more results' tab is clicked.</p> <p>The problem can be seen here:</p> <p><a href="http://i.stack.i...
0
2016-07-25T18:20:07Z
38,575,098
<p>The second page for this website seems to be generated via AJAX call. If you look into network tab of any browser inspection tool, you'll see something like: </p> <p><a href="http://i.stack.imgur.com/jTQj6.png" rel="nofollow"><img src="http://i.stack.imgur.com/jTQj6.png" alt="firebug network tab"></a></p> <p>In t...
0
2016-07-25T18:34:33Z
[ "python", "scrapy", "web-crawler" ]
Python pandas - remove group based on collective NaN count
38,574,872
<p>I have a dataset based on different weather stations for several variables (Temperature, Pressure, etc.),</p> <pre><code>stationID | Time | Temperature | Pressure |... ----------+------+-------------+----------+ 123 | 1 | 30 | 1010.5 | 123 | 2 | 31 | 1009.0 | 202 | 1 ...
3
2016-07-25T18:20:19Z
38,574,978
<p>This should work:</p> <pre><code>df.groupby('stationID').filter(lambda g: g.isnull().sum().sum() &lt; 4) </code></pre> <p>You can replace <code>4</code> with a threshold number you would like it to be.</p> <pre><code>df.groupby('stationID').filter(lambda g: g.isnull().sum().sum() &lt; 4) stationID Time ...
4
2016-07-25T18:27:09Z
[ "python", "pandas" ]
differentiate sudo <command> and <command>
38,574,999
<p>I would like to make my user run as sudo and as a normal user depending on his choice.He could use sudo or normal but on not using sudo I have to disable some functionalities to get rid of errors.So how could I know that user as given me sudo permissions to execute or not? I am building my application on python.</...
-2
2016-07-25T18:28:27Z
38,575,416
<p>After having read your question a few times, I think I know what you are asking. Am I correct in thinking that you want to know how to tell whether or not your python script as root permissions during runtime?</p> <p>If you really want to check ahead of time, you could query the system for the user id with <code>os...
1
2016-07-25T18:53:00Z
[ "python", "linux", "bash", "sudo" ]
How to create dynamic methods with python?
38,575,042
<p>For my project I need to dynamically create custom (Class) methods.</p> <p>I found out it is not so easy in Python:</p> <pre><code>class UserFilter(django_filters.FilterSet): ''' This filter is used in the API ''' # legacy below, this has to be added dynamically #is_field_type1 = MethodFilter(a...
1
2016-07-25T18:30:58Z
38,575,879
<p>You can use <a href="https://docs.python.org/3/library/functions.html?highlight=classmethod#classmethod" rel="nofollow">classmethod</a>. Here is example how you can use it:</p> <pre><code>class UserFilter: @classmethod def filter_field(cls, queryset, value, field = None): # do somthing retur...
0
2016-07-25T19:23:29Z
[ "python", "django" ]
How to create dynamic methods with python?
38,575,042
<p>For my project I need to dynamically create custom (Class) methods.</p> <p>I found out it is not so easy in Python:</p> <pre><code>class UserFilter(django_filters.FilterSet): ''' This filter is used in the API ''' # legacy below, this has to be added dynamically #is_field_type1 = MethodFilter(a...
1
2016-07-25T18:30:58Z
38,715,896
<p>You are asking for:</p> <blockquote> <p>custom (Class) methods.</p> </blockquote> <p>So we take an existing class and derive a subclass where you can add new methods or overwrite the methods of the original existing class (look into the code of the original class for the methods you need) like this:</p> <pre><c...
0
2016-08-02T08:52:47Z
[ "python", "django" ]
How to create dynamic methods with python?
38,575,042
<p>For my project I need to dynamically create custom (Class) methods.</p> <p>I found out it is not so easy in Python:</p> <pre><code>class UserFilter(django_filters.FilterSet): ''' This filter is used in the API ''' # legacy below, this has to be added dynamically #is_field_type1 = MethodFilter(a...
1
2016-07-25T18:30:58Z
38,731,069
<blockquote> <p>Exception Value: 'UserFilter' object has no attribute 'is_bound'</p> </blockquote> <p>You are getting this error because the class methods you are generating, are not bound to any class. To bound them to the class, you need to use setattr()</p> <p>Try this on a console:</p> <pre><code>class MyClass...
1
2016-08-02T21:49:36Z
[ "python", "django" ]
Scraping Table With Python/BS4
38,575,120
<p>Im trying to scrape the "Team Stats" table from <a href="http://www.pro-football-reference.com/boxscores/201602070den.htm" rel="nofollow">http://www.pro-football-reference.com/boxscores/201602070den.htm</a> with BS4 and Python 2.7. However Im unable to get anywhere close to it, </p> <pre><code>url = 'http://www.pr...
0
2016-07-25T18:35:18Z
38,575,322
<p>The problem in this case is that the <em>"Team Stats" table is located inside a comment</em> in the HTML source which you download with <code>requests</code>. Locate the comment and reparse it with <code>BeautifulSoup</code> into a "soup" object:</p> <pre><code>import requests from bs4 import BeautifulSoup, Navigab...
0
2016-07-25T18:47:51Z
[ "python", "python-2.7", "beautifulsoup" ]
Python UDP socket resend data if no data recieved
38,575,154
<p>I want to send some data to a sensor and if the python script doesn't receive the data I want the receive function to timeout and resend the data.</p> <pre><code>def subscribe(): UDP_IP = "192.168.1.166" UDP_PORT = 10000 MESSAGE = '6864001e636caccf2393730420202020202004739323cfac202020202020'.decode('hex')...
1
2016-07-25T18:38:01Z
38,575,543
<p>You get the "currently in use" exception because you are recreating the sockets every time you call either of those functions, without closing them first.</p> <p>Try creating the sockets beforehand. The response might come before the receiving socket is created in which case the packet is just going to be rejected....
0
2016-07-25T18:59:43Z
[ "python", "python-sockets" ]
Join and sum on subset of rows in a dataframe
38,575,213
<p>I have a pandas dataframe which stores date ranges and some associated colums: </p> <pre><code> date_start date_end ... lots of other columns ... 1 2016-07-01 2016-07-02 2 2016-07-01 2016-07-03 3 2016-07-01 2016-07-04 4 2016-07-02 2016-07-07 5 2016-07-05 2016-07-06 </co...
2
2016-07-25T18:41:00Z
38,575,482
<p>First make sure that <code>pikachu_sightings</code> has a datetime index and is sorted.</p> <pre><code>p = pikachu_sightings.squeeze() # force into a series p.index = pd.to_datetime(p.index) p = p.sort_index() </code></pre> <p>Then make sure your <code>date_start</code> and <code>date_end</code> are datetime.</p> ...
2
2016-07-25T18:56:26Z
[ "python", "pandas", "dataframe" ]
Join and sum on subset of rows in a dataframe
38,575,213
<p>I have a pandas dataframe which stores date ranges and some associated colums: </p> <pre><code> date_start date_end ... lots of other columns ... 1 2016-07-01 2016-07-02 2 2016-07-01 2016-07-03 3 2016-07-01 2016-07-04 4 2016-07-02 2016-07-07 5 2016-07-05 2016-07-06 </co...
2
2016-07-25T18:41:00Z
38,577,611
<p>A sketch of a vectorized solution:</p> <p>Start with a <code>p</code> as in piRSquared's answer.</p> <p>Make sure <code>date_</code> cols have <code>datetime64</code> dtypes, i.e.:</p> <pre><code>df['date_start'] = pd.to_datetime(df.date_time) </code></pre> <p>Then calculate cumulative sums:</p> <pre><code>psum...
2
2016-07-25T21:19:47Z
[ "python", "pandas", "dataframe" ]
Get result of value_count() to excel from Pandas
38,575,246
<p>I have a data frame <code>"df"</code> with a column called <code>"column1"</code>. By running the below code: </p> <pre><code>df.column1.value_counts() </code></pre> <p>I get the output which contains values in column1 and its frequency. I want this result in the excel. When I try to this by running the below code...
1
2016-07-25T18:43:10Z
38,575,432
<p>If go through the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html" rel="nofollow">documentation</a> <code>Series</code> had no method <code>to_excel</code>it applies only to <code>Dataframe</code>. So either you can save it another frame and create an excel as:</p> <pre><code>a=df....
1
2016-07-25T18:53:51Z
[ "python", "pandas" ]
Get result of value_count() to excel from Pandas
38,575,246
<p>I have a data frame <code>"df"</code> with a column called <code>"column1"</code>. By running the below code: </p> <pre><code>df.column1.value_counts() </code></pre> <p>I get the output which contains values in column1 and its frequency. I want this result in the excel. When I try to this by running the below code...
1
2016-07-25T18:43:10Z
38,575,600
<p>You are using <code>index = None</code>, You need the index, its the name of the values. </p> <pre><code>pd.DataFrame(df.column1.value_counts()).to_excel("result.xlsx") </code></pre>
2
2016-07-25T19:03:26Z
[ "python", "pandas" ]
Suppress hyperlinks from matplotlib sphinx extension
38,575,265
<p>I am using the <code>matplotlib.sphinxext.plot_directive</code> extension for <code>sphinx</code> to create some plots dynamically in some documentation. In one of my <code>.rst</code> files I have the following command</p> <pre><code>.. plot:: plots/normal_plots.py </code></pre> <p>This essentially just runs some...
0
2016-07-25T18:44:02Z
38,585,214
<p>There are two configuration options for this:</p> <ul> <li><code>plot_html_show_source_link</code></li> <li><code>plot_html_show_formats</code></li> </ul> <p>Set both options to <code>False</code> in conf.py to suppress the hyperlinks.</p> <p>Reference: <a href="http://matplotlib.org/devel/documenting_mpl.html#co...
1
2016-07-26T08:51:48Z
[ "python", "matplotlib", "python-sphinx" ]
Collapsing list to unique IDs with a range of dates
38,575,328
<p>I have a large list of IDs that repeat with different ranges of dates. I need to create a unique list of IDs with just one range of dates that includes the earliest start date and latest end date from the uncollapsed list.</p> <p>this is an example of what I have:</p> <pre><code> id start_date end_date 1 ...
1
2016-07-25T18:48:07Z
38,575,431
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow"><code>groupby/aggregate</code></a>:</p> <pre><code>In [12]: df.groupby('id').agg({'start_date':min, 'end_date':max}) Out[12]: start_date end_date id 1 2015-08-25 2015-11-01 2 2015-09-02 2015-10-29 3 ...
2
2016-07-25T18:53:44Z
[ "python", "pandas", "dataframe" ]
django cannot import name 'Item'
38,575,332
<p>After running a successful runserver,<br> To create a super user in django project, I updated the admin.py in my app directory as </p> <pre><code>from django.contrib import admin from .models import Item admin.site.register(Item) </code></pre> <p>by running the following </p> <p>$: python manage.py createsuperu...
0
2016-07-25T18:48:25Z
38,575,439
<p>Is your <code>manage.py</code> and <code>models.py</code> in the same directory? <code>from .models import Item</code> means you are trying to import the <code>models</code> from the same package(<a href="https://www.python.org/dev/peps/pep-0328/#guido-s-decision" rel="nofollow">relative import</a>), if not then you...
0
2016-07-25T18:54:17Z
[ "python", "django", "import" ]
django cannot import name 'Item'
38,575,332
<p>After running a successful runserver,<br> To create a super user in django project, I updated the admin.py in my app directory as </p> <pre><code>from django.contrib import admin from .models import Item admin.site.register(Item) </code></pre> <p>by running the following </p> <p>$: python manage.py createsuperu...
0
2016-07-25T18:48:25Z
38,575,588
<p>Do Not Update <code>manage.py</code></p> <p>There must be a file called <code>admin.py</code> in your app folder. Whenever you create a new app, <code>admin.py</code> is automatically cerated in your app directory (<code>django-admin startapp your_app_name</code> )</p> <p>open admin.py: move your code into it.</p...
1
2016-07-25T19:02:41Z
[ "python", "django", "import" ]
django cannot import name 'Item'
38,575,332
<p>After running a successful runserver,<br> To create a super user in django project, I updated the admin.py in my app directory as </p> <pre><code>from django.contrib import admin from .models import Item admin.site.register(Item) </code></pre> <p>by running the following </p> <p>$: python manage.py createsuperu...
0
2016-07-25T18:48:25Z
38,576,054
<p>You have identified the problem in this comment:</p> <blockquote> <p>models.py : from django.db import models</p> </blockquote> <p><code>Item</code> is not something that comes with Django. You will need to define a model named <code>Item</code> yourself. My guess is you ahve missed a pretty important step in yo...
1
2016-07-25T19:37:00Z
[ "python", "django", "import" ]
What is the proper way to import large amounts data into a Firebase database?
38,575,340
<p>I'm working with a dataset of political campaign contributions that ends up being an approximately 500mb JSON file (originally a 124mb CSV). It's far too big to import in the Firebase web interface (trying before crashed the tab on Google Chrome). I attempted manually uploading objects as they were made from the CSV...
0
2016-07-25T18:48:46Z
38,670,009
<p>I got around the problem by giving up on the Firebase Streaming Import and writing my own tool that used csvtojson to convert the CSV and then the Firebase Node API to upload each object one at a time.</p> <p>Here's the script:</p> <pre><code>var firebase = require("firebase"); firebase.initializeApp({ serviceAc...
0
2016-07-30T03:11:32Z
[ "python", "json", "csv", "firebase-database", "ijson" ]
QPX. How many returns per query?
38,575,369
<p>I'm looking to use this API for Google Flights to gather some flight data for project I hope to complete. I have one question tho. Can anyone see a way to request multiple dates for the same route in just one call? Or does it have to multiple requests? Thanks so much I have seen it suggested that it is possible but ...
0
2016-07-25T18:50:12Z
39,146,729
<p>It is possible to add more than one flight to the request, see the google developer tutorial for qpx. I am not sure though how many flights fit in one request.</p>
0
2016-08-25T13:30:43Z
[ "python", "json", "api", "web-scraping" ]
Joining Lists Within A List?
38,575,371
<p>I am trying to make a join of some lists within a list in python here is an example of what I am doing (the lists are much bigger in the real code):</p> <pre><code>import itertools listenv = ["IN","VC","VS"] listsize = ["U17-1","U17-2"] listevnsize = list(itertools.product(listenv, listsize,)) print listevnsize ...
0
2016-07-25T18:50:24Z
38,575,403
<p>This would work, just use zip</p> <pre><code>new_list = [] for i,j in zip(listenv, listsize): new_list.append(('{0}-{1}').format(i,j)) </code></pre>
0
2016-07-25T18:52:15Z
[ "python", "list", "join" ]
Joining Lists Within A List?
38,575,371
<p>I am trying to make a join of some lists within a list in python here is an example of what I am doing (the lists are much bigger in the real code):</p> <pre><code>import itertools listenv = ["IN","VC","VS"] listsize = ["U17-1","U17-2"] listevnsize = list(itertools.product(listenv, listsize,)) print listevnsize ...
0
2016-07-25T18:50:24Z
38,575,414
<p>use <code>str.join</code> </p> <pre><code>S.join(iterable) -&gt; string Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. l = [] for x in listevnsize: l.append('-'.join(i for i in x)) </code></pre>
0
2016-07-25T18:52:53Z
[ "python", "list", "join" ]
Joining Lists Within A List?
38,575,371
<p>I am trying to make a join of some lists within a list in python here is an example of what I am doing (the lists are much bigger in the real code):</p> <pre><code>import itertools listenv = ["IN","VC","VS"] listsize = ["U17-1","U17-2"] listevnsize = list(itertools.product(listenv, listsize,)) print listevnsize ...
0
2016-07-25T18:50:24Z
38,575,549
<pre><code>listenvsize = ["{}-{}".format(x,y) for x in listenv for y in listsize] </code></pre> <p>The result will not be a list of tuples anyway since there is only one element in the tuple you want.</p>
0
2016-07-25T19:00:14Z
[ "python", "list", "join" ]
Converting Tuple of integers and strings to just a string
38,575,407
<p>I want to convert a tuple which contains strings and integers into a string, I have tried using the '.join' method but this only seems to work for a tuple of strings. </p> <p>Can anyone help me? I am using Python 3.5, thanks!</p>
-1
2016-07-25T18:52:30Z
38,575,421
<pre><code>" ".join(map(str,my_list)) </code></pre> <p>I guess ...</p> <p>or <code>" ".join(str(x) for x in my_list)</code></p>
3
2016-07-25T18:53:22Z
[ "python" ]
Converting Tuple of integers and strings to just a string
38,575,407
<p>I want to convert a tuple which contains strings and integers into a string, I have tried using the '.join' method but this only seems to work for a tuple of strings. </p> <p>Can anyone help me? I am using Python 3.5, thanks!</p>
-1
2016-07-25T18:52:30Z
38,575,761
<p>This Might Help</p> <pre><code>&gt;&gt;&gt; a = ( "aty",3,"bob",5,6) &gt;&gt;&gt; tuple(map( str , a ) ) ('aty', '3', 'bob', '5', '6') </code></pre>
1
2016-07-25T19:15:49Z
[ "python" ]
Pandas resample to return just one column after an apply as been made
38,575,443
<pre><code>def wk(args): return args['Open'].mean() - args['Close'].mean() df = pd.DataFrame() df = data.resample("2B").apply(wk) </code></pre> <p>I run the following code on the below dataframe:</p> <pre><code> Open High Low Close Volume Date 201...
2
2016-07-25T18:54:26Z
38,575,537
<h1>Row-wise Apply and Resampler <em>Dispatch</em></h1> <p>Use a row-wise <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html#pandas-dataframe-apply" rel="nofollow"><code>.apply(func, axis=1)</code></a> and turn your <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries...
2
2016-07-25T18:59:22Z
[ "python", "pandas" ]
How to parse labeled values of columns into a Pandas Dataframe (some column values are missing)?
38,575,481
<p>The follow are two rows from my unlabeled dataset, a small subset:</p> <pre><code>random1 147 sub1 95 34 dewdfa3 15000 -1238 SBAASBAQSBARSBATSBAUSBAXBELAAX AAA:COL:UVTWUVWDUWDUWDWW BBB:COL:F CCC:COL:GTATGTCA DDD:COL:K20 EEE:COL:54T GGG:COL:-30.5 HHH:COL:000.1 III:COL:2 JJJ:COL:0 random2 ...
2
2016-07-25T18:56:24Z
38,575,806
<p>This will do it:</p> <pre><code>text = """random1 147 sub1 95 34 dewdfa3 15000 -1238 SBAASBAQSBARSBATSBAUSBAXBELAAX AAA:COL:UVTWUVWDUWDUWDWW BBB:COL:F CCC:COL:GTATGTCA DDD:COL:K20 EEE:COL:54T GGG:COL:-30.5 HHH:COL:000.1 III:COL:2 JJJ:COL:0 random2 123 sub1 996 12 kwnc239 10027 144 ...
2
2016-07-25T19:18:48Z
[ "python", "parsing", "pandas", "dataframe" ]
Sieve of Eratosthenes returning incorrect answers
38,575,520
<p>I'm a beginner trying to create a function to determine whether or not a value is prime or not. </p> <pre><code>def isPrime(number): marked = [] ## create empty list for i in xrange(2, number+1): if i not in marked: ## begin loop to remove multiples of i in list for j in xrange(i * i, nu...
-1
2016-07-25T18:58:40Z
38,575,980
<p>I'm answering this even if this is not really new stuff. It answers the question, gives 2 ways of working and is tested and in python. Should be ontopic.</p> <p>First, computing the sieve each time is very unefficient to test for one number. If you have a lot of numbers to test, then that's the way. A working versi...
1
2016-07-25T19:31:40Z
[ "python", "if-statement", "boolean", "primes", "sieve-of-eratosthenes" ]
TensorFlow: 2 layer feed forward neural net
38,575,578
<p>I'm trying to implement a simple fully-connected feed-forward neural net in TensorFlow (Python 3 version). The network has 2 inputs and 1 output, and I'm trying to train it to output the XOR of the two inputs. My code is as follows:</p> <pre><code>import numpy as np import tensorflow as tf sess = tf.InteractiveSes...
0
2016-07-25T19:02:10Z
38,575,943
<p>Your implementation looks correct. Here are a few things you could try:</p> <ul> <li>Change <code>tf.nn.sigmoid</code> to other non-linear activation functions</li> <li>Use a smaller learning rate (1e-3 to 1e-5)</li> <li>Use more layers</li> <li>Follow the <a href="http://mnemstudio.org/neural-networks-multilayer-p...
0
2016-07-25T19:28:43Z
[ "python", "machine-learning", "neural-network", "tensorflow" ]
TensorFlow: 2 layer feed forward neural net
38,575,578
<p>I'm trying to implement a simple fully-connected feed-forward neural net in TensorFlow (Python 3 version). The network has 2 inputs and 1 output, and I'm trying to train it to output the XOR of the two inputs. My code is as follows:</p> <pre><code>import numpy as np import tensorflow as tf sess = tf.InteractiveSes...
0
2016-07-25T19:02:10Z
38,576,462
<p>There are several issues in your code. In the following I'm going to comment each line to bring you to the solution.</p> <p>Note: XOR is not linearly separable. You need more than 1 hidden layer.</p> <p>N.B: The lines that starts with <code># [!]</code> are the lines where you were wrong.</p> <pre><code>import nu...
0
2016-07-25T20:04:03Z
[ "python", "machine-learning", "neural-network", "tensorflow" ]
unbound method with "enum-like" class
38,575,589
<p>Consider the following code:</p> <pre><code>ff = lambda x : x gg = lambda x : x*2 class FunctionCollection(object): f = ff g = gg def FunctionCaller(x, Type = FunctionCollection.f): return Type(x) y = FunctionCaller(x) </code></pre> <p>It returns an </p> <blockquote> <p>unbound method () must be c...
0
2016-07-25T19:02:42Z
38,575,642
<p>Your code actually <em>does</em> work on python3.x. If you need to support python2.x, you can use a staticmethod:</p> <pre><code>ff = lambda x : x gg = lambda x : x*2 class FunctionCollection(object): f = staticmethod(ff) g = staticmethod(gg) def FunctionCaller(x, Type = FunctionCollection.f): return ...
1
2016-07-25T19:06:29Z
[ "python" ]
Describe and Info for SFrame
38,575,629
<p>It would be nice to see summary of the <a href="https://github.com/turi-code/SFrame" rel="nofollow">SFrame</a>, something similar to what pandas DataFrame gives you with methods <code>.info()</code> and <code>.describe()</code></p> <p>What is the easiest way to do this except <code>sf.to_dataframe().info()</code>, ...
0
2016-07-25T19:05:25Z
38,632,060
<p>You're probably looking for <code>sf.show()</code>, which launches an interactive Canvas window allowing you to also see basic data visualizations like scatterplots, lineplots etc besides the summary stats.</p> <p>One caveat here the <code>show()</code> function is only available in the commercial version of graphl...
2
2016-07-28T09:17:16Z
[ "python", "pandas", "sframe" ]
Merge two data frames while using boolean indices (to filter)
38,575,661
<p>I have what may be a simple question related to syntax, but can't figure out.</p> <p>I have two data frames, df1 and df2, that I'd like to a) merge on specific columns, while b) simultaneously checking another column in each data frame for a boolean relationship (>, &lt;, or ==). </p> <p>The crucial part is that ...
0
2016-07-25T19:08:23Z
38,590,532
<p>Try this:</p> <pre><code>import pandas as pd df1_col1 = pd.Series(['A', 'B', 'A', 'B', 'A', 'B'], index=[0, 1, 2, 3, 4, 5 ]) df1_col2 = pd.Series(['B', 'A', 'B', 'A', 'B', 'A'], index=[0, 1, 2, 3, 4, 5]) df1_col3 = pd.Series([1, 3, 2, 5, 2, 1], index=[0, 1, 2, 3, 4, 5]) df1 = pd.concat([df1_col1, df1_col2, df1_col...
1
2016-07-26T12:57:31Z
[ "python", "pandas", "merge", "boolean" ]
pandas: create pivot table by two different dimensions?
38,575,672
<p>I am a pandas newbie. I have a dataframe of examinations taken by sponsor and company:</p> <pre><code>import pandas pd df = pd.DataFrame({ 'sponsor': ['A71991', 'A71991', 'A71991', 'A81001', 'A81001'], 'sponsor_class': ['Industry', 'Industry', 'Industry', 'NIH', 'NIH'], 'year': [2012, 2013, 2013, 2012, 2013]...
4
2016-07-25T19:09:01Z
38,576,127
<p>I can see how to do it in quite a few steps:</p> <pre><code>import numpy as np, pandas as pd df['total'] = df['passed'].astype(int) ldf = pd.pivot_table(df,index=['sponsor','sponsor_class'],columns='year', values=['total'],aggfunc=len) # total counts rdf = pd.pivot_table(df,index=['sponsor','sp...
2
2016-07-25T19:41:48Z
[ "python", "pandas" ]
pandas: create pivot table by two different dimensions?
38,575,672
<p>I am a pandas newbie. I have a dataframe of examinations taken by sponsor and company:</p> <pre><code>import pandas pd df = pd.DataFrame({ 'sponsor': ['A71991', 'A71991', 'A71991', 'A81001', 'A81001'], 'sponsor_class': ['Industry', 'Industry', 'Industry', 'NIH', 'NIH'], 'year': [2012, 2013, 2013, 2012, 2013]...
4
2016-07-25T19:09:01Z
38,576,262
<pre><code># set index to prep for unstack df1 = df.set_index(['sponsor', 'sponsor_class', 'year']).astype(int) # groupby all the stuff in the index gb = df1.groupby(level=[0, 1, 2]).passed # use agg to get sum and count # swaplevel and sort_index to get stuff sorted out df2 = gb.agg({'passed': 'sum', 'total': 'c...
3
2016-07-25T19:51:53Z
[ "python", "pandas" ]
Doing calculations on Pandas DataFrame with groupby and then passing it back into a DataFrame?
38,575,673
<p>I have a data frame that I want to group by two variables, and then perform calculation within those variables. Is there any easy way to do this and put the information BACK into a DataFrame when I'm done, i.e. like this:</p> <pre><code>df=pd.DataFrame({'A':[1,1,1,2,2,2,30,12,122,345], 'B':[1,1,1,2,3,3,3,2,3,4], 'C...
1
2016-07-25T19:09:01Z
38,575,853
<p>You can use <code>pandas</code> aggregate function after <code>groupby</code>:</p> <pre><code>import pandas as pd import numpy as np df.groupby(['A', 'B'])['C'].agg({'total': np.sum, 'avg': np.mean}).reset_index() # A B total avg # 0 1 1 343 114.333333 # 1 2 2 122 122.000...
2
2016-07-25T19:22:04Z
[ "python", "pandas", "dataframe", "grouping" ]
Removed Rows from Pandas Dataframe - Now Indexes Are Messed Up?
38,575,701
<p>So I have a dataframe in pandas that includes the genders of some patients. I wanted to sort by gender so I used:</p> <pre><code>df = df[df.Gender == 0] </code></pre> <p>but now when I print the dataframe I get something like: </p> <pre><code> Gender 0 0 2 0 5 0 </code></pre> <p>where the row inde...
2
2016-07-25T19:11:16Z
38,575,993
<pre><code>df = df[df.Gender == 0] </code></pre> <p>is taking a slice of <code>df</code> where <code>df.Gender</code> was equal to <code>0</code>. This is as you expected. It is also bringing along with it, the row indices for each of the rows that <code>df.Gender</code> was equal to <code>0</code>. This is correct...
1
2016-07-25T19:32:49Z
[ "python", "pandas", "dataframe" ]
How to parse an XML file to a list?
38,575,724
<p>I am trying to parse an XML file to a list with Python. I have looked at some solutions on this site and others and could not make them work for me. I have managed to do it but in a laborious way that seems stupid to me. It seems that there should be an easier way.</p> <p>I have tried to adapt other peoples code to...
0
2016-07-25T19:13:21Z
38,575,995
<p>The problem you're posing isn't very well defined. The XML structure doesn't conform very well to a list structure to begin with. If you're new to python, I think the best way to go about what you're trying to do is to use something like <a href="https://github.com/martinblech/xmltodict" rel="nofollow">xmltodict</...
1
2016-07-25T19:33:01Z
[ "python", "xml" ]
How to parse an XML file to a list?
38,575,724
<p>I am trying to parse an XML file to a list with Python. I have looked at some solutions on this site and others and could not make them work for me. I have managed to do it but in a laborious way that seems stupid to me. It seems that there should be an easier way.</p> <p>I have tried to adapt other peoples code to...
0
2016-07-25T19:13:21Z
38,585,499
<p>Thanks for the comments. Sorry if the question was not well posed. I have found an answer myself. I was looking to parse the XML child elements into a list for later use in another program. I figured it out. Thank you for your patience.</p>
0
2016-07-26T09:04:05Z
[ "python", "xml" ]
Python parse javascript for variable name and it's value
38,575,729
<p>I'm trying to parse a javascript tag that has a variable named <code>options</code>. The value of options is an array, </p> <pre><code>"options: [[], []]" </code></pre> <p>How can I return the options list?</p> <p>Currently I'm using BeautifulSoup but having trouble finding the text and also how the search would ...
-3
2016-07-25T19:13:42Z
38,575,800
<pre><code>json.loads(re.search("options: (.*)","adsasd\noptions: [[],[]]\nqqt").group(1)) </code></pre> <p>is one way I guess... not a very good way i dont think ... I think we are missing alot of details in order to actually provide a useful answer</p> <p>althoug I suspect your data looks more like this</p> <pre><...
1
2016-07-25T19:18:42Z
[ "python", "regex", "beautifulsoup" ]
Selendroid - Can't connect to Selendroid server, assuming it is not running
38,575,749
<p>I'm trying to automate some actions in a browser, using selendroid. I managed to get the server going. If I go to <a href="http://localhost:4444/wd/hub/status" rel="nofollow">http://localhost:4444/wd/hub/status</a>, here's the response</p> <pre><code>{"value":{"os":{"name":"Linux","arch":"amd64","version":"4.6.4-1-...
1
2016-07-25T19:15:01Z
38,635,872
<p>I managed to get it working by switching to different operating system. I switched to a ubuntu based one, but I guess it doesn't matter.</p>
0
2016-07-28T12:05:11Z
[ "python", "selenium", "selenium-webdriver", "selendroid" ]
Python 3 Can't print dictionary outside of for loop
38,575,776
<p>I am working with CSV file data that I need to split into to dictionaries. I am using the following code:</p> <pre><code>ga_session_data = {} ga_pageviews_data = {} file = open('files/data.csv', 'r') for line in file: page, sessions, pageviews = line.split(',') sessions = int(sessions.strip()) pagevie...
-2
2016-07-25T19:16:53Z
38,575,801
<p>In each iteration of the loop you create new dictionaries with single item.</p> <p>To fix this, inside the <code>for</code> loop, change:</p> <pre><code>ga_session_data = {page: sessions} ga_pageviews_data = {page: pageviews} </code></pre> <p>To:</p> <pre><code>ga_session_data[page] = sessions ga_pageviews_d...
2
2016-07-25T19:18:43Z
[ "python", "for-loop" ]
Python 3 Can't print dictionary outside of for loop
38,575,776
<p>I am working with CSV file data that I need to split into to dictionaries. I am using the following code:</p> <pre><code>ga_session_data = {} ga_pageviews_data = {} file = open('files/data.csv', 'r') for line in file: page, sessions, pageviews = line.split(',') sessions = int(sessions.strip()) pagevie...
-2
2016-07-25T19:16:53Z
38,575,802
<p>You are not adding anything to the initial, empty dictionaries. You are <strong>replacing</strong> them each time with a <em>new</em> dictionary:</p> <pre><code>ga_session_data = {page: sessions} ga_pageviews_data = {page: pageviews} </code></pre> <p>That's two new dictionaries, each with <em>one</em> key-valu...
5
2016-07-25T19:18:43Z
[ "python", "for-loop" ]
Python 3 Can't print dictionary outside of for loop
38,575,776
<p>I am working with CSV file data that I need to split into to dictionaries. I am using the following code:</p> <pre><code>ga_session_data = {} ga_pageviews_data = {} file = open('files/data.csv', 'r') for line in file: page, sessions, pageviews = line.split(',') sessions = int(sessions.strip()) pagevie...
-2
2016-07-25T19:16:53Z
38,575,833
<h1>The issue</h1> <p>It is printing the entire dictionary. Your problem lies in your loop as you're creating the dictionaries:</p> <pre><code>ga_session_data = {page: sessions} ga_pageviews_data = {page: pageviews} </code></pre> <p>This will create a new dictionary after every iteration of the loop, so at the end ...
3
2016-07-25T19:20:01Z
[ "python", "for-loop" ]
Pandas Filtering By Date And OR Condition
38,575,789
<p>I'm using <code>pandas</code> to try and get a count for the members that have purchased a specific type of contract between two dates. The dataframe that I'm working with resembles: </p> <pre><code>Member Nbr Contract-Type Date-Joined 20 1 Year Membership 2011-08-01 3128 3 Month M...
2
2016-07-25T19:17:41Z
38,576,093
<p>Use <code>|</code> instead of <code>or</code>. Also, <code>&amp;</code> takes precedence over <code>|</code>, so your logic needs one more set of parentheses.</p> <pre><code>import io import pandas as pd data = io.StringIO('''\ Member Nbr,Contract-Type,Date-Joined 20,1 Year Membership,2011-08-01 3128,3 Month Me...
4
2016-07-25T19:39:22Z
[ "python", "pandas" ]
Elegant and portable way to handle SNMP tables in Python
38,575,856
<p>I have been searching a lot for this, but not found anything that fits my needs yet. I want an elegant way to work with SNMP tables in Python. I have looked at pysnmp and net-snmp python bindings.</p> <p>At the moment I am working with net-snmp bindings, as it seems more easy to query data with, and it is already e...
1
2016-07-25T19:22:14Z
38,588,278
<p>Speaking of pysnmp, there are two components that may be of interest to you:</p> <ul> <li><a href="http://pysnmp.sourceforge.net/docs/pysnmp-hlapi-tutorial.html#working-with-snmp-tables" rel="nofollow">ObjectType/ObjectIdentity</a> classes representing MIB object and handling OID&lt;->symbol&lt;->index and value ty...
0
2016-07-26T11:10:52Z
[ "python", "snmp", "net-snmp", "pysnmp" ]
Error compiling C code for python hmmlearn package
38,575,860
<p>I'm having some trouble getting the <code>hmmlearn</code> package to install properly (in a virtual environment); it seems to have something to do with the underlying C code. The package installs fine with <code>pip</code>, but when I try to import the core class, I get an error:</p> <pre><code>In [1]: import hmmle...
0
2016-07-25T19:22:29Z
38,576,877
<p>I ran into the same issue a while ago and found the <a href="http://stackoverflow.com/a/35123700/3846213">solution</a> by trying everything possible. For whatever reason in some cases <code>pip</code> skips building C-extensions, when a package is saved into the cache directory. If you force <code>pip</code> to igno...
2
2016-07-25T20:28:37Z
[ "python", "c", "compilation", "pip", "hmmlearn" ]
Python regex stripping punctuation with conditions
38,575,878
<p>I have a dataframe of various company names, and I need to be able to perform a groupby function on them. However, the company names are often law firms, which can be presented in a variety of different ways (ie. "Akin Gump", "Akin, Gump", "Akin,Gump", "Akin Gump Strauss Hauer &amp; Feld LLP", "Akin Gump Strauss Hau...
0
2016-07-25T19:23:28Z
38,575,931
<p>I'd make a first passthrough with regex to correct the offending characters so that they don't cause issues in the rest of the code:</p> <pre><code>import re re.sub(" *[&amp;,] *"," ", company_name) #Add any other special characters you might want </code></pre> <p>This will replace any special characters and all ...
0
2016-07-25T19:27:26Z
[ "python", "regex" ]
Session on Flask server with Python requests package not working
38,575,888
<p>I've written Flask server with flask_login. To login user, I use <code>login_user(user)</code>, and I have one page of my site protected with <code>@login_required</code>. As a client, I use Python requests package, that's the code:</p> <pre><code>import requests sess = requests.session() sess.post("http://page.on/...
1
2016-07-25T19:24:29Z
38,576,862
<p>This appears to exhibit the behavior that you explain:</p> <pre><code>from flask import Flask, request from flask_login import LoginManager, UserMixin, login_user, login_required, \ current_user app = Flask(__name__) app.secret_key = 'This is totally a secret' login_manager = LoginManager()...
0
2016-07-25T20:27:37Z
[ "python", "authentication", "flask", "flask-sqlalchemy", "flask-login" ]
Elasticsearch delay in store and search immediately
38,575,892
<p>I am using <a href="/questions/tagged/elasticsearch" class="post-tag" title="show questions tagged &#39;elasticsearch&#39;" rel="tag"><img src="//i.stack.imgur.com/817gJ.png" height="16" width="18" alt="" class="sponsor-tag-img">elasticsearch</a> with python. and use <code>dsl</code> driver in python.</p> <p>My scr...
1
2016-07-25T19:24:39Z
38,580,216
<p>Yes, once you index a new document, it is not available until a refresh of the index occurs. You have a few options, though, the main ones being.</p> <p>A. You can <code>refresh</code> the <code>test</code> index using the underlying connection just after saving <code>student_doc_obj</code> and before searching for...
1
2016-07-26T02:36:25Z
[ "python", "elasticsearch", "elasticsearch-dsl", "elasticsearch-py" ]
How to preprocess values passed to CreateView
38,575,918
<p>I want to preprocess values submitted to a <code>CreateView</code> in order to get them validated. For example, a custom int-parser for a string entered in the form.</p> <p>In my case I want to convert a string entered in a <code>CreateView</code> form like "1:54.363" to an integer (with an existing function <code>...
1
2016-07-25T19:26:19Z
38,576,528
<p>I think you are on the right track in using the form to validate your data. However, your input is failing the validation test simply because the input data, formatted as a time value, is not the integer that your model requires.</p> <p>You should use an unbound field in the form (or an unbound form) that accepts ...
1
2016-07-25T20:07:47Z
[ "python", "django", "django-models", "django-forms", "django-views" ]
How to preprocess values passed to CreateView
38,575,918
<p>I want to preprocess values submitted to a <code>CreateView</code> in order to get them validated. For example, a custom int-parser for a string entered in the form.</p> <p>In my case I want to convert a string entered in a <code>CreateView</code> form like "1:54.363" to an integer (with an existing function <code>...
1
2016-07-25T19:26:19Z
38,586,051
<p>Laptime is a time and if you expect the user to enter it in the format "1:54.363" the right field to use is <a href="https://docs.djangoproject.com/en/1.9/ref/forms/fields/#timefield" rel="nofollow">TimeField</a></p> <blockquote> <p>Validates that the given value is either a datetime.time or string formatted in...
1
2016-07-26T09:28:46Z
[ "python", "django", "django-models", "django-forms", "django-views" ]
How to keep one body on top of another using Pymunk
38,575,924
<p>I've got a circle, with a box on top:</p> <p><a href="http://i.stack.imgur.com/D9Xa1.png" rel="nofollow"><img src="http://i.stack.imgur.com/D9Xa1.png" alt="Circle with box on top"></a></p> <p>The circle is a simple motor. I want the box to stay directly over the circle. I've tried different constraints, but most o...
2
2016-07-25T19:26:46Z
38,680,981
<p>You can use two pin joints instead of one, with spread out anchor points on the box. Sort of how you would make it stable also in real life :)</p> <pre><code># Create a joint between them constraint = pymunk.constraint.PinJoint(self.box_shape.body, self.circle_shape.body, (-20,0)) self.space.add(constraint) constr...
1
2016-07-31T05:14:01Z
[ "python", "pymunk" ]
Concatenating at the end of a string - Python
38,576,019
<p>I have a file that basically looks like this: </p> <pre><code>atom coordinateX coordinateY coordinateZ atom coordinateX coordinateY coordinateZ ... </code></pre> <p>I'm trying to add the atom number (starting from 0) so that my file would look like this:</p> <pre><code>atom0 coordinateX coordinateY coordinateZ at...
-1
2016-07-25T19:34:29Z
38,576,128
<p>You have 2 combined problems which makes a funny combination: a odd/even problem on your counter and the use of <code>lstrip</code> instead of <code>strip</code>: <code>strip</code> removes the linefeed that shift your lines.</p> <p>I rewrote your code, removing the last part which is now useless and now it works a...
2
2016-07-25T19:41:49Z
[ "python", "string", "file" ]
Concatenating at the end of a string - Python
38,576,019
<p>I have a file that basically looks like this: </p> <pre><code>atom coordinateX coordinateY coordinateZ atom coordinateX coordinateY coordinateZ ... </code></pre> <p>I'm trying to add the atom number (starting from 0) so that my file would look like this:</p> <pre><code>atom0 coordinateX coordinateY coordinateZ at...
-1
2016-07-25T19:34:29Z
38,576,157
<p>Running two counters in your loop can get quite messy. And you're not properly <em>stripping</em> those lines.</p> <p>The following does what you want replacing <code>index</code> and <code>count</code> with an <a href="https://docs.python.org/2/library/itertools.html#itertools.count" rel="nofollow"><code>itertools...
1
2016-07-25T19:43:41Z
[ "python", "string", "file" ]
how to automatically update pyserial to latesT?
38,576,123
<p>I have the following code to raise an exception when pyserial version is less than 2.7,how do I programatically run <code>pip install pyserial --upgrade</code> to automatically update to latest version and ensure that it installed correctly?</p> <pre><code> if py_ser_ver &lt; 2.7: raise StandardError("PySer...
0
2016-07-25T19:41:36Z
38,576,759
<p>use os.system('python -m pip install pyserial --upgrade') or use subprocess</p> <p>Then once the installation is complete, check using python -m pip list command. This will work even if pip is not in the path.</p> <pre><code>import os import subprocess a = os.system('python -m pip install pyserial --upgrade') if ...
-1
2016-07-25T20:21:51Z
[ "python" ]
how to print dictionary data in the tabular form in python
38,576,238
<p>I have a nested dictionary as follows.I want to print the data in the tabular form. Now condition here is i want to print only certain data in table for an example : BIRT, NAME, and SEX. how can i do that? </p> <pre><code> import sys import pandas as pd indi ={} indi = {'@I7@': {'BIRT': '15 NOV 1925', 'F...
-2
2016-07-25T19:50:02Z
38,613,886
<p>Documentation: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html</a></p> <p>You can try to use something like this:</p> <pre><code>print(person.filter(['BIRT', 'NAME', 'SEX']...
0
2016-07-27T13:07:18Z
[ "python" ]
Word Frequency from a CSV Column in Python
38,576,351
<p>I have a .csv file with a column of messages I have collected, I wish to get a word frequency list of every word in that column. Here is what I have so far and I am not sure where I have made a mistake, any help would be appreciated. Edit: The expected output is to write the entire list of words and their count (wit...
-1
2016-07-25T19:57:18Z
38,576,473
<p>The code you uploaded is all over the place, but I think this is what you're getting at. This returns a list of the word and the number of times it appeared in the original file.</p> <pre><code>words= [] with open('comments_word_freqency.csv', 'rb') as csvfile: reader = csv.reader(csvfile) reader.next() ...
0
2016-07-25T20:04:24Z
[ "python", "python-2.7" ]
How to call a certain function inside an if statement in python?
38,576,369
<p>I am relatively new to python, in my foundation year I learned BBC BASIC which is pretty basic and I acquired many bad habits there. I learned python with the aid of codecademy, however, how can I call a function inside an if statement? In my first if statement I called the function <code>mainMenu(menu)</code>, how...
-3
2016-07-25T19:57:59Z
38,576,411
<p>Try putting the <code>MainMenu</code> function at the top. This is because in Python, function definitions have to be before their usage. Also, you never defined <code>menu</code>, so we can just get rid of it.</p> <pre><code>def mainMenu(): print "------------------------------------------------" print "Se...
3
2016-07-25T20:00:56Z
[ "python", "function" ]