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
How to get mean of rows selected with another column's values in pandas
40,074,739
<p>I am trying to get calculate the mean for Score 1 only if column <code>Dates</code> is equal to <code>Oct-16</code>:</p> <p><a href="https://i.stack.imgur.com/PR8jf.png" rel="nofollow"><img src="https://i.stack.imgur.com/PR8jf.png" alt="enter image description here"></a></p> <p>What I originally tried was:</p> <p...
2
2016-10-16T19:51:29Z
40,074,796
<p>Iterating through the rows doesn't take advantage of Pandas' strengths. If you want to do something with a column based on values of another column, you can use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>.loc[]</code></a>:</p> <pre><code>d...
3
2016-10-16T19:57:53Z
[ "python", "pandas", "numpy" ]
How to get mean of rows selected with another column's values in pandas
40,074,739
<p>I am trying to get calculate the mean for Score 1 only if column <code>Dates</code> is equal to <code>Oct-16</code>:</p> <p><a href="https://i.stack.imgur.com/PR8jf.png" rel="nofollow"><img src="https://i.stack.imgur.com/PR8jf.png" alt="enter image description here"></a></p> <p>What I originally tried was:</p> <p...
2
2016-10-16T19:51:29Z
40,074,798
<pre><code>import pandas as pd import numpy as np import os dataFrame = pd.read_csv("test.csv") dates = dataFrame["Dates"] score1s = dataFrame["Score 1"] result = [] for i in range(0,len(dates)): if dates[i] == "Oct-16": result.append(score1s[i]) print(result.mean()) </code></pre>
0
2016-10-16T19:58:09Z
[ "python", "pandas", "numpy" ]
How to get mean of rows selected with another column's values in pandas
40,074,739
<p>I am trying to get calculate the mean for Score 1 only if column <code>Dates</code> is equal to <code>Oct-16</code>:</p> <p><a href="https://i.stack.imgur.com/PR8jf.png" rel="nofollow"><img src="https://i.stack.imgur.com/PR8jf.png" alt="enter image description here"></a></p> <p>What I originally tried was:</p> <p...
2
2016-10-16T19:51:29Z
40,075,040
<p>How about the mean for all dates</p> <pre><code>dataframe.groupby('Dates').['Score 1'].mean() </code></pre>
1
2016-10-16T20:20:08Z
[ "python", "pandas", "numpy" ]
Adding new values to empty nested lists
40,074,768
<p>This is related to <a href="http://stackoverflow.com/questions/6339235/how-to-append-to-the-end-of-an-empty-list">How to append to the end of an empty list?</a>, but I don't have enough reputation yet to comment there, so I posted a new question here.</p> <p>I need to append terms onto an empty list of lists. I sta...
0
2016-10-16T19:54:49Z
40,074,911
<p>The errors you are reporting (strings immutable?) don't make any sense unless your list is actually not empty but already populated with strings. In any event, if you start with an empty list, then the simplest way to populate it is by appending:</p> <pre><code>&gt;&gt;&gt; talks = {} &gt;&gt;&gt; talks['each_file_...
0
2016-10-16T20:07:20Z
[ "python", "list", "assign" ]
Adding new values to empty nested lists
40,074,768
<p>This is related to <a href="http://stackoverflow.com/questions/6339235/how-to-append-to-the-end-of-an-empty-list">How to append to the end of an empty list?</a>, but I don't have enough reputation yet to comment there, so I posted a new question here.</p> <p>I need to append terms onto an empty list of lists. I sta...
0
2016-10-16T19:54:49Z
40,075,068
<p>Some continued experimentation, along with the comments got me moving towards a solution. Rather than appending each individual term, which generates a single long list, I accumulated the terms into a list and then appended each list, as follows:</p> <pre><code>for eachFilename in Talks: for eachTerm in range( ...
0
2016-10-16T20:24:07Z
[ "python", "list", "assign" ]
Syntax error in python2 script using ldap module
40,074,769
<p>Learning python (was chosen for its ldap module) for a new script that has been tossed my way. I'm getting a sytntax error when I try using a ldif. I was getting Syntax errors on the attrs I was trying to assign until I moved it further up the script to near the search fields. I'm not exactly sure why I am getting t...
0
2016-10-16T19:54:52Z
40,074,895
<p>It's a syntax error to have try without except. Because there's a whole lot of unindented code before the except, Python doesn't see it as part of the try. Make sure everything between try and except is indented.</p>
0
2016-10-16T20:06:38Z
[ "python", "python-2.7" ]
Syntax error in python2 script using ldap module
40,074,769
<p>Learning python (was chosen for its ldap module) for a new script that has been tossed my way. I'm getting a sytntax error when I try using a ldif. I was getting Syntax errors on the attrs I was trying to assign until I moved it further up the script to near the search fields. I'm not exactly sure why I am getting t...
0
2016-10-16T19:54:52Z
40,074,909
<p>You haven't ended your <code>try</code> block by the time you reach this line</p> <pre><code>ldif = modlist.addModlist(attrs) </code></pre> <p>since the accompanying <code>except</code> is below. However, you reduced the indentation level and this is causing the syntax error since things in the same block should h...
0
2016-10-16T20:07:11Z
[ "python", "python-2.7" ]
Python system libraries leak into virtual environment
40,074,820
<p>While working on a new python project and trying to learn my way through virtual environments, I've stumbled twice with the following problem:</p> <ul> <li>I create my virtual environment called venv. Running <code>pip freeze</code> shows nothing. </li> <li>I install my dependencies using pip install dependency. th...
0
2016-10-16T20:01:09Z
40,077,668
<p>I realized that my problem arose when moving my virtual environment folder around the system. The fix was to modify the <code>activate</code> and <code>pip</code> scripts located inside the <code>venv/bin</code> folder to point to the new venv location, as suggested by <a href="http://stackoverflow.com/a/16683703/32...
0
2016-10-17T02:28:56Z
[ "python", "osx", "pip", "virtualenv" ]
If a string contains a suffix from a list, how do I strip that specific suffix from the string?
40,074,825
<p>I have a list of strings and a list of suffixes. If a string contains one of the suffixes, how do I strip that specific one from the string? </p> <pre><code>b = ["food", "stuffing", "hobbitses"] y = ["ing", "es", "s", "ly"] def stemming(): for i in range(len(b)): if b[i].endswith(tuple(y)): ...
-1
2016-10-16T20:01:19Z
40,074,891
<p>I'd recommend separating out the stem removal into its own function, and then using a list comprehension or a separate function for the whole list. Here's one way of doing it</p> <pre><code>def remove_stems(word, stems): for stem in stems: if word.endswith(stem): return word[:-len(stem)] ...
0
2016-10-16T20:06:10Z
[ "python", "string", "python-2.7", "stemming" ]
If a string contains a suffix from a list, how do I strip that specific suffix from the string?
40,074,825
<p>I have a list of strings and a list of suffixes. If a string contains one of the suffixes, how do I strip that specific one from the string? </p> <pre><code>b = ["food", "stuffing", "hobbitses"] y = ["ing", "es", "s", "ly"] def stemming(): for i in range(len(b)): if b[i].endswith(tuple(y)): ...
-1
2016-10-16T20:01:19Z
40,074,914
<p>You need to know which ending has been found, so you need to check them one at a time instead of trying to check them all at once. Once you have found an ending, you can chop it off using a slice.</p> <pre><code>def stemming(): for i, word in enumerate(b): for suffix in y: if word.endswith(s...
0
2016-10-16T20:07:38Z
[ "python", "string", "python-2.7", "stemming" ]
If a string contains a suffix from a list, how do I strip that specific suffix from the string?
40,074,825
<p>I have a list of strings and a list of suffixes. If a string contains one of the suffixes, how do I strip that specific one from the string? </p> <pre><code>b = ["food", "stuffing", "hobbitses"] y = ["ing", "es", "s", "ly"] def stemming(): for i in range(len(b)): if b[i].endswith(tuple(y)): ...
-1
2016-10-16T20:01:19Z
40,074,997
<p>assuming you want to strip the first suffix found this will do it</p> <pre><code>def stemming(strings, endings): for i, string in enumerate(strings): for ending in endings: if string.endswith(ending): strings[i] = string[:-len(ending)] continue </code></pre>
0
2016-10-16T20:15:28Z
[ "python", "string", "python-2.7", "stemming" ]
How to use sublime 3 jinja2 highlighter
40,074,856
<p>I have a problem with jinja2 highlighter in sublime 3.All the files associated with .html extensions don't recognize jinja templates blocks..I searched the web but the only solution I found is to make a .jinja.html custom extension..anyone got any idea how to solve this?..This is the plugin I installed <a href="htt...
0
2016-10-16T20:03:26Z
40,080,168
<p>You need to add <code>.j2</code> to your file extension:</p> <p><code>mysupertemplate.html.j2</code></p> <p>Have a look at the <a href="https://github.com/kudago/jinja2-tmbundle/blob/master/Syntaxes/HTML%20(Jinja2).tmLanguage" rel="nofollow">syntax file</a> (under <code>fileTypes</code>)</p> <p>Matt</p>
0
2016-10-17T06:55:30Z
[ "python", "sublimetext3", "jinja2", "syntax-highlighting", "sublime-text-plugin" ]
Looping and saving multiple inputs
40,074,874
<p>I'm trying to loop through a set of inputs where I ask for a user's course grade, course hours and course code. The loop keeps on repeating until the user enters "done". Once the user has entered done I want it to print out the entered courses with grade and hours. </p> <p>For Example: </p> <pre><code>course_count...
1
2016-10-16T20:04:35Z
40,074,927
<p>See if you can relate this simplified example to your code. To get the output you describe, you need to <em>store</em> the output text somehow and access it later:</p> <pre><code>output_lines = [] for i in range(10): input_string = input("Enter some input") output_lines.append(input_string) for output_line in...
1
2016-10-16T20:08:38Z
[ "python" ]
Looping and saving multiple inputs
40,074,874
<p>I'm trying to loop through a set of inputs where I ask for a user's course grade, course hours and course code. The loop keeps on repeating until the user enters "done". Once the user has entered done I want it to print out the entered courses with grade and hours. </p> <p>For Example: </p> <pre><code>course_count...
1
2016-10-16T20:04:35Z
40,074,964
<p>You may find it useful to keep your information in a <code>dictionary</code> structure where the key is stored as the course code. Then it is as simple as iterating over each course saved in your dictionary to get the details.</p> <p><strong>Example:</strong> </p> <pre><code>course_count = False course_info = {} #...
1
2016-10-16T20:11:58Z
[ "python" ]
Looping and saving multiple inputs
40,074,874
<p>I'm trying to loop through a set of inputs where I ask for a user's course grade, course hours and course code. The loop keeps on repeating until the user enters "done". Once the user has entered done I want it to print out the entered courses with grade and hours. </p> <p>For Example: </p> <pre><code>course_count...
1
2016-10-16T20:04:35Z
40,075,095
<p>Use an output string <code>output_string</code></p> <p>Add each new line to the output string</p> <pre><code>... output_string += "Course: {} Weight: {} hours Grade: {}\n".format(course_code, course_hours, course_grade" #ELSE END LOOP ... </code></pre> <p>This accumulates the information into a string, using stan...
0
2016-10-16T20:26:43Z
[ "python" ]
Interpolating a variable with regular grid to a location not on the regular grid with Python scipy interpolate.interpn value error
40,074,882
<p>I have a variable from a netcdf file it is a function of time, height, lon, and lat of regular gridded data: U[time,height,lon,lat]. I want to interpolate this variable to a defined location of lon_new,lat_new that is not on the regular grid (it is in between grid points). I want to be able to have the variable U[0,...
0
2016-10-16T20:05:20Z
40,075,119
<p>You can use any appropriate multivariate interpolation function from <a href="http://docs.scipy.org/doc/scipy/reference/interpolate.html" rel="nofollow">scipy</a>. With corrections below your example produces proper result.</p> <pre><code># -*- coding: utf-8 -*- import numpy as np from scipy import interpolate x_...
1
2016-10-16T20:29:44Z
[ "python", "scipy", "interpolation" ]
How to filter the list by selecting for unique combinations of characters in the elements (Python)?
40,074,884
<p>I have the the following pairs stored in the following list</p> <pre><code> sample = [[CGCG,ATAT],[CGCG,CATC],[ATAT,TATA]] </code></pre> <p>Each pairwise comparison can have only two unique combinations of characters, if not then those pairwise comparisons are eliminated. eg,</p> <pre><code> In sample[1] C ...
1
2016-10-16T20:05:25Z
40,075,027
<p>The core of this task is extracting the pairs from your sublists and counting the number of unique pairs. Assuming your samples actually contain strings, you can use <code>zip(*sub_list)</code> to get the pairs. Then you can use <code>set()</code> to remove duplicate entries.</p> <pre><code>sample = [['CGCG','ATA...
1
2016-10-16T20:19:01Z
[ "python", "list", "unique", "combinations" ]
How to filter the list by selecting for unique combinations of characters in the elements (Python)?
40,074,884
<p>I have the the following pairs stored in the following list</p> <pre><code> sample = [[CGCG,ATAT],[CGCG,CATC],[ATAT,TATA]] </code></pre> <p>Each pairwise comparison can have only two unique combinations of characters, if not then those pairwise comparisons are eliminated. eg,</p> <pre><code> In sample[1] C ...
1
2016-10-16T20:05:25Z
40,075,034
<pre><code>sample = [[CGCG,ATAT],[CGCG,CATC],[ATAT,CATC]] result = [] for s in sample: first = s[0] second = s[1] combinations = [] for i in range(0,len(first)): comb = [first[i],second[i]] if comb not in combinations: combinations.append(comb) if len(combinations) == 2: ...
1
2016-10-16T20:19:27Z
[ "python", "list", "unique", "combinations" ]
How to filter the list by selecting for unique combinations of characters in the elements (Python)?
40,074,884
<p>I have the the following pairs stored in the following list</p> <pre><code> sample = [[CGCG,ATAT],[CGCG,CATC],[ATAT,TATA]] </code></pre> <p>Each pairwise comparison can have only two unique combinations of characters, if not then those pairwise comparisons are eliminated. eg,</p> <pre><code> In sample[1] C ...
1
2016-10-16T20:05:25Z
40,075,035
<pre><code>def filter_sample(sample): filtered_sample = [] for s1, s2 in sample: pairs = {pair for pair in zip(s1, s2)} if len(pairs) &lt;= 2: filtered_sample.append([s1, s2]) return filtered_sample </code></pre> <p>Running this</p> <pre><code>sample = [["CGCG","ATAT"],["CGCG...
2
2016-10-16T20:19:31Z
[ "python", "list", "unique", "combinations" ]
Read list of lists of tuples in Python from file
40,074,923
<p>I'd like to read and write a list of lists of tuples from and to files.</p> <pre><code>g_faces = [[(3,2)(3,5)],[(2,4)(1,3)(1,3)],[(1,2),(3,4),(6,7)]] </code></pre> <p>I used</p> <ul> <li><code>pickle.dump(g_faces, fp)</code></li> <li><code>pickle.load(fp)</code></li> </ul> <p>But the file is not human readable. ...
0
2016-10-16T20:08:16Z
40,074,961
<p>Try the json module.</p> <pre><code>import json g_faces = [[(3,2), (3,5)],[(2,4), (1,3), (1,3)],[(1,2), (3,4), (6,7)]] json.dump(g_faces, open('test.json', 'w')) g_faces = json.load(open('test.json')) # cast back to tuples g_faces = [[tuple(l) for l in L] for L in g_faces] </code></pre>
0
2016-10-16T20:11:32Z
[ "python", "serialization", "pickle" ]
Numerology with certain rules
40,074,994
<p><strong>The challenge is to :</strong> Create a function name_numerology(name) which takes input and turns this input into single digit value and then returns it.</p> <p><strong>The rules are:</strong></p> <ul> <li>function must ignore all kind of characters that are not in the list of letters above, treat them as...
-1
2016-10-16T20:15:04Z
40,075,142
<p>I think the purpose is that you start adding digits only after you have processed all input characters:</p> <pre><code>letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' numbers = '12345678912345678912345678' def name_numerology(name): if not isinstance(name, str): return 'Please enter a name' summed = 0 for...
0
2016-10-16T20:33:15Z
[ "python", "python-3.x" ]
python - read email from postfix in python on linux
40,075,029
<p>I'm very new to postfix and python. I've setup postfix on Ubuntu and have configured the <code>main.cf</code> with <code>mailbox_command = /home/someuser/test.py</code></p> <p>test.py:</p> <pre><code>#!/usr/bin/python import sys, MySQLdb email_input = sys.stdin db = MySQLdb.connect(host="localhost", ...
0
2016-10-16T20:19:13Z
40,075,084
<p><code>sys.stdin</code> is an object of type <code>TextIOWrapper</code> and <code>cur.execute</code> is expecting a string. You need to instruct <code>sys.stdin</code> to read input and return the string representing it. Use either <code>readline</code> or <code>readlines</code> depending on what you're trying to do....
1
2016-10-16T20:25:32Z
[ "python", "linux", "postfix" ]
Replace values in pandas Series with dictionary
40,075,106
<p>I want to replace values in a pandas <code>Series</code> using a dictionary. I'm following @DSM's <a href="http://stackoverflow.com/questions/20250771/remap-values-in-pandas-column-with-a-dict">accepted answer</a> like so:</p> <pre><code>s = Series(['abc', 'abe', 'abg']) d = {'b': 'B'} s.replace(d) </code></pre> <...
2
2016-10-16T20:28:05Z
40,075,212
<p>You can do it using <code>regex=True</code> parameter:</p> <pre><code>In [37]: s.replace(d, regex=True) Out[37]: 0 aBc 1 aBe 2 aBg dtype: object </code></pre> <p>As you have already <a href="http://stackoverflow.com/questions/40075106/replace-values-in-pandas-series-with-dictionary/40075212#comment6742361...
1
2016-10-16T20:41:06Z
[ "python", "pandas", "dictionary", "replace" ]
Determine mean value of ‘data’ where the highest number of CONTINUOUS cond=True
40,075,164
<p>I have a pandas Dataframe with a 'data' and 'cond'(-ition) column. I need the mean value (of the data column) of the rows with the highest number of CONTINUOUS True objects in 'cond'. </p> <pre><code> Example DataFrame: cond data 0 True 0.20 1 False 0.30 2 True 0.90 3 True 1...
3
2016-10-16T20:36:09Z
40,075,274
<p>Here's a NumPy based approach -</p> <pre><code># Extract the relevant cond column as a 1D NumPy array and pad with False at # either ends, as later on we would try to find the start (rising edge) # and stop (falling edge) for each interval of True values arr = np.concatenate(([False],df.cond.values,[False])) # De...
1
2016-10-16T20:47:01Z
[ "python", "performance", "pandas", "numpy" ]
Determine mean value of ‘data’ where the highest number of CONTINUOUS cond=True
40,075,164
<p>I have a pandas Dataframe with a 'data' and 'cond'(-ition) column. I need the mean value (of the data column) of the rows with the highest number of CONTINUOUS True objects in 'cond'. </p> <pre><code> Example DataFrame: cond data 0 True 0.20 1 False 0.30 2 True 0.90 3 True 1...
3
2016-10-16T20:36:09Z
40,075,307
<p>Using the approach from <a href="http://stackoverflow.com/questions/29142487/calculating-the-number-of-specific-consecutive-equal-values-in-a-vectorized-way">Calculating the number of specific consecutive equal values in a vectorized way in pandas</a>:</p> <pre><code>df['data'].groupby((df['cond'] != df['cond'].shi...
2
2016-10-16T20:50:23Z
[ "python", "performance", "pandas", "numpy" ]
Django admin dashboard, not able to "select all" records
40,075,189
<p>I have a weird issue were I am not able to "select all" records for any model in my Django admin dashboard.</p> <p><a href="https://i.stack.imgur.com/HQH57.png" rel="nofollow"><img src="https://i.stack.imgur.com/HQH57.png" alt="Django admin, not able to &quot;select all&quot;"></a></p> <p><strong>This is using Dja...
0
2016-10-16T20:38:45Z
40,077,667
<p>I think you'll need to run </p> <pre><code>python manage.py collectstatic </code></pre> <p>so your js will function on the page.</p>
0
2016-10-17T02:28:46Z
[ "python", "django" ]
GMPY2 Not installing, mpir.h not found
40,075,271
<p>I am trying to install gmpy2 on my Anaconda Python 3.5 distribution using pip. I was able to install other modules such as primefac perfectly. When I try to install gmpy2 this is what I get:</p> <pre><code>(C:\Program Files\Anaconda3) C:\WINDOWS\system32&gt;pip install gmpy2 Collecting gmpy2 Using cached gmpy2-2....
0
2016-10-16T20:46:52Z
40,076,291
<p>I maintain <code>gmpy2</code> and unfortunately I have not been able to build Windows binaries for Python 3.5 and later. <code>gmpy2</code> relies on either the MPIR or GMP libraries, and the MPFR and MPC libraries. There are detailed instructions included in the source distribution but they are not trivial to build...
1
2016-10-16T22:43:13Z
[ "python", "install" ]
Selenium on Elementary OS not working with Firefox
40,075,329
<p>I've got a problem with Selenium on my system. For some reason, it wont launch a Firefox browser window. </p> <p>Here are the steps that I have gone though.</p> <ul> <li>Downloaded Selenium via pip</li> <li>Downloaded the Marionette (gecko) driver</li> <li>Added the directory of the downloaded file to my PATH.</li...
1
2016-10-16T20:52:10Z
40,092,191
<p>PyCharm ignores your PYTHONPATH, instead it builds it based on your project configuration(s), so you need to teach it where it can find <code>gecko</code>. You can do that in either of these 2 ways:</p> <ul> <li>configure your interpreter path to include the gecko's dir, see <a href="https://www.jetbrains.com/help/...
0
2016-10-17T17:18:42Z
[ "python", "selenium", "firefox", "pycharm", "elementary" ]
String splitting within a list
40,075,389
<p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input: <code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p> <p>Then the function should return a list containing two lists of first names and last names, like this: <code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code>...
1
2016-10-16T20:56:33Z
40,075,454
<pre><code>input = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob'] firsts = [] lasts = [] for i in input: s = i.split(',') firsts.append(s[0].strip(' ')) lasts.append(s[1].strip(' ')) result = [lasts,firsts] print result </code></pre> <p>result:-</p> <pre><code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']...
-1
2016-10-16T21:03:31Z
[ "python" ]
String splitting within a list
40,075,389
<p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input: <code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p> <p>Then the function should return a list containing two lists of first names and last names, like this: <code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code>...
1
2016-10-16T20:56:33Z
40,075,455
<p>first split &amp; strip items to get name/first name couples, then recombine to get proper arrangement, using listcomps</p> <pre><code>l = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob'] c = [[y.strip() for y in x.split(",")] for x in l] result = [[n[1] for n in c],[n[0] for n in c]] </code></pre> <p>result:</p> <pre><...
1
2016-10-16T21:03:38Z
[ "python" ]
String splitting within a list
40,075,389
<p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input: <code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p> <p>Then the function should return a list containing two lists of first names and last names, like this: <code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code>...
1
2016-10-16T20:56:33Z
40,075,579
<p>This also works:</p> <pre><code>people = ["Gerber, Len", "Fox, Kate", "Dunn, Bob", "Walsh, Jack"] def lastfirst(the_list): name = [] lastname = [] for i in the_list: lastname.append(i.split(",")[0]) name.append(i.split(", ")[1]) firstlast = [name, lastname] print (firstlast)...
0
2016-10-16T21:16:45Z
[ "python" ]
String splitting within a list
40,075,389
<p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input: <code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p> <p>Then the function should return a list containing two lists of first names and last names, like this: <code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code>...
1
2016-10-16T20:56:33Z
40,075,682
<p>Keep it simple and take advantage of list comprehension!</p> <pre><code>def lastfirst(l): return [[x.split(',')[1].strip() for x in l], [x.split(',')[0].strip() for x in l]] print lastfirst(['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']) </code></pre> <p>It will print</p> <pre><code>[['Len', 'Kate', 'Bob'], ['Ge...
0
2016-10-16T21:28:22Z
[ "python" ]
String splitting within a list
40,075,389
<p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input: <code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p> <p>Then the function should return a list containing two lists of first names and last names, like this: <code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code>...
1
2016-10-16T20:56:33Z
40,075,698
<p>In Repl</p> <pre><code>&gt;&gt;&gt; l = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob'] &gt;&gt;&gt; print [[x.split(',')[1].strip() for x in l], [x.split(',')[0].strip() for x in l]] [['Len', 'Kate', 'Bob'], ['Gerber', 'Fox', 'Dunn']] </code></pre>
0
2016-10-16T21:30:22Z
[ "python" ]
String splitting within a list
40,075,389
<p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input: <code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p> <p>Then the function should return a list containing two lists of first names and last names, like this: <code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code>...
1
2016-10-16T20:56:33Z
40,075,786
<p>Take advantage of <code>zip</code></p> <pre><code>&gt;&gt;&gt; a = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob'] &gt;&gt;&gt; b = [i.split(', ') for i in a] list(zip(*b)) [('Gerber', 'Fox', 'Dunn'), ('Len', 'Kate', 'Bob')] </code></pre> <p>This returns a list of tuples, but if you truly want a list you can use <code>...
1
2016-10-16T21:39:33Z
[ "python" ]
String splitting within a list
40,075,389
<p>I'm supposed to create a function called <code>lastfirst()</code> that takes this input: <code>['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']</code></p> <p>Then the function should return a list containing two lists of first names and last names, like this: <code>[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]</code>...
1
2016-10-16T20:56:33Z
40,075,832
<p>Taking Jean-Francois's proposal one step further (BTW, he was right by not giving this answer)</p> <ol> <li>Flip name and surname in first step</li> </ol> <p><code>c = [[y.strip() for y in x.split(",")][::-1] for x in l]</code></p> <p>The result is</p> <pre><code>In [14]: c Out[14]: [['Len', 'Gerber'], ['Kate', ...
1
2016-10-16T21:46:47Z
[ "python" ]
CountVectorizer: transform method returns multidimensional array on a single text line
40,075,497
<p>Firstly, I fit it on the corpus of sms:</p> <pre><code>from sklearn.feature_extraction.text import CountVectorizer clf = CountVectorizer() X_desc = clf.fit_transform(X).toarray() </code></pre> <p>Seems to works fine:</p> <pre><code>X.shape = (5574,) X_desc.shape = (5574, 8713) </code></pre> <p>But then I applied...
0
2016-10-16T21:07:33Z
40,077,817
<p>You always need to pass an array or vector to <code>transform</code>; if you just want to transform a single element, you need to pass a singleton array, and then extract its contents:</p> <pre><code>clf.transform([str1])[0] </code></pre> <p>Incidentally the reason that you are getting a 2-dimensional array as out...
3
2016-10-17T02:53:15Z
[ "python", "python-2.7", "text", "scikit-learn", "sklearn-pandas" ]
Python program asks for input twice, doesn't return value the first time
40,075,530
<p>Here is my code, in the <code>get_response()</code> function, if you enter 'y' or 'n', it says invalid the first time but then works the second time.<br> How do I fix this?</p> <pre><code>import random MIN = 1 MAX = 6 def main(): userValue = 0 compValue = 0 again = get_response() while again ==...
-2
2016-10-16T21:11:31Z
40,075,549
<p><code>answer != 'y' or answer != 'n':</code> is always true; <code>or</code> should be <code>and</code>.</p>
2
2016-10-16T21:13:31Z
[ "python" ]
Python program asks for input twice, doesn't return value the first time
40,075,530
<p>Here is my code, in the <code>get_response()</code> function, if you enter 'y' or 'n', it says invalid the first time but then works the second time.<br> How do I fix this?</p> <pre><code>import random MIN = 1 MAX = 6 def main(): userValue = 0 compValue = 0 again = get_response() while again ==...
-2
2016-10-16T21:11:31Z
40,075,571
<p>It should be <code>answer != 'y' and answer != 'n':</code></p>
0
2016-10-16T21:16:05Z
[ "python" ]
Python program asks for input twice, doesn't return value the first time
40,075,530
<p>Here is my code, in the <code>get_response()</code> function, if you enter 'y' or 'n', it says invalid the first time but then works the second time.<br> How do I fix this?</p> <pre><code>import random MIN = 1 MAX = 6 def main(): userValue = 0 compValue = 0 again = get_response() while again ==...
-2
2016-10-16T21:11:31Z
40,075,609
<p>You're logically thinking that <em>"answer is not y OR n"</em>, but in code that is </p> <pre><code>not (answer == 'y' or answer == 'n') </code></pre> <p>Apply DeMorgans' rule you get</p> <pre><code>answer != 'y' and answer != 'n' </code></pre> <p>Perhaps you should restructure using <code>in</code>. </p> <p>Yo...
0
2016-10-16T21:19:08Z
[ "python" ]
Python Code works in IDLE but not in VS Code
40,075,578
<p>I'm currently starting to learn Python and chose Al Sweigart's "Automate the Boring Stuff with Python" to help me with my first steps. As I really like the look and feel of Visual Studio Code I tried to switch after the first part of the book. </p> <p>The following code is from the online material and should theref...
1
2016-10-16T21:16:45Z
40,075,717
<p>Only Unicode strings have isdecimal(), so you'd have to mark it as such. </p> <p>To convert a string to a unicode string in python, you can do this:</p> <pre><code>s = "Hello!" u = unicode(s, "utf-8") </code></pre> <p>In your question you can just change <code>print(isPhoneNumber('415-555-4242'))</code> to <co...
1
2016-10-16T21:32:04Z
[ "python", "vscode" ]
Containerization pattern best practice
40,075,618
<p>I am dockerizing a Python webapp using the <a href="https://hub.docker.com/r/tiangolo/uwsgi-nginx" rel="nofollow">https://hub.docker.com/r/tiangolo/uwsgi-nginx</a> image, which uses supervisor to control the uWSGI instance.</p> <p>My app actually requires an additional supervisor-mediated process to run (LibreOffic...
0
2016-10-16T21:20:09Z
40,075,742
<p>You've already blown the "one process per container" -- just add another process. It's not a hard rule, or even one that everybody agrees with.</p> <p>Extend away, or better yet author your own custom container. That way you own it, you understand it, and it's optimized for your purpose.</p>
1
2016-10-16T21:34:20Z
[ "python", "nginx", "docker", "uwsgi", "supervisord" ]
Containerization pattern best practice
40,075,618
<p>I am dockerizing a Python webapp using the <a href="https://hub.docker.com/r/tiangolo/uwsgi-nginx" rel="nofollow">https://hub.docker.com/r/tiangolo/uwsgi-nginx</a> image, which uses supervisor to control the uWSGI instance.</p> <p>My app actually requires an additional supervisor-mediated process to run (LibreOffic...
0
2016-10-16T21:20:09Z
40,084,170
<p>The recommendation for one-process-per-container is sound - Docker only monitors the process it starts when the container runs, so if you have multiple processes they're not watched by Docker. It's also a better design - you have lightweight, focused containers with single responsibilities, and you can manage them i...
2
2016-10-17T10:36:20Z
[ "python", "nginx", "docker", "uwsgi", "supervisord" ]
GAE (Python) Best practice: Load config from JSON file or Datastore?
40,075,640
<p>I wrote a platform in GAE Python with a Datastore database (using NDB). My platform allows for a theme to be chosen by the user. Before <em>every</em> page load, I load in a JSON file (using <code>urllib.urlopen(FILEPATH).read()</code>). Should I instead save the JSON to the Datastore and load it through NDB instead...
0
2016-10-16T21:22:53Z
40,075,677
<p>Do you expect the configuration to change without the application code being re-deployed? That is the scenario where it would make sense to store the configuration in the Datastore.</p> <p>If the changing the configuration involves re-deploying the code anyway, a local file is probably fine - you might even conside...
0
2016-10-16T21:27:59Z
[ "python", "json", "google-app-engine", "gae-datastore", "urllib" ]
Using Python 2.7 and RawInput how do I load code into a string variable then convert to all uppercase?
40,075,689
<p>I need to convert a file into a string using raw input then convert the characters to uppercase? How do I do this?</p>
-2
2016-10-16T21:29:26Z
40,075,914
<p>To convert a string <code>s</code> to uppercase: <code>s.upper()</code>.</p> <p>You use raw input like this: </p> <pre><code>name = raw_input("What is your name? ") print "Hello, %s." % name </code></pre>
0
2016-10-16T21:58:27Z
[ "python" ]
Python: Use specific parts of a string (that looks like a list)
40,075,696
<p>I have a text file (file.txt):</p> <pre><code>(A-&gt;[a:5,a:5,a:5,b:50,c:10,c:10]) (B-&gt;[e:120,g:50]) (C-&gt;[a:5,f:20]) </code></pre> <p>and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:</p> <pre><code>totalValue = 20 # of 'a' #OR totalValue = 50 # of 'b' #OR totalValue =...
1
2016-10-16T21:30:12Z
40,075,816
<p>First, parse the couples using a regular expression which extracts them all.</p> <p>Then use the nice <code>itertools.groupby</code> to gather the values using keys as the <code>a,b,c...</code> letter (first item of the regex tuple).</p> <p>Finally, create tuples with variable, sum of values as integer</p> <pre><...
0
2016-10-16T21:43:52Z
[ "python", "string", "file", "python-3.x" ]
Python: Use specific parts of a string (that looks like a list)
40,075,696
<p>I have a text file (file.txt):</p> <pre><code>(A-&gt;[a:5,a:5,a:5,b:50,c:10,c:10]) (B-&gt;[e:120,g:50]) (C-&gt;[a:5,f:20]) </code></pre> <p>and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:</p> <pre><code>totalValue = 20 # of 'a' #OR totalValue = 50 # of 'b' #OR totalValue =...
1
2016-10-16T21:30:12Z
40,075,848
<pre><code>def find(s, ch): return [i for i, ltr in enumerate(s) if ltr == ch] myFile = open("file.txt", "r") content = myFile.read() totalValue = 0 all_colon_indexes = find(content,':') for i in range(0,len(content)): if content[i]==':': if content[i-1]=='a': #THIS IS WHERE YOU SPECIFY 'a' or 'b' o...
0
2016-10-16T21:49:27Z
[ "python", "string", "file", "python-3.x" ]
Python: Use specific parts of a string (that looks like a list)
40,075,696
<p>I have a text file (file.txt):</p> <pre><code>(A-&gt;[a:5,a:5,a:5,b:50,c:10,c:10]) (B-&gt;[e:120,g:50]) (C-&gt;[a:5,f:20]) </code></pre> <p>and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:</p> <pre><code>totalValue = 20 # of 'a' #OR totalValue = 50 # of 'b' #OR totalValue =...
1
2016-10-16T21:30:12Z
40,075,872
<p>Parse the file using regular expressions:</p> <ul> <li><code>\w</code> stands for a word character</li> <li><code>\d</code> stands for a digit</li> <li><code>+</code> specifies that you want to match one or more of the preceding match groups</li> <li><code>?</code> specifies that you want to match zero or one of th...
0
2016-10-16T21:52:44Z
[ "python", "string", "file", "python-3.x" ]
Python: Use specific parts of a string (that looks like a list)
40,075,696
<p>I have a text file (file.txt):</p> <pre><code>(A-&gt;[a:5,a:5,a:5,b:50,c:10,c:10]) (B-&gt;[e:120,g:50]) (C-&gt;[a:5,f:20]) </code></pre> <p>and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:</p> <pre><code>totalValue = 20 # of 'a' #OR totalValue = 50 # of 'b' #OR totalValue =...
1
2016-10-16T21:30:12Z
40,075,874
<p>If I may suggest a somehow more compact solution that sums up every "key" in the text file and outputs a dictionary:</p> <pre><code>import re from collections import defaultdict with open('a.txt') as f: lines = f.read() tups = re.findall(r'(\w+):(\d+)', lines) print(tups) # tups is a list of tuples in the for...
0
2016-10-16T21:53:10Z
[ "python", "string", "file", "python-3.x" ]
Python: Use specific parts of a string (that looks like a list)
40,075,696
<p>I have a text file (file.txt):</p> <pre><code>(A-&gt;[a:5,a:5,a:5,b:50,c:10,c:10]) (B-&gt;[e:120,g:50]) (C-&gt;[a:5,f:20]) </code></pre> <p>and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:</p> <pre><code>totalValue = 20 # of 'a' #OR totalValue = 50 # of 'b' #OR totalValue =...
1
2016-10-16T21:30:12Z
40,075,933
<p>No intention on stepping on Jean-Francois's toes :-) - I would suggest using <em>Counter</em> for count.</p> <pre><code>import collections with open("file.txt", "r") as myFile: r = re.compile("(\w+):(-?\d+)") res = collections.Counter() for l in myFile: for key, cnt in r.findall(l): ...
0
2016-10-16T22:00:52Z
[ "python", "string", "file", "python-3.x" ]
Retrieveing files form URL in Python returns blank
40,075,703
<p>I'm working on a chess related project for which I have to download a very large quantity of files from <a href="http://chesstempo.com" rel="nofollow">ChessTempo</a>. </p> <p>When running the following code:</p> <pre><code>import urllib.request url = "http://chesstempo.com/requests/download_game_pgn.php?gameids="...
0
2016-10-16T21:31:05Z
40,088,708
<p>In fact, I can only download files 2 &amp; 3, all others are empty...</p> <p>Were you logged in while accessing those files "manually"? (Which I assume to be using a web browser).</p> <p>If so, FYI an http request does not only consist of the URL, lots of other information is transfered. So if you are not getting ...
1
2016-10-17T14:11:59Z
[ "python", "urllib" ]
Bayesian Correlation with PyMC3
40,075,725
<p>I'm trying to convert this <a href="http://www.philippsinger.info/?p=581" rel="nofollow">example of Bayesian correlation for PyMC2</a> to PyMC3, but get completely different results. Most importantly, the mean of the multivariate Normal distribution quickly goes to zero, whereas it should be around 400 (as it is for...
1
2016-10-16T21:32:52Z
40,076,826
<p>The call signature of pymc.Normal is </p> <pre><code>In [125]: pymc.Normal? Init signature: pymc.Normal(self, *args, **kwds) Docstring: N = Normal(name, mu, tau, value=None, observed=False, size=1, trace=True, rseed=True, doc=None, verbose=-1, debug=False) </code></pre> <p>Notice that the third positional argument...
1
2016-10-17T00:03:58Z
[ "python", "correlation", "bayesian", "pymc", "pymc3" ]
TypeError: 'HtmlResponse' object is not iterable
40,075,760
<p>I'm new to python, but trying to get my head around it in order to use Scrapy for work.</p> <p>I'm currently following this tutorial: <a href="http://scrapy2.readthedocs.io/en/latest/intro/tutorial.html" rel="nofollow">http://scrapy2.readthedocs.io/en/latest/intro/tutorial.html</a></p> <p>I've having trouble with ...
0
2016-10-16T21:36:17Z
40,083,781
<p>As the error message states</p> <pre><code> for sel in response: </code></pre> <p>You try to iterate through the <code>response</code> object in your <code>medium_Spider.py</code> file at <strong>line 11</strong>.</p> <p>However <code>response</code> is an <code>HtmlResponse</code> not an <em>iterable</em> which ...
1
2016-10-17T10:17:51Z
[ "python", "xpath", "scrapy", "scrapy-spider" ]
Luhns Algorithm
40,075,829
<p>Hey I am doing Luhn's algorithm for an assignment for school.</p> <p>A few outputs are coming out the correct way; however, some are not. </p> <p><code>0004222222222222</code> is giving me a total of <code>44</code>, </p> <p>and</p> <p><code>0378282246310005</code> is giving me a total of <code>48</code>, </p> ...
3
2016-10-16T21:46:30Z
40,076,095
<p>You almost got it right. Only that the last digit (or first from behind) should be considered as odd for your 16 digit card. So you should set:</p> <pre><code>digit = len(cardNumber) - 1 </code></pre> <p>And then your <em>while</em> condition should stop at <code>&gt;= 0</code> (zeroth item inclusive); note that t...
2
2016-10-16T22:19:44Z
[ "python", "luhn" ]
Luhns Algorithm
40,075,829
<p>Hey I am doing Luhn's algorithm for an assignment for school.</p> <p>A few outputs are coming out the correct way; however, some are not. </p> <p><code>0004222222222222</code> is giving me a total of <code>44</code>, </p> <p>and</p> <p><code>0378282246310005</code> is giving me a total of <code>48</code>, </p> ...
3
2016-10-16T21:46:30Z
40,076,387
<p>So your code is mostly correct, the only issue is that you haven't properly defined what should be considered an "odd" and an "even" number. As you read the number from the end, "odd and even" are also relative from the end, so :</p> <ul> <li>odd numbers start from the <em>last one</em>, and then every other one <...
0
2016-10-16T22:57:11Z
[ "python", "luhn" ]
Unable to access modified value of imported variable
40,075,860
<p>I am new to python and have some problem understanding the scope here.</p> <p>I have a python module A with three global variables :</p> <pre><code>XYZ = "val1" ABC = {"k1" : "v1", "k2" : "v2"} PQR = 1 class Cls_A() : def sm_fn_A(self) : global XYZ global ABC global PQR XYZ = ...
0
2016-10-16T21:51:40Z
40,076,268
<h1>Explanation</h1> <p>Three global variables are defined in module <code>A</code>, in this code:</p> <pre><code>XYZ = "val1" ABC = {"k1" : "v1", "k2" : "v2"} PQR = 1 </code></pre> <p>Then new global variables <code>XYZ</code>, <code>ABC</code>, <code>PQR</code> are defined in module <code>B</code>, in this code:</...
1
2016-10-16T22:39:59Z
[ "python", "python-2.7", "import", "scope", "global-variables" ]
Get input from user at command line and use that input to feed variables into Python script
40,075,894
<p>I have a script named <code>GetStats.py</code>. </p> <p>At a high level, the <code>GetStats.py</code> script does the following:</p> <p>1) makes a connection to an external database 2) retrieves some data from this database 3) writes the data retrieved in step 2 to a csv file</p> <p>Importantly, the <code>GetSta...
-2
2016-10-16T21:55:35Z
40,076,855
<p>Consider sourcing your <em>GetStats.py</em> as a module in a different .py script that receives user input via <code>input()</code> (or <code>raw_input()</code> in Python 2). In this way, you do no need a batch file or entering parameters via command line which is not a user-friendly interface. Plus, you can loop th...
0
2016-10-17T00:08:42Z
[ "python", "batch-file" ]
How to transform a slice of dataframe into a new data frame
40,075,924
<p>I'm new to python and I'm confused sometimes with some operations I have a dataframe called <code>ro</code> and I also have filtered this dataframe using a specific column <code>PN 3D</code> for a specific value <code>921</code> and I assigned the results into a new data frame called <code>headlamp</code> by using t...
1
2016-10-16T21:59:33Z
40,076,219
<p>Use <code>.loc</code></p> <pre><code>headlamp = ro.loc[ro['PN 3D']=="921"] </code></pre> <hr> <p>As for the rest and your comments... I'm very confused. But this is my best guess</p> <p><strong><em>setup</em></strong> </p> <pre><code>import pandas as pd from string import ascii_lowercase chars = ascii_lowerc...
1
2016-10-16T22:32:59Z
[ "python", "pandas", "dataframe", "slice" ]
Compiling f90 function that returns array using f2py
40,075,932
<p>I have a subroutine that calculates a large array and writes it to a file. I'm trying to transform that into a function that returns that array. However, I'm getting a very weird error which seems to be connected to the fact that I am returning an array. When I try to return a float (as a test) it works perfectly fi...
0
2016-10-16T22:00:46Z
40,097,112
<p><em>I think the problem is coming from somewhere from lack of the explicit interface. (not sure may be someone else can point out what is the problem more precisely.)</em></p> <p>Even though, I am not sure about my explanation, I have 2 working cases. <strong>Changing your function into a subroutine</strong> or <st...
0
2016-10-17T23:16:31Z
[ "python", "arrays", "fortran", "f2py" ]
Python 2.7 reading a new line in CSV and store it as variable
40,075,967
<p>I am using the code below to read the last line of my csv. file which is constantly updated and is working great. I am receiving the last line and it is consisted of 11 values which are comma separated. It goes like:</p> <p>10/16/16, -1, false, 4:00:00 PM, 4585 , .......etc</p> <p>Now I want to take the values fr...
1
2016-10-16T22:03:56Z
40,076,247
<p>You certainly can just add a few line in there to get what you want. I would delim each line by comma using <code>line.split(',')</code>. This will return an array like this <code>['10/16/16', '-1', 'false', '4:00:00 PM', '4585' ]</code>. Then you can simply save the array at index 6 ~ 9 for your convenience and use...
0
2016-10-16T22:37:24Z
[ "python", "csv" ]
Accessing Variable in Keras Callback
40,076,021
<p>So I've a CNN implemented. I have made custom callbacks that are confirmed working but I have an issue.</p> <p>This is a sample output. Example of iteration 5 (batch-size of 10,000 for simplicity)</p> <pre><code>50000/60000 [========================&gt;.....] - ETA: 10s ('new lr:', 0.01) ('accuracy:', 0.70) </cod...
0
2016-10-16T22:11:12Z
40,087,960
<p>You can <a href="https://keras.io/callbacks/#create-a-callback" rel="nofollow">create your own callback</a></p> <pre><code>class AccCallback(keras.callbacks.Callback): def on_batch_end(self, batch, logs={}): accuracy = logs.get('acc') # pass accuracy to your 'external' script and set new lr her...
0
2016-10-17T13:38:56Z
[ "python", "keras" ]
Passing request (user) to a class based view
40,076,046
<p>As someone who is a bit new to class based views, I have decided to use them to drive some charts in an application I am working on.</p> <p>However, I would like to make this chart dynamic and would like it to change based on who is seeing it. </p> <p>How can one pass a request (to get the user from) to a class ba...
0
2016-10-16T22:13:32Z
40,076,715
<p>Your class definition is incorrect. A CBV shouldn't inherit from HttpRequest (and I am not even sure if that's what you mean by <code>request</code>) . The correct definition is</p> <pre><code>class LineChartJSONView(BaseLineChartView): </code></pre> <p>This assumes of course that <code>BaseLineChartView</code> ha...
1
2016-10-16T23:44:39Z
[ "python", "django", "django-views", "django-class-based-views" ]
Passing request (user) to a class based view
40,076,046
<p>As someone who is a bit new to class based views, I have decided to use them to drive some charts in an application I am working on.</p> <p>However, I would like to make this chart dynamic and would like it to change based on who is seeing it. </p> <p>How can one pass a request (to get the user from) to a class ba...
0
2016-10-16T22:13:32Z
40,079,588
<p>You do not need to pass <code>request</code> to class based views, it is already there for you if you inherit them from Django's generic views. Generic class based views have methods for handling requests (GET, POST, etc). </p> <p>For example:</p> <pre><code>class LineChartJSONView(generic.View): def get(self,...
1
2016-10-17T06:14:55Z
[ "python", "django", "django-views", "django-class-based-views" ]
Getting Django PROD ready best practice on Heroku
40,076,092
<p>I have recently run into some problems flipping off Debug mode on my Heroku instance of Django (filled from the Heroku Django template).</p> <p>I have begun diving through the specific Heroku logs. However, was wondering if anyone has already made a checklist for things one should do after turning off Debug mode on...
-2
2016-10-16T22:19:18Z
40,123,144
<p>Not specific to Heroku, but I've made the following checklist. You may want to checkout <a href="http://djangodeployment.com/2016/10/18/checklist-for-django-settings-on-deployment/" rel="nofollow">the original list</a>, which expands on static files and links the settings to the Django documentation.</p> <ul> <li><...
1
2016-10-19T05:46:32Z
[ "python", "django", "debugging", "heroku" ]
Annotate graph using data from Array
40,076,093
<p>I have a matplotlib graph that I have created using data from arrays. I want to annotate this graph at certain points. The x axis is populated with dates (14/06/12, 15/06/12) etc.. The y axis is price (6500, 6624) etc... I would like to annotate at point: for example (x,y) (14/06/12, 6500). This is my code so far:</...
0
2016-10-16T22:19:24Z
40,076,234
<p>Here's a quick example using the matplotlib.pyplot text command to add text to a plot at a specified location:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt plt.figure() x = np.arange(-5, 5, 0.1) plt.plot(x, np.cos(x)) plt.text(x=-4, y=0.5, s="Cosine", fontsize=20) plt.show() </code></pre> <p>...
0
2016-10-16T22:35:17Z
[ "python", "matplotlib" ]
Removing duplicate mpatches from a list
40,076,108
<p>I startet to work with buttons in my plots (<code>from matplotlib.widgets import Button</code>). By pressing the buttons different plots will show up. For that reason my legends do change. I handle this by putting the mpatches in a list:</p> <pre><code>red_patch = mpatches.Patch(color='red', label='Numerical averag...
0
2016-10-16T22:21:22Z
40,076,185
<p>The problem is that:</p> <pre><code>red_patch = mpatches.Patch(color='red', label='Numerical average') </code></pre> <p>creates an instance of <code>red_patch</code> every time. The <code>__eq__</code> operator seems to be unimplemented for this particular type, so the <code>set</code> only compares references of ...
1
2016-10-16T22:29:35Z
[ "python", "matplotlib" ]
Python IRC Bot, distinguish from channel messages and private messages
40,076,143
<p>I'm coding a simple IRC bot in Python. Actually, It can connect to a specific channel, read messages and send response, but it can't distinguish between channel messages and private messages. </p> <p><strong>Example</strong>:<br> John, connected to the same channel, send a private message to the Bot's chat, like "!...
1
2016-10-16T22:25:06Z
40,110,181
<p>The source of the message is included in the protocol message, now you are just not using it. </p> <p>In the part where you do this</p> <pre><code>parts = ircmsg_clean.split() </code></pre> <p>you get it in to the list <code>parts</code>.</p> <p>If I remember correctly, and understand the RFQ right, the irc mess...
1
2016-10-18T13:53:22Z
[ "python", "networking", "bots", "irc", "channel" ]
Rectangle collision in pygame? (Bumping rectangles into each other)
40,076,160
<p>I decided to move that Squarey game to pygame, and now I have 2 rectangles that can move around and bump into the walls. However, the rectangles can move right through each other. How would I make them bump into each other and stop? My code:</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mo...
0
2016-10-16T22:26:46Z
40,076,469
<p>To check for collisions, try something like this:</p> <pre><code>def doRectsOverlap(rect1, rect2): for a, b in [(rect1, rect2), (rect2, rect1)]: # Check if a's corners are inside b if ((isPointInsideRect(a.left, a.top, b)) or (isPointInsideRect(a.left, a.bottom, b)) or ...
0
2016-10-16T23:07:34Z
[ "python", "pygame", "collision", "rectangles" ]
Rectangle collision in pygame? (Bumping rectangles into each other)
40,076,160
<p>I decided to move that Squarey game to pygame, and now I have 2 rectangles that can move around and bump into the walls. However, the rectangles can move right through each other. How would I make them bump into each other and stop? My code:</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mo...
0
2016-10-16T22:26:46Z
40,077,464
<p>Use <a href="http://www.pygame.org/docs/ref/rect.html#pygame.Rect.colliderect" rel="nofollow">pygame.Rect.colliderect</a></p> <pre><code>if rect1.colliderect(rect2): print("Collision !!") </code></pre> <hr> <p>BTW: you can create <code>rect1</code> (and <code>rect2</code>) only once - before main loop - and ...
0
2016-10-17T01:54:01Z
[ "python", "pygame", "collision", "rectangles" ]
How to remove data from DataFrame permanently
40,076,176
<p>After reading CSV data file with:</p> <pre><code>import pandas as pd df = pd.read_csv('data.csv') print df.shape </code></pre> <p>I get DataFrame 99 rows (indexes) long:</p> <pre><code>(99, 2) </code></pre> <p>To cleanup DataFrame I go ahead and apply dropna() method which reduces it to 33 rows:</p> <pre><cod...
2
2016-10-16T22:28:45Z
40,076,307
<p>You're being confused by the fact that the row labels have been preserved so the last row label is still <code>99</code>.</p> <p>Example:</p> <pre><code>In [2]: df = pd.DataFrame({'a':[0,1,np.NaN, np.NaN, 4]}) df Out[2]: a 0 0 1 1 2 NaN 3 NaN 4 4 </code></pre> <p>After calling <code>dropna</code> the i...
3
2016-10-16T22:45:12Z
[ "python", "pandas", "dataframe" ]
Finding and printing a specific Pattern in a given string
40,076,198
<p>I am writing a code find a specific pattern in a given string using python or perl. I had some success in finding the pattern using C but python or perl usage is mandatory for this assignment and I am very new in both of these lanuages.</p> <p>My string looks like this (Amino acid sequence) :-</p> <pre><code> MKTS...
-2
2016-10-16T22:30:53Z
40,076,255
<p>Regardless of the language, this looks a task suitable for regular expressions.</p> <p>Here is an example of how you could do the regex in python. If you want the index where the match starts, you can do:</p> <pre><code>m = re.search(r'K(?:[A-JL-Z]+?|K)[KR][A-Z]R', s) print m.start() # prints index print m.group...
0
2016-10-16T22:38:17Z
[ "python", "perl" ]
Finding and printing a specific Pattern in a given string
40,076,198
<p>I am writing a code find a specific pattern in a given string using python or perl. I had some success in finding the pattern using C but python or perl usage is mandatory for this assignment and I am very new in both of these lanuages.</p> <p>My string looks like this (Amino acid sequence) :-</p> <pre><code> MKTS...
-2
2016-10-16T22:30:53Z
40,076,542
<p>You say you want the match to be non-greedy, but that doesn't make sense. I think you are trying to find the minimal match. If so, that's very hard to do. This is the regex match you need:</p> <pre><code>/ K (?: (?: [^KR] | R(?!.R) )+ | . ) [KR] . R /sx </code></pre> <hr> <p>However,...
0
2016-10-16T23:17:23Z
[ "python", "perl" ]
Finding and printing a specific Pattern in a given string
40,076,198
<p>I am writing a code find a specific pattern in a given string using python or perl. I had some success in finding the pattern using C but python or perl usage is mandatory for this assignment and I am very new in both of these lanuages.</p> <p>My string looks like this (Amino acid sequence) :-</p> <pre><code> MKTS...
-2
2016-10-16T22:30:53Z
40,077,287
<p>Only did it this way because I hate back tracking in my regular expressions. But I do find its usually faster if I perform the most restrictive part of the match first. Which in this case is made simpler by reversing the input and the search pattern. This should stop at the first (shortest) possible match; rather...
-1
2016-10-17T01:27:01Z
[ "python", "perl" ]
How to calculate counts and frequencies for pairs in list of lists?
40,076,241
<p>Bases refers to A,T,G and C</p> <pre><code>sample = [['CGG','ATT'],['GCGC','TAAA']] # Note on fragility of data: Each element can only be made up only 2 of the 4 bases. # [['CGG' ==&gt; Only C and G,'ATT' ==&gt; Only A and T],['GCGC'==&gt; Only C and G,'TAAA' ==&gt; Only T and A]] # Elements like "ATGG" are not ...
0
2016-10-16T22:36:35Z
40,076,570
<p>You are not really using <code>Counter</code> any different than a plain <code>dict</code>. Try something like the following approach:</p> <pre><code>&gt;&gt;&gt; sample = [['CGG','ATT'],['GCGC','TAAA']] &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; base_counts = [[Counter(base) for base in sub] for sub...
0
2016-10-16T23:20:53Z
[ "python", "list", "dictionary", "count" ]
DRF auth_token: "non_field_errors": [ "Unable to log in with provided credentials."
40,076,254
<p>Both JWT packages written for Django gave me issues with poor documentation, so I try DRF-auth_token package. This is a good example I followed, <a href="http://stackoverflow.com/questions/14838128/django-rest-framework-token-authentication">Django Rest Framework Token Authentication</a>. You should in theory be abl...
0
2016-10-16T22:38:14Z
40,077,820
<p>I went ahead and did this from the <a href="http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication" rel="nofollow">drf token auth docs</a> and didn't run into any problems with superusers, staffusers, or normal users. Maybe take a look at my code and see if you can find some difference. <...
1
2016-10-17T02:53:57Z
[ "python", "django", "django-rest-framework", "django-rest-auth", "django-1.10" ]
Kivy changing color of a custom button on press
40,076,274
<p>Goes without saying that I am new to kivy, trying to write a simple GUI with triangular buttons (and I want them to be decent, not just images that are still a square canvas that be clicked off the triangular part). So I found this great code that makes a triangle and gets the clickable area. </p> <p>Basically I ju...
3
2016-10-16T22:40:30Z
40,076,499
<p>You are already in the widget, go directly for it, not through <code>ids</code>. <code>Ids</code> are for property <code>id</code> set in the children of a widget in kv language e.g. if your TriangleButton had a child <code>Image</code> with an <code>id: myimage</code>, you'd get it with this:</p> <pre><code>self.i...
0
2016-10-16T23:12:14Z
[ "python", "kivy" ]
How is numpy pad implemented (for constant value)
40,076,280
<p>I'm trying to implement the numpy pad function in theano for the constant mode. How is it implemented in numpy? Assume that pad values are just 0.</p> <p>Given an array </p> <pre><code>a = np.array([[1,2,3,4],[5,6,7,8]]) # pad values are just 0 as indicated by constant_values=0 np.pad(a, pad_width=[(1,2),(3,4)], m...
2
2016-10-16T22:41:30Z
40,077,302
<p>My instinct is to do:</p> <pre><code>def ...(arg, pad): out_shape = &lt;arg.shape + padding&gt; # math on tuples/lists idx = [slice(x1, x2) for ...] # again math on shape and padding res = np.zeros(out_shape, dtype=arg.dtype) res[idx] = arg # may need tuple(idx) return res </code></pre> ...
0
2016-10-17T01:29:20Z
[ "python", "arrays", "numpy", "pad" ]
string in range is not working
40,076,292
<p>I'm new to Python. I'm struggling with range. I'm not good at explaining this problem but I will show you a problem.</p> <p>Here my code:</p> <pre><code>my_hanes = ['Blue', 'Red', 'Grey', 'Black'] my_hanes_len = len(my_hanes) for h in range(0, my_hanes_len): print(my_hanes_len[h]) </code></pre> <p>Every time, ...
0
2016-10-16T22:43:17Z
40,076,334
<p>You can iterate over each object of a list more simply, as you're trying to do</p> <pre><code>my_hanes = ['Blue', 'Red', 'Grey', 'Black'] for hanes in my_hanes: print hanes </code></pre> <p>This will print each item in list <code>my_hanes</code>.</p>
1
2016-10-16T22:49:35Z
[ "python", "int", "range" ]
string in range is not working
40,076,292
<p>I'm new to Python. I'm struggling with range. I'm not good at explaining this problem but I will show you a problem.</p> <p>Here my code:</p> <pre><code>my_hanes = ['Blue', 'Red', 'Grey', 'Black'] my_hanes_len = len(my_hanes) for h in range(0, my_hanes_len): print(my_hanes_len[h]) </code></pre> <p>Every time, ...
0
2016-10-16T22:43:17Z
40,076,377
<p>You need <code>print(my_hanes[h])</code> instead of <code>print(my_hanes_len[h])</code>.</p>
2
2016-10-16T22:55:58Z
[ "python", "int", "range" ]
string in range is not working
40,076,292
<p>I'm new to Python. I'm struggling with range. I'm not good at explaining this problem but I will show you a problem.</p> <p>Here my code:</p> <pre><code>my_hanes = ['Blue', 'Red', 'Grey', 'Black'] my_hanes_len = len(my_hanes) for h in range(0, my_hanes_len): print(my_hanes_len[h]) </code></pre> <p>Every time, ...
0
2016-10-16T22:43:17Z
40,076,397
<p>The problem with your code is that my_hanes is an array of strings. So len(my_hanes) is an integer value (4) indicating the length of your array (aka python list). If you want to get the length of each element of my_hanes as a list, you can iterate to make one:</p> <pre><code>my_hanes = ['Blue', 'Red', 'Grey', 'B...
0
2016-10-16T22:58:51Z
[ "python", "int", "range" ]
Catch anything and save it into a variable
40,076,310
<p>I'm wondering if there is a keyword for "all" in python <code>except</code>. I've ran into this seemingly simple problem:</p> <pre><code>try: #do stuff except any as error: print('error: {err}'.format(err=error)) </code></pre> <p>I know that you can do <code>except:</code> to catch all errors, but I don't...
-1
2016-10-16T22:46:38Z
40,076,331
<p>Yes, just catch <code>Exception</code>:</p> <p><code>except Exception as ex:</code></p>
3
2016-10-16T22:49:15Z
[ "python", "except" ]
Catch anything and save it into a variable
40,076,310
<p>I'm wondering if there is a keyword for "all" in python <code>except</code>. I've ran into this seemingly simple problem:</p> <pre><code>try: #do stuff except any as error: print('error: {err}'.format(err=error)) </code></pre> <p>I know that you can do <code>except:</code> to catch all errors, but I don't...
-1
2016-10-16T22:46:38Z
40,076,340
<p>You can catch almost anything this way:</p> <pre><code>try: #do stuff except Exception as error: print('error: {err}'.format(err=error)) </code></pre> <p>But to catch really everything, you can do this:</p> <pre><code>import sys try: #do stuff except: err_type, error, traceback = sys.exc_info() ...
11
2016-10-16T22:50:05Z
[ "python", "except" ]
pygame: how do I get my game to actually run at 60fps?
40,076,353
<p>In my main loop I have:</p> <pre><code>clock.tick_busy_loop(60) pygame.display.set_caption("fps: " + str(clock.get_fps())) </code></pre> <p>However, the readout says the game is reading at 62.5fps. I then tried to input <code>clock.tick_busy_loop(57.5)</code>, which gave me a readout of 58.82...fps. When I set <co...
0
2016-10-16T22:51:38Z
40,077,658
<p>So I whipped up a simple demo based on my comment above that uses the system time module instead of the pygame.time module. You can ignore the OpenGL stuff as I just wanted to render something simple on screen. The most important part is the timing code at the end of each frame, which I have commented about in the c...
0
2016-10-17T02:26:27Z
[ "python", "pygame", "pygame-clock" ]
matplotlib/pyplot not plotting data from specific .txt file
40,076,368
<p>I have data saved via numpy's savetxt function and am extracting it to plot. When I plot it the script executes without errors but does not show the curves--only empty windows. This is strange because:</p> <ol> <li><p>The same script makes a fine plot when I import .txt data from another file (also saved using save...
1
2016-10-16T22:53:53Z
40,122,293
<p>well, a bit more digging and the problem has been identified. The script <em>is</em> plotting, but the zoom on the plots is so poor that they are obscured by the thick lines on the border. So the problem was a user error. </p> <p>This is why engineers shouldn't try to be artists... </p>
0
2016-10-19T04:42:56Z
[ "python", "numpy", "matplotlib", "plot" ]
Connecting to Google Cloud Storage using standalone Python script using service account
40,076,417
<p>I am trying to connect to Google Cloud Storage from a standalone python script using a service account. I am running this script from my local system. I have also activated the service account using gcloud auth and added "GOOGLE_APPLICATION_CREDENTIALS" to point to the client_secrets.json file. </p> <p>The authenti...
0
2016-10-16T23:00:55Z
40,076,473
<p>The last line of the traceback indicates that your Python script cannot access a resource on disk with the correct permissions.</p> <p><code>IOError: [Errno 13] Permission denied</code></p> <p>A simple fix is to run this script with sudo.</p>
0
2016-10-16T23:07:56Z
[ "python", "google-cloud-storage", "google-api-python-client", "service-accounts" ]
Connecting to Google Cloud Storage using standalone Python script using service account
40,076,417
<p>I am trying to connect to Google Cloud Storage from a standalone python script using a service account. I am running this script from my local system. I have also activated the service account using gcloud auth and added "GOOGLE_APPLICATION_CREDENTIALS" to point to the client_secrets.json file. </p> <p>The authenti...
0
2016-10-16T23:00:55Z
40,076,479
<p>From the error it looks like a simple permissions problem. Did you run the program with root priviges? If not then run the file from the command line with <code>sudo</code> at the beginning.</p> <p>Note: IDLE doesn't run it with root.</p>
1
2016-10-16T23:08:45Z
[ "python", "google-cloud-storage", "google-api-python-client", "service-accounts" ]
Global array storing counters updated by each thread; main thread to read counters on demand?
40,076,481
<p>Here's the scenario: a main thread spawns upto N worker threads that each will update a counter (say they are counting number of requests handled by each of them).</p> <p>The total counter also needs to be read by the main thread on an API request.</p> <p>I was thinking of designing it like so:</p> <p>1) Global h...
0
2016-10-16T23:08:59Z
40,076,739
<p>Just use an <code>std::atomic&lt;int&gt;</code> to keep a running count. When any thread updates its counter it also updates the running count. When the main thread needs the count it reads the running count. The result may be less than the actual total at any given moment, but whenever things settle down, the total...
0
2016-10-16T23:47:57Z
[ "java", "python", "c++", "multithreading", "pthreads" ]
Global array storing counters updated by each thread; main thread to read counters on demand?
40,076,481
<p>Here's the scenario: a main thread spawns upto N worker threads that each will update a counter (say they are counting number of requests handled by each of them).</p> <p>The total counter also needs to be read by the main thread on an API request.</p> <p>I was thinking of designing it like so:</p> <p>1) Global h...
0
2016-10-16T23:08:59Z
40,077,181
<p>Your design sounds like the correct approach. Don't think of them as per-thread mutexes: think of them as per-counter mutexes (each element of your array should probably be a mutex/counter pair).</p> <p>In the main thread there may be no need to lock all of the mutexes and then read all of the counters: you might ...
0
2016-10-17T01:04:12Z
[ "java", "python", "c++", "multithreading", "pthreads" ]
How to drop duplicate from DataFrame taking into account value of another column
40,076,534
<p>When I drop <code>John</code> as duplicate specifying 'name' as the column name: </p> <pre><code>import pandas as pd data = {'name':['Bill','Steve','John','John','John'], 'age':[21,28,22,30,29]} df = pd.DataFrame(data) df = df.drop_duplicates('name') </code></pre> <p>pandas drops all matching entities leaving t...
5
2016-10-16T23:15:38Z
40,076,558
<p>Try this:</p> <pre><code>In [75]: df Out[75]: age name 0 21 Bill 1 28 Steve 2 22 John 3 30 John 4 29 John In [76]: df.sort_values('age').drop_duplicates('name', keep='last') Out[76]: age name 0 21 Bill 1 28 Steve 3 30 John </code></pre> <p>or this depending on your goals:</...
4
2016-10-16T23:19:54Z
[ "python", "pandas", "dataframe" ]
MongoDB query syntax error
40,076,599
<p>I've run into an issue when querying a collection I've made of Twitch JSON objects. However, the following query throws "SyntaxError: invalid syntax".</p> <pre><code>objflat = db.twitchstreams.find({'_links': [ 'streams': [ {'channel': {'game': gameName} } ] }) </code></pre> <p...
0
2016-10-16T23:24:57Z
40,076,678
<p>In your nested data structure you do have a syntax error after 'streams'. A list only takes elements, not key/value pairs. </p> <p>Example below is using IPython:</p> <p>This works:</p> <pre><code>In [5]: {"foo":["bar"]} </code></pre> <p>This doesn't:</p> <pre><code>In [6]: {"foo":["bar": 1]} File "&lt;ipyt...
0
2016-10-16T23:37:03Z
[ "python", "json", "mongodb", "twitch" ]
I write this code of Simulated Annealing for TSP and I have been trying all day to debug it but something goes wrong
40,076,618
<p>This code suppose to reduce the distance of initial tour: distan(initial_tour) &lt; distan(best) . Can you help me plz? I 've been trying all day now. <strong>Do I need to change my swapping method?</strong> Something goes wrong and the simulated annealing does'not work:</p> <pre><code>def prob(currentDistance,neig...
2
2016-10-16T23:28:05Z
40,077,348
<p>Your problem is in the first line of your <code>while</code> loop, where you write</p> <pre><code>new_solution= current_best </code></pre> <p>What this does is puts a reference to the <code>current_best</code> list into <code>new_solution</code>. This means that when you change <code>new_solution</code>, you're a...
0
2016-10-17T01:35:46Z
[ "python", "traveling-salesman", "simulated-annealing" ]
Where do you save a notepad file so python can open it in the program?
40,076,672
<p>My program can't locate the file. How do I save the text file in the python directory on Windows? I've looked through other similar questions but cant find a basic guide to save into the same directory. Thanks for the help</p> <pre><code>user_input = input("file name") fh=open(user_input,"r",encoding="utf-8") </cod...
-4
2016-10-16T23:36:04Z
40,076,708
<p>If i understood your question right, all you have to do is search for the python directory, press the Windows key and type the name of a folder, and the folder will show up among the Start menu search results. Save the notepad file in that directory. Hopefully that helps you.</p>
0
2016-10-16T23:43:31Z
[ "python", "file" ]
Where do you save a notepad file so python can open it in the program?
40,076,672
<p>My program can't locate the file. How do I save the text file in the python directory on Windows? I've looked through other similar questions but cant find a basic guide to save into the same directory. Thanks for the help</p> <pre><code>user_input = input("file name") fh=open(user_input,"r",encoding="utf-8") </cod...
-4
2016-10-16T23:36:04Z
40,076,762
<p>You are probably giving relative paths to <code>user_input</code>. Relative paths are resolved based on the <em>current working directory</em> (cwd). cwd is the directory from which python was started, which can be anything (not only where it is located), depending on how you start the script.</p> <p>To find out wh...
0
2016-10-16T23:53:03Z
[ "python", "file" ]
python how to debug errors by logging issues
40,076,683
<p>I'm very new to python and have a script that runs when an email is sent to the server. My issue is trying to debug the script. How can I push any errors to a log file?</p> <p>Here is the script:</p> <pre><code>#!/usr/bin/python import sys, email email_input = email.message_from_string(sys.stdin.read()) directory...
0
2016-10-16T23:37:36Z
40,076,754
<p>There are at least a couple ways to do this:</p> <ol> <li><p>You can print to stdout and redirect to a file. Here is an example</p> <p>➜ ~ python print_this.py &amp;> log.txt</p> <p>➜ ~ cat log.txt </p> <p>this message</p> <p>➜ ~ cat print_this.py </p> <p>print("this message")</p></li> <li><p>You can...
0
2016-10-16T23:51:42Z
[ "python" ]
multiples section on Restplus swagger documentation
40,076,752
<p>On Restplus documentation (using B!ueprints) we see : a full example: <a href="https://flask-restplus.readthedocs.io/en/0.2.3/example.html" rel="nofollow">https://flask-restplus.readthedocs.io/en/0.2.3/example.html</a></p> <p>The created swagger documentation has only one section "todos : TODO operations "</p> <p>...
0
2016-10-16T23:51:33Z
40,078,477
<p>You need to use Namespaces to achieve this. Each Namespace becomes a separate section in swagger doc.</p> <p><a href="http://flask-restplus.readthedocs.io/en/stable/scaling.html" rel="nofollow">http://flask-restplus.readthedocs.io/en/stable/scaling.html</a></p>
1
2016-10-17T04:24:57Z
[ "python", "swagger", "flask-restplus" ]
Pandas merge not keeping 'on' column
40,076,806
<p>I'm trying to merge two dataframes in <code>pandas</code> on a common column name (orderid). The resulting dataframe (the merged dataframe) is dropping the orderid from the 2nd data frame. Per the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow" title="docu...
3
2016-10-17T00:00:59Z
40,076,945
<p>Rename the <code>orderid</code> columns so that <code>df</code> has a column named <code>orderid_left</code>, and <code>df2</code> has a column named <code>orderid_right</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame([[1,'a'], [2, 'b'], [3, 'c']], columns=['orderid', 'ordervalue']) df['orderid'] =...
3
2016-10-17T00:24:10Z
[ "python", "pandas" ]
install nvidia digits - ImportError: No module named wtforms
40,076,808
<pre><code> ___ ___ ___ ___ _____ ___ | \_ _/ __|_ _|_ _/ __| | |) | | (_ || | | | \__ \ |___/___\___|___| |_| |___/ 5.0.0-rc.1 Traceback (most recent call last): File "/home/jj/anaconda2/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/home/jj/anac...
0
2016-10-17T00:01:23Z
40,077,092
<p>This is one of the canonical use cases for virtualenv. Because you are using sudo to install, there are now two potential paths where items could be installed: User and Root paths.</p> <p>Try creating a virtualenv:</p> <p>then pip install from inside virtualenv.</p>
0
2016-10-17T00:48:48Z
[ "python", "deep-learning", "nvidia", "caffe", "digits" ]
How to merge two DataFrames into single matching the column values
40,076,861
<p>Two DataFrames have matching values stored in their corresponding 'names' and 'flights' columns. While the first DataFrame stores the distances the other stores the dates:</p> <pre><code>import pandas as pd distances = {'names': ['A', 'B','C'] ,'distances':[100, 200, 300]} dates = {'flights': ['C', 'B', 'A'] ,'...
5
2016-10-17T00:09:22Z
40,076,983
<p>There is nothing that ties these dataframes together other than the positional index. You can accomplish your desired example output with <code>pd.concat</code></p> <pre><code>pd.concat([distancesDF, datesDF.dates], axis=1) </code></pre> <p><a href="https://i.stack.imgur.com/5YLVN.png" rel="nofollow"><img src="ht...
3
2016-10-17T00:30:21Z
[ "python", "pandas", "dataframe" ]
Vectorized lookup of MySQL, and add to DataFrame
40,076,884
<p>I'm trying to do the following:</p> <ol> <li>Go through a DataFrame, that contains Columns 'Col1' and 'Col2'</li> <li>Take each row in 'Col1', Search MySQL db using that value</li> <li>Replace the value on the same row in 'Col2' with the result</li> </ol> <p>I'm leaning towards a For loop approach, but is there a ...
0
2016-10-17T00:13:04Z
40,077,565
<p>Consider merging the MySQL query with the Pandas dataframe by importing the query into a separate dataframe. This way you match across all cases at once without looping and any conditional changes to columns can be done in one call.</p> <p>Below is a <code>left</code> join merge to keep all records in <em>rsp_df</e...
1
2016-10-17T02:13:14Z
[ "python", "mysql", "dataframe" ]
Convert python abbreviated month name to full name
40,076,887
<p>How can I convert an abbreviated month anme e.g. <code>Apr</code> in python to the full name?</p>
3
2016-10-17T00:13:27Z
40,076,927
<p>a simple dictionary would work</p> <p>eg</p> <pre><code>month_dict = {"jan" : "January", "feb" : "February" .... } </code></pre> <blockquote> <blockquote> <blockquote> <p>month_dict["jan"]</p> <p>'January'</p> </blockquote> </blockquote> </blockquote>
1
2016-10-17T00:20:43Z
[ "python", "datetime" ]
Convert python abbreviated month name to full name
40,076,887
<p>How can I convert an abbreviated month anme e.g. <code>Apr</code> in python to the full name?</p>
3
2016-10-17T00:13:27Z
40,076,928
<p>If you insist on using <code>datetime</code> as per your tags, you can convert the short version of the month to a datetime object, then reformat it with the full name:</p> <pre><code>import datetime datetime.datetime.strptime('apr','%b').strftime('%B') </code></pre>
3
2016-10-17T00:20:50Z
[ "python", "datetime" ]