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
Approach behind having everything as an object in Python
37,674,728
<p>Why is everything in Python, an object? According to what I read, everything including functions is an object. It's not the same in other languages. So what prompted this shift of approach, to treat everything including, even functions, as objects.</p>
2
2016-06-07T08:52:14Z
37,675,534
<p>In my opinion, the 'Everything is object' is great in Python. In this language, you don't react to what are the objects you have to handle, but how they can interact. A function is just an object that you can <code>__call__</code>, a list is just an object that you can <code>__iter__</code>. But why should we divide...
-1
2016-06-07T09:30:37Z
[ "python" ]
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2013' in position 637: ordinal not in range(256)
37,674,947
<p>This is driving me crazy and i have tried different suggestions from the community but it doesnt seem to work. I tried even recreating the db using just utf-8 and still it gives me this error.</p> <p>Basically i am using pymysql module and writing to the db.</p> <p>openconnect = pymysql.connect(host='xxxx',port=33...
0
2016-06-07T09:04:02Z
37,775,353
<p>I was able to resolve the issue by defining a charset in pymysql connect</p> <p>openconnect = pymysql.connect(host='xxxx',port=3306,user='xxx',passwd='xxx',db='xxxx',charset='utf8')</p> <p>Please note it is utf8 and not utf-8 </p>
5
2016-06-12T14:27:07Z
[ "python", "python-2.7", "python-3.x", "utf-8", "latin1" ]
How to make Python generators as fast as possible?
37,675,026
<p>For writing an event-driven simulator, I'm relying on <a href="https://simpy.readthedocs.io/en/latest/" rel="nofollow">simpy</a>, which heavily uses Python generators. I'm trying to understand how to make generators as fast as possible, i.e., minimize the state save/restore overhead. I tried three alternatives</p> ...
4
2016-06-07T09:07:34Z
37,675,466
<p>The only state that a generator needs to save is a reference to the stack frame, so saving and restoring state takes exactly the same time no matter how much state is involved and wherever you put the data.</p> <p>The difference you see in the timings is purely down to the speed with which Python can access values:...
6
2016-06-07T09:27:14Z
[ "python", "python-3.x", "generator" ]
How to make Python generators as fast as possible?
37,675,026
<p>For writing an event-driven simulator, I'm relying on <a href="https://simpy.readthedocs.io/en/latest/" rel="nofollow">simpy</a>, which heavily uses Python generators. I'm trying to understand how to make generators as fast as possible, i.e., minimize the state save/restore overhead. I tried three alternatives</p> ...
4
2016-06-07T09:07:34Z
37,675,802
<p>The generator actually retains the actual <em>call frames</em> when <em>yield</em> happens. It doesn't really affect performance whether you have 1 or 100 local variables.</p> <p>The performance difference really comes from how Python (here I am using the CPython a.k.a. the one that you'd download from <a href="htt...
10
2016-06-07T09:43:13Z
[ "python", "python-3.x", "generator" ]
Getting a PRAW subreddit object from self text link to the subreddit
37,675,116
<p>I'm using PRAW with Python and I want to be able to:</p> <ol> <li>Go through the "new" posts on a subreddit</li> <li>Detect if there is a link to a subreddit in the posts selftext</li> <li>If there is a subreddit linked, get that subreddit as a PRAW object that will be used later.</li> </ol> <p>I can do step 1, bu...
0
2016-06-07T09:12:08Z
37,697,157
<p>I have found my own answer now. Here is the code that works for me:</p> <pre><code>#! python3 # Reply with subreddit info from subreddit in text body import praw, bs4, re from pprint import pprint # Bot login details USERNAME = "AutoMobBot"; PASSWORD = "&lt;Password&gt;"; UA = "[Subreddit Info Provider (Update 4...
0
2016-06-08T08:29:50Z
[ "python", "regex", "reddit", "praw" ]
Extracting Data from PDF with particular heading in python
37,675,203
<p>I wanted to parse the PDF file in python. I have seen examples with PDFMiner which could not explain my requirement.</p> <p>For Example if I want to parse a resume, it contains various fields like Summary, Experience and Hobbies. </p> <p>I am interested to extract only experience and this experience field will...
-1
2016-06-07T09:16:21Z
37,680,867
<p>There are 2 viable approaches to extract that field data:</p> <ol> <li><p>Search for some predefined keyword, like <code>Experience</code> to get its location. Then search for the next section's keyword (<code>Hobbies</code>) and then just determine coordinates of the text partition between these 2 sections and ext...
1
2016-06-07T13:31:32Z
[ "python", "parsing", "pdf", "pdfminer", "pdf-parsing" ]
Coherece many some list in many dictionaries python
37,675,341
<p>I'm struggling with a problem concerning lists and dictionaries.</p> <p>I have 4 simple lists (same length):</p> <pre><code>Fe = [27.8, 11.08, 13.5, 31.23, 41.56, 1.0, 1.56, 28.86, 20.19, 5.91, 50.47, 39.38, 25.58, 45.24, 25.48, 44.1, 47.72, 27.59, 53.06] Ca = [110.8, 124.34, 132.07, 82.14, 213.04, 91.47, 133.31, ...
-1
2016-06-07T09:21:41Z
37,675,474
<p>I think this will work for you!</p> <pre><code>data = [] for i in range(len(Fe)): temp = {} temp["Fe"] = Fe[i] temp["Ca"] = Ca[i] temp["Mg"] = Mg[i] temp["label"] = label[i] data.append(temp) </code></pre>
1
2016-06-07T09:27:31Z
[ "python", "list", "dictionary" ]
Coherece many some list in many dictionaries python
37,675,341
<p>I'm struggling with a problem concerning lists and dictionaries.</p> <p>I have 4 simple lists (same length):</p> <pre><code>Fe = [27.8, 11.08, 13.5, 31.23, 41.56, 1.0, 1.56, 28.86, 20.19, 5.91, 50.47, 39.38, 25.58, 45.24, 25.48, 44.1, 47.72, 27.59, 53.06] Ca = [110.8, 124.34, 132.07, 82.14, 213.04, 91.47, 133.31, ...
-1
2016-06-07T09:21:41Z
37,675,487
<pre><code>from itertools import izip [dict(izip(['Fe','Ca','Mg','label'], i)) for i in izip(Fe, Ca, Mg, label)] #Out[52]: #[{'Ca': 110.8, 'Fe': 27.8, 'Mg': 18.07, 'label': u'2818/22/0834'}, # {'Ca': 124.34, 'Fe': 11.08, 'Mg': 21.55, 'label': u'2818/22/0851'}, # ... </code></pre> <p><code>Pandas</code> approach:</p>...
3
2016-06-07T09:28:10Z
[ "python", "list", "dictionary" ]
Coherece many some list in many dictionaries python
37,675,341
<p>I'm struggling with a problem concerning lists and dictionaries.</p> <p>I have 4 simple lists (same length):</p> <pre><code>Fe = [27.8, 11.08, 13.5, 31.23, 41.56, 1.0, 1.56, 28.86, 20.19, 5.91, 50.47, 39.38, 25.58, 45.24, 25.48, 44.1, 47.72, 27.59, 53.06] Ca = [110.8, 124.34, 132.07, 82.14, 213.04, 91.47, 133.31, ...
-1
2016-06-07T09:21:41Z
37,675,658
<p>Try python list comprehension:</p> <pre><code>data = [{'Fe':Fe[i], 'Ca':Ca[i], 'Mg':Mg[i], 'label':label[i]} for i in range(len(Fe))] </code></pre>
1
2016-06-07T09:36:22Z
[ "python", "list", "dictionary" ]
How to output an empty object to JSON using Python
37,675,362
<p>Using the json module for Python, I want to be able to output empty objects/arrays into my JSON. But this module seems to just ignore them.</p> <p>Part of the legacy code I am working with, requires these objects to be defined even if empty.</p> <p>This is the code:</p> <pre><code>import json import sys filename...
0
2016-06-07T09:22:41Z
37,699,365
<p>The code worked fine. I was told it didn't, and I should have checked. </p> <p>So the above code all works as it should.</p> <p>Do I delete the question or leave it here for people to view? Do I accept this as the answer?</p>
0
2016-06-08T10:03:31Z
[ "python", "json" ]
Swig : best way to handle a simplified interface
37,675,364
<p>We have a set of C++ classes that we expose to Python using Swig. We are often adding new arguments to the methods. On the other side, we have a set of Python scripts that we want to maintain as easily as possible. So, when we change the set of arguments of an exposed method in C++, we don't want to have to change a...
0
2016-06-07T09:22:48Z
37,733,885
<p>I think you can solve your problem nicely with SWIG by playing tricks with its <code>%ignore</code>, <code>%rename</code> and <code>%extend</code> directives. Please look them up in the <a href="http://www.swig.org/Doc3.0/SWIGDocumentation.html" rel="nofollow">SWIG docs</a> for details. But for your above example, y...
0
2016-06-09T18:44:34Z
[ "python", "c++", "swig" ]
I need to process a corpus consisting of over 300,000 words in Python. Is there a distributed environment that I can consider?
37,675,506
<pre><code>pattern = r'[A-Z][A-Z]+' corpus_copy = corpus.split() corrected_corpus = '' for term in corrected_corpus: if (len(re.findall(pattern, term)) == 0 and wordnet.synsets(term) != ''): corrected_corpus += spell(term)+" " </code></pre> <p>This takes forever for execution, and eventually b...
0
2016-06-07T09:29:19Z
37,676,000
<p>Generator functions may solve your problem.To know more about application of Generators in text files See section 5.3.1 from this link <a href="http://anandology.com/python-practice-book/iterators.html" rel="nofollow">http://anandology.com/python-practice-book/iterators.html</a></p>
1
2016-06-07T09:51:11Z
[ "python" ]
I need to process a corpus consisting of over 300,000 words in Python. Is there a distributed environment that I can consider?
37,675,506
<pre><code>pattern = r'[A-Z][A-Z]+' corpus_copy = corpus.split() corrected_corpus = '' for term in corrected_corpus: if (len(re.findall(pattern, term)) == 0 and wordnet.synsets(term) != ''): corrected_corpus += spell(term)+" " </code></pre> <p>This takes forever for execution, and eventually b...
0
2016-06-07T09:29:19Z
37,677,590
<p>In case you'd want a more durable and general solution for larger problems I'd recommend something along the lines of <a href="http://www.celeryproject.org/" rel="nofollow">Celery</a>.</p> <p>There's also other alternatives such as <a href="http://python-rq.org/" rel="nofollow">RQ</a> (which is simpler than Celery)...
0
2016-06-07T11:03:07Z
[ "python" ]
Extract files from a zip folder with sub folders into a single folder
37,675,584
<p>I have a zip folder with several subfolders. testfolder.zip contains files in the given format</p> <blockquote> <pre><code>testfolder/files 1,2,3 testfolder/Test1folder/files 5,6 testfolder/Test2folder/files 7,8 </code></pre> </blockquote> <p>I need the output as</p> <blockquote> <p>testfolder/files 1,2,3,4,5,6...
2
2016-06-07T09:32:53Z
37,676,513
<p>Replace:</p> <pre><code>zip_handler.extractall(dir_name) </code></pre> <p>with something like this:</p> <pre><code>for z in zip_handler.infolist(): zip_handler.extract(z, dir_name) </code></pre> <p>This should by taking each file in the archive at a time and extracting it to the same point in the directory.<...
1
2016-06-07T10:15:04Z
[ "python", "file" ]
Why does Flask's app.config.from_object() behave differently with gunicorn?
37,675,636
<p>I'm using Flask with virtualenv, and my demo Flask app is structured as follows:</p> <pre><code>app/ hello.py config/ settings.py venv/ virtualenv files </code></pre> <p>Contents of <code>hello.py</code></p> <pre><code>from flask import Flask def create_app(): app = Flask(__name__, instance_rela...
0
2016-06-07T09:35:10Z
37,676,587
<p>Not the most elegant yet still perfectly working solution:</p> <pre><code>from os.path import abspath, join from flask import Flask def create_app(): app = Flask(__name__, instance_relative_config=True) config_file_path = abspath( join(app.instance_path, '../config/settings.py') ) app.conf...
1
2016-06-07T10:17:43Z
[ "python", "flask", "gunicorn" ]
Python: Append correct string to END of list
37,675,699
<p>I am using the below code that split a bit of text at the first space </p> <pre><code>splitdata = details[2].split(' ', 1) details[2] = splitdata[0] details.extend(splitdata[1:]) </code></pre> <p>so will take a string like:</p> <blockquote> <p>['(Class 6)', '(0-60, 4yo+)', '1m4f Standard']</p> </blockquote> <p...
1
2016-06-07T09:38:38Z
37,675,770
<p>Use some python swapping like this,</p> <pre><code> details = ['(Class 6)', '(0-60, 4yo+)', '1m4f Standard'] splitdata = details[2].split(' ', 1) details[2] = splitdata[0] details.extend(splitdata[1:]) details[2], details[3] = details[3], details[2] # Swap print details </code></pre>
2
2016-06-07T09:41:42Z
[ "python" ]
Python: Append correct string to END of list
37,675,699
<p>I am using the below code that split a bit of text at the first space </p> <pre><code>splitdata = details[2].split(' ', 1) details[2] = splitdata[0] details.extend(splitdata[1:]) </code></pre> <p>so will take a string like:</p> <blockquote> <p>['(Class 6)', '(0-60, 4yo+)', '1m4f Standard']</p> </blockquote> <p...
1
2016-06-07T09:38:38Z
37,675,772
<p>Do you need opposite order of two last elements? If yes, just change order of indices:</p> <pre><code>splitdata = details[2].split(' ', 1) details[2] = splitdata[1] details.extend(splitdata[0]) </code></pre>
1
2016-06-07T09:41:45Z
[ "python" ]
Python: Append correct string to END of list
37,675,699
<p>I am using the below code that split a bit of text at the first space </p> <pre><code>splitdata = details[2].split(' ', 1) details[2] = splitdata[0] details.extend(splitdata[1:]) </code></pre> <p>so will take a string like:</p> <blockquote> <p>['(Class 6)', '(0-60, 4yo+)', '1m4f Standard']</p> </blockquote> <p...
1
2016-06-07T09:38:38Z
37,675,779
<p>Instead of your last two lines:</p> <pre><code>details[2:] = reversed(splitdata) </code></pre>
4
2016-06-07T09:41:53Z
[ "python" ]
Find the correct intermediate cert type in a list of files using python
37,675,727
<p>I'm new into python and i want to do something like:</p> <pre><code>for i in $(ls -1 *.crt) ; do echo $i ; openssl x509 -noout -text -in $i | grep -i telesec ; done </code></pre> <p>to find out the type of intermediate certificates.</p> <p>I managed to get the filelist but im not sure how to continue with that op...
-1
2016-06-07T09:40:06Z
37,676,214
<p>Here's one way:</p> <pre><code>#!/usr/bin/env python import subprocess import glob def openssl_509(path): rval = subprocess.check_output('openssl x509 -noout -text -in {0}'.format(path) return rval def main(): for filename in glob.iglob('*.crt'): text = openssl_509(filename) if 'telese...
0
2016-06-07T10:00:40Z
[ "python", "ssl" ]
Python-script working in VirtualBox (py 2.7.10) but not on Raspberry Pi 3 (py 2.7.11)
37,675,841
<p>I'm trying to execute a script on my Raspberry Pi (Ubuntu MATE), which was working perfectly fine in my VM (Oracle VM Virtual Box/Ubuntu 15.10). On the Raspberry Pi, I've tried Raspbian and currently I'm running Ubuntu MATE (16.04) because I wanted to see if it works there.</p> <p>Basically my script goes through a...
-1
2016-06-07T09:44:31Z
37,676,965
<p><strong>EDIT:</strong> From this answer <a href="https://stackoverflow.com/questions/23142719/pyqt-app-exec-stops-all-following-code-from-running">PyQt: app.exec_() stops all following code from running</a> <code>app.exec_()</code> starts a blocking <code>PyQt4</code> instance which is why further code isn't execute...
0
2016-06-07T10:34:04Z
[ "python", "qt", "pyqt", "raspberry-pi", "pyqt4" ]
Automation of scripts to sync generation and capture of packets between different machines for different iterations
37,675,865
<p>I have the following scenario</p> <p>Machine A: (Generator)</p> <p>I am generating traffic using tcpreplay on Machine A.</p> <p>So the generator script will call the following</p> <pre><code>tcpreplay --loop=100000 --intf1=eth0 64.pcap # then I do the above for other pcaps, 128.pcap, 256.pcap etc </code></pre> ...
0
2016-06-07T09:45:18Z
37,677,683
<p>There's a bunch of ways to approach this. I'd use Machine B to control Machine A via <a href="https://docs.python.org/2/howto/sockets.html" rel="nofollow">sockets</a> and code you implement to send and handle specific commands/messages to/from each machine.</p> <p>You'd still need to start your script/daemon on bot...
0
2016-06-07T11:06:42Z
[ "python", "shell", "networking", "scripting", "automation" ]
How can I conditionally update multiple columns in a panda dataframe
37,675,869
<p>I'm trying to conditionally update multiple rows in my panda dataframe. Here's my data:</p> <pre><code>df = pd.DataFrame([[1,1,1], [2,2,2], [3,3,3]], columns=list('ABC')) </code></pre> <p>I can do the update I want in two steps:</p> <pre><code>df.loc[df['A'] == 1, 'B'] = df['C'] +10 df.loc[df['A'] == 1, 'A'] = df...
1
2016-06-07T09:45:26Z
37,675,916
<p>You don't need to pass a 2-element list here:</p> <pre><code>In [52]: df.loc[df['A'] == 1, ['A', 'B']] = df['C'] + 10 df Out[52]: A B C 0 11 11 1 1 2 2 2 2 3 3 3 </code></pre> <p>The assignment on the lhs will just work as the rhs will be broadcast to the shape on the lhs</p>
0
2016-06-07T09:47:24Z
[ "python", "pandas", "dataframe" ]
How can I conditionally update multiple columns in a panda dataframe
37,675,869
<p>I'm trying to conditionally update multiple rows in my panda dataframe. Here's my data:</p> <pre><code>df = pd.DataFrame([[1,1,1], [2,2,2], [3,3,3]], columns=list('ABC')) </code></pre> <p>I can do the update I want in two steps:</p> <pre><code>df.loc[df['A'] == 1, 'B'] = df['C'] +10 df.loc[df['A'] == 1, 'A'] = df...
1
2016-06-07T09:45:26Z
37,678,145
<p>I'm nor sure whether it's the best way to achieve that, but it works:</p> <pre><code>In [284]: df.loc[df['A'] == 1, ['A', 'B']] = pd.DataFrame({'A':df.C + 10, 'B':df.C + 11}, index=df.index) In [285]: df Out[285]: A B C 0 11 12 1 1 2 2 2 2 3 3 3 </code></pre>
1
2016-06-07T11:28:59Z
[ "python", "pandas", "dataframe" ]
Remove unicode character from python when sending response back to javascript
37,675,941
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>elif self.path == "/recQuery": content_length = int(self.headers.getheader('content-length')) cont_Length = content_length print "Query Received...
0
2016-06-07T09:48:27Z
37,678,030
<p>You need to encode your output. </p> <p>If I were you I'll use python3, since python2 encoding is a headache. Anyways I made a super encoding function to help you:</p> <pre><code>def encode_dict(dic, encoding='utf-8'): new_dict={} for key, value in dic.items(): new_key=key.encode(encoding) ...
1
2016-06-07T11:23:05Z
[ "javascript", "python", "json", "unicode" ]
Numpy - Calculating product of a diagonal
37,676,091
<p>Newbie question: assuming I have a matrix A, is there a numpy function which will calculate the product of the diagonal elements of A? </p> <p>EG: </p> <p><a href="http://i.stack.imgur.com/Zmdri.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zmdri.png" alt="enter image description here"></a></p> <p>Wher...
0
2016-06-07T09:55:27Z
37,676,672
<p>You can use the <code>diagonal</code> and <code>prod</code> methods:</p> <pre><code>import numpy as np a = np.matrix([[1, 1, 1], [1, 2, 3], [3, 3, 3]]) prod_diag = a.diagonal().prod() print(prod_diag) # gives 6 as answer </code></pre> <p><code>diagonal</code> returns the diagonal compone...
2
2016-06-07T10:21:08Z
[ "python", "numpy", "matrix" ]
compare dataframes by values
37,676,257
<p>I have two files with geometrical measurements: each file contains a large number of points (defined by x, y and z)</p> <p>I would like to compare the depth (z-value) where the horizontal coordinates are the same <code>(df1['x'] == df2['x']) &amp; (df1['y'] == df2['y'])</code>. The order of the horizontal coordinat...
1
2016-06-07T10:02:38Z
37,676,374
<p>You can <code>merge</code> and then subtract:</p> <pre><code>In [67]: merged = df.merge(df1, left_on=['x1','y1'], right_on=['x2','y2']) merged['z'] = merged['z1'] - merged['z2'] merged.drop(['x2','y2','z1','z2'],axis=1,inplace=True) merged = merged.rename(columns={'x1':'x','y1':'y'}) merged Out[67]: x y z 0...
1
2016-06-07T10:08:20Z
[ "python", "pandas" ]
Jupyter issue with python / pyspark versions
37,676,404
<p>I am running a Jupyter notebook using the pyspark kernel. I am getting the following error. How can I force Jupyter (ideally from within Jupyter) to use the right driver?</p> <p><em>Python in worker has different version 2.6 than that in driver 2.7, PySpark cannot run with different minor versions</em></p> <p>Than...
0
2016-06-07T10:09:32Z
37,699,056
<p>It could be a problem in your pyspark <strong>kernel.json</strong> configuration. For example my pyspark kernel is located at:</p> <pre><code>/usr/local/share/jupyter/kernels/pyspark/kernel.json </code></pre> <p>and contains:</p> <pre><code>{ "display_name": "pySpark (Spark 1.6.0)", "language": "python", "argv...
0
2016-06-08T09:50:22Z
[ "python", "pyspark", "jupyter", "jupyter-notebook" ]
pandas tricky intra-column logic
37,676,413
<p>I have a DataFrame with three columns, <code>t</code>, <code>b</code> and <code>h</code>:</p> <pre><code> t b h 0 NaN False 6 1 6.023448 False 38 2 12.996233 False 46 3 2.484907 False 67 4 5.062595 ...
2
2016-06-07T10:09:54Z
37,677,706
<p>First, I reverse the order of the dataframe. It made it simpler for me, but it's not necessary:</p> <pre><code>df = df.iloc[::-1] </code></pre> <p>In order to isolate the instances where <code>b == True</code>, I added a new column:</p> <pre><code>df['cum_b'] = df['b'].cumsum() </code></pre> <p>This means that I...
1
2016-06-07T11:07:35Z
[ "python", "pandas", "dataframe", null, "cumsum" ]
pandas tricky intra-column logic
37,676,413
<p>I have a DataFrame with three columns, <code>t</code>, <code>b</code> and <code>h</code>:</p> <pre><code> t b h 0 NaN False 6 1 6.023448 False 38 2 12.996233 False 46 3 2.484907 False 67 4 5.062595 ...
2
2016-06-07T10:09:54Z
37,677,943
<p>You can use:</p> <pre><code>#create NaN where False values df['i'] = np.where(df.b, df.h, np.nan) #bfill all NaN df['i'] = df.i.fillna(method='bfill') #create NaN by condition a = df[::-1].groupby('i')['t'].apply(lambda x: (x &gt; 9.5).shift().cumsum()) &gt;= 1 df['i'] = df.i.mask(a, np.nan) print (df) ...
2
2016-06-07T11:19:24Z
[ "python", "pandas", "dataframe", null, "cumsum" ]
Django filter not filtering by user_id
37,676,459
<p>I have a view that allows you to search courses and shows you the profile/s(which in turn belong to a user) that have taken those courses. The search is working just fine but the problem is that it's not filtering based on the user_id. </p> <p>models.py</p> <pre><code>class EmployeeProfile(models.Model): user ...
0
2016-06-07T10:12:41Z
37,676,798
<p>I figured it out. When I added the specific course, it was adding the course to the wrong user because I was using self.request.user instead of grabbing the id from the URL via self.kwargs['pk'].</p> <p>Sorry to have wasted anyone's time.</p>
1
2016-06-07T10:27:10Z
[ "python", "django", "django-views" ]
numpy padding matrix of different row size
37,676,539
<p>I have a numpy array of different row size</p> <pre><code>a = np.array([[1,2,3,4,5],[1,2,3],[1]]) </code></pre> <p>and I would like to become this one into a dense (fixed n x m size, no variable rows) matrix. Until now I tried with something like this</p> <pre><code>size = (len(a),5) result = np.zeros(size) r...
0
2016-06-07T10:15:50Z
37,678,270
<p>There's really no way to pad a <a href="https://en.wikipedia.org/wiki/Jagged_array" rel="nofollow">jagged array</a> such that it would loose its jaggedness, without having to iterate over the rows of the array. You'll have to iterate over the array twice even: once to find out the maximum length you need to pad to, ...
1
2016-06-07T11:34:40Z
[ "python", "arrays", "numpy", "padding", "rows" ]
How to extract only 3 eigen vectors of an nxn image in opencv?
37,676,665
<p>I am trying to convert a RGB image to Grayscale using the following <a href="https://www.semanticscholar.org/paper/Novel-PCA-based-color-to-gray-image-conversion-Seo-Kim/7c23493d4cbe69c6eed697f6394d0f31c660e6ca/pdf" rel="nofollow">paper</a>.</p> <p>The main algorithm using in the paper is this: <a href="http://i.st...
2
2016-06-07T10:21:01Z
38,364,345
<h1>Background</h1> <p>When Seo and Kim ask for <code>lambda_i, v_i &lt;- PCA(Iycc)</code>, for <code>i = 1, 2, 3</code>, they want:</p> <pre><code>from numpy.linalg import eig lambdas, vs = eig(np.dot(Izycc, Izycc.T)) </code></pre> <p>for a 3×N array <code>Izycc</code>. That is, they want the three eigenvalues and...
0
2016-07-14T01:59:47Z
[ "python", "opencv", "linear-algebra" ]
TypeError: create() takes 2 positional arguments but 4 were given
37,676,731
<p>Here is my code file with name is CreateNode.py</p> <pre><code>#!/usr/bin/python import py2neo from py2neo import Graph, Node def createNodeWithLabelProperties(): print("Start Create label with prperties") py2neo.authenticate ("localhost:7474", "neo4j", "XXXXXXX") graph = Graph("http://loc...
0
2016-06-07T10:24:01Z
37,676,811
<p>This message:</p> <pre><code>TypeError: create() takes 2 positional arguments but 4 were given </code></pre> <p>refers to this call:</p> <pre><code>graph.create(node1, node2, node3) </code></pre> <p>The call is passing four arguments (counting the invocant <code>graph</code> as well as <code>node1</code>, <code>...
1
2016-06-07T10:27:31Z
[ "python", "neo4j", "py2neo" ]
TypeError: create() takes 2 positional arguments but 4 were given
37,676,731
<p>Here is my code file with name is CreateNode.py</p> <pre><code>#!/usr/bin/python import py2neo from py2neo import Graph, Node def createNodeWithLabelProperties(): print("Start Create label with prperties") py2neo.authenticate ("localhost:7474", "neo4j", "XXXXXXX") graph = Graph("http://loc...
0
2016-06-07T10:24:01Z
37,697,792
<p>In py2neo v3, the <code>create</code> method (and all similar methods) take only a single argument, which can be any graphy object (see the <a href="http://py2neo.org/v3/types.html" rel="nofollow">manual page on types</a>). You can therefore create multiple nodes by unioning them into a subgraph to pass as the argum...
3
2016-06-08T08:57:33Z
[ "python", "neo4j", "py2neo" ]
Python : how to convert max int64 number to float?
37,676,764
<p>Is there a way to convert max int64 number to float number?</p> <p>I have a max int64 number <code>9223372036854775807</code> I want to convert this to float or double. How can I do it in python?</p> <p>I am developing an automated trading system using a well known broker's API. API sent that number as a response ...
0
2016-06-07T10:25:37Z
37,676,957
<p>try this !</p> <pre><code>a = float(9223372036854775807) </code></pre>
0
2016-06-07T10:33:41Z
[ "python", "floating-point", "int64" ]
Python : how to convert max int64 number to float?
37,676,764
<p>Is there a way to convert max int64 number to float number?</p> <p>I have a max int64 number <code>9223372036854775807</code> I want to convert this to float or double. How can I do it in python?</p> <p>I am developing an automated trading system using a well known broker's API. API sent that number as a response ...
0
2016-06-07T10:25:37Z
37,677,827
<pre><code>import sys print float(sys.maxint) </code></pre>
0
2016-06-07T11:13:43Z
[ "python", "floating-point", "int64" ]
Django serves file.tar.gz not compressed
37,676,767
<p>I have made a view to serve some file.tar.gz but when I download it, the file is not compressed.</p> <p>Files on server, where my app is running has 63 438 bytes:</p> <pre><code>-rw-r--r-- 1 root root 63448 Nov 5 14:13 file.tar.gz </code></pre> <p>but when I download it it has 716 800 bytes.</p> <p>This is my ...
0
2016-06-07T10:25:41Z
37,679,653
<p>As Klaus D. said in comment this was a problem with encoding.</p> <p>When I changed</p> <pre><code>if encoding is not None: response['Content-Encoding'] = encoding </code></pre> <p>to</p> <pre><code>response['Content-Encoding'] = 'tar' </code></pre> <p>Everything stated to working properly.</p>
1
2016-06-07T12:39:51Z
[ "python", "django", "download", "tar" ]
Twisted url action routing
37,676,872
<p>If I have for example this simple TCP server:</p> <pre><code>from twisted.internet import reactor from twisted.web.resource import Resource from twisted.web.server import Site from resources import SomeResource logging.info("Starting server...") root = Resource() root.putChild("test", SomeResource()) reactor.lis...
0
2016-06-07T10:30:02Z
37,689,813
<p>If you want everything that goes to /test/.... to get to the render (render_GET/render_POST) method of SomeResource, just define it as a <a href="https://twistedmatrix.com/documents/current/web/howto/using-twistedweb.html#resource-objects" rel="nofollow">leaf</a>:</p> <pre><code>class SomeResource(Resource): is...
0
2016-06-07T21:37:21Z
[ "python", "twisted", "twisted.web", "twisted.internet" ]
Getting Dataframe from existing Dataframe after some filter
37,676,904
<p>I have a Data frame something like this.</p> <pre><code>Aman Aggarwal Amar Jannela Vipin Kumar Roshan Pati BlackBuck DJ CHETAS WOW Editions MensXP Transport/Freight Musician/Band Furniture News/Media Website Like Like Like Like NaN ...
0
2016-06-07T10:31:27Z
37,749,173
<p>You will obviously have to do it column by column, as the names and categories are not aligned. I use <code>apply</code> to work column by column, and filter out values that are either null or in the list of strings to avoid:</p> <pre><code>filter = ['Like', 'Liked'] df.apply(lambda column: column[~(column.is...
1
2016-06-10T13:10:19Z
[ "python", "python-2.7", "pandas", "data-cleaning" ]
Tkinter visual with Fill=X
37,676,908
<p>the problem is realy simple, all funcions .packs(fill=X) for some reason don't work and in other hand if I use .pack(fill=X,pady=10) only pady works and fill=X is ignored. I hope that someone can explain to me why this is happing.</p> <pre><code>from tkinter import * import json import time #opens file where pinger...
0
2016-06-07T10:31:34Z
37,677,145
<p>You never expand / fill the frame widget, so the frame is only as large as necessary for it to hold all of it's children.</p> <p>The padding options will increase the size (padding) of the children, and you'll be able to see the difference. Whereas with <code>fill</code> there's nothing for the child widget to fill...
1
2016-06-07T10:42:41Z
[ "python", "tkinter" ]
Multiprocessing and SQLAlchemy Error
37,676,960
<p>We are building a software that reads thousands of XML files and imports their content into a SQLite database using SQLAlchemy.</p> <p>Please find below the relevant parts of our code:</p> <p><strong>File 1:</strong></p> <pre><code>from multiprocessing.dummy import Pool as ThreadPool ... for file in os.listdir(pa...
0
2016-06-07T10:33:50Z
37,677,331
<p>You're calling the session factory <code>session</code>, when you should be calling the <code>scoped_session</code> instead (see <a href="http://docs.sqlalchemy.org/en/latest/orm/contextual.html#contextual-thread-local-sessions" rel="nofollow">Contextual/Thread-local Sessions</a>).</p> <p>So it should be</p> <pre>...
2
2016-06-07T10:51:45Z
[ "python", "sqlite", "sqlalchemy" ]
Multiprocessing and SQLAlchemy Error
37,676,960
<p>We are building a software that reads thousands of XML files and imports their content into a SQLite database using SQLAlchemy.</p> <p>Please find below the relevant parts of our code:</p> <p><strong>File 1:</strong></p> <pre><code>from multiprocessing.dummy import Pool as ThreadPool ... for file in os.listdir(pa...
0
2016-06-07T10:33:50Z
37,678,159
<p>The fix for this was simply to replace this:</p> <pre><code>def open(sqlite_db_path = None): engine = create_engine('sqlite:///' + sqlite_db_path) session = sessionmaker() session.configure(bind=engine) return scoped_session(session()) </code></pre> <p>With this:</p> <pre><code>engine = create_eng...
2
2016-06-07T11:29:45Z
[ "python", "sqlite", "sqlalchemy" ]
How to to restrict method resolution to only one parent in python multiple inheritance?
37,677,097
<p>Lets say I have,</p> <pre><code>class A(object): def __init__(self, var): print("The parent class is A") def methodA(self): print("This method should only be accessed by a child of class A") class B(object): def __init__(self, var): print("The parent class is B") def methodB...
0
2016-06-07T10:40:23Z
37,686,584
<p>If you want to do this I would recommend a factory approach as suggested by user2357112 in the comments:</p> <pre><code>def C(parameter): if parameter == "a": return(A()) else: return(B()) </code></pre> <p>Of course these are not subclasses, so if you want to add methods/attributes to it yo...
0
2016-06-07T18:20:49Z
[ "python", "inheritance", "multiple-inheritance", "method-resolution-order" ]
How can i check if one of two piped subprocess fails in python?
37,677,101
<p>Take this code as an example (tar can compress by -z -J -j and there is a tarfile specific module, i know, but it's to represent a long running process)</p> <pre><code> from subprocess import Popen, PIPE with open('tarball.tar.gz', 'w+') as tarball: tarcmd = Popen(['tar', '-cvf', '-', '/home'], stdou...
0
2016-06-07T10:40:31Z
37,684,753
<blockquote> <p>if i check its returncode i always get none</p> </blockquote> <p>If the value is <code>None</code> then it means that the corresponding child process is still alive. btw, there is no need to call <code>tarcmd.poll()</code> in a loop. You could block until it exits using <code>tarcmd.wait()</code>.</p...
0
2016-06-07T16:35:57Z
[ "python", "exception", "pipe", "subprocess" ]
Adding holidays columns in a Dataframe in Python
37,677,112
<p>I am trying to add holidays column for France in a Dataframe by using workalendar package but it gives me an error of </p> <blockquote> <p>Series' object has no attribute 'weekday'</p> </blockquote> <p>Below is my code;</p> <pre><code>from workalendar.europe import France df1 = pd.read_csv('C:\Users\ABC.csv') d...
0
2016-06-07T10:41:04Z
37,685,298
<p>Try this.</p> <pre><code>df1['Holiday'] = df1.Date.apply(lambda x: cal.is_working_day(pd.to_pydatetime(x))) </code></pre> <p>You have to convert the object type to <code>datetime</code>. </p> <p>BTW, I thought that <code>working_day</code> would might not be <code>Holiday</code>...</p> <p><a href="http://stackov...
0
2016-06-07T17:07:52Z
[ "python", "calendar" ]
python: removing 1st word in string using partition(" ")
37,677,128
<p>i am using the following to try remove the first character from the string</p> <pre><code>details[2].partition(" ")[2] </code></pre> <p>but it does not do anything</p> <p>below is the current string (list)(before and after)</p> <blockquote> <p>['n/a', '(5yo+) ', '2m½f Good 9 hdles', '2m90y)']</p> </blockquote...
-1
2016-06-07T10:42:03Z
37,677,217
<p>You never assign the result to the original list. Try this. </p> <pre><code>details[2] = details[2].partition(' ')[2] </code></pre>
2
2016-06-07T10:46:19Z
[ "python" ]
python: removing 1st word in string using partition(" ")
37,677,128
<p>i am using the following to try remove the first character from the string</p> <pre><code>details[2].partition(" ")[2] </code></pre> <p>but it does not do anything</p> <p>below is the current string (list)(before and after)</p> <blockquote> <p>['n/a', '(5yo+) ', '2m½f Good 9 hdles', '2m90y)']</p> </blockquote...
-1
2016-06-07T10:42:03Z
37,677,226
<p>I hope I understood your question well. This would do the trick as per my understanding.</p> <pre><code>details = ['n/a', '(5yo+) ', '2m½f Good 9 hdles', '2m90y)'] print (details[2].split(' ', 1)[1] ) </code></pre>
0
2016-06-07T10:46:47Z
[ "python" ]
How can I patch the Stripe Subscription
37,677,148
<p>I'm writing tests for module which using Stripe for payment. And I'd like to make a mock for it to don't send queries to API. I use the next code for it, but still I have queries to API. I don't understand why? Such query appears at the Stripe log every time I'm running the test: </p> <pre><code>/v1/customers/cus_*...
0
2016-06-07T10:42:52Z
37,725,594
<p>I have found a solution. I patched update_subscription function:</p> <pre><code>@mock.patch.object(stripe.Customer, 'update_subscription', autospec=True) </code></pre>
0
2016-06-09T12:08:52Z
[ "python", "testing", "mocking", "patch" ]
How does Python assign expression to Object Properties?
37,677,160
<p>I have been working with PHP for a while and just started with Python. there is a feature in Python that i came across while learning.</p> <p><strong>IN Python</strong></p> <pre><code>class A: #some class Properties class B: a = A() # assiging an expression to the class Property is possible with python. </...
0
2016-06-07T10:43:27Z
37,677,605
<p>I believe this is language-specific thing. From the <a href="https://docs.python.org/2.7/tutorial/classes.html#class-definition-syntax" rel="nofollow">docs</a></p> <blockquote> <pre><code>class ClassName: &lt;statement-1&gt; . . . &lt;statement-N&gt; </code></pre> <p>Class definitions, lik...
0
2016-06-07T11:03:37Z
[ "php", "python", "oop" ]
How does Python assign expression to Object Properties?
37,677,160
<p>I have been working with PHP for a while and just started with Python. there is a feature in Python that i came across while learning.</p> <p><strong>IN Python</strong></p> <pre><code>class A: #some class Properties class B: a = A() # assiging an expression to the class Property is possible with python. </...
0
2016-06-07T10:43:27Z
37,678,475
<p><strong>in Python</strong></p> <p>Variables declared inside the class definition</p> <pre><code>class A: #some class Properties class B: a = A() # assigning to the class Property # class properties are shared across all instances of class B # this is a static property </code></pre> <p>Variables d...
2
2016-06-07T11:44:17Z
[ "php", "python", "oop" ]
Define units in a netcdf file using python
37,677,175
<p>I am creating a netcdf file with a few variables. I got my netcdf file as useful as I expected but I don't know how define the units of my variables.</p> <p>This is what my code looks like right now:</p> <pre><code>import netCDF4 import numpy as np ncfile = netCDF4.Dataset('state.global.nc', 'r') u = ncfile.varia...
1
2016-06-07T10:44:20Z
37,775,828
<p>The way to define your units is with attributes in the netCDF file. </p> <p>Although you can do this any way you like, the best idea is to stick with netCDF conventions and defined a text attribute called "units" for the variable, and put the SI units in.</p> <p>There's a good example here: <a href="http://schuber...
1
2016-06-12T15:15:32Z
[ "python", "unit-testing", "netcdf", "units-of-measurement" ]
Python: deleting string from first numeric character
37,677,220
<p>How could I delete/split the string below from the first numeric character?</p> <blockquote> <p>Good 11 hdle</p> </blockquote> <p>would become </p> <blockquote> <p>Good</p> </blockquote> <p>the only things I can seem to find are removing numbers OR letters from the whole string</p>
-1
2016-06-07T10:46:31Z
37,677,304
<pre><code>import re str = "some text 12345 other text" result = re.split("\d+", str)[0] </code></pre>
5
2016-06-07T10:50:05Z
[ "python" ]
How to fetch values from a one2many field in odoo
37,677,273
<p>In customer invoice in the account module there is a one2many field,</p> <pre><code>invoice_line = fields.One2many('account.invoice.line', 'invoice_id', string='Invoice Lines') </code></pre> <p>Using this field we can add multiple products in the invoice. After adding multiple products how to segregate those produ...
0
2016-06-07T10:48:36Z
37,685,038
<p>For your question i can only give you a general answer. I hope, you can start with it.</p> <p>In a odoo model (<code>osv.osv</code>, ...) you can use <code>self.pool.get("model name")</code> to get the object pool for any model. With this pool you can use the method <code>read()</code> to read the data.<br> A Odoo ...
2
2016-06-07T16:52:04Z
[ "python", "odoo-8" ]
Extracting user data from stackoverflow using Selenium
37,677,305
<p>I'm pretty new to this web scraping (Data extraction) stuff. I want to extract the user's reputation from his stackoverflow account. I'm using Selenium. I've successfully logged in but I can't get the data from the next url, which is <a href="http://stackoverflow.com">http://stackoverflow.com</a></p> <p>This is my ...
1
2016-06-07T10:50:07Z
37,678,359
<p>It takes some time to update the <code>browser.current_url</code> after redirecting. You can use either <code>browser.refresh()</code> or <code>time.sleep()</code> to get the updated value.</p> <pre><code>from selenium import webdriver browser = webdriver.Chrome() browser.get('https://stackoverflow.com/users/login...
1
2016-06-07T11:39:02Z
[ "python", "selenium", "web-scraping" ]
Workflow for Python with Docker + IDE for non-web applications
37,677,476
<p>I am currently trying to insert Docker in my Python development workflow of non-web applications.</p> <p>What are the current best practices in Python development using Docker and an IDE? I need the possibility to isolate my environments with Docker and debug my code.</p> <p>On the web I found many articles about ...
3
2016-06-07T10:58:14Z
38,688,421
<p>Actually, I believe that using the Docker interpreter in PyCharm is the way to go. Which version of PyCharm do you have? If you have the 2016 version, it should be set up within seconds. You just have to make sure your docker machine is running and you must have your image built that you would like to use with your ...
0
2016-07-31T21:10:23Z
[ "python", "docker", "ide", "development-environment" ]
loading excel file into pandas dataframe flask app running with mod_wsgi apache that user uploaded
37,677,681
<p>I have a flask app where a user uploads files to an upload folder. Then I want to take those files and read them into pandas dataframes for further processing. The process works fine using app.run() on my localhost. I am trying to get it to work on aws with mod_wsgi and apache. </p> <pre><code> @app.route('/uplo...
0
2016-06-07T11:06:37Z
37,678,266
<p>Hi I suggest you check the flask documentation about upload files <a href="http://flask.pocoo.org/docs/0.11/patterns/fileuploads/" rel="nofollow">here</a> and later re-check your code.</p>
0
2016-06-07T11:34:24Z
[ "python", "excel", "apache", "flask" ]
loading excel file into pandas dataframe flask app running with mod_wsgi apache that user uploaded
37,677,681
<p>I have a flask app where a user uploads files to an upload folder. Then I want to take those files and read them into pandas dataframes for further processing. The process works fine using app.run() on my localhost. I am trying to get it to work on aws with mod_wsgi and apache. </p> <pre><code> @app.route('/uplo...
0
2016-06-07T11:06:37Z
37,695,671
<p>Instead of </p> <p><code>f=send_from_directory(folder_path,filename))</code> </p> <p>I use </p> <p><code>f = open(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))</code></p> <p>to open the file. I just assumed <code>send_from_directory</code> would work as it does when I used flask <code>app.r...
0
2016-06-08T07:16:51Z
[ "python", "excel", "apache", "flask" ]
Sqlite: link entries to multiple entries (ingredients and recipes)
37,677,787
<p>I want to create a database to show relations between ingredients and recipes. For this I have defined two tables with ingredient types (might be later joined into one table):</p> <pre><code>Ingredients1 -id /primary -name -description -... Ingredients2 -id /primary -name -description -... </code></pre> <p>I want...
0
2016-06-07T11:11:46Z
37,692,484
<p>If you have two ingredient columns (a bad design) they can both have be foreign keys to the same table. A foreign key says that subrow values in a referencing table appear as subrow values for columns that form a candidate key in a referenced table.</p> <p>The straighforward design has an ingredient table, a recipe...
0
2016-06-08T02:56:37Z
[ "python", "sqlite", "database-design", "sqlite3", "foreign-keys" ]
Crosscompile Python bdist_wininst executeables
37,677,833
<p>I'm using a 64bit Windows machine with 64bit python3. I need to build a installable package for a windows 32bit machine and stumbled upon the cross compile feature of the bdist feature: <a href="https://docs.python.org/3/distutils/builtdist.html" rel="nofollow">https://docs.python.org/3/distutils/builtdist.html</a><...
0
2016-06-07T11:14:00Z
37,785,261
<p>As I found out this is a reported bug <a href="https://github.com/pypa/setuptools/issues/253" rel="nofollow">https://github.com/pypa/setuptools/issues/253</a></p> <p>The setuptools do only check for the OS architecture and ignore the plat-name string for the installation of scripts.</p> <p>Workaround (until this i...
0
2016-06-13T08:43:07Z
[ "python", "cpu-architecture" ]
Storing list in to csv file using python
37,677,867
<p>I'm trying to store a type list variable in to a csv file using python. Here is what I got after hours on StackOverflow and python documentation:</p> <p>Code:</p> <pre><code>row = {'SgDescription': 'some group', 'SgName': 'sku', 'SgGroupId': u'sg-abcdefgh'} new_csv_file = open("new_file.csv",'wb') ruleswriter = cs...
2
2016-06-07T11:15:19Z
37,677,999
<p>Extract your desired data before writing into a csv file, </p> <pre><code>row = [row['SgDescription'], row['SgName'], row['SgGroupId']] # ['some group', 'sku', u'sg-abcdefgh'] # write to a csv file with open("new_file.csv",'wb') as f: ruleswriter = csv.writer(f) ruleswriter.writerow(row) </code></pr...
1
2016-06-07T11:21:54Z
[ "python", "csv" ]
Storing list in to csv file using python
37,677,867
<p>I'm trying to store a type list variable in to a csv file using python. Here is what I got after hours on StackOverflow and python documentation:</p> <p>Code:</p> <pre><code>row = {'SgDescription': 'some group', 'SgName': 'sku', 'SgGroupId': u'sg-abcdefgh'} new_csv_file = open("new_file.csv",'wb') ruleswriter = cs...
2
2016-06-07T11:15:19Z
37,678,050
<p><code>writerows()</code> expects a sequence of sequences, for example a list of lists. You're passing in a dict, and a dict happens to be iterable: It returns the keys of the dictionary. Each key -- a string -- happens to be iterable as well. So what you get is an element of each iterable per cell, which is a charac...
1
2016-06-07T11:24:01Z
[ "python", "csv" ]
How to read a file inside a folder which itself is inside a zip file
37,677,990
<p>I have a zip file which consists of a single folder having the same name as the zip file( ie if the name of the zip folder is 1.zip then the name of the folder inside the zip file will be 1.)<br/> Now this folder contains a text file say atextfile.txt, I want to print the contents of this file.<br/> I wrote the code...
2
2016-06-07T11:21:23Z
37,678,261
<p>You can add the path name to the filename that you are extracting with <code>ZipFile.open()</code>. Here's how to do it automatically using the naming scheme that you describe in your question:</p> <pre><code>for zip_name in glob.glob('[0-9].zip'): # the zip file name one numeric digit only. z=zipfile.ZipFile(z...
2
2016-06-07T11:34:16Z
[ "python", "zip" ]
Suds client does not make the right SOAP request
37,678,064
<p>I am using Python SUDS in order to make some SOAP requests and access an API.</p> <p>The SOAP request should look like:</p> <pre><code>&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://portal.vidyo.com/user/v1_1"&gt; &lt;soapenv:Header/&gt; &lt;soapenv:Body&gt; ...
0
2016-06-07T11:24:20Z
37,687,330
<p>Can you give <a href="https://pypi.python.org/pypi/zeep/0.8.0" rel="nofollow">https://pypi.python.org/pypi/zeep/0.8.0</a> a try? But of a shameless plug since i'm the author, but it should handle this fine. </p>
0
2016-06-07T19:03:26Z
[ "python", "web-services", "soap", "suds" ]
Split a dataframe into two files based on the values of a column
37,678,265
<p>I need to split a dataframe into 2 parts. For example if the below dataframe is split randomly based on Col1 both the files should contain samples from each category 1,2 and 3.</p> <pre><code>Col1 col2 1 a 1 b 2 c 2 d 3 e </code></pre> <p>So far I am able to split the data into desired ra...
0
2016-06-07T11:34:23Z
37,681,533
<p>Take a look at <code>StratifiedKFold</code> object. </p> <p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedKFold.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedKFold.html</a></p> <p>There is a short example in t...
1
2016-06-07T14:00:12Z
[ "python", "sklearn-pandas" ]
multiple functions as arguments in python
37,678,316
<p>I have the following problem: I have two sets of data (set T and set F). And the following functions:</p> <pre><code>x(T) = arctan(T-c0), A(x(T)) = arctan(x(T) -c1), B(x(T)) = arctan(x(T) -c2) and Y(x(t),F) = ((A(x(t)) - B(x(t)))/2 - A(x(t))arctan(F-c3) + B(x(t))arctan(F-c4)) # where c0,c1,c2,c3,c4 are cons...
0
2016-06-07T11:36:50Z
37,678,807
<p>It is absolutely possible to use functions as input parameters to other functions. A use case could look like:</p> <pre><code>def plus_one(standard_input_parameter_like_int): return standard_input_parameter_like_int + 1 def apply_function(function_as_input, standard_input_parameter): return function_as_inp...
0
2016-06-07T12:00:30Z
[ "python", "function", "numpy", "plot" ]
multiple functions as arguments in python
37,678,316
<p>I have the following problem: I have two sets of data (set T and set F). And the following functions:</p> <pre><code>x(T) = arctan(T-c0), A(x(T)) = arctan(x(T) -c1), B(x(T)) = arctan(x(T) -c2) and Y(x(t),F) = ((A(x(t)) - B(x(t)))/2 - A(x(t))arctan(F-c3) + B(x(t))arctan(F-c4)) # where c0,c1,c2,c3,c4 are cons...
0
2016-06-07T11:36:50Z
37,733,299
<ol> <li><blockquote> <p>[...] somethin like <code>def s(x,y,z,*args,*args2):</code> will yield an error.</p> </blockquote></li> </ol> <p>This is perfectly normal as (at least as far as I know) there is only one variable length non-keyword argument list allowed per function (that has to be exactly labeled as *args...
0
2016-06-09T18:10:36Z
[ "python", "function", "numpy", "plot" ]
python pyqt multiple classes
37,678,338
<p>I am writing a program where I have do the following. </p> <ol> <li>Get User Credentials using a Dialog Box</li> <li>If successful Launch another application, if Unsuccessful prompt again for credentials. I am implementing this using two classes called x_LoginForm and x_Application The code is as follows class x_L...
0
2016-06-07T11:37:52Z
37,678,776
<p>What is happening is that <code>form.show()</code> returns immediately and your program does the <code>if</code> check then which is likely evaluating to <code>False</code> since you have <code>main_window_flag=0</code> if you change <code>form.show()</code> to <code>form.exec_()</code> it will wait until the form c...
0
2016-06-07T11:59:07Z
[ "python", "class", "login", "pyqt" ]
Python enums with complex types
37,678,418
<p>I'm new to Python and I'm wondering if I can build enums with complex structures, not just primitive type. For instance (in pseudo-code):</p> <pre><code>Point::Enum x, y constructor ( x, y ) { ... } bottom_left = Point ( 0, 0 ) top_left = Point ( 0, 100 ) top_right = Point ( 100, 100 ) bottom_rig...
3
2016-06-07T11:41:52Z
37,678,637
<p>Try this:</p> <pre><code>class Point(object): def __init__(self, x, y): self.x = x self.y = y class Enum: bottom_left = Point(0, 0) top_left = Point(0, 100) top_right = Point(100, 100) bottom_right = Point(100, 0) </code></pre>
0
2016-06-07T11:52:03Z
[ "python", "enums", "complextype" ]
Python enums with complex types
37,678,418
<p>I'm new to Python and I'm wondering if I can build enums with complex structures, not just primitive type. For instance (in pseudo-code):</p> <pre><code>Point::Enum x, y constructor ( x, y ) { ... } bottom_left = Point ( 0, 0 ) top_left = Point ( 0, 100 ) top_right = Point ( 100, 100 ) bottom_rig...
3
2016-06-07T11:41:52Z
37,678,842
<p>You can declare them as global variables like <code>BOTTOM_LEFT</code>, <code>TOP_LEFT</code>, <code>TOP_RIGHT</code>, <code>BOTTOM_RIGHT</code>.</p> <p>As you might be aware unlike other languages (C++, Java) Python doesn't have, You just declare it and don't change it (Gentleman's game)</p> <p>Yet Alex Martelli'...
1
2016-06-07T12:02:08Z
[ "python", "enums", "complextype" ]
Python enums with complex types
37,678,418
<p>I'm new to Python and I'm wondering if I can build enums with complex structures, not just primitive type. For instance (in pseudo-code):</p> <pre><code>Point::Enum x, y constructor ( x, y ) { ... } bottom_left = Point ( 0, 0 ) top_left = Point ( 0, 100 ) top_right = Point ( 100, 100 ) bottom_rig...
3
2016-06-07T11:41:52Z
37,684,706
<p>If you want <code>Point</code> as a separate entity from the <code>Enum</code> that tracks the corners, then you need them to be separate:</p> <pre><code>from enum import Enum class Point(object): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return 'Point(%r, ...
1
2016-06-07T16:32:54Z
[ "python", "enums", "complextype" ]
tkinter how to store a number from an entry box so every entry is added to the next
37,678,445
<p>I am trying to learn tkinter as a python beginner. I am trying to write a program where you enter a number in to an entry box click a button and it prints the number you entered and it prints the number you entered multiplied by 0.008. </p> <p>Then stores the numbers so the next time you enter a number it adds it t...
0
2016-06-07T11:43:05Z
37,680,253
<p>What's stopping you from using a regular variable ?</p> <pre><code>from tkinter import * def calculatemoney(): global oldValue # Making it global so you can set it's value done = float(Lines1.get()) salary3 = done * 0.08 salary4 = done salary5 = (done + oldValue) * 0...
0
2016-06-07T13:04:46Z
[ "python", "python-3.x", "tkinter", "entry" ]
I am trying to implement GridSearchCV to tune the parameters of K nearest neighbor classifier
37,678,471
<pre><code>import sklearn.cross_validation import sklearn.grid_search import sklearn.metrics import sklearn.neighbors import sklearn.decomposition import sklearn import pandas as pd df = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data", names=...
0
2016-06-07T11:44:01Z
37,682,402
<p>I believe your target "Y_train" must be a 1-D array (468, ). Try: </p> <pre><code>X_train.ravel() </code></pre> <p>before training the classifier.</p>
1
2016-06-07T14:40:44Z
[ "python", "numpy", "scikit-learn", "knn" ]
Make a diff of 2 text file quickly using python
37,678,529
<p>I have 2 big text files (right now 17MB but could be GB), as such I don't want to load them in the ram because their size could exceed my ram capacity.</p> <p>The code I wrote for now is this :</p> <pre><code>def stopIfFileExist(filename): if os.path.isfile(filename): raise Exception("%s already exist...
0
2016-06-07T11:46:44Z
37,681,795
<p>I was able to diff two 20 megabyte files in a little over 3 minutes using the following test code.</p> <p>Every 10,000 lines I put a random number, which you can see diff'd in the results.</p> <pre><code>import random import difflib import os import time start = time.time() NUM_LINES = int(10000000 / 4) t1 = 'te...
-1
2016-06-07T14:12:57Z
[ "python", "python-2.7" ]
Quandl is not being imported
37,678,580
<p>I'm getting started for Machine learning using Python and would like to use Quandl for computing. I installed the Quandl using <code>pip install Quandl</code> and also, pandas using <code>pip install pandas</code>. Later, the <code>import</code> for pandas is successful, but, I couldn't import quandl. I get error as...
0
2016-06-07T11:49:22Z
37,678,607
<p>Looking at <a href="https://www.quandl.com/tools/python" rel="nofollow">the docs</a>, it is lower case:</p> <pre><code>import quandl </code></pre>
3
2016-06-07T11:50:38Z
[ "python", "quandl" ]
List of tuple to string in Python
37,678,612
<p>I have a list like this:</p> <pre><code>l = ['b', '7', 'a', 'e', 'a', '6', 'a', '7', '9', 'c', '7', 'b', '6', '9', '9', 'd', '7', '5', '2', '4', 'c', '7', '8', 'b', '3', 'f', 'f', '7', 'b', '9', '4', '4'] </code></pre> <p>and I want to make a string from it like this:</p> <pre><code>7bea6a7ac9b796d957427cb8f37f9b...
3
2016-06-07T11:50:45Z
37,678,648
<p>You can concatenate each pair of letters, then <code>join</code> the whole result in a generator expression</p> <pre><code>&gt;&gt;&gt; ''.join(i+j for i,j in zip(l[1::2], l[::2])) '7bea6a7ac9b796d957427cb8f37f9b44' </code></pre>
11
2016-06-07T11:52:51Z
[ "python" ]
List of tuple to string in Python
37,678,612
<p>I have a list like this:</p> <pre><code>l = ['b', '7', 'a', 'e', 'a', '6', 'a', '7', '9', 'c', '7', 'b', '6', '9', '9', 'd', '7', '5', '2', '4', 'c', '7', '8', 'b', '3', 'f', 'f', '7', 'b', '9', '4', '4'] </code></pre> <p>and I want to make a string from it like this:</p> <pre><code>7bea6a7ac9b796d957427cb8f37f9b...
3
2016-06-07T11:50:45Z
37,678,817
<p>You can just use a simple list comprehension to swap (provide you are sure to have an even size) and then join:</p> <pre><code>''.join([ l[i+1] + l[i] for i in range(0, len(l), 2) ]) </code></pre>
2
2016-06-07T12:01:02Z
[ "python" ]
List of tuple to string in Python
37,678,612
<p>I have a list like this:</p> <pre><code>l = ['b', '7', 'a', 'e', 'a', '6', 'a', '7', '9', 'c', '7', 'b', '6', '9', '9', 'd', '7', '5', '2', '4', 'c', '7', '8', 'b', '3', 'f', 'f', '7', 'b', '9', '4', '4'] </code></pre> <p>and I want to make a string from it like this:</p> <pre><code>7bea6a7ac9b796d957427cb8f37f9b...
3
2016-06-07T11:50:45Z
37,679,336
<p>Group adjacent list items using zip;</p> <pre><code>group_adjacent = lambda a, k: zip(*([iter(a)] * k)) </code></pre> <p>Then concatenate them by swapping in the for loop </p> <pre><code>print (''.join( j+i for i,j in group_adjacent(l,2)) ) </code></pre>
1
2016-06-07T12:24:56Z
[ "python" ]
PyQt5 QML treeview example
37,678,626
<p>I try to setup a simple treeview example with PyQt5.6 (Python 3.4) and QML. I just found a few C++ examples, but nothing related to PyQt. I picked up the simpletreemodel example comming with PyQt source and modified it (<a href="https://github.com/baoboa/pyqt5/tree/master/examples/itemviews/simpletreemodel" rel="nof...
0
2016-06-07T11:51:31Z
37,739,078
<pre><code>root_context = view.rootContext().setContextProperty('model', model) </code></pre> <p>Don't use <strong>model</strong> as the name of model.</p>
0
2016-06-10T02:34:59Z
[ "python", "qml", "qt5", "pyqt5" ]
How to reset a dictionary for every one hour
37,678,864
<p>Is it possible to reset python dictionary in every one hour?</p> <p>Original dictionary:</p> <pre><code>d = {1: 5, 2: 1, 3: 2} </code></pre> <p>For every one hour the dictionary should be empty (or new dictionary should be created)</p> <pre><code>d = {} </code></pre> <p>But the program below is not working</p>...
0
2016-06-07T12:03:20Z
37,678,978
<pre><code>import time, threading d = {1: 5, 2: 1, 3: 2} def updates_dict(): d = {} print "Updated on",time.ctime() threading.Timer(10*60*60, foo).start() updates_dict() </code></pre> <p>You can implement with using <code>threading</code>.</p>
1
2016-06-07T12:08:49Z
[ "python", "dictionary", "time" ]
How to reset a dictionary for every one hour
37,678,864
<p>Is it possible to reset python dictionary in every one hour?</p> <p>Original dictionary:</p> <pre><code>d = {1: 5, 2: 1, 3: 2} </code></pre> <p>For every one hour the dictionary should be empty (or new dictionary should be created)</p> <pre><code>d = {} </code></pre> <p>But the program below is not working</p>...
0
2016-06-07T12:03:20Z
37,679,027
<pre><code>import time d = {1: 5, 2: 1, 3: 2} start = time.time() while True: diff = time.time() - start if not round(diff) % 60: d = {} print d </code></pre>
0
2016-06-07T12:11:12Z
[ "python", "dictionary", "time" ]
How to reset a dictionary for every one hour
37,678,864
<p>Is it possible to reset python dictionary in every one hour?</p> <p>Original dictionary:</p> <pre><code>d = {1: 5, 2: 1, 3: 2} </code></pre> <p>For every one hour the dictionary should be empty (or new dictionary should be created)</p> <pre><code>d = {} </code></pre> <p>But the program below is not working</p>...
0
2016-06-07T12:03:20Z
37,680,171
<p>I'd recommend taking a look at <a href="http://apscheduler.readthedocs.io/en/latest/" rel="nofollow">the APScheduler module</a>. It has a lot of options for timed events.</p>
0
2016-06-07T13:01:33Z
[ "python", "dictionary", "time" ]
Checking if program is running
37,678,954
<p>I was wondering how you could check if program is running using python and if not run it. I have 2 python scripts one is GUI which monitors another script. So basically if second script for some reason crashes i would like it start over. P.S. I'm using python 3.4.2 on Windows.</p>
1
2016-06-07T12:07:37Z
37,679,719
<p>The module psutil can help you. To list all process runing use:</p> <pre><code>import psutil print(psutil.pids()) # Print all pids </code></pre> <p>To access the process information, use:</p> <pre><code>p = psutil.Process(1245) # The pid of desired process print(p.name()) # If the name is "python.exe" is called...
1
2016-06-07T12:42:37Z
[ "python" ]
update database, how to check it wrote the data
37,678,966
<p>I am using Python to write on a mongoDB database a very large amount of data. Some of this data can actually overwrite old data already in the database. I am using pymongo and MongoClient using update function.</p> <p>Since i am writing ten of thousands of datapoints in the database, can i make sure that the data i...
0
2016-06-07T12:08:07Z
37,680,028
<p>When you execute an insert_one or insert_many instruction, you should get a result value. You can check this to make sure that the insert was successful.</p> <pre><code>result = posts.insert_many(new_posts) print result.inserted_id </code></pre>
2
2016-06-07T12:55:32Z
[ "python", "mongodb", "pymongo" ]
Find a substring in a line and print the line in python and only print the line once?
37,679,105
<p>I am trying to print all the lines in my text file that contain any of the words in my list, caled "names". The problem I am having is that my program iterates so much that, duplicate lines get printed because of the multiple iterations. How can I print the line occurance only once? Also how can I print the line(s) ...
1
2016-06-07T12:15:07Z
37,679,192
<p>No need to split the lines, just check if the line as a whole contains the name. Also, no need to check for every name, the first match will do. <a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow"><code>any</code></a> will help you avoid some bumpy code:</p> <pre><code>with open("base.txt"...
0
2016-06-07T12:18:51Z
[ "python", "substring" ]
Find a substring in a line and print the line in python and only print the line once?
37,679,105
<p>I am trying to print all the lines in my text file that contain any of the words in my list, caled "names". The problem I am having is that my program iterates so much that, duplicate lines get printed because of the multiple iterations. How can I print the line occurance only once? Also how can I print the line(s) ...
1
2016-06-07T12:15:07Z
37,679,255
<p>Check once for all names and use <code>any()</code> as follows. </p> <pre><code>names=['bob','carter','jim','mike'] with open("base.txt") as openfile: for line in openfile: if any([n in line for n in names]): print line.strip() </code></pre> <p>What <code>[n in line for n in names]</code...
0
2016-06-07T12:20:57Z
[ "python", "substring" ]
Find a substring in a line and print the line in python and only print the line once?
37,679,105
<p>I am trying to print all the lines in my text file that contain any of the words in my list, caled "names". The problem I am having is that my program iterates so much that, duplicate lines get printed because of the multiple iterations. How can I print the line occurance only once? Also how can I print the line(s) ...
1
2016-06-07T12:15:07Z
37,679,384
<p>You can use regular expressions to match the strings :</p> <pre><code>import re names=["bob","carter","jim","mike"] match_string = "(" + ")|(".join(names)+")" #create a regex that can match all the words in the list names outfile = open("out.txt","w") #open output file with open("base.txt") as openfile: ...
0
2016-06-07T12:26:55Z
[ "python", "substring" ]
Find a substring in a line and print the line in python and only print the line once?
37,679,105
<p>I am trying to print all the lines in my text file that contain any of the words in my list, caled "names". The problem I am having is that my program iterates so much that, duplicate lines get printed because of the multiple iterations. How can I print the line occurance only once? Also how can I print the line(s) ...
1
2016-06-07T12:15:07Z
37,679,392
<p>As others already posted, you can use <code>any</code> to confirm the occurrence of at least one of the names in the line. Use a list comprehension to put all the matching lines into a list:</p> <pre><code>with open("base.txt") as openfile, open("output.txt", "w") as outputfile: result = [line if any(n in line...
0
2016-06-07T12:27:19Z
[ "python", "substring" ]
Django: How do I use STATICFILES_FINDERS
37,679,106
<p>It seems default settings given in STATICFILES_FINDERS are for looking in the static folder <em>within an app</em>. But I am trying to get Django to search within the <em>top-level</em> static (same level as manage.py), but it doesn't seem to do that despite defining the static_root directory in settings.py and doin...
0
2016-06-07T12:15:10Z
37,679,254
<p><code>STATIC_ROOT</code> is designed for usage with <code>collectstatic</code> command <a href="https://docs.djangoproject.com/en/1.9/ref/settings/#static-root" rel="nofollow">read docs</a>. If you want your folder to be discovered you need to add it in to <a href="https://docs.djangoproject.com/en/1.9/ref/settings/...
1
2016-06-07T12:20:57Z
[ "python", "django" ]
"module" object has no attribute error when trying to get Checkbutton status
37,679,332
<p>I'm trying to get the status of the redundancyCheckbutton, in order to see if the <code>test.py</code> script should be run. As it works now, once a button is clicked, <code>run.py</code> fires off and runs the testSomething function fine. Whenever I try to get the status using <code>.get()</code> or something simil...
0
2016-06-07T12:24:29Z
37,680,003
<p><code>redundancyCheckbutton</code> belongs to an instance of some instance of a class. I don't know what class, because you didn't show enough code. </p> <p>The line that is likely causing the problem (I'm assuming, since you didn't show the actual error message) is this:</p> <pre><code>import Tool Tool.redundancy...
0
2016-06-07T12:54:47Z
[ "python", "tkinter" ]
computation of test data in tensorflow tutorial
37,679,382
<p>I was going through the tutorial of tensorflow- <a href="https://www.tensorflow.org/versions/r0.9/tutorials/mnist/beginners/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.9/tutorials/mnist/beginners/index.html</a></p> <pre><code>import tensorflow as tf from tensorflow.examples.tutorials.mnist imp...
1
2016-06-07T12:26:52Z
37,688,547
<p><code>accuracy</code> depends on <code>correct_prediction</code> which depends on <code>y</code>. </p> <p>So when you call <code>sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})</code>, <code>y</code> is computed before <code>accuracy</code> is computed. All this happen inside the Tensor...
1
2016-06-07T20:18:24Z
[ "python", "machine-learning", "tensorflow", "deep-learning" ]
computation of test data in tensorflow tutorial
37,679,382
<p>I was going through the tutorial of tensorflow- <a href="https://www.tensorflow.org/versions/r0.9/tutorials/mnist/beginners/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.9/tutorials/mnist/beginners/index.html</a></p> <pre><code>import tensorflow as tf from tensorflow.examples.tutorials.mnist imp...
1
2016-06-07T12:26:52Z
37,688,643
<p><code>y</code> is computed here:</p> <pre><code>y = tf.nn.softmax(tf.matmul(x, W) + b) # Line 7 </code></pre> <p>specifically what you are looking for is with in that line:</p> <pre><code>tf.matmul(x, W) + b </code></pre> <p>the output of which is put through the softmax function to identify the class.</p> <p>T...
1
2016-06-07T20:23:07Z
[ "python", "machine-learning", "tensorflow", "deep-learning" ]
Python multiprocessing starts processes, but only one is active
37,679,394
<p>I got the following code from the accepted answer in the following question. When I run it up on my windows 10 x64bit machine, in Python 3.5.1 it starts the threads but only one of them shows any CPU usage, and it is very little at that. While this is happening the terminal is scrolling up numbers from the print s...
0
2016-06-07T12:27:31Z
37,679,468
<p>You're not running anything asynchronously here; you call the functions before passing to the async workers. You should pass the callable, not the result:</p> <pre><code>pool.apply_async(do_job, (first_bit,)) </code></pre> <p>Also note that the return value from <code>apply_async</code> is an <a href="https://docs...
3
2016-06-07T12:31:07Z
[ "python", "multithreading", "python-3.x" ]
Converting csv to xml using Python
37,679,511
<p>I have a csv file which resembles the format below:</p> <pre><code>=============================================================== #Type 1 Definition #============================================================================ #TYPE, &lt;name&gt; #Some tag for type--------------------------------------------------...
0
2016-06-07T12:32:53Z
37,684,190
<p>You need to store parameters from commented line to dictionary to process</p> <p><code>#TYPESomeTag, id, name, param</code></p> <p>into </p> <p><code>tags = {"TYPESomeTag":["id", "name", "param"]}</code></p> <p>this way you can parse every comment line without handcoding parameters list. Below is sample code to ...
0
2016-06-07T16:03:33Z
[ "python", "xml", "csv" ]
Converting csv to xml using Python
37,679,511
<p>I have a csv file which resembles the format below:</p> <pre><code>=============================================================== #Type 1 Definition #============================================================================ #TYPE, &lt;name&gt; #Some tag for type--------------------------------------------------...
0
2016-06-07T12:32:53Z
37,692,501
<p>Consider using an xml module to build the xml document and not concatenate string representation of elements. In this way, you can read the csv line by line adding children elements and text values conditionally according to line position. Below adds generic <code>&lt;tags&gt;</code> for grandchildren:</p> <pre><co...
0
2016-06-08T02:58:46Z
[ "python", "xml", "csv" ]
Converting csv to xml using Python
37,679,511
<p>I have a csv file which resembles the format below:</p> <pre><code>=============================================================== #Type 1 Definition #============================================================================ #TYPE, &lt;name&gt; #Some tag for type--------------------------------------------------...
0
2016-06-07T12:32:53Z
37,698,135
<p>Well that's a rather complex question:</p> <ul> <li>you first need to parse the definition comments to determine the tag names that will be used in the xml file</li> <li>you need to parse the csv file, skipping the comments and empty lines</li> <li>you need to build a XML file (or tree) with the following rules: <...
1
2016-06-08T09:12:31Z
[ "python", "xml", "csv" ]
increasing pandas dataframe imputation performance
37,679,553
<p>I want to impute a large datamatrix (90*90000) and later an even larger one (150000*800000) using pandas. At the moment I am testing with the smaller one on my laptop (8gb ram, Haswell core i5 2.2 GHz, the larger dataset will be run on a server).</p> <p>The columns have some missing values that I want to impute wi...
2
2016-06-07T12:34:47Z
37,683,514
<p>try this:</p> <pre><code>df_imputed = df.iloc[:, 6:].fillna(df.iloc[:, 6:].apply(lambda x: x.mode()).iloc[0]) </code></pre>
2
2016-06-07T15:29:32Z
[ "python", "pandas", "optimization", "runtime" ]
increasing pandas dataframe imputation performance
37,679,553
<p>I want to impute a large datamatrix (90*90000) and later an even larger one (150000*800000) using pandas. At the moment I am testing with the smaller one on my laptop (8gb ram, Haswell core i5 2.2 GHz, the larger dataset will be run on a server).</p> <p>The columns have some missing values that I want to impute wi...
2
2016-06-07T12:34:47Z
37,699,607
<p>I tried different approaches. The key learning is that the <code>mode</code> function is really slow. Alternatively, I implemented the same functionality using <code>np.unique</code> (<code>return_counts=True</code>) and <code>np.bincount</code>. The latter is supposedly faster, but it doesn't work with <code>NaN</c...
2
2016-06-08T10:14:07Z
[ "python", "pandas", "optimization", "runtime" ]
Check variables against a dictionary, and print the dictionary contents remaining
37,679,642
<p>I want to check user inputs against a dictionary, and then print the values that still exist in the dictionary that were not inputed by the user.</p> <p>Here's my code that takes user input, checks it against the dictionary and sends it to the print function below.</p> <pre><code> elif choice == '7': print(...
0
2016-06-07T12:39:20Z
37,679,769
<p>If I understood correctly, you can simply use <code>dict.pop()</code>. <code>pop</code> returns the value of a specified key, then removes it from the dictionary. It the specified key doesn't exist in the dictionary it will return None by default.</p> <pre><code>a_dict = {'a': 1, 'b': 2, 'c': 3} print(a_dict.pop('...
1
2016-06-07T12:44:49Z
[ "python", "dictionary", "set", "theory" ]
Check variables against a dictionary, and print the dictionary contents remaining
37,679,642
<p>I want to check user inputs against a dictionary, and then print the values that still exist in the dictionary that were not inputed by the user.</p> <p>Here's my code that takes user input, checks it against the dictionary and sends it to the print function below.</p> <pre><code> elif choice == '7': print(...
0
2016-06-07T12:39:20Z
37,680,053
<p>Use the <code>difference</code> function to compute set difference.</p> <pre><code>number_of_inputs = ... inputs = [] dictionary = {...} def print_diff(): for i in range(number_of_inputs + 1): inputs.append(str(input("enter pitch {}".format(i + 1)))) if inputs[-1] == 'Done': del inputs[-1] ...
1
2016-06-07T12:56:24Z
[ "python", "dictionary", "set", "theory" ]
matplotlib axes.clear() of twinx axes does not clear second y-axis label
37,679,671
<p>I have an issue with updated twinx axes. In the following code, I expect that ax_hist.clear() clears data, ticks and axes labels altogether. But when I plot again in the same axes, second y-axis labels from the previous ax_hist.hist() are still there. How can I remove the old y-axis labels?</p> <p>I have tested wi...
3
2016-06-07T12:40:35Z
37,679,780
<p>The problem is caused by your second <code>ax_hist = ax.twinx()</code> which creates a <em>second</em> twin axis of the first <code>ax</code>. You only need to create the twin axis once.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() d1 = np.random.random(100) d2 = np.r...
1
2016-06-07T12:45:28Z
[ "python", "matplotlib" ]