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
Script execution time on different computers (python 3.5, miniconda)
38,737,144
<p>I was faced with the following problem: on a computer (number 2) script execution time is significantly greater than on another computer (computer 1).</p> <ul> <li>Computer 1 - i3 - 4170 CPU @ 3.7 GHz (4 core), 4GB RAM (Execution time 9.5 minutes)</li> <li>Computer 2 - i7 - 3.07GHz (8 core), 8GB RAM (Execution time...
0
2016-08-03T07:31:21Z
38,737,237
<p>It runs on single core, the computer1 has higher clock rate = faster single threaded processing.</p>
1
2016-08-03T07:35:15Z
[ "python", "excel", "python-3.5", "execution-time", "miniconda" ]
Script execution time on different computers (python 3.5, miniconda)
38,737,144
<p>I was faced with the following problem: on a computer (number 2) script execution time is significantly greater than on another computer (computer 1).</p> <ul> <li>Computer 1 - i3 - 4170 CPU @ 3.7 GHz (4 core), 4GB RAM (Execution time 9.5 minutes)</li> <li>Computer 2 - i7 - 3.07GHz (8 core), 8GB RAM (Execution time...
0
2016-08-03T07:31:21Z
38,737,662
<p>As explained in a comment, Python uses the <a href="https://en.wikipedia.org/wiki/Global_interpreter_lock" rel="nofollow">Global Interpreter Lock (GIL)</a>. As stated on the Wiki: "An interpreter that uses GIL always allows <strong>exactly one thread</strong> to execute at a time, <strong>even if run on a multi-core...
0
2016-08-03T07:57:08Z
[ "python", "excel", "python-3.5", "execution-time", "miniconda" ]
Extracting key value pairs from string with quotes
38,737,250
<p>I am having trouble coding an 'elegant' parser for this requirement. (One that does not look like a piece of C breakfast). The input is a string, key value pairs separated by ',' and joined '='.</p> <pre><code>key1=value1,key2=value2 </code></pre> <p>The part tricking me is values can be quoted (") , and inside th...
3
2016-08-03T07:35:59Z
38,738,277
<p>I'm not sure that it does not look like piece of C breakfast and that it is quite elegant :)</p> <pre><code>data = {} original = 'key1=value1,key2="value2,still_value2"' converted = '' is_open = False for c in original: if c == ',' and not is_open: c = '\n' elif c in ('"',"'"): is_open = no...
2
2016-08-03T08:25:58Z
[ "python", "parsing" ]
Extracting key value pairs from string with quotes
38,737,250
<p>I am having trouble coding an 'elegant' parser for this requirement. (One that does not look like a piece of C breakfast). The input is a string, key value pairs separated by ',' and joined '='.</p> <pre><code>key1=value1,key2=value2 </code></pre> <p>The part tricking me is values can be quoted (") , and inside th...
3
2016-08-03T07:35:59Z
38,738,409
<p>Using some regex magic from <a href="http://stackoverflow.com/questions/16710076/python-split-a-string-respect-and-preserve-quotes">Split a string, respect and preserve quotes</a>, we can do:</p> <pre><code>import re string = 'key1=value1,key2="value2,still_value2"' key_value_pairs = re.findall(r'(?:[^\s,"]|"(?:\...
5
2016-08-03T08:32:07Z
[ "python", "parsing" ]
Extracting key value pairs from string with quotes
38,737,250
<p>I am having trouble coding an 'elegant' parser for this requirement. (One that does not look like a piece of C breakfast). The input is a string, key value pairs separated by ',' and joined '='.</p> <pre><code>key1=value1,key2=value2 </code></pre> <p>The part tricking me is values can be quoted (") , and inside th...
3
2016-08-03T07:35:59Z
38,738,508
<p>I came up with this regular expression solution:</p> <pre><code>import re match = re.findall(r'([^=]+)=(("[^"]+")|([^,]+)),?', 'key1=value1,key2=value2,key3="value3,stillvalue3",key4=value4') </code></pre> <p>And this makes "match":</p> <pre><code>[('key1', 'value1', '', 'value1'), ('key2', 'value2', '', 'value2'...
3
2016-08-03T08:37:03Z
[ "python", "parsing" ]
Extracting key value pairs from string with quotes
38,737,250
<p>I am having trouble coding an 'elegant' parser for this requirement. (One that does not look like a piece of C breakfast). The input is a string, key value pairs separated by ',' and joined '='.</p> <pre><code>key1=value1,key2=value2 </code></pre> <p>The part tricking me is values can be quoted (") , and inside th...
3
2016-08-03T07:35:59Z
38,738,754
<p>Based on several other answers, I came up with the following solution:</p> <pre><code>import re import itertools data = 'key1=value1,key2="value2,still_value2"' # Based on Alan Moore's answer on http://stackoverflow.com/questions/2785755/how-to-split-but-ignore-separators-in-quoted-strings-in-python def split_on_...
1
2016-08-03T08:48:45Z
[ "python", "parsing" ]
Extracting key value pairs from string with quotes
38,737,250
<p>I am having trouble coding an 'elegant' parser for this requirement. (One that does not look like a piece of C breakfast). The input is a string, key value pairs separated by ',' and joined '='.</p> <pre><code>key1=value1,key2=value2 </code></pre> <p>The part tricking me is values can be quoted (") , and inside th...
3
2016-08-03T07:35:59Z
38,738,997
<p>I would advise against using regular expressions for this task, because the language you want to parse is not regular.</p> <p>You have a character string of multiple key value pairs. The best way to parse this is not to match patterns on it, but to properly tokenize it.</p> <p>There is a module in the Python stand...
2
2016-08-03T09:00:01Z
[ "python", "parsing" ]
Redis - Pyredis iterating through results from SINTER on SET
38,737,271
<p>I have 2 SET structures with the following values added:</p> <pre><code>r.sadd("clONE", 'abc') r.sadd("clONE", 'def') r.sadd("clONE", 'ghi') r.sadd("TWO", 'abc') r.sadd("TWO", 'def') print(r.sinter("clONE", "TWO")) OUTPUT: set(['abc', 'def']) </code></pre> <p>How do I get the value 'abc' and the 'def' out of th...
0
2016-08-03T07:37:01Z
38,738,248
<p>sets are not indexed. The order depends on the internal hash. Never rely on the order in a set, even if it appears logical.</p> <p>You can do the following:</p> <pre><code>s = r.sinter("clONE", "TWO") # iterate through the set, unsorted for i in s: print(i) </code></pre> <p>or</p> <pre><code>l = sorted(s) ...
1
2016-08-03T08:24:21Z
[ "python", "redis" ]
How can I use global variable in python class?
38,737,314
<p>the Java code runs, while python code not, why? How can I access global variable inside class in Python?</p> <p><strong>Python code:</strong></p> <pre><code>Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None ...
1
2016-08-03T07:39:06Z
38,737,429
<p>Try this instead: </p> <pre><code> class Solution(object): previous = None def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True if not self.isValidBST(root.left): ...
0
2016-08-03T07:45:34Z
[ "java", "python" ]
How can I use global variable in python class?
38,737,314
<p>the Java code runs, while python code not, why? How can I access global variable inside class in Python?</p> <p><strong>Python code:</strong></p> <pre><code>Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None ...
1
2016-08-03T07:39:06Z
38,738,029
<p>You should simply use global keyword. As previous = None is defined outside class Solution, so to use same variable inside class, add a line.</p> <pre><code>global previous if previous!=None and previous &gt;= root.val: your logic </code></pre> <p>this will do your work. </p>
0
2016-08-03T08:13:15Z
[ "java", "python" ]
replacing the values in a numpy array with the values of another array against value of one array as index in another
38,737,403
<p>I want to change the values in a numpy <strong>array(x)</strong> corresponding to the value in numpy <strong>array(y)</strong> at <code>index = x[index]</code></p> <p>A numpy array <code>x = [1,2,3,4,0,1,2,3]</code> another Numpy Array <code>y = [3,4,0,1,2]</code></p> <pre><code>for i in range(len(x)): x[i] = ...
0
2016-08-03T07:43:49Z
38,737,460
<p>Use:</p> <pre><code>x = y[x] </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x = np.array( [1,2,3,4,0,1,2,3] ) &gt;&gt;&gt; y = np.array( [3,4,0,1,2] ) &gt;&gt;&gt; y[x] array([4, 0, 1, 2, 3, 4, 0, 1]) </code></pre> <p>Or, to demonstrate assignment:</p> <pre><code>&gt;&gt;&...
0
2016-08-03T07:47:21Z
[ "python", "numpy" ]
how ctypes bitfields really work?
38,737,497
<p>In python, using ctypes, following is legal:</p> <pre><code>from ctypes import * class POINT(Structure): _fields_ = [("x", c_int), ("y", c_int)] p = POINT(10,20) sum = p.x + p.y </code></pre> <p>But how this works? I mean how p.x is perfectly legal? What kind of trick provides this? thanks.</p>
0
2016-08-03T07:48:50Z
38,738,032
<p>When you initialize an instance of a subclass the <code>Structure</code> class it reads the <code>_fields_</code> and associates attributes based on the field names in that list. </p> <p>This is all done in C, so if you want to see exactly how it is done you need to use the source, in particular the definition of t...
2
2016-08-03T08:13:17Z
[ "python", "bit-fields" ]
what is the difference in ways setting indexes
38,737,528
<p>What is the difference between how I set index of the data frame?</p> <pre><code>data = [['A', 5], ['B', 6], ['C', 7]] df = pd.DataFrame(data=data, columns=['key', 'amount'], index= ['key']) </code></pre> <p>I get following error:</p> <pre><code>Shape of passed values is (2, 3), indices imply (2, 1) </code></pre>...
2
2016-08-03T07:50:29Z
38,737,661
<p>In the first way:</p> <pre><code>data = [['A', 5], ['B', 6], ['C', 7]] df = pd.DataFrame(data=data, columns=['key', 'amount'], index= ['key']) </code></pre> <p>You are specifying the index to be a single value of <code>'key'</code>. Said another way, there will be a single row whose label is <code>'key'</code>.</...
2
2016-08-03T07:57:03Z
[ "python", "pandas", "dataframe" ]
what is the difference in ways setting indexes
38,737,528
<p>What is the difference between how I set index of the data frame?</p> <pre><code>data = [['A', 5], ['B', 6], ['C', 7]] df = pd.DataFrame(data=data, columns=['key', 'amount'], index= ['key']) </code></pre> <p>I get following error:</p> <pre><code>Shape of passed values is (2, 3), indices imply (2, 1) </code></pre>...
2
2016-08-03T07:50:29Z
38,737,690
<p>On the one hand, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>pd.Dataframe</code></a> expects index to be an array, and will be used as index for the rows, for example :</p> <pre><code>In [17]: data Out[17]: [['A', 5], ['B', 6], ['C', 7]] In [18]: df = ...
2
2016-08-03T07:58:35Z
[ "python", "pandas", "dataframe" ]
Sorting words in query in alphabetical order and remove duplicate words from individual rows
38,737,561
<p>I want to sort the words of a given query from each row of Pandas DataFrame and then remove duplicates from them. How can I perform this task on each row separately like : Given DataFrame :</p> <pre><code>Sr.No | Query ------------- 1. war gears of war 2. call of duty 3. legend of troy legend 4. reside...
1
2016-08-03T07:51:57Z
38,737,751
<p>You can first create <code>Series</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>split</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>:</p> ...
1
2016-08-03T08:00:57Z
[ "python", "pandas" ]
Sorting words in query in alphabetical order and remove duplicate words from individual rows
38,737,561
<p>I want to sort the words of a given query from each row of Pandas DataFrame and then remove duplicates from them. How can I perform this task on each row separately like : Given DataFrame :</p> <pre><code>Sr.No | Query ------------- 1. war gears of war 2. call of duty 3. legend of troy legend 4. reside...
1
2016-08-03T07:51:57Z
38,737,858
<h3>Setup</h3> <pre><code>df = pd.DataFrame([ ['war gears of war'], ['call of duty'], ['legend of troy legend'], ['resident evil'], ], pd.Index(['1.', '2.', '3.', '4.'], name='Sr.No'), ['Query']) df </code></pre> <p><a href="http://i.stack.imgur.com/bh9IF.png" rel="nofollow"><im...
3
2016-08-03T08:05:42Z
[ "python", "pandas" ]
Import set of builtin functions from a python file to another python file
38,737,599
<p>I have set of inbuilt functions in 'pythonfile1.py' located at '/Users/testuser/Documents', the file contains</p> <pre><code>import os import sys import time </code></pre> <p>Now i want to import 'pythonfile1.py' to 'pythonfile2.py', which is located at '/Users/testuser/Documents/execute' I have tried with my foll...
1
2016-08-03T07:53:51Z
38,737,730
<p>if you want to import stuff from another file, you should use python modules.</p> <p>If you will create file named <strong>init</strong>.py then the execute folder becomes a module. After that you can use</p> <pre><code>from .pythonfile1 import function_name </code></pre> <p>or you can use</p> <pre><code>from .p...
0
2016-08-03T08:00:06Z
[ "python", "file" ]
Import set of builtin functions from a python file to another python file
38,737,599
<p>I have set of inbuilt functions in 'pythonfile1.py' located at '/Users/testuser/Documents', the file contains</p> <pre><code>import os import sys import time </code></pre> <p>Now i want to import 'pythonfile1.py' to 'pythonfile2.py', which is located at '/Users/testuser/Documents/execute' I have tried with my foll...
1
2016-08-03T07:53:51Z
38,739,470
<p>Your question is a bit unclear. Basically, there are two things 'wrong'. </p> <ul> <li><p>First, your import statement is broken:</p> <pre><code>import pythonfile1.py </code></pre> <p>This specifies a <strong>file</strong> name, not a <strong>module</strong> name - modules don't contain dots and extensions. This ...
1
2016-08-03T09:20:15Z
[ "python", "file" ]
The best way to check if all elements of a list matches a condition in for loop?
38,737,872
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition">How to check if all elements of a list matches a condition</a>. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like...
-3
2016-08-03T08:06:21Z
38,737,942
<p>Here: </p> <pre><code>items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] def check_list(items): for item in items: if item[2] != 0: return False return True print(check_list(items)) </code></pre> <p>If you want to make it a bit more generic:</p> <pre><code>def my_all(enumerable, condition)...
1
2016-08-03T08:10:00Z
[ "python", "list", "for-loop" ]
The best way to check if all elements of a list matches a condition in for loop?
38,737,872
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition">How to check if all elements of a list matches a condition</a>. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like...
-3
2016-08-03T08:06:21Z
38,737,947
<p>Try This:-</p> <pre><code>prinBool = True for item in items: if item[2] != 0: prinBool = False break print prinBool </code></pre>
0
2016-08-03T08:10:11Z
[ "python", "list", "for-loop" ]
The best way to check if all elements of a list matches a condition in for loop?
38,737,872
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition">How to check if all elements of a list matches a condition</a>. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like...
-3
2016-08-03T08:06:21Z
38,737,985
<p>You could use a <code>for</code> loop with the <code>else</code> clause:</p> <pre><code>for item in items: if item[2] != 0: print False break else: print True </code></pre> <p>The statements after <code>else</code> are executed when the items of a sequence are exhausted, i.e. when the loop wa...
0
2016-08-03T08:11:40Z
[ "python", "list", "for-loop" ]
The best way to check if all elements of a list matches a condition in for loop?
38,737,872
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition">How to check if all elements of a list matches a condition</a>. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like...
-3
2016-08-03T08:06:21Z
38,738,199
<p>Do you mean something like this?</p> <pre><code>for item in items: for x in range (0,3): if item[x] == 0: print "True" </code></pre>
-1
2016-08-03T08:21:27Z
[ "python", "list", "for-loop" ]
The best way to check if all elements of a list matches a condition in for loop?
38,737,872
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition">How to check if all elements of a list matches a condition</a>. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like...
-3
2016-08-03T08:06:21Z
38,738,231
<p>With <code>functools</code>, it will be easier : </p> <pre><code>from functools import reduce items = [[1, 2, 0], [1, 0, 1], [1, 2, 0]] f = lambda y,x : y and x[2] == 0 reduce(f,items) </code></pre>
0
2016-08-03T08:23:19Z
[ "python", "list", "for-loop" ]
The best way to check if all elements of a list matches a condition in for loop?
38,737,872
<p>My question is quite similar to <a href="http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition">How to check if all elements of a list matches a condition</a>. But I couldn't find a right way to do the same thing in a for loop. For example, using all in python is like...
-3
2016-08-03T08:06:21Z
38,738,276
<p>If you want to have an <code>if</code> and an <code>else</code>, you can still use the <code>any</code> method:</p> <pre><code>if any(item[2] == 0 for item in items): print('There is an item with item[2] == 0') else: print('There is no item with item[2] == 0') </code></pre> <p>The <code>any</code> comes fr...
1
2016-08-03T08:25:58Z
[ "python", "list", "for-loop" ]
TypeError: list indices must be integers, not str (boolean convertion actually)
38,737,955
<pre><code>import nltk import random from nltk.corpus import movie_reviews documents=[(list(movie_reviews.words(fileid)),category) for category in movie_reviews.categories() for fileid in movie_reviews.fileids(category)] random.shuffle(documents) #print(documents[1]) all_words=[] for w in movi...
1
2016-08-03T08:10:31Z
38,738,209
<p><code>features</code> must be initialized to a <code>dict</code> rather than a <code>list</code>. </p> <p>The error was because <code>word_features</code> is a list of <em>strings</em> which you were trying to index using a list and lists can't have string indices.</p> <pre><code>features={} for w in word_features...
2
2016-08-03T08:21:58Z
[ "python", "find", "movie", "review" ]
TypeError: list indices must be integers, not str (boolean convertion actually)
38,737,955
<pre><code>import nltk import random from nltk.corpus import movie_reviews documents=[(list(movie_reviews.words(fileid)),category) for category in movie_reviews.categories() for fileid in movie_reviews.fileids(category)] random.shuffle(documents) #print(documents[1]) all_words=[] for w in movi...
1
2016-08-03T08:10:31Z
38,738,263
<p>You have tried to index a list <code>features</code> with a string and it is not possible with python. <strong>List indices can only be integers</strong>. What you need is a <code>dictionary</code>. </p> <p>Try using a <code>defaultdict</code> meaning that even if a key is not found in the dictionary, instead of a ...
3
2016-08-03T08:25:26Z
[ "python", "find", "movie", "review" ]
Most reliable way to automatically choose line styles in matplotlib in combination with seaborn
38,738,019
<p>I'm looking for a reliable way to automatically choose line styles for my plots. Right now I have 8 lines for a plot and I hope it is feasible to automatically choose line styles that are distinguishable from each other. </p> <p>As of now, I have basically two ways. Setting markers or defining styles. Both seem to ...
6
2016-08-03T08:13:01Z
39,107,966
<p>If you want to keep the rcParams that you have in matplotlib and are using the latest version of seaborn (>= 0.7.1), the easiest way is to use <code>import seaborn.apionly</code> as explained in <a href="https://stanford.edu/~mwaskom/software/seaborn/whatsnew.html" rel="nofollow">what's new</a></p>
0
2016-08-23T18:05:43Z
[ "python", "matplotlib", "seaborn" ]
Where to activate my proxy setting in my django app
38,738,151
<p>I am trying send an activation mail to the users in my django app. I am developing in my company and it has proxy. So, when i try to send email to the user, it gives connection timeout error. But when i try it in my home it works perfectly. I have got the proxy settings from my company but I am confused where to upd...
0
2016-08-03T08:18:51Z
38,739,319
<p>Looks like you want to use HTTP proxy to access external SMTP server. It is feasible if your proxy server supports Socks or CONNECT methods. Consider using this libraries to wrap your smtp-related code:</p> <ol> <li><a href="http://socksipy.sourceforge.net/" rel="nofollow">http://socksipy.sourceforge.net/</a></li> ...
1
2016-08-03T09:14:22Z
[ "python", "django", "proxy" ]
Python enumerate reverse index only
38,738,548
<p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p> <p>Assume I have the following:</p> <pre><code>&gt;&gt; range(5) [0, 1, 2, 3, 4] </code></pre> <p>If I enumerate this I would get the following:</p> <pre><code>&gt;&gt; list(enum...
5
2016-08-03T08:38:41Z
38,738,634
<p>Just take the length of your list and subtract the index from that...</p> <pre><code>L = range(5) for i, n in L: my_i = len(L) -1 - i ... </code></pre> <p>Or if you really need a generator:</p> <pre><code>def reverse_enumerate(L): # Only works on things that have a len() l = len(L) for i, n in e...
1
2016-08-03T08:42:35Z
[ "python", "python-3.x", "reverse", "enumerate" ]
Python enumerate reverse index only
38,738,548
<p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p> <p>Assume I have the following:</p> <pre><code>&gt;&gt; range(5) [0, 1, 2, 3, 4] </code></pre> <p>If I enumerate this I would get the following:</p> <pre><code>&gt;&gt; list(enum...
5
2016-08-03T08:38:41Z
38,738,652
<p>How about using zip instead with a reversed range?</p> <pre><code>&gt;&gt;&gt; zip(range(9, -1, -1), range(10)) [(9, 0), (8, 1), (7, 2), (6, 3), (5, 4), (4, 5), (3, 6), (2, 7), (1, 8), (0, 9)] &gt;&gt;&gt; def reversedEnumerate(l): return zip(range(len(l)-1, -1, -1), l) &gt;&gt;&gt; reversedEnumerate(rang...
8
2016-08-03T08:43:26Z
[ "python", "python-3.x", "reverse", "enumerate" ]
Python enumerate reverse index only
38,738,548
<p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p> <p>Assume I have the following:</p> <pre><code>&gt;&gt; range(5) [0, 1, 2, 3, 4] </code></pre> <p>If I enumerate this I would get the following:</p> <pre><code>&gt;&gt; list(enum...
5
2016-08-03T08:38:41Z
38,738,731
<p>I don't know if this solution is better for you, but at least it's shorter:</p> <pre><code>&gt;&gt;&gt; [(4 - x, x) for x in range(5)] [(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)] </code></pre>
3
2016-08-03T08:47:57Z
[ "python", "python-3.x", "reverse", "enumerate" ]
Python enumerate reverse index only
38,738,548
<p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p> <p>Assume I have the following:</p> <pre><code>&gt;&gt; range(5) [0, 1, 2, 3, 4] </code></pre> <p>If I enumerate this I would get the following:</p> <pre><code>&gt;&gt; list(enum...
5
2016-08-03T08:38:41Z
38,738,806
<p>Assuming your list is not long and you will not run into performance errors, you may use <code>list(enumerate(range(5)[::-1]))[::-1]</code>.</p> <p>Test:</p> <p><code>&gt;&gt;&gt; list(enumerate(range(5)[::-1]))[::-1] [(0, 4), (1, 3), (2, 2), (3, 1), (4, 0)]</code></p>
1
2016-08-03T08:50:55Z
[ "python", "python-3.x", "reverse", "enumerate" ]
Python enumerate reverse index only
38,738,548
<p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p> <p>Assume I have the following:</p> <pre><code>&gt;&gt; range(5) [0, 1, 2, 3, 4] </code></pre> <p>If I enumerate this I would get the following:</p> <pre><code>&gt;&gt; list(enum...
5
2016-08-03T08:38:41Z
38,738,812
<p>Actually I'm using the same logic as @RemcoGerlich did, but I use <code>list comprehension</code> directly, which make the code now become 1-liner:</p> <pre><code>def generatelist(x): return [(x-1-i,n) for i,n in enumerate(range(x))] </code></pre> <p>Regarding the dilemma of choosing <code>generator</code> or ...
2
2016-08-03T08:51:15Z
[ "python", "python-3.x", "reverse", "enumerate" ]
Python enumerate reverse index only
38,738,548
<p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p> <p>Assume I have the following:</p> <pre><code>&gt;&gt; range(5) [0, 1, 2, 3, 4] </code></pre> <p>If I enumerate this I would get the following:</p> <pre><code>&gt;&gt; list(enum...
5
2016-08-03T08:38:41Z
38,738,832
<p>If you're going to re-use it several times, you can make your own generator:</p> <pre><code>def reverse_enum(lst): for j, item in enumerate(lst): yield len(lst)-1-j, item print list(reverse_enum(range(5))) # [(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)] </code></pre> <p>or</p> <pre><code>def reverse_enum(...
0
2016-08-03T08:52:21Z
[ "python", "python-3.x", "reverse", "enumerate" ]
Stream a huge Excel file, creating it on the fly?
38,738,655
<p>I'm writing a web application that might sometimes output dozens of thousands of rows (or even more) in an Excel file. openpyxl was chosen for Excel output preparation, but I'm not sure if I could read the data from the database and output it at the same time. Is there a way to do that? Here's an example of what I m...
2
2016-08-03T08:43:33Z
38,739,666
<p>openpyxl already provides a <code>write-only</code> mode designed for streaming use. However, as all XSLX files are actually zip files and, as the zip format does not allow streaming, it is not possible to stream XLSX files while they are being written.</p>
1
2016-08-03T09:29:31Z
[ "python", "excel", "streaming", "bigdata", "openpyxl" ]
How to drawing shapes using XLSXWriter
38,738,706
<p>I wana draw some simple shapes in excel file like as "arrow, line, rectangle, oval" using XLSXWriter, but i can find any example to do it. Is it possible ? If not, what library of python can do that ? Thanks!</p>
2
2016-08-03T08:46:35Z
38,740,317
<blockquote> <p>is it possible?</p> </blockquote> <p>Unfortunately not. Shapes aren't supported in XlsxWriter, apart from Textbox. </p>
0
2016-08-03T09:58:36Z
[ "python", "xlsxwriter" ]
Insert a value in json file with python
38,738,717
<p>For a project, I need to use json for store some values :</p> <pre><code>{ "Serial_011": "011", "Servers_011": [ { "hostname": "srv-a.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google....
0
2016-08-03T08:46:54Z
38,739,072
<p>You're appending a string value instead of the dictionary. Instead of:</p> <pre><code>dic['Servers_011'][0]['services'].append('{"uri":"http://www.google.com", "expected_code": 200}') </code></pre> <p>Do</p> <pre><code>dic['Servers_011'][0]['services'].append({"uri":"http://www.google.com", "expected_code": 200})...
0
2016-08-03T09:02:53Z
[ "python", "json" ]
Insert a value in json file with python
38,738,717
<p>For a project, I need to use json for store some values :</p> <pre><code>{ "Serial_011": "011", "Servers_011": [ { "hostname": "srv-a.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google....
0
2016-08-03T08:46:54Z
38,739,127
<pre><code>with open('test.json', 'r') as f: dic = json.load(f) dic['Servers_011'][0]['services'].append({"uri": "http://www.google.com", "expected_code": 200}) with open('test.json', 'w') as f: json.dump(dic, f) </code></pre>
0
2016-08-03T09:06:10Z
[ "python", "json" ]
Insert a value in json file with python
38,738,717
<p>For a project, I need to use json for store some values :</p> <pre><code>{ "Serial_011": "011", "Servers_011": [ { "hostname": "srv-a.11", "ipv4_address": "0.0.0.0", "services": [ { "uri": "http://www.google....
0
2016-08-03T08:46:54Z
38,739,510
<p>You are doing the correct thing.But problem was like passing as a string.A small change is needed.Just remove the single quote while passing the structure. Ultimately you want in the form of dict but you are passing as a string. That's obviously not possible.Please see the below to :</p> <pre><code>with open('Examp...
0
2016-08-03T09:21:53Z
[ "python", "json" ]
Generating gray codes.
38,738,835
<p>I tried generating gray codes in <em>Python</em>. This code works correctly. The issue is that I am initialising the base case (<code>n=1,[0,1]</code>) in the <code>main</code> function and passing it to <code>gray_code</code> function to compute the rest. I want to generate all the gray codes inside the function it...
0
2016-08-03T08:52:31Z
38,739,120
<pre><code>def gray_code(n): def gray_code_recurse (g,n): k=len(g) if n&lt;=0: return else: for i in range (k-1,-1,-1): char='1'+g[i] g.append(char) for i in range (k-1,-1,-1): g[i]='0'+g[i] gra...
1
2016-08-03T09:05:45Z
[ "python", "algorithm", "recursion", "gray-code" ]
Generating gray codes.
38,738,835
<p>I tried generating gray codes in <em>Python</em>. This code works correctly. The issue is that I am initialising the base case (<code>n=1,[0,1]</code>) in the <code>main</code> function and passing it to <code>gray_code</code> function to compute the rest. I want to generate all the gray codes inside the function it...
0
2016-08-03T08:52:31Z
38,739,875
<p>It's relatively easy to do if you implement the function iteratively (even if it's defined recursively). This will often execute more quickly as it generally requires fewer function calls.</p> <pre><code>def gray_code(n): if n &lt; 1: g = [] else: g = ['0', '1'] n -= 1 while ...
1
2016-08-03T09:38:56Z
[ "python", "algorithm", "recursion", "gray-code" ]
Generating gray codes.
38,738,835
<p>I tried generating gray codes in <em>Python</em>. This code works correctly. The issue is that I am initialising the base case (<code>n=1,[0,1]</code>) in the <code>main</code> function and passing it to <code>gray_code</code> function to compute the rest. I want to generate all the gray codes inside the function it...
0
2016-08-03T08:52:31Z
38,745,459
<p>Generating Gray codes is easier than you think. The secret is that the Nth gray code is in the bits of N^(N>>1)</p> <p>So:</p> <pre><code>def main(): n=int(raw_input()) for i in range(0, 1&lt;&lt;n): gray=i^(i&gt;&gt;1) print "{0:0{1}b}".format(gray,n), main() </code></pre>
2
2016-08-03T13:46:05Z
[ "python", "algorithm", "recursion", "gray-code" ]
Why my view is not found in django rest framework?
38,738,883
<p>I am working on mezzanine rest api and adding some more views to be able to work easily. I coded one view and made its serializer but when trying to hit from postman, I am getting error not found 404</p> <p><code>Views.py</code></p> <pre><code>@csrf_exempt @api_view(['POST']) def create_site_record(request): s...
2
2016-08-03T08:54:34Z
38,739,074
<p>It looks like a problem with your url path. There is no need to have the digit capture for a create endpoint, since that is generally used for referencing an existing object. Try changing the path to <code>url(r'^create/$', create_site_record)</code> and send the POST request to<code>http://localhost:8000/api/create...
1
2016-08-03T09:03:17Z
[ "python", "django", "django-rest-framework" ]
How to implement a mouse hovering callback on canvas items in tkinter?
38,738,915
<p>I used the code below which I found on internet to implement a mouse hovering action in python:</p> <pre><code>from tkinter import * import numpy as np class rect: def __init__(self, root): self.root = root self.size = IntVar() self.canvas = Canvas(self.root, width=800, height=300) ...
2
2016-08-03T08:56:02Z
38,740,329
<p>I changed <code>motion</code> method and added <code>self.last = None</code> to <code>__init__</code> method:</p> <pre><code>from tkinter import * import numpy as np class rect: def __init__(self, root): self.root = root self.size = IntVar() self.canvas = Canvas(self.root, width=800, he...
0
2016-08-03T09:59:14Z
[ "python", "tkinter", "tkinter-canvas", "mousehover" ]
How to implement a mouse hovering callback on canvas items in tkinter?
38,738,915
<p>I used the code below which I found on internet to implement a mouse hovering action in python:</p> <pre><code>from tkinter import * import numpy as np class rect: def __init__(self, root): self.root = root self.size = IntVar() self.canvas = Canvas(self.root, width=800, height=300) ...
2
2016-08-03T08:56:02Z
38,740,334
<p>You can pass the argument <code>activefill</code> when creating your rectangle.</p> <p>From <a href="http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_rectangle-method" rel="nofollow">effboot.org</a>:</p> <blockquote> <p>Fill color to use when the mouse pointer is moved over the item, if different...
3
2016-08-03T09:59:30Z
[ "python", "tkinter", "tkinter-canvas", "mousehover" ]
PyQt - Hide MainWindow and show QDialog without the taskbar icon disappearing
38,739,009
<p>I've been using the code from this example <a href="http://stackoverflow.com/questions/22538247/pyqt-how-to-hide-qmainwindow">PyQt: How to hide QMainWindow</a>:</p> <pre><code>class Dialog_02(QtGui.QMainWindow): def __init__(self, parent): super(Dialog_02, self).__init__(parent) # ensure this wi...
0
2016-08-03T09:00:23Z
38,749,079
<p>Just guessing (because I don't know what platform you're on, and I don't use a task-bar myself, so I cant really test it), but try getting rid of the parent:</p> <pre><code>class Dialog_02(QtGui.QMainWindow): def __init__(self, other_window): super(Dialog_02, self).__init__() # ensure this windo...
1
2016-08-03T16:29:15Z
[ "python", "pyqt", "pyside" ]
How to group each block's data together instead of being grouped by the their xpath?
38,739,014
<p>Let's say I'm scraping data from structure that looks like this:</p> <pre><code>&lt;div id="main"&gt; &lt;span class="name"&gt;$somename&lt;/span&gt; &lt;span class="email"&gt;$someemial&lt;/span&gt; &lt;span class="phone"&gt;$phone&lt;/span&gt; &lt;/div&gt; </code></pre> <p>The scrapy code tha...
1
2016-08-03T09:00:32Z
38,740,063
<p>I'd suggest using a zipped variable for it. Something like this: </p> <pre><code>for sel in xpath('//body'): name = sel.xpath('//div[@id="main"]/span[@class="name"]') email = sel.xpath('//div[@id="main"]/span[@class="email"]') phone = sel.xpath('//div[@id="main"]/span[@class="phone"]') result = zip(...
1
2016-08-03T09:47:04Z
[ "python", "scrapy" ]
How to group each block's data together instead of being grouped by the their xpath?
38,739,014
<p>Let's say I'm scraping data from structure that looks like this:</p> <pre><code>&lt;div id="main"&gt; &lt;span class="name"&gt;$somename&lt;/span&gt; &lt;span class="email"&gt;$someemial&lt;/span&gt; &lt;span class="phone"&gt;$phone&lt;/span&gt; &lt;/div&gt; </code></pre> <p>The scrapy code tha...
1
2016-08-03T09:00:32Z
38,743,544
<p>This is more of a python question. For this kinds of data structure the best way to accomplish this is by using dictionaries:</p> <pre><code>dictExample={} dictExample['name']=sel.xpath('//div[@id="main"]/span[@class="name"]') dictExample['email']=sel.xpath('//div[@id="main"]/span[@class="email"]') dictExample['pho...
1
2016-08-03T12:22:23Z
[ "python", "scrapy" ]
access site behind login.microsoftonline oatuth2 with python requests
38,739,057
<p>trying to login login to a website hosted behind login.microsoftonline.com (think this a Azure cloud deployment) oauth2 site with python requests</p> <p>How should i go about structuring the request?</p>
0
2016-08-03T09:02:10Z
38,970,981
<p>@chris, I see you want to access a website via construct a request with access token which got by authentication with OAuth2 on Azure. Please follow the <a href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-protocols-oauth-code/#register-your-application-with-your-ad-tenant" rel="nofollo...
0
2016-08-16T09:16:52Z
[ "python", "azure", "python-requests" ]
Python dictionary operation
38,739,113
<p>I have something like the following dictionary:</p> <pre><code>dict = {} dict[(-1,"first")]=3 dict[(-1,"second")]=1 dict[(-1,"third")]=5 dict[(0,"first")]=4 dict[(0,"second")]=6 dict[(0,"third")]=7 dict[(1,"first")]=34 dict[(1,"second")]=45 dict[(1,"third")]=66 dict[(2,"first")]=3 dict[(2,"second")]=1 dict[(2,"thir...
2
2016-08-03T09:05:28Z
38,739,340
<p>Why do you want to keep the order ? I suggest you to use this kind of loop</p> <pre><code>dict_r = {} dict_r["first"] = [] dict_r["second"] = [] dict_r["third"] = [] for i in range (0,3): dict_r["first"].append(dict[i,"first"]) dict_r["second"].append(dict[i,"second"]) dict_r["third"].append(dict[i,"thi...
2
2016-08-03T09:15:10Z
[ "python", "dictionary" ]
Python dictionary operation
38,739,113
<p>I have something like the following dictionary:</p> <pre><code>dict = {} dict[(-1,"first")]=3 dict[(-1,"second")]=1 dict[(-1,"third")]=5 dict[(0,"first")]=4 dict[(0,"second")]=6 dict[(0,"third")]=7 dict[(1,"first")]=34 dict[(1,"second")]=45 dict[(1,"third")]=66 dict[(2,"first")]=3 dict[(2,"second")]=1 dict[(2,"thir...
2
2016-08-03T09:05:28Z
38,739,417
<p>I will do something like that (using <a class='doc-link' href="http://stackoverflow.com/documentation/python/498/collections/1636/collections-defaultdict#t=201608030921439071977">defaultdict</a> for convenient):</p> <pre><code>from collections import defaultdict new_dict = defaultdict(list) for (x,k),v in sorted(o...
1
2016-08-03T09:18:28Z
[ "python", "dictionary" ]
Python dictionary operation
38,739,113
<p>I have something like the following dictionary:</p> <pre><code>dict = {} dict[(-1,"first")]=3 dict[(-1,"second")]=1 dict[(-1,"third")]=5 dict[(0,"first")]=4 dict[(0,"second")]=6 dict[(0,"third")]=7 dict[(1,"first")]=34 dict[(1,"second")]=45 dict[(1,"third")]=66 dict[(2,"first")]=3 dict[(2,"second")]=1 dict[(2,"thir...
2
2016-08-03T09:05:28Z
38,739,820
<pre><code>dict = {} dict[(-1,"first")]=3 dict[(-1,"second")]=1 dict[(-1,"third")]=5 dict[(0,"first")]=4 dict[(0,"second")]=6 dict[(0,"third")]=7 dict[(1,"first")]=34 dict[(1,"second")]=45 dict[(1,"third")]=66 dict[(2,"first")]=3 dict[(2,"second")]=1 dict[(2,"third")]=2 dict_1 = {} for num,txt in sorted(dict.keys()): ...
0
2016-08-03T09:36:06Z
[ "python", "dictionary" ]
Python/Pandas Iterating through columns
38,739,196
<p>I have a DataFrame which looks like this (with many additional columns)</p> <pre><code> age1 age2 age3 age 4 \ Id# 1001 5 6 2 8 1002 7 6 1 0 1003 10 9 7 5 1004 9 12 5 ...
4
2016-08-03T09:09:14Z
38,739,320
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add.html" rel="nofollow"><code>add</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html" rel="nofollow"><code>shift</code></a>ed <code>DataFrame</code>:</p> <pre><code>pr...
2
2016-08-03T09:14:24Z
[ "python", "loops", "pandas", "dataframe", "iteration" ]
Python/Pandas Iterating through columns
38,739,196
<p>I have a DataFrame which looks like this (with many additional columns)</p> <pre><code> age1 age2 age3 age 4 \ Id# 1001 5 6 2 8 1002 7 6 1 0 1003 10 9 7 5 1004 9 12 5 ...
4
2016-08-03T09:09:14Z
38,739,650
<p>It sounds like <code>cumsum</code> is what you are looking for:</p> <pre><code>In [5]: df Out[5]: age1 age2 age3 age4 Id# 1001 5 6 2 8 1002 7 6 1 0 1003 10 9 7 5 1004 9 12 5 9 In [6]: df.cumsum(axis=1) Out[6]: a...
2
2016-08-03T09:28:58Z
[ "python", "loops", "pandas", "dataframe", "iteration" ]
How to install gensim on windows
38,739,250
<p>Not able to install gensim on windows.Please help me I need to gensim Immediately and tell me installation steps with More details and other software that needs to be installed before it. thanks</p>
0
2016-08-03T09:11:31Z
38,739,531
<p>Gensim depends on scipy and numpy.You must have them installed prior to installing gensim.Simple way to install gensim in windows is, open cmd and type</p> <p>pip install -U gensim</p> <p>Or download gensim for windows from</p> <p><a href="https://pypi.python.org/pypi/gensim" rel="nofollow">https://pypi.python.or...
0
2016-08-03T09:22:43Z
[ "python", "gensim" ]
How to install gensim on windows
38,739,250
<p>Not able to install gensim on windows.Please help me I need to gensim Immediately and tell me installation steps with More details and other software that needs to be installed before it. thanks</p>
0
2016-08-03T09:11:31Z
38,758,779
<p>I struggled with this a bit today trying to figure out if I needed a python 2.7 environment or if I could use my 3.5. I ended up doing this from an Anaconda 3.5 install:</p> <p>conda install -c anaconda gensim=0.12.4</p> <p>After a few hours of trying various things, suddenly it all worked on 3.5. My error was t...
0
2016-08-04T04:59:45Z
[ "python", "gensim" ]
Receiving data from com port by pyserial
38,739,336
<p>I can't receive data from com port by pyserial! I have compiled program that send data and receive answer from controller correctly! I used comport monitor program to spy request and answer from controller:<a href="http://i.stack.imgur.com/7lOt5.png" rel="nofollow">correct send and answer</a></p> <p>But when I send...
0
2016-08-03T09:14:55Z
38,740,027
<p>You'll not receive your own message on the com port you write it to. Either connect the other side of the cable to a different port, or communicate with a device that will answer you.</p>
0
2016-08-03T09:45:31Z
[ "python", "serial-port", "pyserial" ]
How to set Python Tornado pretty log
38,739,384
<p>I write log from tornado like this:</p> <pre><code>app_log = logging.getLogger("tornado.application") </code></pre> <p>And logs output without color:</p> <pre><code>[W 160803 17:04:32 test:68] warn [E 160803 17:04:32 test:69] error [I 160803 17:04:32 test:72] info </code></pre> <p>Even I call <code>enable_pretty...
0
2016-08-03T09:16:55Z
38,757,469
<p>Color is used when two conditions are met:</p> <ul> <li>stderr is a tty (i.e. not redirected to a file or pipe)</li> <li>the <code>curses</code> module believes that color is supported (based on the <code>TERM</code> environment variable)</li> </ul> <p>If <code>TERM</code> is unset, try setting <code>TERM=ansi</co...
0
2016-08-04T02:17:43Z
[ "python", "logging", "tornado" ]
Django error: render_to_response() got an unexpected keyword argument 'context_instance'
38,739,422
<p>After upgrading to Django 1.10, I get the error <code>render_to_response() got an unexpected keyword argument 'context_instance'</code>.</p> <p>My view is as follows:</p> <pre><code>from django.shortcuts import render_to_response from django.template import RequestContext def my_view(request): context = {'foo...
7
2016-08-03T09:18:34Z
38,739,423
<p>The <code>context_instance</code> parameter in <code>render_to_response</code> was <a href="https://docs.djangoproject.com/en/1.10/releases/1.8/#dictionary-and-context-instance-arguments-of-rendering-functions">deprecated in Django 1.8</a>, and removed in Django 1.10.</p> <p>The solution is to switch to the <a href...
23
2016-08-03T09:18:34Z
[ "python", "django" ]
Is it possible to mix Eve (Python) Mongo schemata and Eve SQLAlchemy schemata?
38,739,457
<p>I want to create an API which on one side can use the normal mongodb interface for storing documents but on the other side access user data which is stored in a SQL database.</p> <p>Therefore: Is it possible to mix Eve Mongo and <a href="https://eve-sqlalchemy.readthedocs.io/en/stable/tutorial.html" rel="nofollow">...
1
2016-08-03T09:19:43Z
38,761,803
<p>No, currently that's not possible since you can either use the default mongo data engine <em>or</em> switch it with the Eve-Sqlalchemy engine.</p>
0
2016-08-04T08:06:54Z
[ "python", "sqlalchemy", "eve" ]
need help : python3.5.2 & pygame
38,739,472
<p>I'm from Taiwan, and I need help to install pygame.<br> I've been trying for a long time.<br> <a href="http://i.stack.imgur.com/Pr63F.png" rel="nofollow">pygame file</a><br> <a href="http://i.stack.imgur.com/rhwJp.png" rel="nofollow">cmd result</a><br> I want to ask if I download the right pygame file. If not please...
2
2016-08-03T09:20:19Z
38,739,808
<p><strong>Option 1:</strong> You have a 32bit install of Python (even if your Windows is 64-bit).</p> <p>You can check if this is the case by looking at the output of </p> <pre><code>import struct;print(struct.calcsize("P") * 8) </code></pre> <p>if so, you will need to download the 32bit version of pygame not the 6...
0
2016-08-03T09:35:33Z
[ "python", "pygame" ]
Python print both the matching groups in regex
38,739,589
<p>I want to find two fixed patterns from a log file. Here is a line in a log file looks like</p> <blockquote> <p>passed dangerb.xavier64.423181.k000.drmanhattan_resources.log Aug 23 04:19:37 84526 362</p> </blockquote> <p>From this log, I want to extract <code>drmanhattan</code> and <code>362</code> w...
0
2016-08-03T09:25:39Z
38,739,709
<p><code>|</code> mean OR so your regex catch <code>(\w+_\w+)</code> OR <code>(\d+$)</code></p> <p>Maybe you want something like this :</p> <pre><code>((\w+_\w+).*?(\d+$)) </code></pre>
1
2016-08-03T09:31:11Z
[ "python", "regex", "python-2.7" ]
Python print both the matching groups in regex
38,739,589
<p>I want to find two fixed patterns from a log file. Here is a line in a log file looks like</p> <blockquote> <p>passed dangerb.xavier64.423181.k000.drmanhattan_resources.log Aug 23 04:19:37 84526 362</p> </blockquote> <p>From this log, I want to extract <code>drmanhattan</code> and <code>362</code> w...
0
2016-08-03T09:25:39Z
38,739,745
<pre><code>line = 'Passed dangerb.xavier64.423181.r000.drmanhattan_resources.log Aug 23 04:19:37 84526 362' match1 = re.search(r'(\w+_\w+).*?(\d+$)', line) if match1: print match1.groups() # ('drmanhattan_resources', '362') </code></pre> <p>If you have a <code>test.txt</code> file that contains the following ...
1
2016-08-03T09:32:50Z
[ "python", "regex", "python-2.7" ]
Python print both the matching groups in regex
38,739,589
<p>I want to find two fixed patterns from a log file. Here is a line in a log file looks like</p> <blockquote> <p>passed dangerb.xavier64.423181.k000.drmanhattan_resources.log Aug 23 04:19:37 84526 362</p> </blockquote> <p>From this log, I want to extract <code>drmanhattan</code> and <code>362</code> w...
0
2016-08-03T09:25:39Z
38,739,853
<p>With <code>re.search</code> you only get the first match, if any, and with <code>|</code> you tell <code>re</code> to look for <em>either</em> this <em>or</em> that pattern. As suggested in other answers, you could replace the <code>|</code> with <code>.*</code> to match "anything in between" those two pattern. Alte...
1
2016-08-03T09:37:42Z
[ "python", "regex", "python-2.7" ]
Protobuf3: Serialize a Python object to JSON
38,739,603
<p>According to <a href="https://github.com/google/protobuf/releases/tag/v3.0.0" rel="nofollow">the manual</a>, Protobuf 3.0.0 supports JSON serialization:</p> <blockquote> <p>A well-defined encoding in JSON as an alternative to binary proto encoding.</p> </blockquote> <p><strong>What have I tried</strong></p> <ul...
1
2016-08-03T09:26:22Z
38,740,630
<p>There is a function 'MessageToJson' in the json_format module. This function can be used to serialize the message.</p>
2
2016-08-03T10:11:10Z
[ "python", "json", "serialization", "protocol-buffers-3" ]
Protobuf3: Serialize a Python object to JSON
38,739,603
<p>According to <a href="https://github.com/google/protobuf/releases/tag/v3.0.0" rel="nofollow">the manual</a>, Protobuf 3.0.0 supports JSON serialization:</p> <blockquote> <p>A well-defined encoding in JSON as an alternative to binary proto encoding.</p> </blockquote> <p><strong>What have I tried</strong></p> <ul...
1
2016-08-03T09:26:22Z
38,741,473
<h1>Caveats</h1> <p>I have mistakingly installed <code>protobuf3</code> - I thought it the, well, <code>protobuf3</code> Python package, but it's an unofficial <strong>Python 3 protobuf 2 package</strong>, not the other way around. Remove it before you start.</p> <h1>Solution</h1> <p>After some trial and error, the ...
1
2016-08-03T10:49:55Z
[ "python", "json", "serialization", "protocol-buffers-3" ]
pyyaml 3.11 pass dictionary to iterator?
38,739,689
<p>I use following YAML data:</p> <pre><code>Document: InPath: /home/me OutPath: /home/me XLOutFile: TestFile1.xlsx Sheets: - Sheet: Test123 InFile: Test123.MQSC Server: Testsystem1 - Sheet: Test345 InFile: Test345.MQSC Server: Testsystem2 Title: A: "Server Name" B: "MQ Version" C...
4
2016-08-03T09:30:16Z
38,741,944
<p>In your code <code>self.ymldata['Sheets']</code> is a list of dictionaries because your YAML source for that:</p> <pre><code> - Sheet: Test123 InFile: Test123.MQSC Server: Testsystem1 - Sheet: Test345 InFile: Test345.MQSC Server: Testsystem2 </code></pre> <p>is a sequence of mappings (and this i...
2
2016-08-03T11:12:17Z
[ "python", "python-2.7", "dictionary", "iterator", "pyyaml" ]
Install Python package: "Package missing in current win-64 channels"
38,739,694
<p>I want to install GSEApy on Anaconda (I use 64bit Windows 10).<br> <a href="https://bioconda.github.io/recipes/gseapy/README.html" rel="nofollow">https://bioconda.github.io/recipes/gseapy/README.html</a><br> <a href="https://anaconda.org/bioconda/gseapy" rel="nofollow">https://anaconda.org/bioconda/gseapy</a> </p> ...
4
2016-08-03T09:30:33Z
38,739,991
<p>You need to use a channel that has a win-64 version. Use:</p> <pre><code>conda install -c bioninja gseapy </code></pre> <p>The option <code>-c</code> or <code>--channel</code> allows to specify a channel. You can also add a channel permanently via:</p> <pre><code>conda config --add channels bioninja </code></pre>...
2
2016-08-03T09:43:58Z
[ "python", "packages", "anaconda", "conda" ]
Install Python package: "Package missing in current win-64 channels"
38,739,694
<p>I want to install GSEApy on Anaconda (I use 64bit Windows 10).<br> <a href="https://bioconda.github.io/recipes/gseapy/README.html" rel="nofollow">https://bioconda.github.io/recipes/gseapy/README.html</a><br> <a href="https://anaconda.org/bioconda/gseapy" rel="nofollow">https://anaconda.org/bioconda/gseapy</a> </p> ...
4
2016-08-03T09:30:33Z
38,998,705
<p>Now you could install lastest gseapy through bioconda, too </p> <pre><code>conda install -c bioconda gseapy </code></pre>
0
2016-08-17T13:54:12Z
[ "python", "packages", "anaconda", "conda" ]
How to bring keyboard focus to QTextEdit in PyQt?
38,739,714
<p>I've inserted a simple <code>QTextEdit</code> widget into my PyQt user interface. When the user wants to type text into that widget, he has to click on it. My program should be able to make this happen automatically at certain occasions, such that the user can start typing text into that <code>QTextEdit</code> widge...
1
2016-08-03T09:31:15Z
38,740,228
<p>Use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qwidget.html#setFocus" rel="nofollow"><code>setFocus()</code></a> method.</p> <pre><code>def focus(self): self.setFocus() </code></pre>
1
2016-08-03T09:54:20Z
[ "python", "python-3.x", "pyqt", "pyqt5" ]
'str' object has no attribute 'message_from_bytes'
38,739,739
<p>I have a piece of code to get emails from messages from my inbox (gmail). Getting emails work correct when I print <code>email_from</code> but I would like to do some operation on data split name and email etc. but then code broke after print first loop step and I got the error:</p> <pre><code>Traceback (most recen...
1
2016-08-03T09:32:19Z
38,739,949
<p>In your code you replaced the email variable..</p> <p>Try this...</p> <pre><code>import imaplib import email from email.header import Header, decode_header, make_header # Connection settings HOST = 'imap.gmail.com' USERNAME = '***' PASSWORD = '***' m = imaplib.IMAP4_SSL(HOST, 993) m.login(USERNAME, PASSWORD) m.s...
3
2016-08-03T09:42:09Z
[ "python", "gmail-imap" ]
Comparing dictionaries by corresponding keys?
38,739,936
<p>I'm quite the beginner in Python. </p> <p>I have two dictionaries, where each key is a product and each value is the price to each product. </p> <pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2':...
0
2016-08-03T09:41:22Z
38,740,115
<p>In Python 3.5:</p> <pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2': '15'} keys = set (productData_1.keys () + productData_2.keys ()) for key in keys: try: if productData_1 [key] !=...
0
2016-08-03T09:49:15Z
[ "python", "dictionary" ]
Comparing dictionaries by corresponding keys?
38,739,936
<p>I'm quite the beginner in Python. </p> <p>I have two dictionaries, where each key is a product and each value is the price to each product. </p> <pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2':...
0
2016-08-03T09:41:22Z
38,740,125
<pre><code>for key in productData_1.keys()|productData_2.keys(): if key not in productData_1: print('{} missing from productData_1!'.format(key)) continue if key not in productData_2: print('{} missing from productData_2!'.format(key)) continue print('Difference in prices for...
0
2016-08-03T09:49:42Z
[ "python", "dictionary" ]
Comparing dictionaries by corresponding keys?
38,739,936
<p>I'm quite the beginner in Python. </p> <p>I have two dictionaries, where each key is a product and each value is the price to each product. </p> <pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2':...
0
2016-08-03T09:41:22Z
38,740,269
<pre><code>keys_unique_to_1 = [key for key in productData_1 if key not in productData_2] keys_unique_to_2 = [key for key in productData_2 if key not in productData_1] common_keys = [key for key in productData_1 if key in productData_2] diff = {key: int(productData_1[key]) - int(productData_2[key]) for key in common_ke...
0
2016-08-03T09:56:01Z
[ "python", "dictionary" ]
Comparing dictionaries by corresponding keys?
38,739,936
<p>I'm quite the beginner in Python. </p> <p>I have two dictionaries, where each key is a product and each value is the price to each product. </p> <pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2':...
0
2016-08-03T09:41:22Z
38,740,327
<p>There's a good page <a href="http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops-in-python">here</a> on this issue. You can loop through both your dictionaries and compare their values. The example hereunder shows how you can print the keys for which your values are equal.</p> <p>...
0
2016-08-03T09:59:07Z
[ "python", "dictionary" ]
Comparing dictionaries by corresponding keys?
38,739,936
<p>I'm quite the beginner in Python. </p> <p>I have two dictionaries, where each key is a product and each value is the price to each product. </p> <pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2':...
0
2016-08-03T09:41:22Z
38,740,508
<pre><code>productData_1 = {'product_1': '18', 'product_2': '15', 'product_3': '10', 'product_4': '9'} productData_2 = {'product_1': '18', 'product_3': '12', 'product_2': '15'} matched_keys = [] unmatched_keys = [] matched_value = [] unmatched_value = [] for ind,value in productData_1.items(): if ind in productDa...
0
2016-08-03T10:06:14Z
[ "python", "dictionary" ]
Does ply's YACC support the Extended Backus-Naur Form?
38,740,061
<p><a href="http://www.dabeaz.com/ply/PLYTalk.pdf" rel="nofollow">The examples I've seen</a> always use the "simple" BNF. Here's an example of a part of my silly development:</p> <pre><code>def p_expression(p): """expression : NUMBER | NAME | NEGATION | INCREMENT ...
0
2016-08-03T09:47:02Z
38,747,805
<p>No, PLY (like yacc) does not support extended BNF.</p> <p>The page you refer to provides a strategy for constructing <em>top-down</em> parsers, while the parsers built by yacc (as well as Bison, PLY and other derivatives) build bottom-up parsers. The advantage of a bottom-up parser is that the grammar used to parse...
1
2016-08-03T15:27:16Z
[ "python", "parsing", "yacc", "bnf", "ply" ]
Python subprocess.check_call() not recognising pushd and popd
38,740,215
<p>I'm on Ubuntu 15.04 (not by choice obviously) and Python 3.4.3 and I'm trying to execute something like the following.</p> <pre><code>subprocess.check_call("pushd /tmp", shell=True) </code></pre> <p>I need the <code>shell=True</code> because the actual code I'm trying to execute contains wildcards that need to be ...
0
2016-08-03T09:53:54Z
38,740,640
<p>You have two problems with your code. The first one is that the shell used by default is <code>/bin/sh</code> which doesn't support <code>pushd</code> and <code>popd</code>. In your question you failed to provide the whole error output, and at the top of it you should see the line:</p> <pre><code>/bin/sh: 1: popd:...
2
2016-08-03T10:11:34Z
[ "python", "bash", "python-3.x", "subprocess", "ubuntu-15.04" ]
How to define a triple layer dictionary in python?
38,740,300
<p>I want to create the following structure for a dictionary:</p> <pre><code>{ id1: {id2: {id3: [] }}} </code></pre> <p>That would be a triple dictionary that will finally point to a list.</p> <p>I use the following code to initiate it in Python:</p> <pre><code>for i in range(2160): for j in range(2160): ...
3
2016-08-03T09:57:48Z
38,740,548
<p>Do you really need 10 billion entries (2,160 ** 3 == 10,077,696,000) in this structure? It's unlikely that any disk-based solution will be quicker than a memory-based one, but at the same time your program might be exceeding the bounds of real memory, causing "page thrashing" to occur.</p> <p>Without knowing anythi...
2
2016-08-03T10:07:55Z
[ "python", "dictionary", "optimization", "data-structures" ]
Django Mezzanine ImportError: No module named apps
38,740,421
<p>I had a working mezzanine project configured with apache and mod_wsgi. I tried to added an app to the project and restarted apache and suddenly the project is throwing the error even after undoing the changes. Getting the same error when I'm trying to run python manage.py check:</p> <pre><code>Traceback (most recen...
1
2016-08-03T10:03:02Z
38,747,153
<p>You say you have a folder named <code>apps</code> in your Django installation, but the traceback shows it is executing code that was removed in 1.7, the same version that introduced <code>django.apps</code>. Your installation is most likely corrupt and has files from different versions.</p> <p>Uninstall Django from...
0
2016-08-03T14:58:28Z
[ "python", "django", "mezzanine" ]
How to split dataframe according to intersection point in Python?
38,740,423
<p>I am working on a project which is aiming to show difference between good form and bad form of an exercise. To do this we collected the acceleration data with wrist based accelerometer. <a href="http://i.stack.imgur.com/bZg1U.png" rel="nofollow"><img src="http://i.stack.imgur.com/bZg1U.png" alt="enter image descript...
0
2016-08-03T10:03:04Z
38,791,129
<p>Well, I found another way to detect periodic parts of my accelerometer data. So, Here is my code:</p> <pre><code>import numpy as np from peakdetect import peakdetect import datetime as dt import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib import style from pandas import DataFrame...
0
2016-08-05T14:00:12Z
[ "python", "pandas", "dataframe" ]
merge adjacent number in a list in python
38,740,424
<p>I have a list that contains a random number of ints. I would like to iterate over this list, and if a number and the successive number are within one numeric step of one another, I would like to concatenate them into a sublist.</p> <p>For example:</p> <pre><code>input = [1,2,4,6,7,8,10,11] output = [[1,2],[4],[6,7...
1
2016-08-03T10:03:05Z
38,740,829
<p>Nice way (found the "splitting" indices and then <a class='doc-link' href="http://stackoverflow.com/documentation/python/1494/list-slicing-selecting-parts-of-lists/4863/selecting-a-sublist-from-a-list#t=201608031037013525241">slice</a> the list accordingly):</p> <pre><code>input = [1,2,4,6,7,8,10,11] idx = [0] + [i...
0
2016-08-03T10:20:55Z
[ "python", "list", "python-3.x", "list-comprehension", "listiterator" ]
merge adjacent number in a list in python
38,740,424
<p>I have a list that contains a random number of ints. I would like to iterate over this list, and if a number and the successive number are within one numeric step of one another, I would like to concatenate them into a sublist.</p> <p>For example:</p> <pre><code>input = [1,2,4,6,7,8,10,11] output = [[1,2],[4],[6,7...
1
2016-08-03T10:03:05Z
38,741,384
<p>Unless you have to have a one-liner, you could use a simple generator function, combining elements until you hit a non consecutive element:</p> <pre><code>def consec(lst): it = iter(lst) prev = next(it) tmp = [prev] for ele in it: if prev + 1 != ele: yield tmp tmp = [...
0
2016-08-03T10:46:08Z
[ "python", "list", "python-3.x", "list-comprehension", "listiterator" ]
merge adjacent number in a list in python
38,740,424
<p>I have a list that contains a random number of ints. I would like to iterate over this list, and if a number and the successive number are within one numeric step of one another, I would like to concatenate them into a sublist.</p> <p>For example:</p> <pre><code>input = [1,2,4,6,7,8,10,11] output = [[1,2],[4],[6,7...
1
2016-08-03T10:03:05Z
38,742,081
<p>Simplest version I have without any imports:</p> <pre><code>def mergeAdjNum(l): r = [[l[0]]] for e in l[1:]: if r[-1][-1] == e - 1: r[-1].append(e) else: r.append([e]) return r </code></pre> <p>About 33% faster than one liners.</p> <p>This one handles the charac...
0
2016-08-03T11:18:54Z
[ "python", "list", "python-3.x", "list-comprehension", "listiterator" ]
Transform numpy array to RGB image array
38,740,495
<p>Consider the following code:</p> <pre><code>import numpy as np rand_matrix = np.random.rand(10,10) </code></pre> <p>which generates a 10x10 random matrix.</p> <p>Following code to display as colour map:</p> <pre><code>import matplotlib.pyplot as plt plt.imshow(rand_matrix) plt.show() </code></pre> <p>I would li...
0
2016-08-03T10:05:49Z
38,740,915
<p>You can save time by saving to a <code>io.BytesIO</code> instead of to a file:</p> <pre><code>import io import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from PIL import Image def ax_to_array(ax, **kwargs): fig = ax.figure frameon = ax.get_frame_on() ax.set_frame_on(Fa...
1
2016-08-03T10:24:31Z
[ "python", "image", "numpy", "rgb" ]
Python in C++ or C++ pure for file templates manipulation?
38,740,520
<p>(I don't know if I can post such a question here)</p> <p>I have a problem for which I need a suggestion. I've a C++ code that derive several parameters (which are numbers basically). Such numbers have to be used to generate further code, of which I have templates, as very trivial example a template could look as so...
1
2016-08-03T10:06:52Z
38,740,743
<p>Although I am a Python enthusiast, I think for this one you should stay within C++ (since it seems you have already a significant amount of C++ code) and use a decent library like Boost. You could consider using Cython as a bridge, but my estimation is that it would be overkill.</p>
1
2016-08-03T10:16:42Z
[ "python", "c++", "file" ]
Is plug-in based approach considered good practice for GUI app development in PyQt?
38,740,649
<p>I'm thinking of using a plug-in based UI architecture to develop my PyQt project, i.e. create a skeleton main window which will dynamically load all the other UI components and these UI components will be made as PyQt plugins. </p> <p>Since I'm quite new to PyQt, I'm wondering if this is a good practice that people...
1
2016-08-03T10:12:11Z
38,787,357
<p>A plugin based architecture is a very powerful way to design scalable, maintainable, extensible software. If you intend to build software where you consider certain parts of it should be plugins just go for it because in python implementing plugins is straightforward.</p> <p>Of course, all depends what type of soft...
0
2016-08-05T10:46:45Z
[ "python", "python-2.7", "pyqt" ]
How to make python import an identically named module from the local directory instead site-packages?
38,740,672
<p>I'm a bit confused on how python separates between modules installed in site-packages and modules in the local directory if they have identical names and what's the best way to make python import the module from the local directory instead of the installed one. </p> <p>Basically I have a command line app and I'm us...
0
2016-08-03T10:13:19Z
38,740,880
<p>The easiest way to nominate additional directories to be searched when trying to import modules is to add them to the <code>sys.path</code> list.</p> <p>The interpreter looks at an environment variable called <code>$PYTHONPATH</code>, which should be a colon-separated (Windows: semi-colon separated) list of directo...
0
2016-08-03T10:23:25Z
[ "python", "setuptools" ]
How to make python import an identically named module from the local directory instead site-packages?
38,740,672
<p>I'm a bit confused on how python separates between modules installed in site-packages and modules in the local directory if they have identical names and what's the best way to make python import the module from the local directory instead of the installed one. </p> <p>Basically I have a command line app and I'm us...
0
2016-08-03T10:13:19Z
38,741,016
<p>if scriptA.py is in the same directory of main.py can't you just <code>import .scriptA</code> ?</p> <p>The <code>.</code> is a shortcut that tells python to search in current package before rest of the <code>PYTHONPATH</code></p>
0
2016-08-03T10:29:10Z
[ "python", "setuptools" ]
Python simple brackets parser
38,740,853
<p>I basically have a file with this structure: </p> <pre><code>root \ { field1 { subfield_a { "value1" } subfield_b { "value2" } subfield_c { "value1" "value2" "value3" } subfield_d { } } field2 { subfield_a { "value1" } subfield_b ...
0
2016-08-03T10:22:10Z
38,933,432
<p>You can let pyparsing take care of the matching and iterating over the input, just define what you want it to match, and pass it the body of the file as a string:</p> <pre><code>def magic_parse_function(fld_name, source): from pyparsing import Keyword, nestedExpr # define parser parser = Keyword(fld_na...
1
2016-08-13T13:53:43Z
[ "python", "parsing" ]
XGBoost difference in train and test features after converting to DMatrix
38,740,885
<p>Just wondering how is possible next case:</p> <pre><code> def fit(self, train, target): xgtrain = xgb.DMatrix(train, label=target, missing=np.nan) self.model = xgb.train(self.params, xgtrain, self.num_rounds) </code></pre> <p><a href="http://i.stack.imgur.com/8GQ0v.png" rel="nofollow"><img src="http://i....
1
2016-08-03T10:23:37Z
38,875,449
<p>This situation can happen after one-hot encoding. For example,</p> <pre><code>ar = np.array([ [1, 2], [1, 0] ]) enc = OneHotEncoder().fit(ar) ar2 = enc.transform(ar) b = np.array([[1, 0]]) b2 = enc.transform(b) xgb_ar = xgb.DMatrix(ar2) xgb_b = xgb.DMatrix(b2) print(b2.shape) # (1, 3) print(xgb_b....
1
2016-08-10T13:54:31Z
[ "python", "python-2.7", "numpy", "machine-learning", "xgboost" ]
XGBoost difference in train and test features after converting to DMatrix
38,740,885
<p>Just wondering how is possible next case:</p> <pre><code> def fit(self, train, target): xgtrain = xgb.DMatrix(train, label=target, missing=np.nan) self.model = xgb.train(self.params, xgtrain, self.num_rounds) </code></pre> <p><a href="http://i.stack.imgur.com/8GQ0v.png" rel="nofollow"><img src="http://i....
1
2016-08-03T10:23:37Z
38,887,112
<p>One another possibility is to have one feature level exclusively in training data not in testing data. This situation happens mostly while post one hot encoding whose resultant is big matrix have level for each level of categorical features. In your case it looks like "f5232" is either exclusive in training or test ...
1
2016-08-11T04:08:16Z
[ "python", "python-2.7", "numpy", "machine-learning", "xgboost" ]
What mistake am I making in my code?
38,740,997
<p>For some reason my code doesn't seem to add to q, it prints out 0 for q even though there are 11 lines in the csv file, all I want to check if the csv file is empty, the code doesn't work in my script, but in the python console it works fine.</p> <pre><code>with open('File.csv', 'r') as FILE: q=0;LS = reader(F...
1
2016-08-03T10:28:19Z
38,741,286
<p>The <code>i</code> is iterating through the rows in <code>LS</code>, so if you have a file with 1 line it will be 1, if you have an empty file it will be 0, etc... I suspect your file is empty, or the opening did not succeed.</p>
1
2016-08-03T10:41:41Z
[ "python", "csv", "with-statement" ]
What mistake am I making in my code?
38,740,997
<p>For some reason my code doesn't seem to add to q, it prints out 0 for q even though there are 11 lines in the csv file, all I want to check if the csv file is empty, the code doesn't work in my script, but in the python console it works fine.</p> <pre><code>with open('File.csv', 'r') as FILE: q=0;LS = reader(F...
1
2016-08-03T10:28:19Z
38,741,359
<p>Are you sure the file name is correct and in the same folder? I ran your script with a csv file I quickly made (contents: 1,2) and it outputted 1 as expected. Also make sure that your example code can be executed by itself, so include <code>from csv import reader</code> in the future.</p>
2
2016-08-03T10:44:52Z
[ "python", "csv", "with-statement" ]
Reading excel and storing data with xlrd
38,741,099
<p>I have this data in excel sheet </p> <pre><code>FT_NAME FC_NAME C_NAME FT_NAME1 FC1 C1 FT_NAME2 FC21 C21 FC22 C22 FT_NAME3 FC31 C31 FC32 C32 FT_NAME4 FC4 C4 </code></pre> <p>where column names are </p> <blockquote> <p>FT_NAME,FC_NAME,C_NAME</p> </block...
0
2016-08-03T10:32:55Z
38,741,855
<p>You can use <code>pandas</code>. It reads the data into a DataFrame which is essentially a big dictionary. </p> <pre><code>import pandas as pd data =pd.read_excel('file.xlsx', 'Sheet1') data = data.fillna(method='pad') print(data) </code></pre> <p>it gives the following output:</p> <pre><code> FT_NAME FC_NAM...
0
2016-08-03T11:07:06Z
[ "python", "xlrd" ]
Python: count specific occurrences in a dictionary
38,741,110
<p>Say I have a dictionary like this:</p> <pre><code>d={ '0101001':(1,0.0), '0101002':(2,0.0), '0101003':(3,0.5), '0103001':(1,0.0), '0103002':(2,0.9), '0103003':(3,0.4), '0105001':(1,0.0), '0105002':(2,1.0), '0105003':(3,0.0)} </code></pre> <p>Considering that the first four digits of each key consitute the identif...
0
2016-08-03T10:33:19Z
38,741,203
<p>Use a <a href="https://docs.python.org/2/library/collections.html#counter-objects" rel="nofollow">Counter</a>, add the first four digits of the key if the value is what you're looking for:</p> <pre><code>from collections import Counter counts = Counter() for key, value in d.items(): if value[1] == 0.0: ...
3
2016-08-03T10:37:45Z
[ "python", "dictionary", "find-occurrences" ]
Python: count specific occurrences in a dictionary
38,741,110
<p>Say I have a dictionary like this:</p> <pre><code>d={ '0101001':(1,0.0), '0101002':(2,0.0), '0101003':(3,0.5), '0103001':(1,0.0), '0103002':(2,0.9), '0103003':(3,0.4), '0105001':(1,0.0), '0105002':(2,1.0), '0105003':(3,0.0)} </code></pre> <p>Considering that the first four digits of each key consitute the identif...
0
2016-08-03T10:33:19Z
38,741,555
<p>You can use a <a class='doc-link' href="http://stackoverflow.com/documentation/python/498/collections/1636/collections-defaultdict#t=201608031052568500106"><code>defaultdict</code></a>:</p> <pre><code>from _collections import defaultdict res = defaultdict(int) for k in d: if d[k][1] == 0.0: res[k[:4]] ...
2
2016-08-03T10:53:34Z
[ "python", "dictionary", "find-occurrences" ]
RQ Timeout does not kill multi-threaded jobs
38,741,173
<p>I'm having problems running multithreaded tasks using python RQ (tested on v0.5.6 and v0.6.0).</p> <p>Consider the following piece of code, as a simplified version of what I'm trying to achieve:</p> <h1>thing.py</h1> <pre><code>from threading import Thread class MyThing(object): def say_hello(self): ...
1
2016-08-03T10:36:26Z
38,747,032
<p>When you run <code>t.join()</code>, the <code>hello_task</code> thread blocks and waits until the <code>say_hello</code> thread returns - thus not receiving the timeout signal from rq. You can allow the main thread to run and properly receive the timeout signal by using <code>Thread.join</code> with a set amount of ...
1
2016-08-03T14:52:40Z
[ "python", "multithreading", "python-2.7", "python-rq", "django-rq" ]
Pandas - How to rename a table name?
38,741,177
<p>I am trying create dynamic table names by using variable from the for loop. I am using Python 2.7.</p> <p>This is the function I intend to write:</p> <p>where columns can be parsed from the external sources.</p> <p>FUNCTION: </p> <pre><code>def cutoff(row): if (row['CourierCode']=='DP'): for TAT in ...
0
2016-08-03T10:36:31Z
38,742,390
<p>In your case, if you do want to accomplish it this way use:</p> <pre><code>exec("CombinedDataProjected%s = %s" % (month, 'pd.DataFrame(CombinedData)')) </code></pre> <p>But this is a very poor way of executing in python since Python has perfectly good concepts for representing a bunch of variables --- lists and di...
1
2016-08-03T11:33:18Z
[ "python", "pandas", "dataframe", "rename" ]
Averaging pandas dataframes from certain columns
38,741,288
<p>I am new to pandas. I have several <code>dfs</code>. The data in column <code>0</code> is the <code>ID</code> and in columns <code>1-10</code> are probabilities. I want to take the column-wise average of columns <code>1-10</code> across the <code>dfs</code>. The rows may not be in the same order. </p> <p>Is there a...
1
2016-08-03T10:41:52Z
38,741,412
<p>It looks like need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mean.html" rel="nofollow"><code>mean</code></a>:</p> <pre><code>import pandas as pd df1 = ...
1
2016-08-03T10:47:21Z
[ "python", "pandas", "dataframe", "mean", "ensembles" ]