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
Why does it not find the variable?
39,766,919
<p>So below is my code, and I need to get the variable 'p' from the Entry widget, set it as a new variable name, the print it. For some reason, I get the following error 'NameError: name 'p' is not defined'. I have absolutely no idea how to fix it and this is my last resort. Please help me.</p> <p>Code:</p> <pre><cod...
-3
2016-09-29T09:45:39Z
39,767,215
<p>I won't try to give a complete answer (for there might be more that one error in your program), but let me tell you what your problem is:</p> <p>You didn't take into account <strong>variable scopes</strong>. Whenever naming a variable, it is only accessible in a specific region of your code.</p> <p>In your code, f...
0
2016-09-29T10:00:52Z
[ "python", "variables", "tkinter", "nameerror" ]
Quit button assistance needed
39,767,084
<p>I'm trying to make a code for this topic i'm doing and I've manage to get some of it done but when it comes to quiting my tkinter menu it doesn't close unless I manually close it, I've got the the button for the option to close it but it doesn't work. Can anyone help with my problem. Here's my code below.</p> <pre>...
-2
2016-09-29T09:54:23Z
39,767,287
<p>First off, the <code>def function</code> needs to be inline with the others. secondly, do <code>import os</code> at the beginning of your programe and then change the function to:</p> <pre><code>def quit1(): # Needs to be here or it breaks the program os._exit(0) return </code></pre>
0
2016-09-29T10:03:44Z
[ "python", "button", "tkinter" ]
Quit button assistance needed
39,767,084
<p>I'm trying to make a code for this topic i'm doing and I've manage to get some of it done but when it comes to quiting my tkinter menu it doesn't close unless I manually close it, I've got the the button for the option to close it but it doesn't work. Can anyone help with my problem. Here's my code below.</p> <pre>...
-2
2016-09-29T09:54:23Z
39,787,009
<p>For Tkinter you can just pass <code>gen.quit</code> to the command of a button widget, like so:</p> <pre><code>close = Button(gen, text = 'Close', command = gen.quit).pack() </code></pre>
0
2016-09-30T08:30:10Z
[ "python", "button", "tkinter" ]
Reading large text files line-by-line is still using all my memory
39,767,227
<p>I'm writing a simple program that is supposed to read a large file (263.5gb to be exact) with JSON on each line (<a href="https://www.reddit.com/r/datasets/comments/3mg812/full_reddit_submission_corpus_now_available_2006/" rel="nofollow">link here</a>). I've done some research and the best method I've found is to re...
0
2016-09-29T10:01:19Z
39,768,216
<p>You have a memory leak here:</p> <pre><code>except: numberOfErrors += 1 errors[comments] = sys.exc_info()[0] </code></pre> <p>With a huge number of input lines, number of errors can also be huge, especially if you have some error in your algorithm.</p> <p>Plain <code>except</code> is evil because it hides...
1
2016-09-29T10:47:45Z
[ "python", "file", "optimization", "text" ]
Reading large text files line-by-line is still using all my memory
39,767,227
<p>I'm writing a simple program that is supposed to read a large file (263.5gb to be exact) with JSON on each line (<a href="https://www.reddit.com/r/datasets/comments/3mg812/full_reddit_submission_corpus_now_available_2006/" rel="nofollow">link here</a>). I've done some research and the best method I've found is to re...
0
2016-09-29T10:01:19Z
39,783,866
<p>I worked out where the memory leak was. On this line where I was printing to the console after every line:</p> <pre><code> print("Comments scanned: " + str(comments) + "\nFound: " + str(found) + "\n") </code></pre> <p>Print 200 million times and your computer is bound to run out of memory trying to hold it all in ...
0
2016-09-30T04:47:32Z
[ "python", "file", "optimization", "text" ]
How one can run xgboost on hadoop cluster for distributed model training?
39,767,280
<p>I am trying to built a CTR prediction model using XGBoost on 100 million of impressions for contextual ads and in order to achieve the same, I want to try XGboost on hadoop as I have all of the impressions data available in HDFS.</p> <p>Can someone cite a working tutorial for the same for python? </p>
0
2016-09-29T10:03:27Z
39,769,979
<p>There are many ways to do it:</p> <ol> <li><p>If in case you have some lower level logical grouping say CTR for some item department and you want to make localized models for departments then you can go for map reduce type of setting. It will make sure all data belonging to single department will end up in single Y...
0
2016-09-29T12:11:12Z
[ "python", "hadoop", "machine-learning", "xgboost" ]
How to use SHA256-HMAC in python code?
39,767,297
<p><a href="https://doc.periscopedata.com/doc/embed-api" rel="nofollow">I am taking message and key from this URL</a></p> <pre><code>import hmac import hashlib import base64 my = "/api/embedded_dashboard?data=%7B%22dashboard%22%3A7863%2C%22embed%22%3A%22v2%22%2C%22filters%22%3A%5B%7B%22name%22%3A%22Filter1%22%2C%22val...
0
2016-09-29T10:04:04Z
39,767,589
<p>You are not making use of <code>hmac</code> at all in your code. </p> <p>Typical way to use <code>hmac</code>, construct an HMAC object from your key, message and identify the hashing algorithm by passing in its constructor:</p> <pre><code>h = hmac.new( key, my, hashlib.sha256 ) print( h.hexdigest() ) </code></pre...
1
2016-09-29T10:18:31Z
[ "python", "oauth", "sha256", "hmac" ]
How to download large files in Python 2
39,767,343
<p>I'm trying to download large files (approx. 1GB) with mechanize module, but I have been unsuccessful. I've been searching for similar threads, but I have found only those, where the files are publicly accessible and no login is required to obtain a file. But this is not my case as the file is located in the private ...
1
2016-09-29T10:06:46Z
39,767,529
<p>Try downloading/writing it by chunks. Seems like file takes all your memory.</p> <p>You should specify Range header for your request if server supports it.</p> <p><a href="https://en.wikipedia.org/wiki/List_of_HTTP_header_fields" rel="nofollow">https://en.wikipedia.org/wiki/List_of_HTTP_header_fields</a></p>
-1
2016-09-29T10:15:55Z
[ "python", "download", "mechanize" ]
How to download large files in Python 2
39,767,343
<p>I'm trying to download large files (approx. 1GB) with mechanize module, but I have been unsuccessful. I've been searching for similar threads, but I have found only those, where the files are publicly accessible and no login is required to obtain a file. But this is not my case as the file is located in the private ...
1
2016-09-29T10:06:46Z
39,768,280
<p>You can use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"><em>bs4</em></a> and <a href="http://docs.python-requests.org/en/master/user/quickstart/" rel="nofollow"><em>requests</em></a> to get you logged in then write the <em>streamed</em> content. There are a few form fields requir...
1
2016-09-29T10:50:54Z
[ "python", "download", "mechanize" ]
How to generate spatial weight matrix in python script?
39,767,425
<p>I need to create spatial weights matrices for different point shapefiles,so I tried to batch process in stand-alone Python script. Here is the example code exported from the ModelBuilder in the ArcGIS 10.2 software. </p> <pre><code>import arcpy test_shp = "D:\\My Documents\\ArcGIS\\test.shp" tset_swm = "D:\\My Do...
0
2016-09-29T10:10:42Z
39,898,933
<p>I don't see anything wrong here. But isn't tset_swm in your code the output you are looking for? That is the output spatial weight matrix you generated based on your input shapefile. </p>
0
2016-10-06T14:39:24Z
[ "python", "arcgis", "arcpy" ]
Looping over a slice copy of a list
39,767,440
<p>I am trying to understand the difference between <strong>looping over a list</strong> and <strong>looping over a "slice" copy of a list</strong>.</p> <p>So, for example, in the following list, the element whose length is greater than 6 is appended to the beginning of the list:</p> <pre><code>words = ['cat', 'windo...
1
2016-09-29T10:11:30Z
39,767,564
<p>The list <code>words</code> has three elements. The copy of <code>words</code> also does. You iterate over the copy, insert something in <code>words</code> if the current element is longer than 6 characters, and are done.</p> <p>Now let's see what happens when you iterate over <code>words</code> directly:</p> <p>T...
4
2016-09-29T10:17:26Z
[ "python" ]
Looping over a slice copy of a list
39,767,440
<p>I am trying to understand the difference between <strong>looping over a list</strong> and <strong>looping over a "slice" copy of a list</strong>.</p> <p>So, for example, in the following list, the element whose length is greater than 6 is appended to the beginning of the list:</p> <pre><code>words = ['cat', 'windo...
1
2016-09-29T10:11:30Z
39,767,590
<p>In your first approach, you are performing a shallow copy of your list <code>words</code>, iterating over it and appending long words to the list <code>words</code>. So you iterate over a fixed list, and extend a different list.</p> <p>With your last approach, the list <code>words</code> grows with each iteration, ...
2
2016-09-29T10:18:34Z
[ "python" ]
Looping over a slice copy of a list
39,767,440
<p>I am trying to understand the difference between <strong>looping over a list</strong> and <strong>looping over a "slice" copy of a list</strong>.</p> <p>So, for example, in the following list, the element whose length is greater than 6 is appended to the beginning of the list:</p> <pre><code>words = ['cat', 'windo...
1
2016-09-29T10:11:30Z
39,767,656
<p><code>words[:]</code> means a new copy of the <code>words</code> and length is fixed. So you are iterating over a fixed list.</p> <p>But in the second situation, iterating over and extending the same list which makes it infinity.</p> <pre><code>words = ['cat', 'window', 'blahblah'] new_words = [_ for _ in words if...
1
2016-09-29T10:21:35Z
[ "python" ]
Looping over a slice copy of a list
39,767,440
<p>I am trying to understand the difference between <strong>looping over a list</strong> and <strong>looping over a "slice" copy of a list</strong>.</p> <p>So, for example, in the following list, the element whose length is greater than 6 is appended to the beginning of the list:</p> <pre><code>words = ['cat', 'windo...
1
2016-09-29T10:11:30Z
39,767,671
<p>When you are doing <code>words[:]</code>, you are iterating over the copy of list, whereas with <code>words</code>, you are iterating over the original copy of list.</p> <p>In the case <code>II</code>, your interpreter is freezing because when you are at the last index, the condition is satisfied and you insert the...
2
2016-09-29T10:22:34Z
[ "python" ]
Looping over a slice copy of a list
39,767,440
<p>I am trying to understand the difference between <strong>looping over a list</strong> and <strong>looping over a "slice" copy of a list</strong>.</p> <p>So, for example, in the following list, the element whose length is greater than 6 is appended to the beginning of the list:</p> <pre><code>words = ['cat', 'windo...
1
2016-09-29T10:11:30Z
39,767,689
<p>The following loop</p> <pre><code>for word in words: // do something </code></pre> <p>is roughly equivalent to the following one (when <code>words</code> is a list and not another kind of <code>iterable</code>):</p> <pre><code>i = 0 while i != len(words): word = words[i] // do something (assuming no '...
2
2016-09-29T10:23:29Z
[ "python" ]
Flask CGI app issues with print statement
39,767,441
<p>I have a simple flask application deployed using CGI+Apache running on a shared hosting server.</p> <p>The app runs Flask 0.11.1 on Python 2.6 along with Flask-Mail 0.9.1.</p> <p>One of the pages in the app has a contact form that sends an email and redirects back to the same page.</p> <p>The contact form has a P...
0
2016-09-29T10:11:32Z
39,767,611
<p>Print statement should not create an error as it is one of the statement like others. Instead since you are not checking for <code>request.method=='POST'</code>, this should create and throw an error in your get request. To redirect to the same page <code>return redirect("/sendmail")</code> Do not forget to import f...
0
2016-09-29T10:19:24Z
[ "python", "flask" ]
Syntax error when installing csc-pysparse
39,767,528
<p>I am new to Python and I am trying to install recsys package.</p> <p><a href="http://ocelma.net/software/python-recsys/build/html/installation.html" rel="nofollow">http://ocelma.net/software/python-recsys/build/html/installation.html</a></p> <p>For this i need to install some pre-requiste packages, so i have to ru...
0
2016-09-29T10:15:52Z
39,767,936
<p>The error is coming from the installation code of recsys package. In order to avoid this error, you need to install setuptools separately.</p> <p>For debian machines, the below command will work.</p> <pre><code>sudo apt-get install python3-setuptools </code></pre> <p>For other machines, please checkout installati...
-1
2016-09-29T10:35:14Z
[ "python", "python-3.x", "pip" ]
Syntax error when installing csc-pysparse
39,767,528
<p>I am new to Python and I am trying to install recsys package.</p> <p><a href="http://ocelma.net/software/python-recsys/build/html/installation.html" rel="nofollow">http://ocelma.net/software/python-recsys/build/html/installation.html</a></p> <p>For this i need to install some pre-requiste packages, so i have to ru...
0
2016-09-29T10:15:52Z
39,768,227
<p>The code triggering the error is Python 2-specific and is illegal in Python 3.</p> <p>Apparently, <code>csc-pysparse</code> doesn't support Python 3 (<a href="https://github.com/rspeer/csc-pysparse/blob/master/README" rel="nofollow">its <code>README</code></a> only mentions 2.6) and <a href="https://github.com/rspe...
0
2016-09-29T10:48:33Z
[ "python", "python-3.x", "pip" ]
Django messages framework not displaying message?
39,767,570
<p>I'm trying to build a community portal and am working on displaying one-time message to the user such as "login successful" and the like; and am working with Django's messages framework. </p> <p>My template has the following line which currently does nothing:</p> <pre><code>{% if messages %}{% for message in messa...
0
2016-09-29T10:17:50Z
39,767,716
<p>Don't use <code>render_to_response</code> in your <code>test</code> view. It doesn't run context processors which are required to insert things like <code>messages</code> - and other useful items such as <code>user</code> - into the context.</p> <p>Use <code>render</code> instead:</p> <pre><code>return render(requ...
1
2016-09-29T10:24:54Z
[ "python", "django", "authentication", "authorization", "django-messages" ]
pip install MySQL-python failed in linux
39,767,586
<p>I've created a Django project and its works as well now I'm trying to config it with MySql so searched in Google and did some ways but when I <code>pip install MySQL-python</code> the below problem occurs:</p> <pre><code>Collecting MySQL-python Using cached MySQL-python-1.2.5.zip Complete output from command python...
0
2016-09-29T10:18:25Z
39,767,673
<p>This library is not compatible with Python 3. Follow the <a href="https://docs.djangoproject.com/en/1.10/ref/databases/#mysql-db-api-drivers" rel="nofollow">advice in the Django docs</a> and install mysqlclient instead.</p>
2
2016-09-29T10:22:37Z
[ "python", "mysql", "linux", "django", "python-3.4" ]
NLTK sentiment vader: ordering results
39,767,603
<p>I've just run the Vader sentiment analysis on my dataset: </p> <pre><code>from nltk.sentiment.vader import SentimentIntensityAnalyzer from nltk import tokenize sid = SentimentIntensityAnalyzer() for sentence in filtered_lines2: print(sentence) ss = sid.polarity_scores(sentence) for k in sorted(ss): ...
0
2016-09-29T10:19:08Z
39,769,725
<p>You can use a simple counter for each of the classes:</p> <pre><code>positive, negative, neutral = 0, 0, 0 </code></pre> <p>Then, inside the sentence loop, test the compound value and increase the corresponding counter:</p> <pre><code> ... if ss['compound'] &gt; 0: positive += 1 elif ss['compou...
1
2016-09-29T11:58:38Z
[ "python", "python-3.x", "nltk" ]
NLTK sentiment vader: ordering results
39,767,603
<p>I've just run the Vader sentiment analysis on my dataset: </p> <pre><code>from nltk.sentiment.vader import SentimentIntensityAnalyzer from nltk import tokenize sid = SentimentIntensityAnalyzer() for sentence in filtered_lines2: print(sentence) ss = sid.polarity_scores(sentence) for k in sorted(ss): ...
0
2016-09-29T10:19:08Z
39,769,760
<p>By far not the most pythonic way of doing it but I think this would be the easiest to understand if you don't have much experience with python. Essentially you create a dictionary with 0 values and increment the value in each one of the cases. </p> <pre><code>from nltk.sentiment.vader import SentimentIntensityAnaly...
1
2016-09-29T12:00:44Z
[ "python", "python-3.x", "nltk" ]
NLTK sentiment vader: ordering results
39,767,603
<p>I've just run the Vader sentiment analysis on my dataset: </p> <pre><code>from nltk.sentiment.vader import SentimentIntensityAnalyzer from nltk import tokenize sid = SentimentIntensityAnalyzer() for sentence in filtered_lines2: print(sentence) ss = sid.polarity_scores(sentence) for k in sorted(ss): ...
0
2016-09-29T10:19:08Z
39,770,040
<p>I might define a function that returns the type of inequality that's being represented by a document:</p> <pre><code>def inequality_type(val): if val == 0.0: return "equal" elif val &gt; 0.0: return "greater" return "less" </code></pre> <p>Then use this on the compound scores of all the sentenc...
0
2016-09-29T12:13:55Z
[ "python", "python-3.x", "nltk" ]
pandas assign with new column name as string
39,767,718
<p>I recently discovered pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow">"assign" method</a> which I find very elegant. My issue is that the name of the new column is assigned as keyword, so it cannot have spaces or dashes in it. </p> <pre><code>df = D...
1
2016-09-29T10:25:08Z
39,767,887
<p><code>assign</code> expects a bunch of key word arguments. It will, in turn, assign columns with the names of the key words. That's handy, but you can't pass an expression as the key word. This is spelled out by @EdChum in the comments with this <a href="https://docs.python.org/3.2/reference/lexical_analysis.html...
1
2016-09-29T10:33:29Z
[ "python", "pandas", "assign", "columnname" ]
Does __bin__ (or __binary__) operator exists in python?
39,767,750
<p>In Python, the <code>__oct__</code> and <code>__hex__</code> operators exists to implement specific bahavior for <code>oct()</code> and <code>hex()</code>. See <a href="https://docs.python.org/2/reference/datamodel.html?#object.__oct__" rel="nofollow">Emulating numeric types</a></p> <p>But I don’t understand why ...
1
2016-09-29T10:26:57Z
39,768,083
<p>You can use <a href="https://docs.python.org/2/reference/datamodel.html?#object.__index__" rel="nofollow"><code>object.__index__</code></a> to handle <code>bin()</code> calls in Python 2. From Python 3 onwards it works for <code>hex()</code> and <code>oct()</code> as well but not in Python 2.</p> <p>From <a href="h...
2
2016-09-29T10:41:18Z
[ "python", "python-2.7", "operators" ]
Getting substring based on another column in a pandas dataframe
39,767,787
<p>Hi is there a way to get a substring of a column based on another column?</p> <pre><code>import pandas as pd x = pd.DataFrame({'name':['bernard','brenden','bern'],'digit':[2,3,3]}) x digit name 0 2 bernard 1 3 brenden 2 3 bern </code></pre> <p>What i would expect is something like:</p> <pre><co...
2
2016-09-29T10:28:57Z
39,767,811
<p>Use <code>apply</code> with <code>axis=1</code> for row-wise with a <code>lambda</code> so you access each column for slicing:</p> <pre><code>In [68]: x = pd.DataFrame({'name':['bernard','brenden','bern'],'digit':[2,3,3]}) x.apply(lambda x: x['name'][:x['digit']], axis=1) Out[68]: 0 be 1 bre 2 ber dtype:...
3
2016-09-29T10:29:58Z
[ "python", "pandas", "dataframe" ]
Cannot run tensorflow examples
39,767,788
<p>I am trying to run this tensorflow example: <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/skflow/text_classification_character_cnn.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/skflow/text_classification_character_cnn.py</a></p> <p>Ho...
1
2016-09-29T10:29:09Z
40,031,713
<p>What about trying to open the tar file using the full path? BTW the link gave is 404 not found. </p>
0
2016-10-13T21:59:11Z
[ "python", "tensorflow" ]
Cannot run tensorflow examples
39,767,788
<p>I am trying to run this tensorflow example: <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/skflow/text_classification_character_cnn.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/skflow/text_classification_character_cnn.py</a></p> <p>Ho...
1
2016-09-29T10:29:09Z
40,047,743
<p>When you get that error, you can look at the downloaded dbpedia_dsv.tar.gz in a text editor, and you might find that it is actually a 404 webpage. The file you want seems to be available here as well (I found this link <a href="https://github.com/zhangxiangxiao/Crepe" rel="nofollow">here</a>): <a href="https://drive...
0
2016-10-14T16:16:27Z
[ "python", "tensorflow" ]
Can't install psycopg2 package through pip install... Is this because of Sierra?
39,767,810
<p>I am working on a project for one of my lectures and I need to download the package psycopg2 in order to work with the postgresql database in use. Unfortunately, when I try to pip install psycopg2 the following error pops up:</p> <pre><code>ld: library not found for -lssl clang: error: linker command failed with ex...
2
2016-09-29T10:29:47Z
39,769,266
<p>It looks like the openssl package is not installed. Try installing it and <code>pip install</code> again. I'm not a macos user, but I believe that <a href="http://brew.sh/" rel="nofollow"><code>brew</code></a> simplifies package management on that platform.</p> <p>You might also need to install the Python developme...
0
2016-09-29T11:39:07Z
[ "python", "pip", "psycopg2" ]
Can't install psycopg2 package through pip install... Is this because of Sierra?
39,767,810
<p>I am working on a project for one of my lectures and I need to download the package psycopg2 in order to work with the postgresql database in use. Unfortunately, when I try to pip install psycopg2 the following error pops up:</p> <pre><code>ld: library not found for -lssl clang: error: linker command failed with ex...
2
2016-09-29T10:29:47Z
39,800,677
<p>I fixed this by installing Command Line Tools</p> <pre><code>xcode-select --install </code></pre> <p>then installing openssl via Homebrew and manually linking my homebrew-installed openssl to pip:</p> <pre><code>env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" pip install psycopg2 </cod...
11
2016-09-30T22:01:18Z
[ "python", "pip", "psycopg2" ]
Can't install psycopg2 package through pip install... Is this because of Sierra?
39,767,810
<p>I am working on a project for one of my lectures and I need to download the package psycopg2 in order to work with the postgresql database in use. Unfortunately, when I try to pip install psycopg2 the following error pops up:</p> <pre><code>ld: library not found for -lssl clang: error: linker command failed with ex...
2
2016-09-29T10:29:47Z
40,039,093
<ol> <li><p>Install/update Xcode developer tools </p> <pre><code>xcode-select --install </code></pre></li> <li><p>Query postgres path</p> <pre><code>find / -name pg_config 2&gt;/dev/null </code></pre></li> <li><p>Install psycopg2, use the path you got in <strong>step 2</strong>. Mine was '/usr/local/Cellar/postgres...
0
2016-10-14T09:00:09Z
[ "python", "pip", "psycopg2" ]
What is the best way to collect errors and send a summary?
39,767,881
<p>I have a script executing several independent functions in turn. I would like to collect the errors/exceptions happening along the way, in order to send an email with a summary of the errors.</p> <p>What is the best way to raise these errors/exceptions and collect them, while allowing the script to complete and go ...
0
2016-09-29T10:33:15Z
39,767,932
<p>use simple <code>try</code> <code>except</code> statements and do logging for the exceptions that would be standard way to collect all your errors.</p>
0
2016-09-29T10:35:03Z
[ "python" ]
What is the best way to collect errors and send a summary?
39,767,881
<p>I have a script executing several independent functions in turn. I would like to collect the errors/exceptions happening along the way, in order to send an email with a summary of the errors.</p> <p>What is the best way to raise these errors/exceptions and collect them, while allowing the script to complete and go ...
0
2016-09-29T10:33:15Z
39,768,191
<p>There are two options:</p> <ol> <li>Use decorator in which you catch all exceptions and save it somewhere.</li> <li>Add try/except everywhere.</li> </ol> <p>Using decorator might be much better and cleaner, and code will be easier to maintain.</p> <p>How to store errors? Your decision. You can add them to some li...
0
2016-09-29T10:46:31Z
[ "python" ]
What is the best way to collect errors and send a summary?
39,767,881
<p>I have a script executing several independent functions in turn. I would like to collect the errors/exceptions happening along the way, in order to send an email with a summary of the errors.</p> <p>What is the best way to raise these errors/exceptions and collect them, while allowing the script to complete and go ...
0
2016-09-29T10:33:15Z
39,768,492
<p>You could wrap each function in try/except, usually better for small simple scripts.</p> <pre><code>def step_1(): # Code that can raise errors/exceptions def step_2(): # Code that can raise errors/exceptions def step_3(): # Code that can raise errors/exceptions def main(): try: step_1_res...
1
2016-09-29T11:02:43Z
[ "python" ]
TypeError: match() takes from 2 to 3 positional arguments but 5 were given
39,767,891
<p>Full Error: </p> <pre><code>Traceback (most recent call last): File "N:/Computing (Programming)/Code/name.py", line 3, in &lt;module&gt; valid = re.match("[0-9]","[0-9]","[A-Z]","[a-z]" ,tutorGroup) TypeError: match() takes from 2 to 3 positional arguments but 5 were given </code></pre> <p>My code:</p> <pre...
0
2016-09-29T10:33:33Z
39,767,948
<p>The problem is, that <code>re.match</code> take 2 or 3 arguments, not 5. First the regex pattern, and the string to match. optionally it takes a 3rd argument with flags. If you want to match a single digit or a letter, you would use <code>[0-9a-zA-Z]</code> as regex. If you want multiple letters or digits, you can u...
1
2016-09-29T10:35:45Z
[ "python" ]
Create zip archive with multiple files
39,767,904
<p>I'm using following code where I pass .pdf file names with their paths to create zip file.</p> <pre><code>for f in lstFileNames: with zipfile.ZipFile('reportDir' + str(uuid.uuid4()) + '.zip', 'w') as myzip: myzip.write(f) </code></pre> <p>It only archives one file though. <strong>I need to arch...
0
2016-09-29T10:34:11Z
39,767,950
<p>Order is incorrect. You are creating new zipfile object for each item in <code>lstFileNames</code></p> <p>Should be like this.</p> <pre><code>with zipfile.ZipFile('reportDir' + str(uuid.uuid4()) + '.zip', 'w') as myzip: for f in lstFileNames: myzip.write(f) </code></pre>
4
2016-09-29T10:35:48Z
[ "python" ]
How to detect closed eyes for three seconds?
39,767,988
<p>I have discovered the parts such as the face, eyes, 2 containers eyes. Normally, I can see face, eyes area and two eyes. When I see face, eyes area but not see two eyes, that's when detected eyes closed. And now, I want to detect when eyes closed for three seconds.Someone can suggest me a solution. I tried to time.s...
-1
2016-09-29T10:37:21Z
39,769,281
<p>You will want to use a timer for this specific application. time.sleep() basically just halts the program, it does not keep track of time. This should work for what you want:</p> <pre><code>closed = False timer = 0 if detect(eyes_closed) and not closed: timer = time.time() closed = True else if closed: if...
0
2016-09-29T11:39:41Z
[ "python", "opencv" ]
Python QT how to visualise that the button is clicked
39,768,065
<p>I have a <code>QtCreator</code> generated gui. After import i am setting images to the buttons and when i click them the button below probably indicates the click but the <code>QIcon</code> doesn't change in any way. Is there a way to make it visible? This is my button code:</p> <pre><code> self.pushButton.setIcon(...
0
2016-09-29T10:40:23Z
39,769,120
<p>You can use the <code>:pressed</code> <a href="http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-pseudo-states" rel="nofollow">pseudo-state</a> in your style sheet to specify the behaviour when the button is pressed:</p> <pre><code>self.pushButton.setStyleSheet(""" QPushButton{ border: 0px solid; ...
0
2016-09-29T11:32:39Z
[ "python", "qt", "qt-creator", "pyqt5" ]
Sphinx - what is different between toctree and content?
39,768,133
<p>I can create table of contents in two ways:</p> <pre><code>.. contents:: :local: depth: 1 </code></pre> <p>or as </p> <pre><code>.. toctree:: :maxdepth: 1 index </code></pre> <p>What is difference? Where I should use the toctree and where the contents?</p>
0
2016-09-29T10:43:48Z
39,770,866
<p><a href="http://docutils.sourceforge.net/docs/ref/rst/directives.html#table-of-contents" rel="nofollow"><code>.. contents</code></a> is a doctutils directive (the underlying library which defines ReST and associated utilities) and <strong><em>automatically</em></strong> generates a table of contents from headlines w...
3
2016-09-29T12:51:54Z
[ "python", "python-sphinx" ]
Python SSH using Popen
39,768,169
<p>How do I <code>ssh</code> using <code>Popen</code> by answering yes by default when faced with this?</p> <pre><code>The authenticity of host '`XXXXX`' can't be established. ECDSA key fingerprint is SHA256:LA2RqbdzD8Uxgi36KWOM12giS9T+ceOQYhYjVKReMks. Are you sure you want to continue connecting (yes/no)? </code></pr...
0
2016-09-29T10:45:13Z
39,768,243
<p>From the man page:</p> <blockquote> <p>StrictHostKeyChecking</p> <p>If this flag is set to “yes”, ssh(1) will never automatically add host keys to the ~/.ssh/known_hosts file, and refuses to connect to hosts whose host key has changed. This provides maximum protection against trojan horse attacks, ...
-3
2016-09-29T10:49:13Z
[ "python", "ssh", "subprocess", "popen" ]
Python SSH using Popen
39,768,169
<p>How do I <code>ssh</code> using <code>Popen</code> by answering yes by default when faced with this?</p> <pre><code>The authenticity of host '`XXXXX`' can't be established. ECDSA key fingerprint is SHA256:LA2RqbdzD8Uxgi36KWOM12giS9T+ceOQYhYjVKReMks. Are you sure you want to continue connecting (yes/no)? </code></pr...
0
2016-09-29T10:45:13Z
39,771,367
<p>Not sure how subprocess do it, next is another way, maybe helpful to you. FYI.</p> <pre><code>import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect("192.168.1.6", 22, "username", "password") stdin, stdout, stderr = ssh.exec_command('ls') // your command he...
0
2016-09-29T13:14:51Z
[ "python", "ssh", "subprocess", "popen" ]
Converting python tuple, lists, dictionaries containing pandas objects (series/dataframes) to json
39,768,230
<p>I know I can convert pandas object like <code>Series</code>, <code>DataFrame</code> to json as follows:</p> <pre><code>series1 = pd.Series(np.random.randn(5), name='something') jsonSeries1 = series1.to_json() #{"0":0.0548079371,"1":-0.9072821424,"2":1.3865642993,"3":-1.0609052074,"4":-3.3513341839} </code></pre> <...
2
2016-09-29T10:48:38Z
39,768,286
<p>call <code>pd.DataFrame</code> on <code>seriesmap</code> then use <code>to_json</code></p> <pre><code>pd.DataFrame(seriesmap).to_json() '{"key1":{"0":0.8513342674,"1":-1.3357052602,"2":0.2102391775,"3":-0.5957492995,"4":0.2356552588}}' </code></pre>
1
2016-09-29T10:51:15Z
[ "python", "json", "pandas" ]
Plotting a type of Histogram
39,768,288
<p>I have data in the following format</p> <pre><code>0 0.69 1 0.87 1 0.87 0 0.87 0 0.87 </code></pre> <p>So the first column is either zero or one. Second column is a decimal number. If you look at the table, at 0.69, there is only one zero and no ones. Also at 0.87, there are two zeros and two ones. I wan...
0
2016-09-29T10:51:16Z
39,768,385
<p>use <code>groupby</code>, <code>size</code>, and <code>unstack</code></p> <pre><code>df.groupby([0, 1]).size().rename_axis([None, None]).unstack(0).plot.bar() </code></pre> <p><a href="http://i.stack.imgur.com/9Tqna.png" rel="nofollow"><img src="http://i.stack.imgur.com/9Tqna.png" alt="enter image description here...
3
2016-09-29T10:57:24Z
[ "python", "pandas", "numpy", "histogram" ]
Incorrect pattern displayed
39,768,309
<p>In the second while loop the asterisk(*) is displayed just once for every cycle. </p> <pre><code>import sys n = 0 a = 0 while (n &lt; 6): n = n + 1 while(a &lt; n): sys.stdout.write('*') a = a +1 print '' </code></pre> <p>Pattern displayed is :</p> <pre><code>* * * * * * </code></pre...
-5
2016-09-29T10:52:15Z
39,768,460
<p>Assuming you want it to print out 6 patterns of 6 stars with a line between, this is what you want to do:</p> <pre><code>import sys n = 0 a = 0 while (n &lt; 6): n = n + 1 a=0 while(a &lt; n): sys.stdout.write('*',end="") a = a +1 print '' </code></pre>
0
2016-09-29T11:00:47Z
[ "python" ]
Incorrect pattern displayed
39,768,309
<p>In the second while loop the asterisk(*) is displayed just once for every cycle. </p> <pre><code>import sys n = 0 a = 0 while (n &lt; 6): n = n + 1 while(a &lt; n): sys.stdout.write('*') a = a +1 print '' </code></pre> <p>Pattern displayed is :</p> <pre><code>* * * * * * </code></pre...
-5
2016-09-29T10:52:15Z
39,768,624
<p>Here's a possible solution for your version:</p> <pre><code>import sys n = 0 a = 0 while (n &lt; 6): n = n + 1 a = 0 while(a &lt; n): print('*', end="") a = a + 1 print('') </code></pre> <p>If you want a shorter version, here's a possible one:</p> <pre><code>print('\n'.join(['*'*...
0
2016-09-29T11:08:55Z
[ "python" ]
Replace whole string if it contains substring in pandas
39,768,547
<p>Im sorry if this is a very obvious and easy question but I've been searching the internet for a solution but couldn't come up with one that works (and I don't really have much knowledge in python). I want to replace all strings that contain a specific substring. So for example if I have this dataframe:</p> <pre><co...
2
2016-09-29T11:05:30Z
39,768,574
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html#pandas.Series.str.contains" rel="nofollow"><code>str.contains</code></a> to mask the rows that contain 'ball' and then overwrite with the new value:</p> <pre><code>In [71]: df.loc[df['sport'].str.contains('bal...
2
2016-09-29T11:06:46Z
[ "python", "pandas" ]
Replace whole string if it contains substring in pandas
39,768,547
<p>Im sorry if this is a very obvious and easy question but I've been searching the internet for a solution but couldn't come up with one that works (and I don't really have much knowledge in python). I want to replace all strings that contain a specific substring. So for example if I have this dataframe:</p> <pre><co...
2
2016-09-29T11:05:30Z
39,768,594
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>apply</code></a> with a lambda. The <code>x</code> parameter of the lambda function will be each value in the 'sport' column:</p> <pre><code>df.sport = df.sport.apply(lambda x: 'ball sport' if '...
2
2016-09-29T11:07:23Z
[ "python", "pandas" ]
Replace whole string if it contains substring in pandas
39,768,547
<p>Im sorry if this is a very obvious and easy question but I've been searching the internet for a solution but couldn't come up with one that works (and I don't really have much knowledge in python). I want to replace all strings that contain a specific substring. So for example if I have this dataframe:</p> <pre><co...
2
2016-09-29T11:05:30Z
39,768,663
<p>you can use <code>str.replace</code></p> <pre><code>df.sport.str.replace(r'(^.*ball.*$)', 'ball sport') 0 tennis 1 ball sport 2 ball sport Name: sport, dtype: object </code></pre> <p>reassign with</p> <pre><code>df['sport'] = df.sport.str.replace(r'(^.*ball.*$)', 'ball sport') df </code></pre> <p><...
2
2016-09-29T11:10:55Z
[ "python", "pandas" ]
Not expected result received with scipy's curve_fit
39,768,562
<p>I was trying to do multivariate logarithmic regression on my data with scipy curve_fit and as a result expect to get a line, but get a curve. Here is the code I used : </p> <pre><code>Quercetin=[23,195,6,262,272,158,79,65,136,198] Naringenin=[11,4,8,6,6,7,6,9,7,9] Rutin=[178,165,93,239,202,3325,4427,7607,3499,1762...
0
2016-09-29T11:06:17Z
39,775,906
<p>(I'm assuming that the question is really about plotting). You are asking <code>matplotlib</code> to plot red dots (<code>'ro'</code>) connected by straight lines (<code>-</code>). Matplotlib obliges and connects them in whatever order they are given.</p> <p>If you want to plot a line, just plot it separately:</p>...
2
2016-09-29T16:50:02Z
[ "python", "scipy", "curve-fitting" ]
pretty much lost : self.parent.parent.__class__
39,768,630
<p>I needed to serialize a self referencing hierarchy </p> <pre><code>class Systm(models.Model): ... parent = models.ForeignKey('self', on_delete=models.CASCADE, blank = True, null = True, related_name="children") </code></pre> <p>and I was able to achieve that with the following code:</p> <pre><code>class R...
0
2016-09-29T11:09:19Z
39,772,910
<p>This basically works by getting the top serializer class and instanciating it to return the serialized value of a child. The <code>parent</code> attribute of a serializer (or field) is the serializer instance that declared this as a field.</p> <p><code>self.parent</code> is the List Serializer implicitly created wh...
0
2016-09-29T14:20:48Z
[ "python", "django", "django-rest-framework" ]
Finding the exact string in input file
39,768,676
<p>I am looking for the lines starting with "ND" in an input file. that looks like this:</p> <pre><code>ND 195 4.53434033e+006 5.62453069e+006 2.56369141e+002 ND 196 4.53436645e+006 5.62443565e+006 2.56452118e+002 NS 129 113 97 82 58 59 37 22 17 18 NS 5 6 12 26 42 64 62 85 102 117 </code></pre> <p>I wrote a code li...
1
2016-09-29T11:11:27Z
39,768,757
<p>Well, you're using a flag <code>found_ND</code>, making it <code>True</code> if the line is found (which happens for the first line) and then never change it back to <code>False</code>: </p> <pre><code>if text in line: found_ND = True </code></pre> <p><em><code>found_ND</code> will be <code>True</code> ...
2
2016-09-29T11:15:29Z
[ "python", "string", "python-3.x" ]
set xticks label frequency with python
39,768,742
<p>I want to reduce the frequency of x tick marks. The x values are date :</p> <pre><code>date=['20120101','20120101','20120101',...'20121231'] </code></pre> <p>I have 24 time steps for each day of the year. And I would like to label the xticks each 24 time steps (i.e., each day). </p> <p>Here is the code that I use...
0
2016-09-29T11:14:40Z
39,769,409
<p>Since there is no <em>complete</em> and working example, we have to guess: Is your <code>date</code> properly recognized as datetime object? If not, the <code>set_major_locator</code> in the date-format would result in no x-ticks.</p> <p>You can achieve this using something like <code>date = datetime.datetime.strpt...
1
2016-09-29T11:45:15Z
[ "python", "matplotlib" ]
Error in parsing HL7 using hl7apy
39,768,782
<p>i am using <strong>hl7apy</strong> to parse hl7 files in python and i am following <strong><a href="https://msarfati.wordpress.com/2015/06/20/python-hl7-v2-x-and-hl7apy-introduction-and-parsing-part-1/" rel="nofollow">this</a></strong> link. When i am using the sample.hl7 i am getting the desired result but when i a...
0
2016-09-29T11:17:00Z
39,769,267
<p>You should show a message from your file here for a definitiv answer. </p> <p>But the most probable reason is, that the content of your file does not follow the HL7 rules. Are you sure that you use the correct segment delimiter (ASCII 13 or HEX 0D) ? Do you use non standard segment names?</p> <p>Just a check with ...
2
2016-09-29T11:39:07Z
[ "python", "hl7", "hl7-v2" ]
Difference iterating with tp_iternext or PyIter_Next
39,768,793
<p>If I write a C function that does something with an iterable then I create an Iterator first and then loop over it.</p> <pre><code>iterator = PyObject_GetIter(sequence); if (iterator == NULL) { return NULL; } while (( item = PyIter_Next(iterator) )) { ... } </code></pre> <p>This works fine but I've also se...
0
2016-09-29T11:17:20Z
39,768,987
<p>The <a href="https://hg.python.org/cpython/file/tip/Objects/abstract.c#l3145" rel="nofollow">source code for <code>PyIter_Next</code></a> shows that it simply retrieves the <code>tp_iternext</code> slot and calls it <strong>and clears a <code>StopIteration</code> exception that may or may not have occurred</strong>....
1
2016-09-29T11:26:29Z
[ "python", "python-c-api" ]
Collectd - Perl/Python plugin - registration functions not working
39,768,848
<p>I would like to ask about Collectd's plugins Perl and Python and their registration functions. </p> <p>I tried to code plugin in Perl (and also in Python), set up read and write functions and after that register them into Collectd (plugin_register functions). In all cases it wasnt working. Everytime, the logs show:...
3
2016-09-29T11:19:44Z
39,770,304
<p>Post your configuration if you can.</p> <p>The documentation says that the <em><strong><code>LoadPlugin</code></strong></em> configuration goes in the collectd.conf file (not that that seems to matter in your case from your log file).</p> <p>Put your foobar.pm module at <strong><em><code>/path/to/perl/plugins/Coll...
1
2016-09-29T12:25:46Z
[ "python", "perl", "plugins", "registration", "collectd" ]
Check if Entry widget is selected
39,768,925
<p>I'm making a program on the Raspberry Pi with a touchscreen display. I'm using Python Tkinter that has two entry widgets and one on screen keypad. I want to use the same keypad for entering data on both entry widgets. </p> <p>Can anyone tell me how can i check if an entry is selected? Similar like clicking on the ...
0
2016-09-29T11:23:43Z
39,769,432
<p>You can use events and bindigs to catch FocusIn events for your entries.</p> <pre><code>entry1 = Entry(root) entry2 = Entry(root) def callback_entry1_focus(event): print 'entry1 focus in' def callback_entry2_focus(event): print 'entry2 focus in' entry1.bind("&lt;FocusIn&gt;", callback_entry1_focus) entry...
0
2016-09-29T11:46:19Z
[ "python", "tkinter", "raspberry-pi", "touchscreen", "raspberry-pi3" ]
Check if Entry widget is selected
39,768,925
<p>I'm making a program on the Raspberry Pi with a touchscreen display. I'm using Python Tkinter that has two entry widgets and one on screen keypad. I want to use the same keypad for entering data on both entry widgets. </p> <p>Can anyone tell me how can i check if an entry is selected? Similar like clicking on the ...
0
2016-09-29T11:23:43Z
39,770,561
<p>There is always a widget with the keyboard focus. You can query that with the <code>focus_get</code> method of the root window. It will return whatever widget has keyboard focus. That is the window that should receive input from your keypad. </p>
0
2016-09-29T12:37:55Z
[ "python", "tkinter", "raspberry-pi", "touchscreen", "raspberry-pi3" ]
Mongo TTL cleanup is not working
39,768,934
<p>I'm trying to get Mongo to remove documents with the TTL feature however without success. Have tried many things but mongo doesn't seem to clean up.</p> <p>My index:</p> <pre><code> { "v" : 1, "key" : { "date" : 1 }, "name" : "date_1", "ns" : "history.history", "expireAfterSecond...
4
2016-09-29T11:24:01Z
39,773,284
<p>As you have guessed, the problem is in how you insert the date value. I'll quote the <a href="https://docs.mongodb.com/manual/core/index-ttl/" rel="nofollow">docs</a>:</p> <blockquote> <p>If the indexed field in a document is not a date or an array that holds a date value(s), the document will not expire.</p> <...
2
2016-09-29T14:37:24Z
[ "python", "mongodb", "ttl" ]
how to delete entire row in csv file and save changes on same file?
39,769,041
<p>i'm new with python and try to modify csv file so i will able to delete specific rows with specific fields according to given list. in my current code i get the rows which i want to delete but i can't delete it and save the changes on same file (replace). </p> <pre><code> import os, sys, glob import time ,csv # O...
0
2016-09-29T11:29:03Z
39,769,261
<p>Read all the rows into a list using a <em>list comprehension</em> and excluding the unwanted rows. Then <em>rewrite</em> the rows to the file in mode <code>w</code> (write mode) which overwrites or replaces the content of the file:</p> <pre><code>with open(fileslst[-1], 'rb') as csvfile: csvReader = csv.reader(...
3
2016-09-29T11:38:56Z
[ "python", "csv" ]
data manipulation/ indexing python vs R
39,769,196
<p>I am inexperienced with python and am unsure what i should search for this particular task. I am trying to find a way to index a list much like i would index a vector in R:</p> <h1>R</h1> <pre><code>vec=c(1,2,3) &gt; vec==1 [1] TRUE FALSE FALSE </code></pre> <h1>python</h1> <pre><code>&gt;&gt;&gt; list_a=[1,2...
0
2016-09-29T11:36:24Z
39,769,295
<p>What about :</p> <pre><code>&gt;&gt;&gt; [x == 1 for x in list_a] [True, False, False] </code></pre>
3
2016-09-29T11:40:00Z
[ "python" ]
data manipulation/ indexing python vs R
39,769,196
<p>I am inexperienced with python and am unsure what i should search for this particular task. I am trying to find a way to index a list much like i would index a vector in R:</p> <h1>R</h1> <pre><code>vec=c(1,2,3) &gt; vec==1 [1] TRUE FALSE FALSE </code></pre> <h1>python</h1> <pre><code>&gt;&gt;&gt; list_a=[1,2...
0
2016-09-29T11:36:24Z
39,769,400
<p>an alternative:</p> <pre><code>map(lambda x: x == 1, list_a) #[True, False, False] </code></pre>
1
2016-09-29T11:44:54Z
[ "python" ]
Parse pandas df column with regex extracting substrings
39,769,300
<p>I have a pandas df containing a column composed of text like:</p> <pre><code>String1::some_text::some_text;String2::some_text::;String3::some_text::some_text;String4::some_text::some_text </code></pre> <p>I can see that:</p> <ol> <li>The start of the text always contains the first string I want to extract</li> <l...
0
2016-09-29T11:40:15Z
39,769,413
<p>try this:</p> <pre><code>In [136]: df.txt.str.findall(r'String\d+').str.join(', ') Out[136]: 0 String1, String2, String3, String4 Name: txt, dtype: object </code></pre> <p>Data:</p> <pre><code>In [137]: df Out[137]: ...
1
2016-09-29T11:45:23Z
[ "python", "regex", "pandas", "text" ]
Parse pandas df column with regex extracting substrings
39,769,300
<p>I have a pandas df containing a column composed of text like:</p> <pre><code>String1::some_text::some_text;String2::some_text::;String3::some_text::some_text;String4::some_text::some_text </code></pre> <p>I can see that:</p> <ol> <li>The start of the text always contains the first string I want to extract</li> <l...
0
2016-09-29T11:40:15Z
39,772,859
<p>consider the dataframe <code>df</code> with column <code>txt</code></p> <pre><code>df = pd.DataFrame(['String1::some_text::some_text;String2::some_text::;String3::some_text::some_text;String4::some_text::some_text'] * 10, columns=['txt']) df </code></pre> <p><a href="http://i.stack.imgur.com/bMdd...
1
2016-09-29T14:18:45Z
[ "python", "regex", "pandas", "text" ]
Parse pandas df column with regex extracting substrings
39,769,300
<p>I have a pandas df containing a column composed of text like:</p> <pre><code>String1::some_text::some_text;String2::some_text::;String3::some_text::some_text;String4::some_text::some_text </code></pre> <p>I can see that:</p> <ol> <li>The start of the text always contains the first string I want to extract</li> <l...
0
2016-09-29T11:40:15Z
39,773,002
<p>I would just apply a lambda function to do the operation you want to do (split first on ";", then split on "::" and keep the first element, and join them back):</p> <pre><code>df['new_col'] = df['old_col'].apply(lambda s: ", ".join(t.split("::")[0] for t in s.split(";"))) </code></pre> <p>You could also avoid spli...
0
2016-09-29T14:24:40Z
[ "python", "regex", "pandas", "text" ]
AWS Default region not setting using env variable in boto
39,769,527
<p>Python terminal below</p> <pre><code>In [3]: os.environ['AWS_DEFAULT_REGION'] Out[3]: 'us-west-2' In [4]: import boto In [5]: boto.connect_ec2() Out[5]: EC2Connection:ec2.ap-southeast-1.amazonaws.com </code></pre> <p>AWS Default region is not getting set even after using <code>AWS_DEFAULT_REGION</code> as env va...
0
2016-09-29T11:49:48Z
39,785,007
<p><strong>Solution:</strong> </p> <p><code>AWS_DEFAULT_REGION</code> works only with <code>boto3</code>. I was using <code>boto2</code>. Environment variables for region is not supported in <code>boto2</code>.</p> <p>Updating the <code>boto.cfg</code> fixed the <code>problem</code>.</p>
0
2016-09-30T06:26:52Z
[ "python", "amazon-web-services", "boto" ]
Detect and count numerical sequence in Python array
39,769,564
<p>In a numerical sequence (e.g. one-dimensional array) I want to find different patterns of numbers and count each finding separately. However, the numbers can occur repeatedly but only the basic pattern is important. </p> <pre><code># Example signal (1d array) a = np.array([1,1,2,2,2,2,1,1,1,2,1,1,2,3,3,3,3,3,2,2,1,...
-1
2016-09-29T11:51:38Z
39,770,223
<p>I don't use NumPy and I am quite new to Python, so there might be a better and more efficient solution.</p> <p>I would write a function like this:</p> <pre><code>def dac(data, pattern): count = 0 for i in range(len(data)-len(pattern)+1): tmp = data[i:(i+len(pattern))] if tmp == pattern: ...
2
2016-09-29T12:21:58Z
[ "python", "arrays", "numbers", "detection" ]
Detect and count numerical sequence in Python array
39,769,564
<p>In a numerical sequence (e.g. one-dimensional array) I want to find different patterns of numbers and count each finding separately. However, the numbers can occur repeatedly but only the basic pattern is important. </p> <pre><code># Example signal (1d array) a = np.array([1,1,2,2,2,2,1,1,1,2,1,1,2,3,3,3,3,3,2,2,1,...
-1
2016-09-29T11:51:38Z
39,770,233
<p>Here's a one-liner that will do it</p> <pre><code>import numpy as np a = np.array([1,1,2,2,2,2,1,1,1,2,1,1,2,3,3,3,3,3,2,2,1,1,1]) p = np.array([1,2,1]) num = sum(1 for k in [a[j:j+len(p)] for j in range(len(a) - len(p) + 1)] if np.array_equal(k, p)) </code></pre> <p>The innermost part is a ...
1
2016-09-29T12:22:19Z
[ "python", "arrays", "numbers", "detection" ]
Detect and count numerical sequence in Python array
39,769,564
<p>In a numerical sequence (e.g. one-dimensional array) I want to find different patterns of numbers and count each finding separately. However, the numbers can occur repeatedly but only the basic pattern is important. </p> <pre><code># Example signal (1d array) a = np.array([1,1,2,2,2,2,1,1,1,2,1,1,2,3,3,3,3,3,2,2,1,...
-1
2016-09-29T11:51:38Z
39,772,046
<p>The only way I could think of solving your problem with the subpatterns matching was to use <code>regex</code>.</p> <p>The following is a demonstration for findind for example the sequence <code>[1,2,1]</code> in <code>list1</code>:</p> <pre><code>import re list1 = [1,1,2,2,2,2,1,1,1,2,1,1,2,3,3,3,3,3,2,2,1,1,1]...
1
2016-09-29T13:43:52Z
[ "python", "arrays", "numbers", "detection" ]
Python, create new list based on condition applied to an existing list of same length
39,769,958
<p>Ok, I'm sure there is a very easy way to do this, but I'm rusty in python and I can't work out the pythonic way to do this.</p> <p>I have a list, representing the hours of the day:</p> <pre><code>import numpy as np hourOfDay = np.mod(range(0, 100), 24) </code></pre> <p>Then I want to create a new list which is a ...
3
2016-09-29T12:10:23Z
39,770,093
<p>Your list comprehension was slightly off. Also if you want <code>0.4</code> when the hour is between <code>7</code> and <code>22</code>, you need <code>7&lt;= hour &lt;= 22</code>:</p> <pre><code>import numpy as np hourOfDay = np.mod(range(0, 100), 24) newList = [0.4 if 7 &lt;= i &lt;= 22 else 0.2 for i in hourOfD...
1
2016-09-29T12:16:19Z
[ "python", "list", "numpy" ]
Python, create new list based on condition applied to an existing list of same length
39,769,958
<p>Ok, I'm sure there is a very easy way to do this, but I'm rusty in python and I can't work out the pythonic way to do this.</p> <p>I have a list, representing the hours of the day:</p> <pre><code>import numpy as np hourOfDay = np.mod(range(0, 100), 24) </code></pre> <p>Then I want to create a new list which is a ...
3
2016-09-29T12:10:23Z
39,770,117
<p>You can use a mask, but note that for refusing of type casting you should create the first array with data type float.:</p> <pre><code>In [15]: hourOfDay = np.mod(range(0, 100), 24, dtype=np.float) In [16]: mask = np.logical_or(hourOfDay &lt;= 7, hourOfDay &gt;= 22) In [17]: hourOfDay[mask] = 0.4 In [19]: hourOf...
1
2016-09-29T12:17:16Z
[ "python", "list", "numpy" ]
Python, create new list based on condition applied to an existing list of same length
39,769,958
<p>Ok, I'm sure there is a very easy way to do this, but I'm rusty in python and I can't work out the pythonic way to do this.</p> <p>I have a list, representing the hours of the day:</p> <pre><code>import numpy as np hourOfDay = np.mod(range(0, 100), 24) </code></pre> <p>Then I want to create a new list which is a ...
3
2016-09-29T12:10:23Z
39,770,349
<p>One of the alternative approach is to use <code>map()</code> as:</p> <pre><code>map(lambda x: 0.4 if 7 &lt;= x &lt;= 22 else 0.2, hourOfDay) </code></pre>
1
2016-09-29T12:27:53Z
[ "python", "list", "numpy" ]
Is it possible to run Python without installation (without using packagers like py2exe)?
39,770,096
<p>We have a complex tool (coded in Python) for environment validation and configuration. It runs on various Windows flavors. We used this tool within the company so far. However now we want our support engineers to use it on the road. The problem is they will not have permissions to install Python in customer machines...
0
2016-09-29T12:16:25Z
39,770,711
<p>Suppose your script is <code>main.py</code>, </p> <ul> <li>copy all the contents of python directory to the directory it reside in </li> <li>search <code>python*.dll</code> in your windows directory and it to <code>project/python</code></li> <li>create <code>project/main.bat</code>:</li> </ul> <p><strong>main.bat<...
0
2016-09-29T12:45:05Z
[ "python", "dll", "installation", "python-standalone" ]
Write in pre-written xlsx format template in python
39,770,097
<p>I am a bit new in python now working in qgis to automates some time. I have an excel pre-written template file where i have to add different data in different columns.</p> <pre><code>outpufFile = open('d:/template.xlsx','w') for layer in QgsMapLayerRegistry.instance().mapLayers().values(): print layer.name() +...
0
2016-09-29T12:16:26Z
39,770,219
<p>You need a Python library that understands how to handle xlsx files: </p> <p><a href="https://openpyxl.readthedocs.io/en/default/" rel="nofollow">openpyxl</a>, for example.</p>
0
2016-09-29T12:21:54Z
[ "python", "excel" ]
Signal when all urls are loaded in Django
39,770,214
<p>I want to perform magic on all url patterns of django:</p> <p>If they don't have a name, then I want to give them an automated name.</p> <p>Unfortunately django seems to load the url patterns lazy. </p> <p>Implementing this magic-add-name-method is easy and not part of this question.</p> <p>The problem: Where to...
1
2016-09-29T12:21:40Z
39,773,972
<p>I wouldn't use signals to change the created urls after the fact but instead write a drop in replacement wrapper for <code>django.conf.urls.url</code>:</p> <pre><code>def url(*args, **kwargs): if 'name' not in kwargs: kwargs['name'] = modulename(args[1]) # Returns something like 'polls.indexview' ...
0
2016-09-29T15:10:03Z
[ "python", "django", "django-urls", "django-signals" ]
python mpl: how to plot a point on a graph of 3D vectors, and the head of an arrow
39,770,247
<p>I have the following code to generate a triangle (from some lines) and a vector in a 3D figure:</p> <pre><code>from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np import sys # D is the viewing direction. # P is the "eye" point. # A, B, and C are the points of the Triangle be...
2
2016-09-29T12:22:52Z
39,771,983
<ol> <li><p>Add the following line right after your <code>x.quiver...</code> line.</p> <pre><code>ax.scatter(P[0], P[1], P[2], c='r') </code></pre></li> <li><p>Add the following lines right after your <code>x.quiver...</code> line.</p> <pre><code>v = [0, 1, 0] end_v = P + v ax.quiver(end_v[0], end_v[1], end_v[2], v[0...
2
2016-09-29T13:41:37Z
[ "python", "numpy", "matplotlib", "vector", "point" ]
Prepend each line in a string python
39,770,268
<p>I have a variable that holds the below value:</p> <pre><code>From: test@example.com To: user1@us.oracle.com Date: Thu Sep 29 04:25:45 2016 Subject: IMAP Append Client FNBJL MIME-version: 1.0 Content-type: text/plain; charset=UTF-8; format=flowed hocks burdock steelworks propellants resource querying sitings bisc...
0
2016-09-29T12:24:15Z
39,771,006
<p>There are tons of ways to achieve what you want, here's few ones:</p> <pre><code>import re log = """From: test@example.com To: user1@us.oracle.com Date: Thu Sep 29 04:25:45 2016 Subject: IMAP Append Client FNBJL MIME-version: 1.0 Content-type: text/plain; charset=UTF-8; format=flowed hocks burdock steelworks pr...
1
2016-09-29T12:57:41Z
[ "python", "python-2.7" ]
Is there an operator form of map in python?
39,770,352
<p>In Mathematica it is possible to write Map[f,list] as f/@list where /@ is the operator form of Map. In python there is map(f, list) but is there a similar operator form or a package providing this?</p> <p>The application is that deeply nested transformations using many maps end up with a lot of brackets whereas op...
1
2016-09-29T12:28:07Z
39,770,551
<p>There is no easy way to do that. Python doesn't provide any way to define custom operators and the set of operators it provides are pretty standard and mostly used for things like numbers and strings. The <code>map</code> object doesn't support anything like that, but nothing prevents you from writing your own class...
2
2016-09-29T12:37:35Z
[ "python", "functional-programming" ]
Scikit-learn, get accuracy scores for each class
39,770,376
<p>Is there a built-in way for getting accuracy scores for each class separatetly? I know in sklearn we can get overall accuracy by using <code>metric.accuracy_score</code>. Is there a way to get the breakdown of accuracy scores for individual classes? Something similar to <code>metrics.classification_report</code>.</p...
1
2016-09-29T12:29:03Z
39,770,819
<p>You can code it by yourself : the accuracy is nothing more than the ratio between the well classified samples (true positives and true negatives) and the total number of samples you have.</p> <p>Then, for a given class, instead of considering all the samples, you only take into account those of your class.</p> <p>...
2
2016-09-29T12:49:57Z
[ "python", "machine-learning", "scikit-learn" ]
Import Errror for python pg module
39,770,527
<p>I am having trouble using the pg module in my code. I've installed it using pip. But when I go to run it I get the following error:</p> <pre><code>Traceback (most recent call last): File "Contract_gen.py", line 2, in &lt;module&gt; import pg File "C:\Python27\lib\site-packages\pg\__init__.py", line 1, in &l...
-1
2016-09-29T12:36:16Z
39,771,237
<p>It seems like to require the <code>GLFW3</code> library. Download &amp; install it and the error should be gone. If you use macOS you can get it via <code>brew</code>.</p>
0
2016-09-29T13:09:25Z
[ "python", "module", "pg" ]
Numpy 2D array indexing without out of bound and with clipping value
39,770,863
<p>I have indices array </p> <pre><code>a = np.array([ [0, 0], [1, 1], [1, 9] ]) </code></pre> <p>And 2D array</p> <pre><code>b = np.array([ [0, 1, 2, 3], [5, 6, 7, 8] ]) </code></pre> <p>I can do this one</p> <pre><code>b[a[:, 0], a[:, 1]] </code></pre> <p>But it'll be an exception '<strong>out of...
3
2016-09-29T12:51:43Z
39,771,165
<p>Here's an approach -</p> <pre><code>def indexing_with_clipping(arr, indices, clipping_value=0): idx = np.where(indices &lt; arr.shape,indices,clipping_value) return arr[idx[:, 0], idx[:, 1]] </code></pre> <p>Sample runs -</p> <pre><code>In [266]: arr Out[266]: array([[0, 1, 2, 3], [5, 6, 7, 8]]) ...
1
2016-09-29T13:05:25Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
Numpy 2D array indexing without out of bound and with clipping value
39,770,863
<p>I have indices array </p> <pre><code>a = np.array([ [0, 0], [1, 1], [1, 9] ]) </code></pre> <p>And 2D array</p> <pre><code>b = np.array([ [0, 1, 2, 3], [5, 6, 7, 8] ]) </code></pre> <p>I can do this one</p> <pre><code>b[a[:, 0], a[:, 1]] </code></pre> <p>But it'll be an exception '<strong>out of...
3
2016-09-29T12:51:43Z
39,771,262
<p>You can use list comprehension:</p> <pre><code>b[ [min(x,len(b[0])-1) for x in a[:,0]], [min(x,len(b[1])-1) for x in a[:,1]] ] </code></pre> <p><strong>edit</strong> I used last array value as your clipping value, but you can replace the <code>min()</code> function with whatever you want (e.g. trenary oper...
1
2016-09-29T13:10:10Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
Can the runtime of calling Python from Excel (via xlwings RunPython) be improved?
39,770,894
<p>I have written a Python script which uses the xlwings library, in order to get the function inputs from a particular spreadsheet. The idea is for me to run this code from Excel (having imported the xlwings module as a VBA module). I can either run it like this (i.e. from Excel, using the RunPython command in VBA) or...
0
2016-09-29T12:52:43Z
39,773,115
<p>Currently, the default behaviour of xlwings is to fire up a new interpreter session everytime you call <code>RunPython</code>. This naturally comes with an overhead, although on modern systems it's usually just an additional 2-3 seconds rather than what you see.<br> On Windows you can however switch <code>OPTIMIZED_...
0
2016-09-29T14:29:46Z
[ "python", "excel", "vba", "pycharm", "xlwings" ]
Python Boolean comparison
39,771,027
<p>I'm testing Python's Boolean expressions. When I run the following code:</p> <pre><code>x = 3 print type(x) print (x is int) print (x is not int) </code></pre> <p>I get the following results:</p> <pre><code>&lt;type 'int'&gt; False True </code></pre> <p>Why is (x is int) returning false and (x is not int) return...
1
2016-09-29T12:58:46Z
39,771,204
<p>The best way to do this is use <code>isinstance()</code></p> <p>so in your case:</p> <pre><code>x = 3 print isinstance(x, int) </code></pre> <p>Regarding python <code>is</code></p> <blockquote> <p>The operators <code>is</code> and <code>is not</code> test for object identity: x is y is true if and only if x ...
2
2016-09-29T13:07:45Z
[ "python", "boolean", "boolean-logic", "boolean-expression" ]
Python Boolean comparison
39,771,027
<p>I'm testing Python's Boolean expressions. When I run the following code:</p> <pre><code>x = 3 print type(x) print (x is int) print (x is not int) </code></pre> <p>I get the following results:</p> <pre><code>&lt;type 'int'&gt; False True </code></pre> <p>Why is (x is int) returning false and (x is not int) return...
1
2016-09-29T12:58:46Z
39,771,338
<p>If you want to use <code>is</code> you should do:</p> <pre><code>&gt;&gt;&gt; print (type(x) is int) True </code></pre>
0
2016-09-29T13:13:40Z
[ "python", "boolean", "boolean-logic", "boolean-expression" ]
Python Boolean comparison
39,771,027
<p>I'm testing Python's Boolean expressions. When I run the following code:</p> <pre><code>x = 3 print type(x) print (x is int) print (x is not int) </code></pre> <p>I get the following results:</p> <pre><code>&lt;type 'int'&gt; False True </code></pre> <p>Why is (x is int) returning false and (x is not int) return...
1
2016-09-29T12:58:46Z
39,771,421
<p>Try typing these into your interpreter: </p> <pre><code>type(x) int x is 3 x is not 3 type(x) is int type(x) is not int </code></pre> <p>The reason that <code>x is int</code> is false is that it is asking if the number <code>3</code> and the Python int class represent the same object. It should be fairly clear tha...
1
2016-09-29T13:17:33Z
[ "python", "boolean", "boolean-logic", "boolean-expression" ]
Why is the adjoint of a matrix in numpy obtained by np.matrix.getH()
39,771,056
<p>when I want to get the adjoint of a numpy array, I have to type</p> <pre><code>A = np.matrix([...]) A.getH() </code></pre> <p>I am curious about the naming. Why is it</p> <pre><code>np.matrix.getH()? </code></pre> <p>In contrast, transpose and conjugate are implemented as</p> <pre><code>ndarray.transpose() ndar...
1
2016-09-29T13:00:01Z
39,771,380
<p>I think the complex conjugate or the <strong>Hermitian transpose</strong> of a matrix with complex entries <em>A*</em> obtained from <em>A</em> gives the adjoint matrix.</p> <p>Long story short, <strong>getH</strong> smells like <em>get Hermitian transpose</em>.</p>
3
2016-09-29T13:15:31Z
[ "python", "numpy" ]
Top-k on a list of dict in python
39,771,064
<p>Is there an easy way to perform the max k number of key:values pair in this example </p> <pre><code>s1 = {'val' : 0} s2 = {'val': 10} s3 = {'val': 5} s4 = {'val' : 4} s5 = {'val' : 6} s6 = {'val' : 7} s7 = {'val' : 3} shapelets = [s1,s2,s3,s4,s5,s6,s7] </code></pre> <p>I want to get the max 5 numbers in the shapel...
2
2016-09-29T13:00:24Z
39,771,145
<p>Here's a working example:</p> <pre><code>s1 = {'val': 0} s2 = {'val': 10} s3 = {'val': 5} s4 = {'val': 4} s5 = {'val': 6} s6 = {'val': 7} s7 = {'val': 3} shapelets = [s1, s2, s3, s4, s5, s6, s7] print(sorted(shapelets, key=lambda x: x['val'])[-5:]) </code></pre>
2
2016-09-29T13:04:32Z
[ "python", "list", "dictionary" ]
Top-k on a list of dict in python
39,771,064
<p>Is there an easy way to perform the max k number of key:values pair in this example </p> <pre><code>s1 = {'val' : 0} s2 = {'val': 10} s3 = {'val': 5} s4 = {'val' : 4} s5 = {'val' : 6} s6 = {'val' : 7} s7 = {'val' : 3} shapelets = [s1,s2,s3,s4,s5,s6,s7] </code></pre> <p>I want to get the max 5 numbers in the shapel...
2
2016-09-29T13:00:24Z
39,771,309
<p>You can use <a href="https://docs.python.org/3.0/library/heapq.html" rel="nofollow"><code>heapq</code></a>:</p> <pre><code>import heapq s1 = {'val': 0} s2 = {'val': 10} s3 = {'val': 5} s4 = {'val': 4} s5 = {'val': 6} s6 = {'val': 7} s7 = {'val': 3} shapelets = [s1, s2, s3, s4, s5, s6, s7] heapq.nlargest(5,[dct['v...
1
2016-09-29T13:12:35Z
[ "python", "list", "dictionary" ]
Top-k on a list of dict in python
39,771,064
<p>Is there an easy way to perform the max k number of key:values pair in this example </p> <pre><code>s1 = {'val' : 0} s2 = {'val': 10} s3 = {'val': 5} s4 = {'val' : 4} s5 = {'val' : 6} s6 = {'val' : 7} s7 = {'val' : 3} shapelets = [s1,s2,s3,s4,s5,s6,s7] </code></pre> <p>I want to get the max 5 numbers in the shapel...
2
2016-09-29T13:00:24Z
39,771,876
<p>You could do it in linear time using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html" rel="nofollow">numpy.argpartition</a>:</p> <pre><code>from operator import itemgetter import numpy as np arr = np.array(list(map(itemgetter("val"), shapelets))) print(arr[np.argpartition(arr, ...
1
2016-09-29T13:37:08Z
[ "python", "list", "dictionary" ]
Python gradient descent - cost keeps increasing
39,771,075
<p>I'm trying to implement gradient descent in python and my loss/cost keeps increasing with every iteration.</p> <p>I've seen a few people post about this, and saw an answer here: <a href="http://stackoverflow.com/questions/17784587/gradient-descent-using-python-and-numpy">gradient descent using python and numpy</a><...
2
2016-09-29T13:00:51Z
39,771,368
<p>Assuming that your derivation of the gradient is correct, you are using: <code>=-</code> and you should be using: <code>-=</code>. Instead of updating <code>theta</code>, you are reassigning it to <code>- (alpha * gradient)</code></p> <p>EDIT (after the above issue was fixed in the code):</p> <p>I ran what the cod...
2
2016-09-29T13:14:53Z
[ "python", "numpy", "machine-learning", "regression", "gradient-descent" ]
Python gradient descent - cost keeps increasing
39,771,075
<p>I'm trying to implement gradient descent in python and my loss/cost keeps increasing with every iteration.</p> <p>I've seen a few people post about this, and saw an answer here: <a href="http://stackoverflow.com/questions/17784587/gradient-descent-using-python-and-numpy">gradient descent using python and numpy</a><...
2
2016-09-29T13:00:51Z
39,779,431
<p>In general, if your cost is increasing, then the very first thing you should check is to see if your learning rate is too large. In such cases, the rate is causing the cost function to jump over the optimal value and increase upwards to infinity. Try different small values of your learning rate. When I face the prob...
1
2016-09-29T20:28:59Z
[ "python", "numpy", "machine-learning", "regression", "gradient-descent" ]
Import Pandas Into Python
39,771,274
<p>I just installed Python 3.5.2. I am working in the shell/IDLE environment and attempting to import Pandas. </p> <p>However when I write: import pandas </p> <p>I get the following:</p> <pre><code>Traceback (most recent call last): File "C:/Users/bartogre/Desktop/Program1.py", line 1, in &lt;module&gt; import...
1
2016-09-29T13:10:47Z
39,781,034
<p>A bit of background: a system can have multiple Python installations. On Windows, each is a directory with python.exe and Lib/site-packages/. To use a package with a particular python.exe, you must install into the corresponding site-packages.</p> <p>In your case, 'python' invokes 'C:\Program Files (x86)\Anaconda...
0
2016-09-29T22:34:08Z
[ "python", "pandas", "importerror", "python-3.5" ]
Import Pandas Into Python
39,771,274
<p>I just installed Python 3.5.2. I am working in the shell/IDLE environment and attempting to import Pandas. </p> <p>However when I write: import pandas </p> <p>I get the following:</p> <pre><code>Traceback (most recent call last): File "C:/Users/bartogre/Desktop/Program1.py", line 1, in &lt;module&gt; import...
1
2016-09-29T13:10:47Z
39,812,411
<p>This is all great feedback - I installed via the conda. And, I am using Spyder over the ILDE environment. Please the below from CMD.</p> <p>Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved.</p> <p>C:\Windows\system32>conda install pyodbc Using Anaconda Cloud api s...
0
2016-10-01T23:24:51Z
[ "python", "pandas", "importerror", "python-3.5" ]
how to slice and combine specific row values in a Pandas groupby?
39,771,306
<p>Consider the following dataframe</p> <pre><code>df = pd.DataFrame({'group1' : ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'], 'group2' : ['C', 'C', 'C', 'C', 'C', 'E', 'E', 'E'], 'time' : [-6,-5,-4,-3,-2,-6,-3,-4] , ...
2
2016-09-29T13:12:26Z
39,771,656
<p>You could do it without <code>groupby</code> like this:</p> <pre><code>dfm = pd.merge(df[df.time == -4],df[df.time == -6],on=["group1","group2"]) dfm['Div'] = dfm.col_y.div(dfm.col_x) df = pd.merge(df,dfm[['group1','group2','Div']],on=["group1","group2"]) </code></pre> <p>Output:</p> <pre><code> col group1 grou...
4
2016-09-29T13:27:08Z
[ "python", "pandas" ]
how to slice and combine specific row values in a Pandas groupby?
39,771,306
<p>Consider the following dataframe</p> <pre><code>df = pd.DataFrame({'group1' : ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'], 'group2' : ['C', 'C', 'C', 'C', 'C', 'E', 'E', 'E'], 'time' : [-6,-5,-4,-3,-2,-6,-3,-4] , ...
2
2016-09-29T13:12:26Z
39,772,563
<p>Your solution in a ridiculously long list iteration (most pythonic way btw). Also, your question makes sense but the ratio for group A,C you have listed as 1/4 is actually 1/3</p> <pre><code>summary = [(name,group[group.time == -6].col.values[0],group[group.time == -4].col.values[0]) for name,group in df.groupby(['...
1
2016-09-29T14:04:58Z
[ "python", "pandas" ]
how to slice and combine specific row values in a Pandas groupby?
39,771,306
<p>Consider the following dataframe</p> <pre><code>df = pd.DataFrame({'group1' : ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'], 'group2' : ['C', 'C', 'C', 'C', 'C', 'E', 'E', 'E'], 'time' : [-6,-5,-4,-3,-2,-6,-3,-4] , ...
2
2016-09-29T13:12:26Z
39,772,974
<p>Another way using <code>groupby</code> with a custom function:</p> <pre><code>def time_selection(row): N_r = row.loc[row['time'] == -6, 'col'].squeeze() D_r = row.loc[row['time'] == -4, 'col'].squeeze() return (N_r/D_r) pd.merge(df, df.groupby(['group1','group2']).apply(time_selection).reset_index(name...
1
2016-09-29T14:23:34Z
[ "python", "pandas" ]
confused about the readline() return in Python
39,771,366
<p>I am a beginner in python. However, I have some problems when I try to use the readline() method.</p> <pre><code>f=raw_input("filename&gt; ") a=open(f) print a.read() print a.readline() print a.readline() print a.readline() </code></pre> <p>and my txt file is </p> <pre><code>aaaaaaaaa bbbbbbbbb ccccccccc </code><...
1
2016-09-29T13:14:49Z
39,771,467
<p>When you open a file you get a pointer to some place of the file (by default: the begining). Now whenever you run <code>.read()</code> or <code>.readline()</code> this pointer moves:</p> <ol> <li><code>.read()</code> reads until the end of the file and moves the pointer to the end (thus further calls to any reading...
5
2016-09-29T13:19:18Z
[ "python" ]
confused about the readline() return in Python
39,771,366
<p>I am a beginner in python. However, I have some problems when I try to use the readline() method.</p> <pre><code>f=raw_input("filename&gt; ") a=open(f) print a.read() print a.readline() print a.readline() print a.readline() </code></pre> <p>and my txt file is </p> <pre><code>aaaaaaaaa bbbbbbbbb ccccccccc </code><...
1
2016-09-29T13:14:49Z
39,771,555
<p>You need to understand the concept of file pointers. When you read the file, it is fully consumed, and the pointer is at the end of the file. </p> <blockquote> <p>It seems that the readline() is not working at all. </p> </blockquote> <p>It is working as expected. There are no lines to read. </p> <blockquote> ...
1
2016-09-29T13:23:15Z
[ "python" ]
confused about the readline() return in Python
39,771,366
<p>I am a beginner in python. However, I have some problems when I try to use the readline() method.</p> <pre><code>f=raw_input("filename&gt; ") a=open(f) print a.read() print a.readline() print a.readline() print a.readline() </code></pre> <p>and my txt file is </p> <pre><code>aaaaaaaaa bbbbbbbbb ccccccccc </code><...
1
2016-09-29T13:14:49Z
39,771,607
<p>The file object <code>a</code> remembers it's position in the file.</p> <ul> <li><code>a.read()</code> reads from the current position to end of the file (moving the position to the end of the file)</li> <li><code>a.readline()</code> reads from the current position to the end of the line (moving the position to the...
0
2016-09-29T13:25:03Z
[ "python" ]
Addition speed of numpy arrays with different contiguous-type
39,771,450
<p>Numpy arrays are stored with different contiguous types (C- and F-). When using numpy.swapaxes(), the contiguous type gets changed. I need to add two multidimensional arrays (3d to be more specific), one of which comes from another array with swapped axes. What I've noticed is that when the first axis gets swapped w...
0
2016-09-29T13:18:37Z
39,771,851
<p>These types (<code>F</code> and <code>C</code>) denote whether a matrix (or multi-dimensional array) is stored in column-major (<code>C</code> as in C language which uses column-major storage) or row-major (<code>F</code> as in Fortran language which uses row-major storage).</p> <p>Both do not really vary in speed....
0
2016-09-29T13:35:52Z
[ "python", "arrays", "performance", "numpy", "contiguous" ]