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
Process a LOT of data
39,800,838
<p>So I'm working with parametric energy simulations and ended up with 500GB+ of data stored in .CSV files. I need to be able to process all this data to compare the results and gain insights of the influence of different parameters. </p> <p>Each csv file name contains information of the parameters used for the simula...
0
2016-09-30T22:16:06Z
39,800,978
<p><a href="http://stackoverflow.com/questions/27203161/convert-large-csv-to-hdf5">Convert</a> the csv files to <a href="https://www.hdfgroup.org/hdf5/" rel="nofollow">hdf5</a>, which was created to deal with massive and complex datasets. It works with <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-hd...
0
2016-09-30T22:29:47Z
[ "python", "csv", "dataframe", "bigdata" ]
Program does not loop
39,800,985
<p>I'm curious as to why this program is not looping. The program will run once but when another game is played it doesn't record the winner and quits.</p> <p>Any assistance will be greatly appreciated!</p> <p>Here is the Python program:</p> <pre><code>import random random.seed() print ("For each round please selec...
0
2016-09-30T22:30:30Z
39,801,308
<p>Wrap the whole thing in a while loop. Try something <em>like</em> this:</p> <pre><code>warriorStr = input("Please choose a warrior: ") warriorStr = warriorStr.lower() acceptables = ['a','c','n','q'] while warriorStr not 'q' and warriorStr in acceptables: warriorStr = input("Please enter a weapon: ") ...
0
2016-09-30T23:10:01Z
[ "python", "loops" ]
Convert an Object dtype column to Number Dtype in a datafrane Pandas
39,800,997
<p>Trying to answer this question <a href="http://stackoverflow.com/questions/39647978/get-list-of-unique-string-values-per-column-in-a-dataframe-using-python">Get List of Unique String per Column</a> we ran into a different problem from my dataset. When I import this CSV file to the dataframe every column is OBJECT ty...
2
2016-09-30T22:32:39Z
39,801,222
<p><strong><em>Option 1</em></strong><br> use <code>pd.to_numeric</code> in an <code>apply</code></p> <pre><code>df.apply(pd.to_numeric, errors='ignore') </code></pre> <p><strong><em>Option 2</em></strong><br> use <code>pd.to_numeric</code> on <code>df.values.ravel</code></p> <pre><code>cvrtd = pd.to_numeric(df.valu...
1
2016-09-30T22:59:20Z
[ "python", "pandas" ]
read CSV file and validate column which on the basis of UTF-8 character
39,801,014
<p>I have to read a CSV file which is containing columns (PersonName, age, address) and I have to validate the the PersonName. "PersonName may only contain UTF-8 characters."</p> <p>I am using python3.x so cant use decode method after opening the file.</p> <p>Please tell me how to open and read the file so that Pers...
0
2016-09-30T22:33:47Z
39,801,097
<p>Assuming the rest of the file requires no checking or is UTF-8 legal (which includes ASCII data), you can <code>open</code> the file with <code>encoding='utf-8'</code> and <code>errors='replace'</code>. This will change any invalid bytes (in UTF-8 encoding) into the Unicode replacement character, <code>\ufffd</code>...
0
2016-09-30T22:43:34Z
[ "python", "python-3.x", "csv", "unicode", "utf-8" ]
Why does my text clustering do this
39,801,020
<p>I have an unlabeled dataset with product names. For example, baseball shirt, bomber jacket, active classic boxer, etc. </p> <p>I created a tf-idf matrix with the data then I ran k-means on the matrix. I plotted a within-cluster sum of squares to find the best k which is 5. </p> <p>After clustering I figured out th...
2
2016-09-30T22:34:30Z
39,806,909
<p>TF-IDF only works for <strong>long text</strong>.</p> <p>Because of this, almost every document is completely different from every other, and they "fan out" like this.</p> <p>I doubt that k-means worked either.</p>
2
2016-10-01T13:00:27Z
[ "python", "scikit-learn", "cluster-analysis", "k-means", "tf-idf" ]
Can't import by library name, even though I have python setup.py develop it
39,801,085
<p>I am running into a very strange python import problem. I wrote my own repo, and used a setup.py script to setup the import path, script below:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from __future__ import division from __future__ import absolute_import fr...
0
2016-09-30T22:42:06Z
39,801,498
<p>Your <code>setup.py</code> file is in the wrong directory. Here is your folder structure</p> <pre><code>/Quantomic setup.py __init__.py settings.py /data __init__.py price.py </code></pre> <p>It should look like this</p> <pre><code>/Quantomic (can be named anything) setup.py ...
1
2016-09-30T23:39:28Z
[ "python", "import" ]
How to document a Python variable?
39,801,102
<p>How can I document a variable in Python. In JavaScript / JSDoc I can do something like that.:</p> <pre><code>/** @type {Array&lt;Number&gt;} */ var foo; /** @type {Number[]} */ var bar; </code></pre> <p>Some IDEs than can give better code completion.</p> <p>Is this also possible in Python?</p>
0
2016-09-30T22:44:18Z
39,801,255
<p><code>x, y, z = [], [], [] # type: (List[int], List[int], List[str])</code> is how it is defined in the spec ... your particular IDE may or may not implement it in this way ...</p> <p>see also: <a href="https://www.python.org/dev/peps/pep-0484/#type-comments" rel="nofollow">https://www.python.org/dev/peps/pep-0484/...
1
2016-09-30T23:02:40Z
[ "python", "documentation" ]
How to use Python Requests to make this POST request
39,801,236
<p>I'm trying to POST to the Adobe Sign API. Even if you're not familiar with the API, this should be a pretty straightforward question. </p> <p>Sign's documentation says the POST I need to do looks like this: </p> <pre><code>POST /api/rest/v5/transientDocuments HTTP/1.1 Host: api.na1.echosign.com Access-Token: MvyAB...
0
2016-09-30T23:00:59Z
39,801,571
<p>It's a nuance, but you need to name the file "File" with a capital F. Otherwise the API doesn't pick it up on the Adobe Sign side. Here is the correct (and working) API call. </p> <pre><code>def createTransientDocument(your_file_base_url, file_name): headers = {'access-token': datafile.accessToken, ...
0
2016-09-30T23:51:16Z
[ "python", "post", "python-requests" ]
analyzing excel using pandas
39,801,265
<p>I wanted to analyze excel files and find out the data range ( min value, max value, min len, max len, blanks etc I want to create a new analysis file which would spit out these insights. I'm looking into the panda library to do this. </p> <pre><code>df = pd.read_excel(open('file.xlsx','rb'), sheetname='TestData') <...
0
2016-09-30T23:03:54Z
39,801,338
<p>Use numpy to get the minimum/maximum etc. The functions require numpy arrays though, so either slice each column of a dataframe, or cast the dataframe as a matrix</p> <p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html" rel="nofollow">https://docs.scipy.org/doc/numpy/reference/generat...
0
2016-09-30T23:14:44Z
[ "python", "excel", "csv", "pandas" ]
analyzing excel using pandas
39,801,265
<p>I wanted to analyze excel files and find out the data range ( min value, max value, min len, max len, blanks etc I want to create a new analysis file which would spit out these insights. I'm looking into the panda library to do this. </p> <pre><code>df = pd.read_excel(open('file.xlsx','rb'), sheetname='TestData') <...
0
2016-09-30T23:03:54Z
39,807,421
<p>you can find out some of those statistics you are looking for - min, max, avg (mean), std. deviation for numeric columns using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html" rel="nofollow">describe()</a> method</p> <p>Demo:</p> <pre><code>df = pd.read_excel(r'/path/t...
0
2016-10-01T13:51:38Z
[ "python", "excel", "csv", "pandas" ]
Select a tag inside a class with bs4
39,801,273
<p>I'm trying to get the href of this part of html:</p> <pre><code>&lt;h3 class="post-title entry-title" itemprop="name"&gt; &lt;a href="http://sslproxies24.blogspot.it/2016/10/01-10-16-free-ssl-proxies-1070.html"&gt;01-10-16 | Free SSL Proxies (1070)&lt;/a&gt; &lt;/h3&gt; </code></pre> <p>So I created this script:</...
2
2016-09-30T23:05:01Z
39,801,387
<p>You can quickly solve it by getting the inner <code>a</code> element:</p> <pre><code>for tag in soup.find_all("h3", "post-title entry-title"): link = tag.a.get("href") </code></pre> <p>where <code>tag.a</code> is a shortcut to <code>tag.find("a")</code>.</p> <p>Or, you can match the <code>a</code> element dir...
1
2016-09-30T23:22:21Z
[ "python", "python-3.x", "beautifulsoup", "bs4" ]
Need help using python subprocess module to navigate Linux directories
39,801,284
<p>First off, I know there are FAR better ways to do this. I'm trying to learn the most basic behavior of subprocess.Popen() when it interacts with various UNIX commands. I'm doing something wrong with directory navigation, and I have no idea what it is. I'm running iPython as my REPL, so the ls command shows the files...
2
2016-09-30T23:06:24Z
39,820,473
<p><code>sub.Popen(['cd', './10dir')</code> raises "OSError: [Errno 2] No such <strong>file</strong> or directory" because there is no such file named <code>cd</code> on your <code>$PATH</code> (and possibly on your computer at all). <code>cd</code> is not a stand alone executable, it's a shell builtin. If it were a st...
1
2016-10-02T18:52:24Z
[ "python", "linux", "shell" ]
How can I get the page source, without showing the page opened, using selenium with chromedriver and python?
39,801,287
<p>I'm using selenium with Chrome driver; How can I get the page source, without showing the page opened? What I should specify in webdriver.ChromeOptions()? Here the code:</p> <pre><code>from selenium.common.exceptions import WebDriverException from selenium.webdriver.chrome.options import Options chrome_options = ...
0
2016-09-30T23:07:01Z
39,801,529
<p>You should not use <code>ChromeDriver</code> but some headless Webdriver like <code>HtmlUnitDriver</code>, explained <a href="http://www.seleniumhq.org/docs/03_webdriver.jsp#htmlunit-driver" rel="nofollow">here</a></p>
0
2016-09-30T23:45:03Z
[ "python", "selenium", "selenium-chromedriver" ]
How can I get the page source, without showing the page opened, using selenium with chromedriver and python?
39,801,287
<p>I'm using selenium with Chrome driver; How can I get the page source, without showing the page opened? What I should specify in webdriver.ChromeOptions()? Here the code:</p> <pre><code>from selenium.common.exceptions import WebDriverException from selenium.webdriver.chrome.options import Options chrome_options = ...
0
2016-09-30T23:07:01Z
39,802,501
<p>If you are adamant to use selenium, then you can use any of the headless browsers such as htmlunit driver. Else you can can just send a get request on the URL and get the response text.</p>
0
2016-10-01T02:42:57Z
[ "python", "selenium", "selenium-chromedriver" ]
Convert string expression to mathematical expression?
39,801,324
<p>I'm looking for something that would take a mathematical expression string as an input and would change it by adding parentheses to it. </p> <p>For examples :</p> <p>Input 1 : <code>"2*4^7"</code></p> <p>Output 1 : <code>"(2*(4^7))"</code></p> <p>Input 2 : <code>"sin(x)*3-8^9"</code></p> <p>Output 2 : <code>"((...
2
2016-09-30T23:13:01Z
39,801,484
<p>Using the <code>ast</code> module, you can parse your string and then traverse it to build a string representation you require:</p> <pre><code>import ast def represent(tree): t = type(tree) if t == ast.Module: return represent(tree.body) elif t == list: # arithmetic expression should on...
1
2016-09-30T23:36:56Z
[ "python", "string", "python-3.x" ]
uwsgi cheaper killing workers processing requests
39,801,326
<p>I have a very basic flask application under uwsgi, managed by signals under supervisorctl. I use cheaper for scaling workers and ran into very disturbing situation. uwsgi is killing oldest worker, even when it is processing a request, causing 500.</p> <p><strong>How to prevent uwsgi from killing workers processing ...
0
2016-09-30T23:13:25Z
39,808,544
<p>Bug fixed &amp; merged in August 2016.</p> <p><a href="https://github.com/unbit/uwsgi/issues/1288" rel="nofollow">https://github.com/unbit/uwsgi/issues/1288</a></p> <p><a href="https://github.com/unbit/uwsgi/commit/f5dd0b855d0d21be62534dc98375fae2cd7c13f0" rel="nofollow">https://github.com/unbit/uwsgi/commit/f5dd0...
0
2016-10-01T15:47:41Z
[ "python", "flask", "uwsgi" ]
How to derive equation from Numpy's polyfit?
39,801,403
<p>Given an array of x and y values, the following code will calculate a regression curve for these data points.</p> <pre><code># calculate polynomial z = np.polyfit(x, y, 5) f = np.poly1d(z) # calculate new x's and y's x_new = np.linspace(x[0], x[-1], 50) y_new = f(x_new) plt.plot(x,y,'o', x_new, y_new) plt.xlim([x...
0
2016-09-30T23:24:55Z
39,801,630
<p>Construct a simple example:</p> <pre><code>In [94]: x=np.linspace(0,1,100) In [95]: y=2*x**3-3*x**2+x-1 In [96]: z=np.polyfit(x,y,3) In [97]: z Out[97]: array([ 2., -3., 1., -1.]) </code></pre> <p>The <code>z</code> coefficients correspond to the [2,-3,1,-1] I used to construct <code>y</code>.</p> <pre><code>In...
2
2016-10-01T00:00:59Z
[ "python", "numpy" ]
How to derive equation from Numpy's polyfit?
39,801,403
<p>Given an array of x and y values, the following code will calculate a regression curve for these data points.</p> <pre><code># calculate polynomial z = np.polyfit(x, y, 5) f = np.poly1d(z) # calculate new x's and y's x_new = np.linspace(x[0], x[-1], 50) y_new = f(x_new) plt.plot(x,y,'o', x_new, y_new) plt.xlim([x...
0
2016-09-30T23:24:55Z
39,801,980
<p>If you want to show the equation, you can use <code>sympy</code> to output latex:</p> <pre><code>from sympy import S, symbols from matplotlib import pyplot as plt import numpy as np x=np.linspace(0,1,100) y=np.sin(2 * np.pi * x) p = np.polyfit(x, y, 5) f = np.poly1d(p) # calculate new x's and y's x_new = np.lins...
1
2016-10-01T01:00:06Z
[ "python", "numpy" ]
Ignoring a value in a list search
39,801,404
<p>I am using lists to store attributes and this problem cropped up when I was searching for equal items:</p> <pre><code>l = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]] if [any,1,2] in l: print ('blue') elif [any,2,3] in l: print('red') </code></pre> <p>desired output</p> <pre><code>blue </code></pre> <p>What...
-1
2016-09-30T23:25:03Z
39,801,455
<p>For filtering equal items (according to your definition) you can use list comprehension and slicing:</p> <pre><code>&gt;&gt;&gt; lst = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]] &gt;&gt;&gt; [e for e in lst if e[1:] == [1,2]] [['a', 1, 2], ['b', 1, 2], ['d', 1, 2]] </code></pre>
0
2016-09-30T23:31:39Z
[ "python", "list" ]
Ignoring a value in a list search
39,801,404
<p>I am using lists to store attributes and this problem cropped up when I was searching for equal items:</p> <pre><code>l = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]] if [any,1,2] in l: print ('blue') elif [any,2,3] in l: print('red') </code></pre> <p>desired output</p> <pre><code>blue </code></pre> <p>What...
-1
2016-09-30T23:25:03Z
39,801,457
<p>for completely generic case simply introduce some magical symbol to denote 'any' like '*' and write your own simple comparator</p> <pre><code>def matches(element, mask): for el, mask_el in zip(element, mask): if mask_el != '*' and el != mask_el: return False return True </code></pre> <p>and now you c...
-1
2016-09-30T23:31:57Z
[ "python", "list" ]
Ignoring a value in a list search
39,801,404
<p>I am using lists to store attributes and this problem cropped up when I was searching for equal items:</p> <pre><code>l = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]] if [any,1,2] in l: print ('blue') elif [any,2,3] in l: print('red') </code></pre> <p>desired output</p> <pre><code>blue </code></pre> <p>What...
-1
2016-09-30T23:25:03Z
39,820,888
<p>:D actually managed to do it in one line thanks to pkacprzak.</p> <pre><code>l = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]] if any(True for x in l if x[1:] == [1,2]): print ('blue') elif any(True for x in l if x[1:] == [2,3]): print('red') </code></pre> <p>Code works like this:</p> <pre><code>True for x in...
0
2016-10-02T19:37:16Z
[ "python", "list" ]
Sampling in pandas
39,801,405
<p>If I want to randomly sample a pandas dataframe I can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html" rel="nofollow">pandas.DataFrame.sample</a>.</p> <p>Suppose I randomly sample 80% of the rows. How do I automatically get the other 20% of the rows that were not pick...
2
2016-09-30T23:25:07Z
39,801,461
<p>As Lagerbaer explains, one can add a column with a unique index to the dataframe, or randomly shuffle the entire dataframe. For the latter, </p> <pre><code>df.reindex(np.random.permutation(df.index)) </code></pre> <p>works. (np means numpy)</p>
3
2016-09-30T23:32:35Z
[ "python", "pandas" ]
Sampling in pandas
39,801,405
<p>If I want to randomly sample a pandas dataframe I can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html" rel="nofollow">pandas.DataFrame.sample</a>.</p> <p>Suppose I randomly sample 80% of the rows. How do I automatically get the other 20% of the rows that were not pick...
2
2016-09-30T23:25:07Z
39,801,503
<pre><code>&gt;&gt;&gt; import pandas as pd, numpy as np &gt;&gt;&gt; df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8,9,10], 'b': [11,12,13,14,15,16,17,18,19,20]}) &gt;&gt;&gt; df a b 0 1 11 1 2 12 2 3 13 3 4 14 4 5 15 5 6 16 6 7 17 7 8 18 8 9 19 9 10 20 # randomly sample 5 rows &gt;&gt;&gt...
2
2016-09-30T23:40:05Z
[ "python", "pandas" ]
Permutations of a list using stack
39,801,420
<p>I'm trying to find a way to enumerate all combinations of a list of numbers without recursion or using itertools. I came up with a solution that works but I think it turned into a recursive function after all. I'm new to Python and not sure how I would make this work without recursion.</p> <p>Any help is apprecia...
0
2016-09-30T23:27:36Z
39,801,605
<p>It is not that intuitive to come up with an algorithm "just like that" that produces all permutations without the use of recursion. </p> <p>But there exist several different such algorithms. Have look at <a href="https://en.wikipedia.org/wiki/Heap%27s_algorithm" rel="nofollow">Heap's algorithm</a> for example:</p> ...
2
2016-09-30T23:56:58Z
[ "python", "algorithm" ]
Permutations of a list using stack
39,801,420
<p>I'm trying to find a way to enumerate all combinations of a list of numbers without recursion or using itertools. I came up with a solution that works but I think it turned into a recursive function after all. I'm new to Python and not sure how I would make this work without recursion.</p> <p>Any help is apprecia...
0
2016-09-30T23:27:36Z
39,803,099
<p>I always liked this method: </p> <p>Until the length of each variation in the queue equals the input's length: place the next input element in all positions of each variation</p> <pre><code>input [1,2,3] queue [[1]] insert 2 in all positions of each variation queue [[2,1],[1,2]] insert 3 in all positions of each ...
1
2016-10-01T04:41:04Z
[ "python", "algorithm" ]
How to inspect program state in the presence of generators/coroutines?
39,801,488
<p>With normal functions calls, the program state is mostly described by a simple call stack. It is printed out as a traceback after an uncaught exception, it can be examined with <code>inspect.stack</code>, and it can be displayed in a debugger after a breakpoint.</p> <p>In the presence of generators, generator-based...
1
2016-09-30T23:37:36Z
39,811,920
<p>You just have to findout all instances fo generators and co-routines, in all "traditional" frames - (either search for them recursively in all objects in all frames, or you mitght try to use the garbage collector (gc) module to get a reference to all these instances)</p> <p>Generators and co-routines have, respect...
1
2016-10-01T22:09:41Z
[ "python", "python-3.x", "python-asyncio", "coroutine", "python-internals" ]
Scipy.optimize not fiting to my data
39,801,490
<p>I cannot get <code>scipy.optimize.curve_fit</code> to properly fit my data which is visually apparent. I know approximately what the parameter values should be and if I evaluate the function with the given parameters the calculated and experimental data appear to agree well:</p> <p><img src="http://i.stack.imgur.co...
-1
2016-09-30T23:38:05Z
39,801,936
<p><a href="http://stackoverflow.com/questions/39801490/scipy-optimize-not-fiting-to-my-data#comment66895673_39801490">@WarrenWeckesser has a really good point</a>, but further note that the y axis is logarithmic. That apparently huge error at the right end is something like 1e-5 in magnitude, while the points on the t...
2
2016-10-01T00:51:32Z
[ "python", "numpy", "math", "scipy", "best-fit-curve" ]
create a list but getting a string?
39,801,516
<pre><code>s = """ 1:A,B,C,D;E,F 2:G,H;J,K &amp;:L,M,N """ def read_nodes(gfile): for line in gfile.split(): nodes = line.split(":")[1].replace(';',',').split(',') for node in nodes: print node print read_nodes(s) </code></pre> <p>I am expected to get <code>['A','B','C','D','E',.....'...
-1
2016-09-30T23:42:55Z
39,801,677
<p>Each <code>line</code> you read will create a new list called nodes. You need to create a list outside this loop and store all the nodes. </p> <pre><code>s = """ 1:A,B,C,D;E,F 2:G,H;J,K &amp;:L,M,N """ def read_nodes(gfile): allNodes = [] for line in gfile.split(): nodes =line.split(":")[1].replac...
0
2016-10-01T00:08:18Z
[ "python", "list", "debugging" ]
create a list but getting a string?
39,801,516
<pre><code>s = """ 1:A,B,C,D;E,F 2:G,H;J,K &amp;:L,M,N """ def read_nodes(gfile): for line in gfile.split(): nodes = line.split(":")[1].replace(';',',').split(',') for node in nodes: print node print read_nodes(s) </code></pre> <p>I am expected to get <code>['A','B','C','D','E',.....'...
-1
2016-09-30T23:42:55Z
39,801,680
<p>Not quite sure what you are ultimately trying to accomplish but this will print what you say you are expecting:</p> <pre><code>s = """ 1:A,B,C,D;E,F 2:G,H;J,K &amp;:L,M,N """ def read_nodes(gfile): nodes = [] for line in gfile.split(): nodes += line.split(":")[1].replace(';',',').split(',') ret...
0
2016-10-01T00:08:47Z
[ "python", "list", "debugging" ]
create a list but getting a string?
39,801,516
<pre><code>s = """ 1:A,B,C,D;E,F 2:G,H;J,K &amp;:L,M,N """ def read_nodes(gfile): for line in gfile.split(): nodes = line.split(":")[1].replace(';',',').split(',') for node in nodes: print node print read_nodes(s) </code></pre> <p>I am expected to get <code>['A','B','C','D','E',.....'...
-1
2016-09-30T23:42:55Z
39,801,689
<p>Add the following code so that the output is ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N'] </p> <pre><code>//Code to be added nodes_list = [] def read_nodes(gfile): for line in gfile.split(): nodes =line.split(":")[1].replace(';',',').split(',') nodes_list.extend(nodes) ...
0
2016-10-01T00:10:21Z
[ "python", "list", "debugging" ]
create a list but getting a string?
39,801,516
<pre><code>s = """ 1:A,B,C,D;E,F 2:G,H;J,K &amp;:L,M,N """ def read_nodes(gfile): for line in gfile.split(): nodes = line.split(":")[1].replace(';',',').split(',') for node in nodes: print node print read_nodes(s) </code></pre> <p>I am expected to get <code>['A','B','C','D','E',.....'...
-1
2016-09-30T23:42:55Z
39,801,702
<p>I believe this is what you're looking for:</p> <pre><code>s = """ 1:A,B,C,D;E,F 2:G,H;J,K &amp;:L,M,N """ def read_nodes(gfile): nodes = [line.split(":")[1].replace(';',',').split(',') for line in gfile.split()] nodes = [n for l in nodes for n in l] return nodes print read_nodes(s) # prints: ['A','B',...
1
2016-10-01T00:12:01Z
[ "python", "list", "debugging" ]
What does it mean that a scope is determined statically and used dynamically?
39,801,617
<p>This is an excerpt of Python docs for Classes I'm struggling to understand:</p> <blockquote> <p>A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.</p> ...
2
2016-09-30T23:58:34Z
39,801,949
<h2>"Defined Statically"</h2> <p>There is global scope and local scope (let's ignore the third one).</p> <p>Whether a variable is global or local in some function is determined before the function is called, i.e. <strong>statically</strong>.</p> <p>For example:</p> <pre><code>a = 1 b = 2 def func1(): c = 3 pr...
1
2016-10-01T00:54:25Z
[ "python", "class", "scope", "namespaces", "documentation" ]
Assign Global Variable Inside Class From Class Variable
39,801,660
<p>I have a question about classes in Python. I have create a class that looks something like this:</p> <pre><code>class Model(Object): __table__ = 'table_name' def func(): def func2(): </code></pre> <p>The table name is a global variable that the functions feed off of. I am trying to add old data so I...
0
2016-10-01T00:06:05Z
39,801,906
<p><code>__table__</code> is a class variabe, which means you can access it from an instance or from the class itself. You can update any instance value according to the value of <code>backfill</code> in the <code>__init__</code> method:</p> <pre><code>class Model(Object): __table__ = 'table_name' def __init__...
1
2016-10-01T00:43:54Z
[ "python", "python-2.7", "class" ]
pyspark: add a new field to a data frame Row element
39,801,691
<p>I have the following element:</p> <pre><code>a = Row(ts=1465326926253, myid=u'1234567', mytype=u'good') </code></pre> <p>The Row is of spark data frame Row class. Can I append a new field to a, so a would look like:</p> <pre><code>a = Row(ts=1465326926253, myid=u'1234567', mytype=u'good', name = u'john') </code...
0
2016-10-01T00:10:28Z
39,801,860
<p>You cannot add new field to the <code>Row</code>. <code>Row</code> is a subclass of <code>tuple</code> and Python <code>tuples</code> are immutable. All you can do is create a new one:</p> <pre><code>from pyspark.sql import Row row = Row(ts=1465326926253, myid=u'1234567', mytype=u'good') Row(**row.asDict(), name...
0
2016-10-01T00:36:54Z
[ "python", "apache-spark", "dataframe", "row", "pyspark" ]
Python Requests getting inconsistent response code
39,801,703
<p>I am attempting to write a webscraper for the stats.nba.com website. Sometimes when I run a script, it comes out at as a 200 return code, but other times it becomes a 400 error code. I suspect that maybe it's takes a response sometimes, but not sure. Here is an example with four, but it's usually at a much bigger on...
2
2016-10-01T00:12:08Z
39,801,928
<p>You need to pass a user-agent:</p> <pre><code>In [11]: for url in urls: ....: r = requests.get(url, headers={"user-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.92 Safari/537.36"}) ....: print(r.status_code) ....: 200 200 200 200 </code></pr...
0
2016-10-01T00:49:11Z
[ "python", "python-requests" ]
How to run a http server which serve a specific path?
39,801,718
<p>this is my Python3 project hiearchy:</p> <pre><code>projet \ script.py web \ index.html </code></pre> <p>From <code>script.py</code>, I would like to run a http server which serve the content of the <code>web</code> folder.</p> <p><a href="https://docs.python.org/3/library/http.server.html" rel="nof...
0
2016-10-01T00:13:59Z
39,801,780
<p><a href="https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler" rel="nofollow">https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler</a></p> <blockquote> <p>This class serves files from the current directory and below, directly mapping the dire...
1
2016-10-01T00:25:24Z
[ "python", "python-3.x", "simplehttpserver" ]
Iterating through iterrows
39,801,726
<p>iterrows can be used to iterate through a pandas dataframe:</p> <pre><code>for row in df.iterrows(): print(row) </code></pre> <p>How can I use a second for loop to iterate through each element in the row?</p>
-1
2016-10-01T00:15:11Z
39,801,796
<p>iterrows returns a tuple. The element indexed by [1] contains the row. You can then iterate through that element.</p> <pre><code>for row in x.iterrows(): print(row[1]) for b in row[1]: print(b) </code></pre>
0
2016-10-01T00:28:07Z
[ "python", "pandas" ]
Using Flask to load a txt file through the browser and access its data for processing
39,801,728
<p>I am making a data visualization tool that takes input from the user (choosing a file on the computer); processes it in Python with Pandas, Numpy, etc; and displays the data in the browser on a local server.</p> <p>I am having trouble accessing the data once the file is selected using an HTML input form. </p> <p>H...
0
2016-10-01T00:15:24Z
39,805,100
<p>A <code>input type=file</code> data isn't passed in as the <code>form</code> dictionary of a request object. It is passed in as <code>request.files</code> (files dictionary in the request object).</p> <p>So simply change:</p> <pre><code>result = request.form['myfile'] </code></pre> <p>to</p> <pre><code>result = ...
1
2016-10-01T09:40:22Z
[ "python", "flask" ]
Using Flask to load a txt file through the browser and access its data for processing
39,801,728
<p>I am making a data visualization tool that takes input from the user (choosing a file on the computer); processes it in Python with Pandas, Numpy, etc; and displays the data in the browser on a local server.</p> <p>I am having trouble accessing the data once the file is selected using an HTML input form. </p> <p>H...
0
2016-10-01T00:15:24Z
39,808,586
<p>Try this. I've been working on saving and unzipping files for the last few days. If you have any trouble with this code, let me know :)</p> <p>I'd suggest saving the file on disk and then reading it. If you don't want to do that, you needn't.</p> <pre><code>from flask import Flask, render_template, request from we...
0
2016-10-01T15:51:19Z
[ "python", "flask" ]
In Python, how can I get a line number corresponding to a given character location?
39,801,748
<p>If I have a text that I've read into memory by using <code>open('myfile.txt').read()</code>, and if I know a certain location in this file, say, at character 10524, how can I find the line number of that location? </p>
0
2016-10-01T00:19:15Z
39,801,759
<p>Examine the text preceding your desired position and count the number of <code>\n</code> characters.</p>
2
2016-10-01T00:21:34Z
[ "python" ]
In Python, how can I get a line number corresponding to a given character location?
39,801,748
<p>If I have a text that I've read into memory by using <code>open('myfile.txt').read()</code>, and if I know a certain location in this file, say, at character 10524, how can I find the line number of that location? </p>
0
2016-10-01T00:19:15Z
39,801,789
<p>Something along the lines of:</p> <pre><code>txt = open('myfile.txt').read() lineno = len([c for c in txt[:10524] if c == '\n']) </code></pre>
1
2016-10-01T00:26:57Z
[ "python" ]
Rsync include/exclude don't work in python subprocess
39,801,862
<p>I use rsync to move files from my home computer to a server. Here's the command that I use to transfer and update the directory of only files that contain a grep + glob. I execute this command from the <code>toplevel/</code> directory in the directory structure I show below.</p> <pre><code> rsync -r --progress --in...
1
2016-10-01T00:37:05Z
39,801,965
<p>Some of those quotes are removed by the shell before being passed to the called process. You need to do this yourself if you call the program with the default <code>shell=False</code>. This little script will tell you what your parameters need to look like</p> <p>test.py</p> <pre><code>#!/usr/bin/env python3 impor...
1
2016-10-01T00:56:25Z
[ "python", "python-3.x", "rsync" ]
How to use the `pos` argument in `networkx` to create a flowchart-style Graph? (Python 3)
39,801,880
<p><strong>I am trying create a linear network graph using <code>Python</code></strong> (preferably with <code>matplotlib</code> and <code>networkx</code> although would be interested in <code>bokeh</code>) similar in concept to the one below. </p> <p><a href="http://i.stack.imgur.com/qojHg.png"><img src="http://i.st...
11
2016-10-01T00:39:45Z
39,863,493
<p>Networkx has decent plotting facilities for exploratory data analysis, it is not the tool to make publication quality figures, for various reason that I don't want to go into here. I hence rewrote that part of the code base from scratch, and made a stand-alone drawing module called netgraph that can be found <a hre...
6
2016-10-05T00:00:50Z
[ "python", "matplotlib", "plot", "graph", "networkx" ]
os.walk(directory) - AttributeError: 'tuple' object has no attribute 'endswith'
39,801,970
<p>I am trying to make a script in python to search for certain type of files (eg: <code>.txt</code>, <code>.jpg</code>, etc.). I started searching around for quite a while (including posts here in SO) and I found the following snippet of code:</p> <pre><code>for root, dirs, files in os.walk(directory): for file i...
-1
2016-10-01T00:58:01Z
39,802,015
<p><code>os.walk()</code> returns a list of results, each of which is itself a tuple.</p> <p>If you assign a single name to each result, then that name will be a tuple.</p> <p>Tuples do not have a <code>.endswith()</code> method.</p>
0
2016-10-01T01:05:51Z
[ "python", "python-3.5", "os.walk", "os.path" ]
os.walk(directory) - AttributeError: 'tuple' object has no attribute 'endswith'
39,801,970
<p>I am trying to make a script in python to search for certain type of files (eg: <code>.txt</code>, <code>.jpg</code>, etc.). I started searching around for quite a while (including posts here in SO) and I found the following snippet of code:</p> <pre><code>for root, dirs, files in os.walk(directory): for file i...
-1
2016-10-01T00:58:01Z
39,802,017
<p>The reason why you use <code>root, dirs, files</code> with <code>os.walk</code> is described in the <a href="https://docs.python.org/2/library/os.html#os.walk" rel="nofollow">docs</a>:</p> <blockquote> <p>For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, ...
1
2016-10-01T01:05:57Z
[ "python", "python-3.5", "os.walk", "os.path" ]
Kivy Image Child Class Produces Two Images
39,801,977
<p>I think this is probably a simple miss understanding about something deeper in kivy, but I have an RoundedImage class that is producing two images, where one is the original without rounded corners and one with the rounded corners off screen a bit. Whats going on?</p> <p>Screenshot: <a href="http://imgur.com/galler...
0
2016-10-01T00:59:31Z
39,882,582
<p>No imports, no other required classes and although I've seen that rounded rectangle somewhere, I don't have a clue what does that custom class do, so no runnable code. Let's work with that anyway.</p> <p>Yes, it's because of that subclassing - the picture is already placed in the canvas and you use the texture of i...
1
2016-10-05T19:53:43Z
[ "python", "image", "canvas", "graphics", "kivy" ]
Kivy Image Child Class Produces Two Images
39,801,977
<p>I think this is probably a simple miss understanding about something deeper in kivy, but I have an RoundedImage class that is producing two images, where one is the original without rounded corners and one with the rounded corners off screen a bit. Whats going on?</p> <p>Screenshot: <a href="http://imgur.com/galler...
0
2016-10-01T00:59:31Z
39,905,268
<p>Ok so this ended up being an issue of not removing a mask in the stencil instructions.</p> <p>I ended up adding this to the .kv definition for the RoundedRectangle</p> <pre><code>''' &lt;-RoundedImage&gt;: canvas: Color: rgb: self.color StencilPush RoundedRectangle: size: self.norm_image_size pos: self.center[0] -...
0
2016-10-06T20:42:16Z
[ "python", "image", "canvas", "graphics", "kivy" ]
Output ascii characters to stdout in Python 3
39,801,978
<p>I have a file named 'xxx.py' like this:</p> <pre><code>print("a simple string") </code></pre> <p>and when I run that like this (Python 3):</p> <pre><code>python xxx.py &gt;atextfile.txt </code></pre> <p>I get a unicode file.</p> <p>I would like an ascii file.</p> <p>I don't mind if an exception is thrown if a ...
3
2016-10-01T00:59:39Z
39,802,037
<p>The <code>stdout</code> encoding is defined by the environment that is executing the python script, e.g.:</p> <pre><code>$ python -c "import sys; print(sys.stdout.encoding)" UTF-8 $ LC_CTYPE=ascii python -c "import sys; print(sys.stdout.encoding)" US-ASCII </code></pre> <p>Try adjusting your environment before run...
0
2016-10-01T01:08:40Z
[ "python", "windows", "python-3.x", "unicode", "character-encoding" ]
Iterating through the Fibonacci sequence
39,802,009
<p>so i'd like to iterate through the Fibonacci sequence (but this could apply to any non-arithmetic sequence). i've written a function fibonacci:</p> <pre><code>from math import sqrt def F(n): return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5)) </code></pre> <p>which returns the fibonacci number for any given ...
2
2016-10-01T01:04:10Z
39,802,079
<p>What is the range of <code>n</code> that you are looking to run the fibonacci number on?<br> Your definition of fibonacci is in a closed form, so you need to give each number you want to calculate:</p> <pre><code>import itertools count = 0 for n in itertools.count(1): if F(n) &gt; 4000000: break if ...
0
2016-10-01T01:17:47Z
[ "python", "iteration", "sequences" ]
How to plot an equation with multiple variables in Python?
39,802,010
<p>Suppose I have a variable list z</p> <pre><code>z = [1,2,3,4,5,6,7,8,9,10] </code></pre> <p>I am trying to plot the equation</p> <pre><code>y = 1a + 2b + 3c + 4d + 5e + 6f + 7g + 8h + 9i + 10k </code></pre> <p>I am confused on how to plot a multi dimensional equation in python. I use the matplotlib library now. ...
-3
2016-10-01T01:04:30Z
39,802,078
<p>Try this:</p> <pre><code>z = [1,2,3,4,5,6,7,8,9,10] equation="y =" for i in range(len(z)): if i&gt;0: equation=equation+" +" equation=equation+" "+str(z[i])+chr(ord('a')+i) print equation </code></pre> <p>The output is:</p> <pre><code>y = 1a + 2b + 3c + 4d + 5e + 6f + 7g + 8h + 9i + 10j </code></p...
-1
2016-10-01T01:17:42Z
[ "python", "numpy", "matplotlib" ]
pandas drop row based on index vs ix
39,802,076
<p>I'm trying to drop pandas dataframe row based on its index (not location).</p> <p>The data frame looks like </p> <pre><code> DO 129518 a developer and 20066 responsible for 571 responsible for 85629 responsible for 5956 by helping them </code></pre> <p>(FYI: "DO" ...
2
2016-10-01T01:17:02Z
39,802,240
<p>You should <code>drop</code> the desired value from the index directly:</p> <pre><code>df.drop(571, inplace=True) </code></pre>
4
2016-10-01T01:48:10Z
[ "python", "pandas", "dataframe" ]
pandas drop row based on index vs ix
39,802,076
<p>I'm trying to drop pandas dataframe row based on its index (not location).</p> <p>The data frame looks like </p> <pre><code> DO 129518 a developer and 20066 responsible for 571 responsible for 85629 responsible for 5956 by helping them </code></pre> <p>(FYI: "DO" ...
2
2016-10-01T01:17:02Z
39,802,783
<pre><code>df.index </code></pre> <p>Is the index of the dataframe. </p> <pre><code>df.index[571] </code></pre> <p>Is the 571st element of the index. Then you dropped whatever that was. You didn't want positional but that's what you did. </p> <p>Use @John Zwinck's answer</p>
2
2016-10-01T03:37:37Z
[ "python", "pandas", "dataframe" ]
Download SVG as JPEG using flask
39,802,098
<p>I'm trying to serve HTML page with SVG attributes on it; so as soon as I click "Create" I want to be able to download that file as .jpg instead of SVG. I looked over at multiple convertors that works with the command line for instance like this.</p> <pre><code>os.system("rsvg-convert -h 32 save.svg &gt; icon-32.jpg...
0
2016-10-01T01:20:50Z
39,805,224
<p>After saving the file and converting it into an image.</p> <p>You can directly return the file from the directory, which will give a download popup to the user.</p> <pre><code>... os.system("rsvg-convert -h 32 save.svg &gt; icon-32.jpg") return send_from_directory("/path/to/saved/image", "icon-32.jpg") </code></pr...
0
2016-10-01T09:55:45Z
[ "python", "flask", "operating-system", "jpeg", "encode" ]
Catch links from a txt file
39,802,143
<p>I have a file txt, where there are severals lines... Some of these are links. My question is: How can I catch all this links and save them on another txt file? I'm a newbie.</p> <p>I tried with this but it doesn't work:</p> <pre><code>filee = open("myfile.txt").readlines() out_file = open("out.txt","w") out_file.w...
1
2016-10-01T01:28:45Z
39,802,335
<p>You can't write to a closed file. Just move the out_file.close() at the end of your code:</p> <pre><code>filee = open("myfile.txt").readlines() out_file = open("out.txt","w") out_file.write("") for x in filee: if x.startswith("http"): out_file.write(x) print (x) out_file.close() </code></pre> ...
4
2016-10-01T02:07:02Z
[ "python", "python-3.x" ]
How can I delete a specific repetitive number in a list?
39,802,166
<p>For example I have </p> <pre><code>[3, 4, 5, 5, 12, 13, 0, 0, 0, 8, 15, 17, 0, 0, 0] </code></pre> <p>I want delete just all the zeros. Note: assume that we have an unknown number of zeros in a list that has an unknown length. </p>
-4
2016-10-01T01:32:40Z
39,802,199
<p>List comprehensions make this easy:</p> <pre><code>new_list = [x for x in orig_list if x != 0] </code></pre> <p>You can push the work to the C layer with <code>filter</code>:</p> <pre><code># If they're all numbers, you can avoid work by using filter with None: new_list = list(filter(None, orig_list)) # List wra...
4
2016-10-01T01:39:59Z
[ "python", "list" ]
How does numpy handle data files with uncertainty values, e.g., 0.6499(6)?
39,802,232
<p>Here is a snippet of a large data set I am working with:</p> <pre><code># p* T* P* U* P*_cs U*_cs Steps dt* 0.1 6.0 0.6499(6) -0.478(2) 0.6525 -0.452 30000 0.002 0.2 6.0 1.442(1) -0.942(2) 1.452 -0.890 30000 0.002 0.3 6.0 2.465(3) -1.376(1) 2.489 -1.298 ...
0
2016-10-01T01:46:19Z
39,802,254
<p>No, there is nothing like that in NumPy. You will either need an external package (even Pandas won't do it), or you can load the columns as strings instead of numbers and process them yourself. For the string approach, the <code>str</code> methods in Pandas would be of some use, e.g. <a href="http://pandas.pydata....
1
2016-10-01T01:50:00Z
[ "python", "numpy", "uncertainty" ]
How does numpy handle data files with uncertainty values, e.g., 0.6499(6)?
39,802,232
<p>Here is a snippet of a large data set I am working with:</p> <pre><code># p* T* P* U* P*_cs U*_cs Steps dt* 0.1 6.0 0.6499(6) -0.478(2) 0.6525 -0.452 30000 0.002 0.2 6.0 1.442(1) -0.942(2) 1.452 -0.890 30000 0.002 0.3 6.0 2.465(3) -1.376(1) 2.489 -1.298 ...
0
2016-10-01T01:46:19Z
39,802,945
<pre><code>In [1]: txt=b"""# p* T* P* U* P*_cs U*_cs Steps dt* ...: 0.1 6.0 0.6499(6) -0.478(2) 0.6525 -0.452 30000 0.002 ...: 0.2 6.0 1.442(1) -0.942(2) 1.452 -0.890 30000 0.002 ...: 0.3 6.0 2.465(3) -1.376(1) 2.489 -1.298 30000 0.002""" In [2]: ...
2
2016-10-01T04:11:50Z
[ "python", "numpy", "uncertainty" ]
Overriding a class to be left hand side of in operator
39,802,249
<p>Apparently the <code>__contains__</code> special method allows to implement the <code>in</code> evaulation when the object with the method is on the right hand side of it. I have a piece of code where the <code>in</code> must be implemented by the left hand operand. How do I go about it?</p>
1
2016-10-01T01:49:41Z
39,802,759
<p>I was able to get this to work by overriding eq (how do you put underscores in the text?).</p> <p>Consider the code "value in some_list". It will iterate through some_list until it finds value. But how does it know if it found value? By comparing it. That's what you want to override.</p> <pre><code>class Twenty(ob...
1
2016-10-01T03:33:11Z
[ "python", "contains" ]
Print Final Statement Outside For Loop
39,802,259
<p>I'm trying to print a final statement that says "The 50th bus arrives at HH:MM." But it appears my print statement is still in my for loop. How do I get it out of it? Also, it seems like my output is still in brackets. I'm not sure how to get rid of that. Sorry, I'm very new to programming.</p> <pre><code>import nu...
0
2016-10-01T01:50:24Z
39,802,552
<p><code>Print</code> is not in <code>for</code> loop. The reason you think that your <code>print</code> is in <code>for</code> loop is because you print <code>cum_l</code> which is a <code>list</code>. But you need only last element:</p> <pre><code>import numpy as np import math import random rateParameter = 1/15 d...
0
2016-10-01T02:52:19Z
[ "python", "python-3.x" ]
Print Value of Key in Lists of Dicts in Python
39,802,429
<p>I am trying to print the value of a specific key in a list of dicts:</p> <p>eg:</p> <pre><code>list = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}] </code></pre> <p>I was hoping to be able to print the following for each dict:</p> <pre><code>print ("a: ", a) print ("b: ", b) </code>...
0
2016-10-01T02:29:14Z
39,802,454
<p>If you're guaranteed those keys exist, a nice solution using <a href="https://docs.python.org/3/library/operator.html#operator.itemgetter" rel="nofollow"><code>operator.itemgetter</code></a>:</p> <pre><code>from operator import itemgetter # Renamed your list; don't name variables list for a, b in map(itemgetter('a...
1
2016-10-01T02:34:02Z
[ "python", "dictionary" ]
Print Value of Key in Lists of Dicts in Python
39,802,429
<p>I am trying to print the value of a specific key in a list of dicts:</p> <p>eg:</p> <pre><code>list = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}] </code></pre> <p>I was hoping to be able to print the following for each dict:</p> <pre><code>print ("a: ", a) print ("b: ", b) </code>...
0
2016-10-01T02:29:14Z
39,802,495
<p>How about some nested loops, to avoid hard-coding it?</p> <pre><code>for dictionary in list: # rename list so you don't overshadow the builtin list for key in ('a', 'b'): print(key + ':', dictionary[key]) </code></pre> <p>which should output:</p> <pre><code>a: 123 b: xyz a: 456 b: cde </code></pre>
0
2016-10-01T02:41:50Z
[ "python", "dictionary" ]
Print Value of Key in Lists of Dicts in Python
39,802,429
<p>I am trying to print the value of a specific key in a list of dicts:</p> <p>eg:</p> <pre><code>list = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}] </code></pre> <p>I was hoping to be able to print the following for each dict:</p> <pre><code>print ("a: ", a) print ("b: ", b) </code>...
0
2016-10-01T02:29:14Z
39,802,585
<pre><code>lst = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}] output=['a','b'] for dct in lst: for k in output: print(k+': '+str(dct[k])) </code></pre>
0
2016-10-01T02:57:25Z
[ "python", "dictionary" ]
Storing Dataframe with Array Entries
39,802,438
<p>I have a Pandas DataFrame with the following structure, which contains both numbers and numpy arrays of fixed shape:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({"num":(23, 42), "list":(np.arange(3), np.arange(1,4)) </code></pre> <p>Assuming I have large (more than 1 GB) amounts of thi...
2
2016-10-01T02:31:26Z
39,802,541
<p>I mean something like this:</p> <pre><code>df_x = pd.concat([df.num, pd.DataFrame(np.vstack(df.list))], keys=["key", "arr"], axis=1) </code></pre> <p>the dataframe:</p> <pre><code> key arr num 0 1 2 0 23 0 1 2 1 42 1 2 3 </code></pre> <hr> <p>convert back with:</p> <pre...
3
2016-10-01T02:50:13Z
[ "python", "pandas", "numpy", "serialization" ]
How to multiply a certain integer in list?
39,802,442
<p>I am very new to Python... If I were to give a list, my function should return the number of times "5" appears times 50. For example, if I were to call fivePoints([1,3,5,5]) it should return 100 since the number 5 appears twice (2*50). Is creating an empty list necessary? Do I use the count function? This is what I ...
0
2016-10-01T02:31:49Z
39,802,480
<p>This is one option:</p> <pre><code>x = [1, 2, 5, 5] def fivePoints(aList): y = [i for i in aList if i == 5] z = len(y) * 50 return z fivePoints(x) 100 </code></pre>
0
2016-10-01T02:39:04Z
[ "python", "list", "arguments" ]
How to multiply a certain integer in list?
39,802,442
<p>I am very new to Python... If I were to give a list, my function should return the number of times "5" appears times 50. For example, if I were to call fivePoints([1,3,5,5]) it should return 100 since the number 5 appears twice (2*50). Is creating an empty list necessary? Do I use the count function? This is what I ...
0
2016-10-01T02:31:49Z
39,802,481
<p>You want to return a number. You just have to write:</p> <pre><code>def fivePoints(aList): return aList.count(5)*50 print(fivePoints([1,3,5,5])) </code></pre>
3
2016-10-01T02:39:23Z
[ "python", "list", "arguments" ]
Python: Check if Twitter user A following user B
39,802,469
<p>I have been trying to use either Tweepy or Twython with the Twitter API to search for a specific hashtag, extract usernames of users tweeting with the hashtage, and then see how many of those users follow one another. My ultimate goal is to then visualize the connections with NetworkX.</p> <p>So far, I have been ab...
0
2016-10-01T02:36:31Z
39,803,142
<p>With Tweepy, you can check if <code>user_a</code> follows <code>user_b</code> using the <a href="http://tweepy.readthedocs.io/en/v3.5.0/api.html#API.exists_friendship" rel="nofollow">API.exists_friendship</a> method. The code would look something like:</p> <pre><code>auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUM...
1
2016-10-01T04:48:52Z
[ "python", "twitter", "tweepy", "twython" ]
Cannot parse the following text file into a pandas dataframe?
39,802,476
<p>I have the following text file <code>file1.txt</code> in this format (showing it exactly as I see it):</p> <pre><code> 3612 11.4 21.5 1.3 cat3 10469 11447 9239174 - Smith David 484 25.1 13.2 0.0 cat3 11505 11675 9238946 - John Mary 239 29.4 1.9 1.0 cat3 ...
2
2016-10-01T02:37:38Z
39,802,521
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pd.read_csv()</a> with a separator and specify the column names and also specify that there are no column headers already included in the csv file.</p> <pre><code>In [24]: pd.read_csv("file1.txt", header=None, na...
2
2016-10-01T02:47:03Z
[ "python", "csv", "pandas", "awk", "dataframe" ]
How to study python to take part in GSoC?
39,802,513
<p>I'm new to python. I have learnt the basics from learnpythonthehardway.org/book and now I'm unable to understand the codes and libraries method of my favorite projects on github. </p> <p>What should I do now in step by step manner so that I become capable enough to contribute and hence take part in GSoC no matter h...
-1
2016-10-01T02:45:22Z
39,802,549
<p>If you are just trying to learn Python I know YouTube has a lot of fantastic resources. Since you've already read <em>Learn Python the Hard Way</em>, I would suggest you look for YouTube videos where the host is creating a project (Look for something which interests you), and follow along until you come across somet...
2
2016-10-01T02:51:57Z
[ "python" ]
How to study python to take part in GSoC?
39,802,513
<p>I'm new to python. I have learnt the basics from learnpythonthehardway.org/book and now I'm unable to understand the codes and libraries method of my favorite projects on github. </p> <p>What should I do now in step by step manner so that I become capable enough to contribute and hence take part in GSoC no matter h...
-1
2016-10-01T02:45:22Z
39,802,713
<p>As mentioned by @Dylan, YouTube hosts a lot of Python tutorials which are helpful for learning more about Python.</p> <p>Additionally, I would invest your time in reading some eBooks. They have a wealth of knowledge that can expand your horizons beyond learning the basics of Python and personally I found it to be a...
0
2016-10-01T03:24:40Z
[ "python" ]
Making Python go a webpage that has a lot of links, scraping each link and seeing if they have a specific piece of text
39,802,626
<p><strong>I have a question pertaining to Python that I hope can be remedied.</strong> I'm not asking to be spoonfed, but any advice will be extremely helpful. </p> <p>I'm working on a mini-project of sorts where I "crawl" the WW1 Database of Canadian Soldiers who died and seeing which pages lack info. </p> <p><a hr...
0
2016-10-01T03:07:33Z
39,802,891
<p>I would like suggest you use Scrapy Framework. In building scrapy spiders, </p> <ol> <li>You can specify how to start request, e.g., the simplest way by setting <code>start_urls</code> or overwrite function <code>start_request</code></li> <li>You can specify how to parse response. Here you can do the xpath selectio...
0
2016-10-01T04:01:49Z
[ "python" ]
TypeError for Python program (string formatting with %d)
39,802,699
<p>My program: A Math Quiz that prompts a user for a choice of difficulty (Beginner, Intermediate, Advanced) and then generates five questions (with random #'s) depending on their choice.</p> <p>It was working completely fine until I started adding the comments and doc strings (I apologize if it's hard to read with th...
-1
2016-10-01T03:21:22Z
39,802,745
<p>You are using <code>sum</code> as a variable name, but that shadows a builtin function <a href="https://docs.python.org/2/library/functions.html#sum" rel="nofollow"><code>sum</code></a>. Change your variable name to something else and the error will go away.</p> <p>With <code>if int(ans) == sum:</code>, all you are...
0
2016-10-01T03:29:11Z
[ "python", "typeerror", "modulus" ]
TypeError for Python program (string formatting with %d)
39,802,699
<p>My program: A Math Quiz that prompts a user for a choice of difficulty (Beginner, Intermediate, Advanced) and then generates five questions (with random #'s) depending on their choice.</p> <p>It was working completely fine until I started adding the comments and doc strings (I apologize if it's hard to read with th...
-1
2016-10-01T03:21:22Z
39,802,750
<p>You use a variable called <code>sum</code> but don't define it. Python has a builtin function called <code>sum</code> - and you really should change your variable name so you don't get this type of problem - and python tried using that function for the <code>%d</code> calculation. Rename it <code>my_sum</code> and y...
0
2016-10-01T03:30:20Z
[ "python", "typeerror", "modulus" ]
TypeError for Python program (string formatting with %d)
39,802,699
<p>My program: A Math Quiz that prompts a user for a choice of difficulty (Beginner, Intermediate, Advanced) and then generates five questions (with random #'s) depending on their choice.</p> <p>It was working completely fine until I started adding the comments and doc strings (I apologize if it's hard to read with th...
-1
2016-10-01T03:21:22Z
39,802,775
<p>You need to change some values.</p> <p>In line</p> <pre><code>ans = input("What's %d plus %d?" % (n1, n2)) </code></pre> <p>Add</p> <pre><code>result = n1 + n2 if int(ans) == result: print("That's correct, well done!\n") correct = correct + 1 else: print("No it's not correct. The answer ...
0
2016-10-01T03:36:32Z
[ "python", "typeerror", "modulus" ]
Function to return True if integer k and n in list?
39,802,828
<p>Very new to python... If I give a list that has two integers n and k, the function should return Boolean True. K has to be in the list the number of n times. For example, if I call matchingValues([1, 2, 1, 4, 1, 1], 1, 4) should return True since 1 is in the list 4 times. I'm guessing I have to use the .count() opti...
-2
2016-10-01T03:49:19Z
39,802,845
<p>Better than a solution involving <code>len()</code> is to use the <code>.count()</code> method for lists. It takes an argument, and returns the number of times that argument appears in the list that it is called on.</p>
1
2016-10-01T03:52:07Z
[ "python", "list" ]
Function to return True if integer k and n in list?
39,802,828
<p>Very new to python... If I give a list that has two integers n and k, the function should return Boolean True. K has to be in the list the number of n times. For example, if I call matchingValues([1, 2, 1, 4, 1, 1], 1, 4) should return True since 1 is in the list 4 times. I'm guessing I have to use the .count() opti...
-2
2016-10-01T03:49:19Z
39,802,872
<p>What you want to do is define a variable which counts how many times n is in the list</p> <pre><code>found = 0 </code></pre> <p>and then, iterate over your list with a loop</p> <pre><code>for x in range(0, len(aList)): if aList[x] == n: found += 1 return(found == k) </code></pre> <p>This is, however,...
1
2016-10-01T03:57:01Z
[ "python", "list" ]
Raise an exception in python3 for this method which check dictionary.get with default value?
39,802,857
<p>I have a requirement that I have to raise an exception in method "meth(a)", only way I can achieve is to declare dictionary "a" to some value such that a.get('v', 0) raise an exception</p> <pre class="lang-python prettyprint-override"><code>def meth(a): if isinstance(a, dict): return a.get('v', 0)# I ha...
-1
2016-10-01T03:54:15Z
39,803,064
<p>Depends on what you mean by <em>declare dictionary "a" to some value</em>. You can create your own class that inherits from <code>dict</code> so that the <code>isinstance</code> test works and implement an unfriendly <code>get</code>.</p> <pre><code>class MyDict(dict): def get(self, name, default=None): ...
1
2016-10-01T04:32:53Z
[ "python", "dictionary", "exception-handling", "default" ]
Maximum value of certain element of all arrays in np array
39,802,867
<p>I have a numpy array with arrays within it:</p> <pre><code>array([[1,2,3],[4,5,6],[7,8,9]]) </code></pre> <p>How am I able to find the maximum of all of the last elements of these inner arrays? ie. for this case the return would be 9 <code>(max(3,6,9))</code></p> <p>I'm able to do this by converting to a Pandas ...
0
2016-10-01T03:55:50Z
39,802,879
<p>Assuming that you meant to write</p> <pre><code>array([[1,2,3],[4,5,6],[7,8,9]]) </code></pre> <p>then you can slice the last column with <code>A[:,-1]</code> and call <code>.max()</code>.</p>
1
2016-10-01T03:58:32Z
[ "python", "numpy" ]
Sending email with python script
39,803,160
<p>What I'm trying to do is get my python code to send an email. This code is supposed to use the yahoo smtp to send the email. I don't need any attachments or anything else. The code bugs out where it says <code>Error: unable to send email.</code> Other than the obvious of putting in correct email receiver and sender ...
1
2016-10-01T04:51:54Z
39,805,628
<p>I don't know about Yahoo, but Google blocked the login via their smtp-port. It would be way too easy to conduct brute force attacks otherwise. So even if your code is perfectly ok, the login might still fail because of that. I have tried to do the exact same thing for my gmail account.</p>
0
2016-10-01T10:41:01Z
[ "python", "email", "smtp", "yahoo-api" ]
Sending email with python script
39,803,160
<p>What I'm trying to do is get my python code to send an email. This code is supposed to use the yahoo smtp to send the email. I don't need any attachments or anything else. The code bugs out where it says <code>Error: unable to send email.</code> Other than the obvious of putting in correct email receiver and sender ...
1
2016-10-01T04:51:54Z
39,807,354
<p>As developer I suggest: <a href="https://github.com/kootenpv/yagmail" rel="nofollow">yagmail</a></p>
0
2016-10-01T13:43:56Z
[ "python", "email", "smtp", "yahoo-api" ]
scrapy response.xpath only picking out the first item
39,803,253
<p>I have the html structure</p> <pre><code> &lt;div class="column first"&gt; &lt;div class="detail"&gt; &lt;strong&gt;Phone: &lt;/strong&gt; &lt;span class="value"&gt; 012-345-6789&lt;/span&gt; &lt;/div&gt; &lt;div class="detail"&gt; &lt;span class="value"&gt;1 Street Address, Big Road,...
0
2016-10-01T05:11:54Z
39,803,354
<p>in items.py, specify-</p> <pre><code>from scrapy.item import Item, Field class yourProjectNameItem(Item): # define the fields for your item here like: name = Field() details= Field() </code></pre> <p>in your scrapy spider: imports:</p> <pre><code>from scrapy.selector import HtmlXPathSelector from scr...
0
2016-10-01T05:30:25Z
[ "python", "scrapy" ]
modifying many columns in pandas dataframe
39,803,254
<p>I have been stuck on this for a while and no amount of googling seems to help. </p> <p>I am reading in a lot of raw data. Some of the variables come in as objects due to the source using letters for various reasons for missing (which I do not care about).</p> <p>So I want to run a fairly large subset of columns th...
2
2016-10-01T05:12:12Z
39,803,974
<p>First of all, see <a href="http://stackoverflow.com/a/39801222/2336654">this answer</a></p> <pre><code># Let numeric = ['lots', 'a', 'columns'] </code></pre> <p><strong><em>Option 1</em></strong></p> <pre><code>df[numeric] = df[numeric].apply(pd.to_numeric, errors='coerce') </code></pre> <p><strong><em>Option 2<...
1
2016-10-01T07:13:55Z
[ "python", "list", "pandas", "dataframe" ]
Is it possible to set two or more types(Integre or float) for 1 field by setting codition in Odoo 9?
39,803,321
<p>I am try to learn how to customize the odoo system to sovle specific problem in business. I am using odoo9.0. Could we set two types of value(integre and float) for a file by setting the specific conditions for each of them? if it is possible, please teach me ththe right steps to follow. Thanks for your time.</p>
0
2016-10-01T05:23:59Z
39,817,870
<p>In Odoo it's not possible to set two data-type for single field. But you can create 2 fields Integer and Float and show/hide by setting condition in view.</p> <p>.py file</p> <pre><code>is_integer = fields.Boolean('Is Integer?') integer_field = fields.Integer('Integer Field') float_field = fields.Float('Float Fiel...
1
2016-10-02T14:13:38Z
[ "python", "file-type", "odoo-9" ]
How to call a view function with argument from template and return a python object in Django?
39,803,339
<p>Here is the questions now I want call a view function from template/html with argument the function most like </p> <pre><code>def function(PageToken,ID): '''Do Something Here''' comments = [[User1,Comment1],[User2,Comment2]] return comments </code></pre> <p>And how I call this function and Use like</p> <p...
0
2016-10-01T05:27:59Z
39,803,890
<p>you can define your own custom template filter that takes arguments. </p> <pre><code># in custom_tags.py from django import template register = template.Library() def build_comments(pagetoken, id): # build comments return comments # it can also be queryset register.assignment_tag(build_comments) </co...
0
2016-10-01T07:01:45Z
[ "javascript", "python", "html", "ajax", "django" ]
Python plotting on remote server using PyCharm
39,803,373
<p>I have started to learn Python and so far my setup has been following - Python 3.5 installation on Win10 64bit local machine with PyCharm as a great IDE. Everything works, matplotlib charts and other visual outputs display fine, debugging works, etc.</p> <p>Now, I have came across some libraries which works only on...
0
2016-10-01T05:34:26Z
40,006,878
<p>Ok, after some more googling I finally managed to get this process working, hope it helps somebody: </p> <p>1) on remote host (VPS, Ubuntu 16.04) I had to install X11 server, which I did by: </p> <pre><code>sudo apt-get install xorg sudo apt-get install openbox </code></pre> <p>2) On remote host I had to make sur...
0
2016-10-12T19:31:46Z
[ "python", "linux", "windows", "matplotlib", "x11" ]
What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib?
39,803,385
<p>In the <a href="http://matplotlib.org/users/legend_guide.html#legend-location" rel="nofollow">"Legend location"</a> section of the "Legend guide" in the matplotlib website, there's a small script where line 9 is <code>plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.)</co...
0
2016-10-01T05:36:24Z
39,806,180
<p>You're right, the 4-tuple in <code>plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3)</code> is set as <code>(x0, y0, width, height)</code> where <code>(x0,y0)</code> are the lower left corner coordinates of the bounding box.</p> <p>While those parameters set the bounding box for the legend, the legend's actual...
3
2016-10-01T11:40:28Z
[ "python", "matplotlib" ]
How to create buttons, text boxes and label in loop in tkinter
39,803,630
<p>I am trying to create a framework to create a label, text box and button as an object, I can extend it easily.</p> <p>Idea:</p> <p><a href="http://i.stack.imgur.com/gsSAR.png" rel="nofollow">Original</a></p> <p><a href="http://i.stack.imgur.com/x8q8C.png" rel="nofollow">after extend</a></p> <p>and it could exten...
0
2016-10-01T06:18:05Z
39,804,134
<p>You have a lot of unnecessary code written like creating a string and assigning a widget to the same variable.<br> Now, I am not certain what the code should look like but I'll give you a way where, in case of making new variables every time in a loop, there is this built-in function <code>exec</code> that might hel...
0
2016-10-01T07:34:26Z
[ "python", "tkinter" ]
How to create buttons, text boxes and label in loop in tkinter
39,803,630
<p>I am trying to create a framework to create a label, text box and button as an object, I can extend it easily.</p> <p>Idea:</p> <p><a href="http://i.stack.imgur.com/gsSAR.png" rel="nofollow">Original</a></p> <p><a href="http://i.stack.imgur.com/x8q8C.png" rel="nofollow">after extend</a></p> <p>and it could exten...
0
2016-10-01T06:18:05Z
39,816,274
<p>Tkinter widgets are no different than any other python objects with respect to creating them in a loop. Your problem seems to be that you don't know how to create a unique variable for an unknown number of widgets. </p> <p>The important thing to know is that you don't need a unique variable for each widget. Instead...
0
2016-10-02T10:57:24Z
[ "python", "tkinter" ]
DictVectorizer with a large dataset
39,803,650
<p>I have a large dataset with categorical values and tried to encode them using <code>DictVectorizer</code>. The following is a snippet of the code I tried.</p> <pre><code>dv = DictVectorizer(sparse=True) _dicts = [] for line in fp: _dict = create_dict_feature(line) _dicts.append(_dict) dv.fit_transform(_dict...
1
2016-10-01T06:20:11Z
39,804,103
<p>According to the docs, <code>fit_transform</code> can take an iterable. If the memory issue is coming from the size of the list, consider using a generator instead of a <code>list</code>, which will yield your <code>dict</code>s one at a time as it is iterated. </p> <pre><code>_dicts = (create_dict_feature(line) fo...
1
2016-10-01T07:30:31Z
[ "python", "scikit-learn" ]
speech to text processing - python
39,803,688
<p>I have a project in which the user will send an audio file from android/web to the server. I need to perform speech to text processing on the server and return some files to the user back on android/web. However the server side is to be done using Python. Please guide me as to how it could be done?</p>
0
2016-10-01T06:27:11Z
39,804,001
<p>Alongside your web application, you can have a queue of tasks that need to be run and worker process(es) to run and track those tasks. This is a popular pattern when web requests need to either start tasks in the background, check in on tasks, or get the result of a task. An introduction to this pattern can be found...
0
2016-10-01T07:16:52Z
[ "python", "speech-recognition", "speech-to-text" ]
Implementing BFS algorithm with a max depth and that prints all shortest paths
39,803,712
<p>This is the BFS algorithm I came up with to print all the shortest paths from root node to any other node in the graph:</p> <pre><code>d = deque() d.append(root) level = 0 while len(d) &gt;= 0 and level &lt;= max_depth: u = d.popleft() print(adjacency_list[u]) for v in adjacency_list[u]: if visi...
0
2016-10-01T06:31:26Z
39,809,079
<p>You are incrementing level at the wrong place. Each node's level is equal to its parent level plus 1. You should not increment level globally in the <code>while</code> loop. Instead you should store the level of each node you put in the queue. Something like this:</p> <pre><code>d = deque() #node,level d....
1
2016-10-01T16:42:20Z
[ "python", "algorithm", "shortest-path", "bfs" ]
peewee and peewee-async: why is async slower
39,803,746
<p>I am trying to wrap my head around Tornado and async connections to Postgresql. I found a library that can do this at <a href="http://peewee-async.readthedocs.io/en/latest/" rel="nofollow">http://peewee-async.readthedocs.io/en/latest/</a>.</p> <p>I devised a little test to compare traditional Peewee and Peewee-asyn...
2
2016-10-01T06:37:17Z
39,807,456
<p>For a long explanation:</p> <p><a href="http://techspot.zzzeek.org/2015/02/15/asynchronous-python-and-databases/" rel="nofollow">http://techspot.zzzeek.org/2015/02/15/asynchronous-python-and-databases/</a></p> <p>For a short explanation: synchronous Python code is simple and mostly implemented in the standard libr...
2
2016-10-01T13:54:58Z
[ "python", "postgresql", "tornado", "python-asyncio", "peewee" ]
peewee and peewee-async: why is async slower
39,803,746
<p>I am trying to wrap my head around Tornado and async connections to Postgresql. I found a library that can do this at <a href="http://peewee-async.readthedocs.io/en/latest/" rel="nofollow">http://peewee-async.readthedocs.io/en/latest/</a>.</p> <p>I devised a little test to compare traditional Peewee and Peewee-asyn...
2
2016-10-01T06:37:17Z
39,811,365
<p>Database ORMs introduce many complexities for async architectures. There are several places within an ORM where blocking may take place and can be overwhelming to alter to an async form. The places where blocking takes place can also vary depending on the database. My guess as to why your results are so slow is beca...
1
2016-10-01T20:51:27Z
[ "python", "postgresql", "tornado", "python-asyncio", "peewee" ]
Can't reshape array with numpy
39,803,776
<p>i want to change a image(17x15) to 2d array with code:</p> <pre><code>from PIL import Image import numpy as np list = [] im = Image.open('plus1.jpg') row,col = im.size print(row,col) for i in range (row): for j in range (col): r, g, b = im.getpixel((i, j)) list.append([r,g,b]) print(list) prin...
2
2016-10-01T06:42:54Z
39,804,185
<p>Your image is 17x15, so there are 255 pixels. For each pixel, there are three color values (r,g,b). This means that your array <code>list</code> has shape <code>(255,1,3)</code>. This means that it contains 755 elements, and an error is raised when you try to reshape it to <code>(17,15)</code>, which does not preser...
1
2016-10-01T07:40:39Z
[ "python", "arrays", "numpy" ]
How can I condense a 'for x in range' statement within a 'if' 'elif' statement within a 'while' statement
39,803,878
<p>I have a code that makes a math table and I feel has the possibility to be reduced as I have three of the same codes repeated but with only slightly different solutions for each of the if/elif statements. </p> <pre><code>num=10 x=str(input("Enter Math Operation (+, -, *): ")) while (x != "+" and x != "-" and x != "...
2
2016-10-01T06:58:53Z
39,803,912
<p>You can use a lookup table to store the different functions</p> <pre><code>num=10 x=str(input("Enter Math Operation (+, -, *): ")) while (x != "+" and x != "-" and x != "*"): x=str(input("\tEnter Math Operation: ")) ops = { '+': lambda x, y: x+y, '-': lambda x, y: x-y, '*': lambda x, y: x*y} fn = o...
2
2016-10-01T07:05:00Z
[ "python", "python-3.x" ]
How can I condense a 'for x in range' statement within a 'if' 'elif' statement within a 'while' statement
39,803,878
<p>I have a code that makes a math table and I feel has the possibility to be reduced as I have three of the same codes repeated but with only slightly different solutions for each of the if/elif statements. </p> <pre><code>num=10 x=str(input("Enter Math Operation (+, -, *): ")) while (x != "+" and x != "-" and x != "...
2
2016-10-01T06:58:53Z
39,803,919
<p>Functions are first class objects in python. Assign the right function to a variable, and then use it.</p> <pre><code>num=10 x=str(input("Enter Math Operation (+, -, *): ")) # Read operation while (x != "+" and x != "-" and x != "*"): x=str(input("\tEnter Math Operation: ")) # Select appropriate function if x=...
2
2016-10-01T07:06:22Z
[ "python", "python-3.x" ]
How can I condense a 'for x in range' statement within a 'if' 'elif' statement within a 'while' statement
39,803,878
<p>I have a code that makes a math table and I feel has the possibility to be reduced as I have three of the same codes repeated but with only slightly different solutions for each of the if/elif statements. </p> <pre><code>num=10 x=str(input("Enter Math Operation (+, -, *): ")) while (x != "+" and x != "-" and x != "...
2
2016-10-01T06:58:53Z
39,803,920
<p>You would typically do something like this:</p> <ul> <li><p>Store the operator as a function in a variable</p></li> <li><p>Use a dictionary to look up operators</p></li> <li><p>Use <code>.format()</code> instead of putting lots of string pieces together</p></li> <li><p>Don't use <code>str()</code> if the argument i...
6
2016-10-01T07:07:01Z
[ "python", "python-3.x" ]
Setting global variables between classes with tKinter
39,803,906
<p>I am currently struggling to use input derived from another class (which uses tkinter) to alter outputs in a different class. This is my code:</p> <pre><code>#there are many of these defs, this is just one i used as an example def command_ssumowrestler(self): self.master.withdraw() toplevel = t...
-1
2016-10-01T07:04:20Z
39,804,244
<p><code>global</code> doesn't create variable - it only informs function/method to use global variable instead of local variable. First you have to create this variable before classes.</p> <hr> <p>BTW: if you use classes so why don't you use in first class</p> <pre><code>self.cs_hobby = 'sumo_wrestler' </code></pre...
1
2016-10-01T07:49:51Z
[ "python", "class", "variables", "tkinter" ]
Why is `self` not used in this method?
39,803,950
<p>I was under the impression that methods within Python classes <em>always</em> require the <code>self</code> argument (I know that it doesn't actually have to be <code>self</code>, just some keyword). But, this class that I wrote doesn't require it:</p> <pre><code>import ZipFile import os class Zipper: def make_...
1
2016-10-01T07:10:45Z
39,803,983
<p>You are trying to use it as a static method. In your example;</p> <pre><code>class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world' a = MyClass() a.f() # This should work. </code></pre> <p>Calling <code>MyClass.f()</code> assumes <code>f</code> is static for <...
0
2016-10-01T07:14:52Z
[ "python", "python-3.x", "typeerror", "self" ]
Why is `self` not used in this method?
39,803,950
<p>I was under the impression that methods within Python classes <em>always</em> require the <code>self</code> argument (I know that it doesn't actually have to be <code>self</code>, just some keyword). But, this class that I wrote doesn't require it:</p> <pre><code>import ZipFile import os class Zipper: def make_...
1
2016-10-01T07:10:45Z
39,805,148
<p>The thing with <code>self</code> is that it's added <em>implicitly</em>. That is, the calling code says <code>Myclass().f()</code>, but the callee sees <code>Myclass().f(self)</code>. It also implies that the method is called from some instance of <code>Myclass</code>, which is placed in <code>self</code> variable. ...
0
2016-10-01T09:45:50Z
[ "python", "python-3.x", "typeerror", "self" ]
using numpy to calculate mean
39,803,952
<p>I am trying to calculate the mean of GNP for each country from 2006 to 2015. But when I apply the aggregation with mean function, it will not calculate the mean from 2006 to 2015. Instead, it just display the values for each year. Pls tell me what went wrong? I am able to sort by country but the mean just wont work ...
0
2016-10-01T07:11:02Z
39,804,414
<p>This should work</p> <pre><code>import pandas as pd import wbdata as wb import datetime wb_indicator = 'NY.GNP.ATLS.CD' data_date = (datetime.datetime(2006, 1, 1), datetime.datetime(2015, 1, 1)) data = wb.get_data(wb_indicator, data_date=data_date, pandas=True) gnp_means = data.reset_index().groupby('country').m...
0
2016-10-01T08:14:07Z
[ "python", "python-2.7" ]