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
Python, search list of list and give next value
39,748,249
<p>I'm creating a program that given a percentage for commission and given an invoice(s), it will look for given invoices, look for the value of that invoice and calculate the commission based on the percentage input. When we input <code>"calculate"</code> it will sum all the commission and give me the total of commiss...
1
2016-09-28T12:57:17Z
39,748,794
<p>You would do better to split up the task of finding the right invoice from the calculations.</p> <p>At present your code will not run at all, as you are using variables whose values you haven't defined. Since you don't need to alter the invoices at all it will be fine just to return the values you want. Here's an e...
0
2016-09-28T13:21:15Z
[ "python", "list", "element" ]
Python, search list of list and give next value
39,748,249
<p>I'm creating a program that given a percentage for commission and given an invoice(s), it will look for given invoices, look for the value of that invoice and calculate the commission based on the percentage input. When we input <code>"calculate"</code> it will sum all the commission and give me the total of commiss...
1
2016-09-28T12:57:17Z
39,748,932
<p>Your 'database' seems to be a list of lists. I'm assuming the input from the user is supposed to match the first part of the list.</p> <p>So given:</p> <pre><code>data_base = [["f1",2000,.24],["f2",150000,.32],["f3",345000,.32]] </code></pre> <p>If the user inputs <code>f1</code>, you want it to match <code>["f1...
0
2016-09-28T13:27:13Z
[ "python", "list", "element" ]
Python, search list of list and give next value
39,748,249
<p>I'm creating a program that given a percentage for commission and given an invoice(s), it will look for given invoices, look for the value of that invoice and calculate the commission based on the percentage input. When we input <code>"calculate"</code> it will sum all the commission and give me the total of commiss...
1
2016-09-28T12:57:17Z
39,748,954
<p>you should try this code. check for the names and indentation </p> <pre><code> total = 0 invoice = "calculate" while invoice!='calculate' for item in data_base: total = total + item[1]*comission_percentage/100 invoice = input("Enter invoice: ")...
0
2016-09-28T13:28:12Z
[ "python", "list", "element" ]
PYTHONPATH order on Ubuntu 14.04
39,748,267
<p>I have two computers running Ubuntu 14.04 server (let's call them A and B). B was initially a 10.04 but it has received two upgrades to 12.04 and 14.04. I do not understand why the python path is different on the two computers.</p> <p>As you can see on the two paths below, the pip installation path <code>/usr/local...
13
2016-09-28T12:58:06Z
39,748,722
<p>PYTHONPATH is environmental variable which you can set how ever you want,to add additional directories.You should not install Python packages manually,use <code>pip</code>.On older Ubuntu,probably you have manually installed modules before the upgrade.</p>
-2
2016-09-28T13:17:45Z
[ "python", "ubuntu", "ubuntu-14.04", "pythonpath", "ubuntu-server" ]
PYTHONPATH order on Ubuntu 14.04
39,748,267
<p>I have two computers running Ubuntu 14.04 server (let's call them A and B). B was initially a 10.04 but it has received two upgrades to 12.04 and 14.04. I do not understand why the python path is different on the two computers.</p> <p>As you can see on the two paths below, the pip installation path <code>/usr/local...
13
2016-09-28T12:58:06Z
39,750,657
<p>You can set the <code>PYTHONPATH</code> to content of <code>Ubuntu A</code></p> <pre><code>env PYTHONPATH="/usr/local/bin:/usr/lib/python2.7:/usr/lib/python2.7/plat-x86_64-linux-gnu:..." python </code></pre>
-1
2016-09-28T14:38:47Z
[ "python", "ubuntu", "ubuntu-14.04", "pythonpath", "ubuntu-server" ]
PYTHONPATH order on Ubuntu 14.04
39,748,267
<p>I have two computers running Ubuntu 14.04 server (let's call them A and B). B was initially a 10.04 but it has received two upgrades to 12.04 and 14.04. I do not understand why the python path is different on the two computers.</p> <p>As you can see on the two paths below, the pip installation path <code>/usr/local...
13
2016-09-28T12:58:06Z
39,807,752
<p>The simplest way is to use <a href="https://docs.python.org/2/library/sys.html#sys.path" rel="nofollow">sys.path</a> to make sure that you will have right order of paths added. <code>sys.path</code> gives out the list of paths that are available in the <code>PYHTONPATH</code> environment variable with the right orde...
-1
2016-10-01T14:26:14Z
[ "python", "ubuntu", "ubuntu-14.04", "pythonpath", "ubuntu-server" ]
PYTHONPATH order on Ubuntu 14.04
39,748,267
<p>I have two computers running Ubuntu 14.04 server (let's call them A and B). B was initially a 10.04 but it has received two upgrades to 12.04 and 14.04. I do not understand why the python path is different on the two computers.</p> <p>As you can see on the two paths below, the pip installation path <code>/usr/local...
13
2016-09-28T12:58:06Z
39,822,069
<p>If you peek into Python's <code>site.py</code>, which you can by opening <code>/usr/lib/python2.7/site.py</code> in a text editor.</p> <p>The sys.path is augmented with directories for packages distributed within the distribution. Local addons go into <code>/usr/local/lib/python/dist-packages</code>, the global add...
1
2016-10-02T21:51:37Z
[ "python", "ubuntu", "ubuntu-14.04", "pythonpath", "ubuntu-server" ]
PYTHONPATH order on Ubuntu 14.04
39,748,267
<p>I have two computers running Ubuntu 14.04 server (let's call them A and B). B was initially a 10.04 but it has received two upgrades to 12.04 and 14.04. I do not understand why the python path is different on the two computers.</p> <p>As you can see on the two paths below, the pip installation path <code>/usr/local...
13
2016-09-28T12:58:06Z
39,844,293
<p>As we cannot explore into your system, I am trying to analysis your first question by illustrating how <code>sys.path</code> is initialized. Available references are <a href="http://mikeboers.com/blog/2014/05/23/where-does-the-sys-path-start" rel="nofollow">where-does-sys-path-starts</a> and <a href="http://pyvideo....
4
2016-10-04T04:41:43Z
[ "python", "ubuntu", "ubuntu-14.04", "pythonpath", "ubuntu-server" ]
Re-compose a Tensor after tensor factorization
39,748,285
<p>I am trying to decompose a 3D matrix using python library <a href="https://github.com/mnick/scikit-tensor">scikit-tensor</a>. I managed to decompose my Tensor (with dimensions 100x50x5) into three matrices. My question is how can I compose the initial matrix again using the decomposed matrix produced with Tensor fac...
12
2016-09-28T12:58:35Z
39,794,464
<p>The CP product of, for example, 4 matrices</p> <p><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=X_%7Babcd%7D+%3D+%5Cdisplaystyle%5Csum_%7Bz%3D0%7D%5E%7BZ%7D%7BA_%7Baz%7D+B_%7Bbz%7D+C_%7Bcz%7D+D_%7Bdz%7D%7D+%2B+%5Cepsilon_%7Babcd%7D" alt="X_{abcd} = \displaystyle\sum_{z=0}^{Z}{A_{az} B_{bz} C_{cz} D_{d...
5
2016-09-30T14:57:48Z
[ "python", "math", "data-science", "scikits" ]
Fill missing values of 1 data frame from another data frame using pandas
39,748,413
<p>Need help in filling 0's.</p> <p>In the below dataframe i have a column "Item_Visibility" which has zeros. I need to fill those with values from second dataframe(image 2). The common column between the 2 dataframes is "Item_Identifier".</p> <p>Thanks in advance</p> <p><a href="http://i.stack.imgur.com/XnvfR.png" ...
0
2016-09-28T13:04:17Z
39,748,655
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow"><code>mask</code></a> with maping by <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a>:</p> <pre>...
1
2016-09-28T13:15:34Z
[ "python", "pandas" ]
Fill missing values of 1 data frame from another data frame using pandas
39,748,413
<p>Need help in filling 0's.</p> <p>In the below dataframe i have a column "Item_Visibility" which has zeros. I need to fill those with values from second dataframe(image 2). The common column between the 2 dataframes is "Item_Identifier".</p> <p>Thanks in advance</p> <p><a href="http://i.stack.imgur.com/XnvfR.png" ...
0
2016-09-28T13:04:17Z
39,748,781
<p>try this:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({"A":["a", "b", "c", "d", "e"], "B":[1, 2, 0, 0, 0]}) s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"]) mask = df["B"] == 0 df.loc[mask, "B"] = s[df.loc[mask, "A"]].values </code></pre> <p>df:</p> <pre><code> A B 0 a...
1
2016-09-28T13:20:40Z
[ "python", "pandas" ]
Kernel Density Estimation Heatmap in python
39,748,477
<p>I have a list of latitude and longitude coordinates and respective Received Signal strength values at each coordinate. How would I plot a kernel density estimation (kde) 2D heatmap for these signal strengths at each lat-lon in python(matplotlib)? </p>
-1
2016-09-28T13:07:38Z
39,748,978
<p>You can use the python library <strong>seaborn</strong>. It has a handy function that plots kernel density estimation for your heatmaps.</p> <p>Check this out :</p> <pre><code>import seaborn as sns lat = [list_of_values] long = [list_of_values] ax = sns.kdeplot(lat, long, cmap="Blues", shade=True, shade_lowest=Fa...
0
2016-09-28T13:29:05Z
[ "python", "matplotlib", "heatmap", "kernel-density" ]
How to avoid invalid token when converting binary to decimal
39,748,689
<p>Okay. first of all i know there is a built-in function converting binary to decimal but i thought i challenge myself and make my own. </p> <p>Here are the codes....</p> <pre><code>def binaryToDecimal(binary): binaryList = list(str(binary)) exponent = len(binaryList) - 1 decimal = 0 for char in bin...
-1
2016-09-28T13:16:49Z
39,749,042
<p>Youre problem is mainly <code>binaryList = list(str(binary))</code>. <code>str(0b010001110)</code> returns <code>'142'</code>, not <code>'0b101010'</code> as you might expect.</p> <p>Consequently, <code>binaryList</code> is <code>['1', '4', '2']</code>.</p> <p>A coincidence made that <code>1 * 2**2 + 4 * 2**1 + 2<...
0
2016-09-28T13:31:23Z
[ "python", "python-3.x" ]
How to avoid invalid token when converting binary to decimal
39,748,689
<p>Okay. first of all i know there is a built-in function converting binary to decimal but i thought i challenge myself and make my own. </p> <p>Here are the codes....</p> <pre><code>def binaryToDecimal(binary): binaryList = list(str(binary)) exponent = len(binaryList) - 1 decimal = 0 for char in bin...
-1
2016-09-28T13:16:49Z
39,749,298
<p><code>0b010001110</code> is <em>already</em> an integer with the decimal value of 142. If you really want to do your own binary conversion function you'll need to pass the binary arg in as a string, eg '010001110', or as a list of bits, which can be strings, integers, or even the boolean values <code>True</code> and...
1
2016-09-28T13:41:50Z
[ "python", "python-3.x" ]
Python 3.5 - method overloading with @overload
39,748,842
<p>There is an <a href="https://pypi.python.org/pypi/overloading" rel="nofollow">overloading</a> package for Python 3.5+. Whith this package, it's possible to redefined methods, but with distinct type hints and its decorator will find out, which overloaded method should be called. </p> <p><strong>Common coding pattern...
0
2016-09-28T13:23:15Z
39,749,114
<p>You'd have to measure it on your own with a real code. </p> <p>I made a very quick look at the code of this library and conclusion is simple. It uses a lot of reflection (inspect package) and type comparison. inspect package on its own is mostly used by debugging tools - they always slow your code down. </p> <p>Ju...
1
2016-09-28T13:34:14Z
[ "python", "overloading", "python-3.5", "method-overloading" ]
Why does Python3.5 have generator based co-routines?
39,748,849
<p>If at all, there's no functional differences (besides syntax) between <code>native</code> and <code>generator</code> based co-routines; why does <code>Python3</code> have both? I understand what a generator based co-routine is.</p> <p>Was there a particular design decision or thought that made sense to have both? <...
1
2016-09-28T13:23:35Z
39,749,725
<p>Before 3.5, there was no real difference between a generator and a co-routine. A generator <em>is</em> a co-routine purely by using <code>yield</code> as an expression and expecting data via <code>send()</code>.</p> <p>This sort-of changed with the new <a href="https://www.python.org/dev/peps/pep-0492/" rel="nofoll...
3
2016-09-28T13:58:32Z
[ "python", "generator", "python-asyncio", "coroutine" ]
Matplotlib 3D scatter autoscale issue
39,748,867
<p>Python 2.7, matplotlib 1.5.1, Win 7, x64</p> <p>I am trying to plot the shortest distances between a node &amp; its geometrical nearest neighbour (ie not its nearest connected neighbour) in a graph using Dijkstra's algorithm. </p> <p>The algorithm is working fine but when it comes to plotting, matplotlib's scaling...
0
2016-09-28T13:24:28Z
39,781,033
<p>If the question here really is "How do I set the limits of a 3d plot in matplotlib?" then the answer would be:</p> <p>Just as you do in the 2d case: </p> <pre><code>ax.set_xlim([xmin, xmax]) ax.set_ylim([ymin, ymax]) ax.set_zlim([zmin, zmax]) </code></pre> <p>Finding the values of min and max for respective cases...
1
2016-09-29T22:34:03Z
[ "python", "matplotlib", "plot" ]
Find maximum value and index in a python list?
39,748,916
<p>I have a python list that is like this,</p> <pre><code>[[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968], [12587982, 0.88], [12587984, 0.8484848484848485], [12587992, 0.7777777777777778], [12587995, 0.8070175438596491], [12588015, 0.4358974358974359], [12588023, 0.89855...
3
2016-09-28T13:26:26Z
39,748,989
<pre><code>from operator import itemgetter a = [[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968], [12587982, 0.88], [12587984, 0.8484848484848485], [12587992, 0.7777777777777778], [12587995, 0.8070175438596491], [12588015, 0.4358974358974359], [12588023, 0.8985507246376812...
0
2016-09-28T13:29:35Z
[ "python", "list", "max" ]
Find maximum value and index in a python list?
39,748,916
<p>I have a python list that is like this,</p> <pre><code>[[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968], [12587982, 0.88], [12587984, 0.8484848484848485], [12587992, 0.7777777777777778], [12587995, 0.8070175438596491], [12588015, 0.4358974358974359], [12588023, 0.89855...
3
2016-09-28T13:26:26Z
39,749,005
<p>Use the <a href="https://docs.python.org/3/library/functions.html#max" rel="nofollow"><code>max</code></a> function and its <code>key</code> parameter, to use only the second element to compare elements of the list.</p> <p>For example,</p> <pre><code>&gt;&gt;&gt; data = [[12587961, 0.7777777777777778], [12587970, ...
7
2016-09-28T13:30:00Z
[ "python", "list", "max" ]
Find maximum value and index in a python list?
39,748,916
<p>I have a python list that is like this,</p> <pre><code>[[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968], [12587982, 0.88], [12587984, 0.8484848484848485], [12587992, 0.7777777777777778], [12587995, 0.8070175438596491], [12588015, 0.4358974358974359], [12588023, 0.89855...
3
2016-09-28T13:26:26Z
39,749,019
<p>Use <code>max</code> with a key.</p> <pre><code>l = [[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968], [12587982, 0.88], [12587984, 0.8484848484848485], [12587992, 0.7777777777777778], [12587995, 0.8070175438596491], [12588015, 0.4358974358974359], [12588023, 0.89855072...
3
2016-09-28T13:30:28Z
[ "python", "list", "max" ]
Find maximum value and index in a python list?
39,748,916
<p>I have a python list that is like this,</p> <pre><code>[[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968], [12587982, 0.88], [12587984, 0.8484848484848485], [12587992, 0.7777777777777778], [12587995, 0.8070175438596491], [12588015, 0.4358974358974359], [12588023, 0.89855...
3
2016-09-28T13:26:26Z
39,749,148
<p>Simple </p> <pre><code>list = [[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968], [12587982, 0.88], [12587984, 0.8484848484848485], [12587992, 0.7777777777777778], [12587995, 0.8070175438596491], [12588015, 0.4358974358974359], [12588023, 0.8985507246376812], [12588037, ...
-1
2016-09-28T13:35:30Z
[ "python", "list", "max" ]
Find maximum value and index in a python list?
39,748,916
<p>I have a python list that is like this,</p> <pre><code>[[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968], [12587982, 0.88], [12587984, 0.8484848484848485], [12587992, 0.7777777777777778], [12587995, 0.8070175438596491], [12588015, 0.4358974358974359], [12588023, 0.89855...
3
2016-09-28T13:26:26Z
39,749,733
<pre><code>allData = [[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968], [12587982, 0.88], [12587984, 0.8484848484848485], [12587992, 0.7777777777777778], [12587995, 0.8070175438596491], [12588015, 0.4358974358974359], [12588023, 0.8985507246376812], [12588037, 0.55555555555...
0
2016-09-28T13:58:52Z
[ "python", "list", "max" ]
Pandas Dataframe row number become the same after selected by condition
39,748,963
<p>So I have 100,000 row of data look like this</p> <p>df</p> <pre><code> date ticker holding 0 2016-09-22 1 788315240 1 2016-09-22 2 429232858 2 2016-09-22 3 1677428346 3 2016-09-22 4 321595332 </code></pre> <p>but when I do:</p> <pre><code>df.loc[df.ticker == 3] </code></pre...
1
2016-09-28T13:28:28Z
39,748,999
<p>You have duplicates values in <code>index</code> only.</p> <p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p> <pre><code>df.reset_index(drop=True, inplace=True) </code></pre> <p>Sample:</p> <pre><code>df = ...
0
2016-09-28T13:29:48Z
[ "python", "pandas", "indexing", "dataframe", "condition" ]
On the default/fill value for outer joins
39,748,976
<p>Below are teeny/toy versions of much larger/complex dataframes I'm working with:</p> <pre><code>&gt;&gt;&gt; A key u v w x 0 a 0.757954 0.258917 0.404934 0.303313 1 b 0.583382 0.504687 NaN 0.618369 2 c NaN 0.982785 0.902166 NaN 3 d 0.898838 0.47...
2
2016-09-28T13:29:04Z
39,749,744
<p>You can fill zeros after the <code>merge</code>:</p> <pre><code>res = pd.merge(A, B, how="outer") res.loc[~res.key.isin(A.key), A.columns] = 0 </code></pre> <p><strong>EDIT</strong></p> <p>to skip <code>key</code> column:</p> <pre><code>res.loc[~res.key.isin(A.key), A.columns.drop("key")] = 0 </code></pre>
1
2016-09-28T13:59:34Z
[ "python", "pandas" ]
Bank ATM Program login
39,749,051
<p>I want to make this program that acts as a bank, how do I make sure the correct ID number must be entered with the correct pin and have it depending on the id you entered print hello then their name and prompt how much money they have in the bank.</p> <pre><code>attempts = 0 store_id = [1057, 2736, 4659, 5691, 1234...
-4
2016-09-28T13:31:46Z
39,750,876
<p>I'm very impressed by how much you've elaborated on your program. Here's how I would view your solution.</p> <hr> <p>So to create a login simulation, I would instead use a <em>dictionary.</em> That way you can assign an ID to a PIN. For example:</p> <pre><code>credentials = { "403703": "121", "3900": "333...
0
2016-09-28T14:47:03Z
[ "python" ]
How to improve a mixin structure in Python?
39,749,146
<p>I have a simple mixin structure in Python. The code should be pretty self-explaining:</p> <pre><code>class Base: def __init__(self): pass class MixinA: def __init__(self): self.x = 0 self.y = 1 def a(self): print('A: x = ' + str(self.x) + ', y = ' + str(self.y)) class M...
1
2016-09-28T13:35:28Z
39,749,418
<p>When your inheritance schemes start to suffer from these sorts of issues it's time to consider using a technique called <em>composition</em> instead. A good readable introduction to the topic <a href="https://www.thoughtworks.com/insights/blog/composition-vs-inheritance-how-choose" rel="nofollow">here</a>. The <a hr...
0
2016-09-28T13:47:16Z
[ "python", "mixins" ]
How to improve a mixin structure in Python?
39,749,146
<p>I have a simple mixin structure in Python. The code should be pretty self-explaining:</p> <pre><code>class Base: def __init__(self): pass class MixinA: def __init__(self): self.x = 0 self.y = 1 def a(self): print('A: x = ' + str(self.x) + ', y = ' + str(self.y)) class M...
1
2016-09-28T13:35:28Z
39,752,890
<p>For python class inherent, I believe there are some tricks you need to know:</p> <ol> <li><p>Class in python2 and python3 are quite different. Python2 support old-style class, but python3 support new-style class only. Simply speaking: in python3, classes always inherent from a base class <code>object</code>, even t...
0
2016-09-28T16:24:08Z
[ "python", "mixins" ]
concatenate excel datas with python or Excel
39,749,152
<p>Here's my problem, I have an Excel sheet with 2 columns (see below)<a href="http://i.stack.imgur.com/jMLBZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/jMLBZ.png" alt="enter image description here"></a></p> <p>I'd like to print (on python console or in a excel cell) all the data under this form : </p> <p...
2
2016-09-28T13:35:41Z
39,749,442
<p>I think you can use <code>parse_cols</code> for parse first column and then filter out all columns from 205 to 1000 by <code>skiprows</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow"><code>read_excel</code></a>:</p> <pre><code>df = pd.read_excel('test.x...
2
2016-09-28T13:47:59Z
[ "python", "excel", "pandas", "xlsxwriter" ]
concatenate excel datas with python or Excel
39,749,152
<p>Here's my problem, I have an Excel sheet with 2 columns (see below)<a href="http://i.stack.imgur.com/jMLBZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/jMLBZ.png" alt="enter image description here"></a></p> <p>I'd like to print (on python console or in a excel cell) all the data under this form : </p> <p...
2
2016-09-28T13:35:41Z
39,749,520
<p>I am not familiar with excel, but pandas could easily handle this problem.</p> <p>First, read the excel to a DataFrame</p> <pre><code>import pandas as pd df = pd.read_excel(filename) </code></pre> <p>Then, print as you like</p> <pre><code>print({"1": list(df.iloc[0:N]['A'])}) </code></pre> <p>where <code>N</cod...
1
2016-09-28T13:51:02Z
[ "python", "excel", "pandas", "xlsxwriter" ]
Save FITS table: The keyword description with its value is too long
39,749,173
<p>I get an error when trying to save astropy Tables retrieved using astroquery to FITS files. In some case it complains that the description of some keywords is too long. The <code>writeto()</code> function seems to have a <code>output_verify</code> argument to avoid this kind of problem, but I cannot find how to pass...
1
2016-09-28T13:36:47Z
39,759,965
<p>The problem is that <code>table.meta['description']</code> is longer than allowed for the header of the fits file you're trying to save. You can simply shorten it to anything below 80 characters and try to write <code>test.fits</code> again:</p> <pre><code>table.meta['description'] = u'AKARI/IRC All-Sky Survey Poin...
2
2016-09-29T01:26:46Z
[ "python", "astropy" ]
Python : why doesn't a.pop() modify the list (custom linked-list class)
39,749,242
<p>I'm trying to define a class Hlist of linked lists as below:</p> <pre><code>class Hlist: def __init__(self, value, hlnext): self.value = value self.hlnext = hlnext def pop(self): res = self.value if not(self.hlnext == None): self = self.hlnext return res def __repr__(self): return...
2
2016-09-28T13:39:24Z
39,749,397
<p>Because <code>self</code> isn't working the way you think it is. <code>self</code> is just another local variable: assigning to it inside <code>pop()</code> won't change the object into another thing. See <a href="http://stackoverflow.com/questions/28531939/python-assignment-to-self-in-constructor-does-not-make-obje...
1
2016-09-28T13:46:25Z
[ "python", "pointers", "linked-list" ]
Python : why doesn't a.pop() modify the list (custom linked-list class)
39,749,242
<p>I'm trying to define a class Hlist of linked lists as below:</p> <pre><code>class Hlist: def __init__(self, value, hlnext): self.value = value self.hlnext = hlnext def pop(self): res = self.value if not(self.hlnext == None): self = self.hlnext return res def __repr__(self): return...
2
2016-09-28T13:39:24Z
39,749,420
<p>It's moslty because you can't change self directly.<br> If you think about pointers, you can't change the pointer address, except if you use a pointer on this pointer. Here, if you consider self as a pointer, when you assign another value to self, you don't really change the self pointer.</p> <p><a href="http://sta...
0
2016-09-28T13:47:19Z
[ "python", "pointers", "linked-list" ]
Python QT. Form from another Form
39,749,268
<p>First i am beginning in programming :)</p> <p>I create in QT Designer Form ( MainForm) and add function in button to open a new form. I do this step from <a href="http://stackoverflow.com/questions/27567208/how-do-i-open-sub-window-after-i-click-on-button-on-main-screen-in-pyqt4">How do I open sub window after I ...
0
2016-09-28T13:40:47Z
39,749,394
<p>Have you compiled your code to python? By default it will be a ui file. You can use <code>pyuic4.exe</code> file.</p> <pre><code>c:\Python27\Lib\site-packages\PyQt4\something&gt; pyuic4.exe full/path/to/input.ui -o full/path/to/output.py </code></pre>
0
2016-09-28T13:46:18Z
[ "python", "qt", "pyqt" ]
Python QT. Form from another Form
39,749,268
<p>First i am beginning in programming :)</p> <p>I create in QT Designer Form ( MainForm) and add function in button to open a new form. I do this step from <a href="http://stackoverflow.com/questions/27567208/how-do-i-open-sub-window-after-i-click-on-button-on-main-screen-in-pyqt4">How do I open sub window after I ...
0
2016-09-28T13:40:47Z
39,767,246
<p>Look into the generated file. Usually <code>pyuic4</code> generates a class that is not a QtWidget it is just a factory with a <code>setupUI</code> method.</p> <p>I usually do this:</p> <pre><code>class MyForm(QtGui.QWidget, Ui_V1): def __init__(self, *args): QtGui.QWidget.__init__(self, *args) ...
0
2016-09-29T10:02:11Z
[ "python", "qt", "pyqt" ]
Simpel Python Calculator - Syntax Error - Indentation errors
39,749,277
<p>I recently started learning Python. I have never coded before, but it seemed like a challenge. The first thing I have made is this calculator. However, I can't seem to get it to work. </p> <pre><code>while True: print("Typ 'plus' to add two numbers") print("Typ 'min' to subtract two numbers") print("Typ...
-4
2016-09-28T13:41:05Z
39,750,237
<p>You missed a colon after an this if statement</p> <pre><code>if user_input == "end" break </code></pre> <p>Should Be:</p> <pre><code>if user_input == "end": break </code></pre>
0
2016-09-28T14:20:18Z
[ "python" ]
Auto convert strings and float columns using genfromtxt from numpy/python
39,749,447
<p>I have several different data files that I need to import using genfromtxt. Each data file has different content. For example, file 1 may have all floats, file 2 may have all strings, and file 3 may have a combination of floats and strings etc. Also the number of columns vary from file to file, and since there are h...
0
2016-09-28T13:48:06Z
39,750,409
<p>If you're able to use the Pandas library, <code>pandas.read_csv</code> is <em>much</em> more generally useful than <code>np.genfromtxt</code>, and will automatically handle the kind of type inference mentioned in your question. The result will be a dataframe, but you can get out a numpy array in one of several ways...
1
2016-09-28T14:26:54Z
[ "python", "numpy", "data-type-conversion", "genfromtxt" ]
Action bar in anchorlayout - KIVY. python
39,749,526
<p>My goal is to make add these 3 buttons to an actionbar on the top of the screen as seen in the screenshot, please help.</p> <p>.kv file</p> <pre><code>AnchorLayout: anchor_x: 'center' anchor_y: 'top' BoxLayout: padding: 30 size_hint: 1, .1 orientation: 'horizontal' Butt...
0
2016-09-28T13:51:15Z
39,758,458
<p>I suggest you use a relative layout inside your box layout:</p> <pre><code>BoxLayout: padding: 30 size_hint: 1, .1 orientation: 'horizontal' RelativeLayout: Button: text: 'Back' pos_hint: {'center_x': 0.1, 'center_y': 0.5} on_press: root.manager.current...
0
2016-09-28T22:08:59Z
[ "python", "android-actionbar", "kivy" ]
python: generate numeric column to column with string
39,749,557
<p>I have a dataframe and it's a part of a column</p> <pre><code>category Search Search Онлайн-магазин Онлайн-магазин Форумы и отзывы Онлайн-магазин Форумы и отзывы Агрегатор Информационный ресурс Онлайн-магазин ...
1
2016-09-28T13:52:28Z
39,749,617
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow"><code>factorize</code></a>:</p> <pre><code>df['numeric_category'] = pd.factorize(df.category)[0] + 1 </code></pre> <p>Then you can also convert it to <code>category</code> for saving memory:</p> <pre><code>df[...
1
2016-09-28T13:54:40Z
[ "python", "pandas" ]
python: generate numeric column to column with string
39,749,557
<p>I have a dataframe and it's a part of a column</p> <pre><code>category Search Search Онлайн-магазин Онлайн-магазин Форумы и отзывы Онлайн-магазин Форумы и отзывы Агрегатор Информационный ресурс Онлайн-магазин ...
1
2016-09-28T13:52:28Z
39,749,906
<pre><code>dict={} for item in df.category: if item not in dict: dict[item]=len(dict)+1 print "category\t"+"numeric_category" for item in df.category: print "%s\t%s"%(item,dict[item]) </code></pre>
1
2016-09-28T14:06:25Z
[ "python", "pandas" ]
How to get a list of useless features using sklearn?
39,749,592
<p>I have a dataset to build a classificator:</p> <pre><code>dataset = pd.read_csv(sys.argv[1], decimal=",",delimiter=";", encoding='cp1251') X=dataset.ix[:, dataset.columns != 'class'] Y=dataset['class'] </code></pre> <p>I want to select important features only, so I do:</p> <pre><code>clf=svm.SVC(probability=True,...
0
2016-09-28T13:53:44Z
39,750,096
<p><code>clf.coef_</code> returns you a list of feature weights (apply after <code>fit()</code>). Sort it by weights and you see which are not very useful.</p>
0
2016-09-28T14:15:01Z
[ "python", "pandas", "scikit-learn", "feature-selection", "sklearn-pandas" ]
How to get a list of useless features using sklearn?
39,749,592
<p>I have a dataset to build a classificator:</p> <pre><code>dataset = pd.read_csv(sys.argv[1], decimal=",",delimiter=";", encoding='cp1251') X=dataset.ix[:, dataset.columns != 'class'] Y=dataset['class'] </code></pre> <p>I want to select important features only, so I do:</p> <pre><code>clf=svm.SVC(probability=True,...
0
2016-09-28T13:53:44Z
39,759,099
<p>You might also want to take a look at <a href="http://scikit-learn.org/stable/modules/feature_selection.html" rel="nofollow">Feature Selection</a>. It describes some techniques and tools to do this more systematically.</p>
1
2016-09-28T23:23:06Z
[ "python", "pandas", "scikit-learn", "feature-selection", "sklearn-pandas" ]
python table view output
39,749,594
<p>I have some thing like this in output.txt file</p> <pre><code>Service1:Aborted Service2:failed Service3:failed Service4:Aborted Service5:failed </code></pre> <p>output in 2nd file(output2.txt) :</p> <pre><code> Service1 Service2 Servive3 Service4 Service5 Aborted failed failed Abor...
0
2016-09-28T13:53:50Z
39,749,880
<p>Very quickly:</p> <pre><code>headers = [] statuses = [] for line in file: line=line.strip() parts=line.split(":") headers.append(parts[0]) statuses.append(parts[1]) format_str = '{:&gt;15}'*(len(headers)) print(format_str.format(*headers)) print(format_str.format(*statuses)) </code></pre>
2
2016-09-28T14:05:18Z
[ "python", "python-2.7", "python-3.x" ]
python table view output
39,749,594
<p>I have some thing like this in output.txt file</p> <pre><code>Service1:Aborted Service2:failed Service3:failed Service4:Aborted Service5:failed </code></pre> <p>output in 2nd file(output2.txt) :</p> <pre><code> Service1 Service2 Servive3 Service4 Service5 Aborted failed failed Abor...
0
2016-09-28T13:53:50Z
39,749,946
<p>You're on your own for figuring out how to get your input data into a numpy array, and what example the reshape function does, but this should get you about 75% to the finish line</p> <pre><code>import numpy as np import pandas as pd A_in = [[1,2,3],[4,5,6]] B = pd.DataFrame(np.array(A_in).reshape(3,2)) B.to_csv('o...
0
2016-09-28T14:07:41Z
[ "python", "python-2.7", "python-3.x" ]
How to groupby and assign an array to a column in python-pandas?
39,749,653
<p>Given a data frame <code>df</code> like that:</p> <pre><code>a b 2 nan 3 nan 3 nan 4 nan 4 nan 4 nan 5 nan 5 nan 5 nan 5 nan ... </code></pre> <p>A critical rule is that each number <code>n</code> in <code>a</code> repeat <code>n-1</code> rows. And my expected outp...
1
2016-09-28T13:55:48Z
39,749,852
<pre><code># make a column that is 0 on the first occurrence of a number in a and 1 after df['is_duplicated'] = df.duplicated(['a']).astype(int) # group by values of a and get the cumulative sum of duplicates # add one since the first duplicate has a value of 0 df['b'] = df[['a', 'is_duplicated']].groupby(['a']).cumsu...
1
2016-09-28T14:04:13Z
[ "python", "pandas", "numpy", "dataframe" ]
How to groupby and assign an array to a column in python-pandas?
39,749,653
<p>Given a data frame <code>df</code> like that:</p> <pre><code>a b 2 nan 3 nan 3 nan 4 nan 4 nan 4 nan 5 nan 5 nan 5 nan 5 nan ... </code></pre> <p>A critical rule is that each number <code>n</code> in <code>a</code> repeat <code>n-1</code> rows. And my expected outp...
1
2016-09-28T13:55:48Z
39,749,910
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a>:</p> <pre><code>df['b'] = df.groupby('a').cumcount() + 1 print (df) a b 0 2 1 1 3 1 2 3 2 3 4 1 4 4 2 5 4 3 6 5 1 7 5 2 8 5 3 9 5 4 </co...
3
2016-09-28T14:06:34Z
[ "python", "pandas", "numpy", "dataframe" ]
Connect MSSQL 2014 using python 3.4
39,749,682
<p>I'm trying to connect MSSQL 2014 database using python (3.4).</p> <p>I installed the pypyodbc package.</p> <pre><code> import pypyodbc connection = pypyodbc.connect('DRIVER ={SQL Server};' 'SERVER = myserver;' 'UID=user;' 'PWD=password;' 'DATABASE = dbo.db') </code></pre> <p>When I tried this, I'm getti...
0
2016-09-28T13:56:57Z
39,751,443
<p>Check which drivers are installed (in Powershell)</p> <pre><code>Get-ItemProperty 'hklm:\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers' </code></pre> <p>Also, Remove the spaces from 'SERVER = myServer' to make 'SERVER=myServer'. For me this works</p> <pre><code>conn = pypyodbc.connect('Driver={SQL Server Native Client ...
1
2016-09-28T15:13:44Z
[ "python", "sql-server", "python-3.x" ]
Passing a list of column names to a query in psycopg2
39,749,684
<p>I have the following query:</p> <pre><code>select distinct * from my_table where %s is NULL; </code></pre> <p>I would like to be able to pass in more than one column name to this query, but I do not know how many columns I will want to be checking for nulls every time.</p> <p>How can I use query parameter techniq...
0
2016-09-28T13:56:59Z
39,794,963
<pre><code>query = ''' select distinct * from my_table where %s or "col1" is NULL and %s or "col2" is NULL and %s or "col3" is NULL and %s ''' </code></pre> <p>Pass <code>True</code> to the conditions which you want to be evaluated. Say you want rows where any of <code>col1<...
1
2016-09-30T15:24:04Z
[ "python", "postgresql", "amazon-redshift", "psycopg2" ]
Convert string within matrix row to matrix with rows and columns, and numbers in string to integers
39,749,745
<p>I saved a sheet from excel into csv format. And after importing the data in python with the code:</p> <pre><code>import csv with open('45deg_marbles.csv', 'r') as f: reader = csv.reader(f,dialect='excel') basis = [] for row in reader: print(row) </code></pre> <p>Output:</p> <pre><code>['1;2;3;...
1
2016-09-28T13:59:35Z
39,749,813
<p>You can append a list without having to replace <code>;</code> with <code>,</code> </p> <pre><code>import csv with open('45deg_marbles.csv', 'r') as f: reader = csv.reader(f) basis = [] for row in reader: basis.append(list(map(float,row[0].split(';')))) </code></pre> <p>The row is coming through as a str...
-1
2016-09-28T14:02:25Z
[ "python", "python-2.7", "python-3.x", "csv", "matrix" ]
Convert string within matrix row to matrix with rows and columns, and numbers in string to integers
39,749,745
<p>I saved a sheet from excel into csv format. And after importing the data in python with the code:</p> <pre><code>import csv with open('45deg_marbles.csv', 'r') as f: reader = csv.reader(f,dialect='excel') basis = [] for row in reader: print(row) </code></pre> <p>Output:</p> <pre><code>['1;2;3;...
1
2016-09-28T13:59:35Z
39,749,882
<p>what you need to do is</p> <pre><code>for row in reader: basis.append(row.split(';')) </code></pre> <p>What you are doing wrong is that you replace ';' with comma ',' this does not make a list from a string, just replaces a symbol in this string. While you should split string to elements.</p>
-2
2016-09-28T14:05:21Z
[ "python", "python-2.7", "python-3.x", "csv", "matrix" ]
Convert string within matrix row to matrix with rows and columns, and numbers in string to integers
39,749,745
<p>I saved a sheet from excel into csv format. And after importing the data in python with the code:</p> <pre><code>import csv with open('45deg_marbles.csv', 'r') as f: reader = csv.reader(f,dialect='excel') basis = [] for row in reader: print(row) </code></pre> <p>Output:</p> <pre><code>['1;2;3;...
1
2016-09-28T13:59:35Z
39,750,009
<p>change separator to a semicolon (default is comma, which does not work here since your input data has semicolons in it) (I think you could omit the <code>dialect='excel'</code> part)</p> <pre><code>import csv with open('45deg_marbles.csv', 'r') as f: reader = csv.reader(f,dialect='excel',delimiter=";") bas...
2
2016-09-28T14:10:50Z
[ "python", "python-2.7", "python-3.x", "csv", "matrix" ]
Optimize Python: Large arrays, memory problems
39,749,807
<p>I'm having a speed problem running a python / numypy code. I don't know how to make it faster, maybe someone else?</p> <p>Assume there is a surface with two triangulation, one fine (..._fine) with M points, one coarse with N points. Also, there's data on the coarse mesh at every point (N floats). I'm trying to do t...
3
2016-09-28T14:02:02Z
39,751,039
<p><strong>Approach #1</strong></p> <p>We are working with large sized datasets and memory is an issue, so I will try to optimize the computations within the loop. Now, we can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> to replace <code>...
1
2016-09-28T14:54:57Z
[ "python", "arrays", "performance", "numpy", "large-data" ]
Optimize Python: Large arrays, memory problems
39,749,807
<p>I'm having a speed problem running a python / numypy code. I don't know how to make it faster, maybe someone else?</p> <p>Assume there is a surface with two triangulation, one fine (..._fine) with M points, one coarse with N points. Also, there's data on the coarse mesh at every point (N floats). I'm trying to do t...
3
2016-09-28T14:02:02Z
39,767,338
<p>First of all thanks for the detailed help. </p> <p>First, Divakar, your solutions gave substantial speed-up. With my data, the code ran for just below 2 minutes depending a bit on the chunk size. </p> <p>I also tried my way around sklearn and ended up with </p> <pre><code>def sklearnSearch_v3(p, p_fine, k): n...
2
2016-09-29T10:06:19Z
[ "python", "arrays", "performance", "numpy", "large-data" ]
os.system does not look the programs that are in my path
39,749,896
<p>I have a problem when calling programs inside a python script. The programs that are giving me problems are those that I have installed manually on my computer and then added them to path on .bashrc file. The programs that where installed using 'sudo apt-get install some_program' don't give me any problem</p> <p>Th...
0
2016-09-28T14:05:51Z
39,750,138
<p>Presumably this is happening because you have modified your login environment to adjust your PATH, but this updated path isn't seen by the shell that's running PyCharm, or PyCharm appears to be nullifying it somehow.</p> <p>You should first of all verify that</p> <pre><code>os.system('/home/bioinfor3/bin/FastQC/fa...
1
2016-09-28T14:16:21Z
[ "python", "bash", "operating-system", "pycharm" ]
Error in query many-to-many relationship in sqlalchemy using flask
39,749,903
<p>I have two models CoreDrive and GamificationTechnique and a generated table of a many-to-many relationship. I'm trying to do a simple query in table cores_techiques , but always get the error. </p> <p>AttributeError: 'Table' object has no attribute 'query'. </p> <p>I'm using python3, flask and sqlalchemy. I'm very...
0
2016-09-28T14:06:16Z
39,906,323
<p>You can list all the <code>CoreDriver</code> and each object have a list of the <code>GamificationTechnique</code></p> <pre><code>cores = CoreDrivers.query.all() for core in cores: print core.techniques </code></pre> <p>With this in mind you can spend only the list <code>cores</code> to page</p>
0
2016-10-06T22:04:29Z
[ "python", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Python Gtk3 Window Icon from SVG / scalable icon from stock theme
39,750,041
<p>How to set an high quality icon to Gtk.Window ? My theme has SVG icons, but I always get an pixel size of 24 px. So what is wrong with my code? Would be very happy for some help. Thanks</p> <p><a href="http://i.stack.imgur.com/7L9p4.png" rel="nofollow"><img src="http://i.stack.imgur.com/7L9p4.png" alt="enter image ...
2
2016-09-28T14:12:38Z
39,819,514
<p>I could be mistaken, here are some ideas:</p> <ul> <li>I don't have <em>any</em> icon on my machine called "applications-mail". I did find many "internet-mail" icons though. </li> </ul> <blockquote> <p>/usr/share/icons/Mint-X/categories/96/applications-mail.svg</p> </blockquote> <ul> <li>Also, I believe svg ico...
1
2016-10-02T17:10:38Z
[ "python", "icons", "gtk3" ]
DRY selection of a subset of a dictionary
39,750,165
<p>Suppose I have a dictionary <code>config</code> which, among others, has the keys <code>username</code> and <code>password</code>. I'd like to create a new dictionary consisting only of the <code>username</code> and <code>password</code> key-value pairs from <code>config</code>. One way to do this is:</p> <pre><cod...
1
2016-09-28T14:17:12Z
39,750,258
<p>You can just create <code>tuple</code> or <code>list</code> that stores names of fields that you want to be copied and iterate through every element</p> <pre><code>new_dictionary = {k: config[k] for k in ('username', 'password')} </code></pre>
3
2016-09-28T14:21:19Z
[ "python", "dictionary" ]
DRY selection of a subset of a dictionary
39,750,165
<p>Suppose I have a dictionary <code>config</code> which, among others, has the keys <code>username</code> and <code>password</code>. I'd like to create a new dictionary consisting only of the <code>username</code> and <code>password</code> key-value pairs from <code>config</code>. One way to do this is:</p> <pre><cod...
1
2016-09-28T14:17:12Z
39,750,880
<p>You could store the username/password pair in a sub dictionary (called credential)</p> <pre><code>config = { 'param1': 'value1', 'credential': { 'username': 'myname', 'password': 'pa22w0rd' } } new-dictionary = config['credential'] </code></pre> <p>You could create a credential class and pass that object around in...
0
2016-09-28T14:47:11Z
[ "python", "dictionary" ]
Python open url with urllib than get back the changed url of opened webpage
39,750,189
<p>I want to send some requests to Google maps. I open the url that is changed based on the request. And I want to get back the changed url. An example:</p> <pre><code>import urllib, urllib2 my_address = '1600 Amphitheatre Parkway Mountain View, CA 94043' data = urllib.urlencode({'output':'csv', 'q':my_address}) req ...
0
2016-09-28T14:17:58Z
39,750,425
<p>you can use the .geturl() method inside urllib2</p> <p>Example:</p> <pre><code>print res_0.geturl() </code></pre>
0
2016-09-28T14:28:08Z
[ "python", "url", "urllib2" ]
Intelligently Determine Image Size in Python
39,750,205
<p>I would like to use Python to intelligently choose dimensions (in inches) for pictures. Were I to do this manually, I would open the picture in some photo editing software and resize the image until it seemed 'good'. </p> <p>Other answers I've seen on SO have pre-specified dimensions, but in this case that's what...
0
2016-09-28T14:18:42Z
39,751,695
<p>Forget dpi. It is a very confusing term. Unless you scan\print (ie use a physical medium), this doesn't mean much.</p> <p>A good <strong>digital</strong> dimension has the following :</p> <ul> <li>The biggest factor of 2 possible. This is why most standard digital resolution (esp. in video have size multiple of 2^...
1
2016-09-28T15:25:10Z
[ "python", "image-processing", "python-imaging-library" ]
Intelligently Determine Image Size in Python
39,750,205
<p>I would like to use Python to intelligently choose dimensions (in inches) for pictures. Were I to do this manually, I would open the picture in some photo editing software and resize the image until it seemed 'good'. </p> <p>Other answers I've seen on SO have pre-specified dimensions, but in this case that's what...
0
2016-09-28T14:18:42Z
39,756,780
<p>I guess I asked a bit prematurely. This hinges more on understanding resolution vs. DPI than it does on programming. Once I learned more, the answer becomes quite easy. Digital images have resolutions, while printed images have DPI. To choose the size of a digital image such that, if printed, that image will hav...
0
2016-09-28T20:09:25Z
[ "python", "image-processing", "python-imaging-library" ]
Responsive IPython notebook with running progress bar of dask/distributed
39,750,223
<p>I am running a cluster with <code>dask.distributed</code>. Currently I submit tasks to the cluster with Jupyter notebook that I use as a GUI.</p> <p>The respective notebook cell contains the following code.</p> <pre><code>%pylab inline %load_ext autoreload %autoreload 2 from distributed import progress sys.path.a...
0
2016-09-28T14:19:42Z
39,807,890
<blockquote> <p>My explanation of this is that r is deleted and its destructor sends cancellation requests to the cluster</p> </blockquote> <p>This is correct. A simple way to avoid this would be to add <code>r</code> to some result set that is not deleted every time you run your cell</p> <pre><code>-- cell 1 -- ...
1
2016-10-01T14:42:07Z
[ "python", "distributed", "jupyter-notebook", "dask" ]
Finding probability of word in string
39,750,449
<p>If I have a longer string, how do I calculate the probability of finding a word of a given length within that string?</p> <p>So far I have this:</p> <pre class="lang-python prettyprint-override"><code>import math from scipy import stats alphabet = list("ATCG") # This is the alphabet I am working with string = "A...
0
2016-09-28T14:29:29Z
39,750,806
<p>I think you should do:</p> <pre><code>n_substrings = len(string) - len(word) +1 </code></pre> <p>In a 5 letter string, with a 4 letter substring you have 2 options: ATCGA can hold ATCG and TCGA</p>
1
2016-09-28T14:44:26Z
[ "python", "statistics" ]
Remove an even/odd number from an odd/even Python list
39,750,474
<p>I am trying to better understand list comprehension in Python. I completed an online challenge on codewars with a rather inelegant solution, given below.</p> <p>The challenge was:</p> <ol> <li>Given a list of even numbers and one odd, return the odd</li> <li>Given a list of odd numbers and one even, return the ev...
1
2016-09-28T14:30:56Z
39,750,601
<p>Your attempt fails because the first <code>if</code> is <em>always going to be true</em>. You'll always have a list with at least 1 element; either the odd one out is odd and you tested a list with all even numbers, otherwise you have a list with the <em>one</em> even number in it. Only an <em>empty</em> list would ...
6
2016-09-28T14:36:38Z
[ "python", "list", "list-comprehension" ]
Remove an even/odd number from an odd/even Python list
39,750,474
<p>I am trying to better understand list comprehension in Python. I completed an online challenge on codewars with a rather inelegant solution, given below.</p> <p>The challenge was:</p> <ol> <li>Given a list of even numbers and one odd, return the odd</li> <li>Given a list of odd numbers and one even, return the ev...
1
2016-09-28T14:30:56Z
39,750,803
<p>The most efficient answer is going to get a little ugly.</p> <pre><code>def f(in_list): g = (i for i in in_list) first = next(g) second = next(g) #The problem as described doesn't make sense for fewer than 3 elements. Let them handle the exceptions. if first%2 == second%2: a = first%2 ...
-1
2016-09-28T14:44:24Z
[ "python", "list", "list-comprehension" ]
Remove an even/odd number from an odd/even Python list
39,750,474
<p>I am trying to better understand list comprehension in Python. I completed an online challenge on codewars with a rather inelegant solution, given below.</p> <p>The challenge was:</p> <ol> <li>Given a list of even numbers and one odd, return the odd</li> <li>Given a list of odd numbers and one even, return the ev...
1
2016-09-28T14:30:56Z
39,750,869
<p>What are the shortcomings of this response (which is at the top of the solution stack on <a href="https://www.codewars.com/kata/find-the-parity-outlier/solutions/python" rel="nofollow">this particular challenge</a>)?</p> <pre><code>def find_outlier(int): odds = [x for x in int if x%2!=0] evens= [x for x in ...
0
2016-09-28T14:46:54Z
[ "python", "list", "list-comprehension" ]
com0com and pyserial virtual serial ports. Can this be used to simulate unplugging a serial usb device?
39,750,547
<p>I am using com0com and pyserial. I open one port, write to it using pyserial and read from it in the YAT emulator. This works great. Can this setup be used to simulate unplugging of a usb device that is emulating a serial port? I want to recreate a UnauthorizedAccessException that is rarely thrown by real devices in...
0
2016-09-28T14:34:07Z
39,760,718
<p>Unauthorized access is simple to replicate. Open up the port with another application, perhaps in another YAT tab. When you try to connect with a different application, you should get an unauthorized access error. However, I'm not sure if that is really the question you are asking.</p> <p>If you really want to emul...
0
2016-09-29T03:03:02Z
[ "python", "windows", "serial-port", "pyserial", "com0com" ]
Python 3 Base64 decode messing up newline characters
39,750,575
<p>I'm trying to decode a base64 multi-line file through the standard python library, however only the first line gets decoded, and the rest gets dumped for no reason.</p> <p>Why is this?</p> <p>The file before it gets encoded (what I'm trying to achieve after decoding):</p> <blockquote> <p>dataFile.dat</p> <...
1
2016-09-28T14:35:18Z
39,751,232
<p>The problem appears to be that you are encoding each line separately and then joining those encoded strings together. A Base-64 encoded string may end in padding characters, and when the decoder sees those padding characters it assumes that's the end of the valid data, so any following data is ignored.</p> <p>Here'...
1
2016-09-28T15:03:50Z
[ "python", "base64", "decoding" ]
Pandas groupby sum
39,750,590
<p>I have a dataframe as follows:</p> <pre><code>ref, type, amount 001, foo, 10 001, foo, 5 001, bar, 50 001, bar, 5 001, test, 100 001, test, 90 002, foo, 20 002, foo, 35 002, bar, 75 002, bar, 80 002, test, 150 002, test, 110 </code></pre> <p>This is what I'm trying to get:</p> <pre><code>ref, type, amount, foo, b...
0
2016-09-28T14:36:07Z
39,750,769
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a> and then <a href="http://pa...
3
2016-09-28T14:43:30Z
[ "python", "pandas", "merge", "group-by", "sum" ]
Pandas groupby sum
39,750,590
<p>I have a dataframe as follows:</p> <pre><code>ref, type, amount 001, foo, 10 001, foo, 5 001, bar, 50 001, bar, 5 001, test, 100 001, test, 90 002, foo, 20 002, foo, 35 002, bar, 75 002, bar, 80 002, test, 150 002, test, 110 </code></pre> <p>This is what I'm trying to get:</p> <pre><code>ref, type, amount, foo, b...
0
2016-09-28T14:36:07Z
39,750,886
<p>A solution using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html">pivot table</a> :</p> <pre><code>&gt;&gt;&gt; b = pd.pivot_table(df, values='amount', index=['ref'], columns=['type'], aggfunc=np.sum) &gt;&gt;&gt; b type bar foo test ref 1 55 15 190 2 155 55 ...
6
2016-09-28T14:47:18Z
[ "python", "pandas", "merge", "group-by", "sum" ]
Python Multi-threading in a recordset
39,750,873
<p>I have a database record set (approx. 1000 rows) and I am currently iterating through them, to integrate more data using extra db query for each record.</p> <p>Doing that, raises the overall process time to maybe 100 seconds.</p> <p>What I want to do is share the functionality to 2-4 processes.</p> <p>I am using ...
1
2016-09-28T14:46:58Z
39,753,853
<p>Your code seems pretty in-depth and so you cannot be sure that <code>multithreading</code> will lead to any performance gains when applied on a high level. Therefore, it's worth digging down to the point that gives you the largest latency and considering how to approach the specific bottleneck. See <a href="http://s...
2
2016-09-28T17:16:48Z
[ "python", "multithreading", "python-2.7", "lambda" ]
How to split text into chunks minimizing the solution?
39,750,879
<p><strong>OVERVIEW</strong> </p> <p>I got a set of possible valid chunks I can use to split a text (if possible).</p> <p>How can i split a given text using these chunks such as the result will be optimized (minimized) in terms of the number of resulting chunks?</p> <p><strong>TEST SUITE</strong></p> <pre><code>if ...
8
2016-09-28T14:47:06Z
39,752,628
<p>Using dynamic programming, you can construct a list <code>(l0, l1, l2, ... ln-1)</code>, where <code>n</code> is the number of characters in your input string and <code>li</code> is the minimum number of chunks you need to arrive at character <code>i</code> of the input string. The overall structure would look as fo...
7
2016-09-28T16:09:29Z
[ "python", "string", "algorithm", "split", "computer-science" ]
How to split text into chunks minimizing the solution?
39,750,879
<p><strong>OVERVIEW</strong> </p> <p>I got a set of possible valid chunks I can use to split a text (if possible).</p> <p>How can i split a given text using these chunks such as the result will be optimized (minimized) in terms of the number of resulting chunks?</p> <p><strong>TEST SUITE</strong></p> <pre><code>if ...
8
2016-09-28T14:47:06Z
39,833,238
<pre><code>def find_shortest_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if start not in graph: return None shortest = None for node in graph[start]: if node not in path: newpath = find_shortest_path(graph, node, end, path)...
2
2016-10-03T13:47:49Z
[ "python", "string", "algorithm", "split", "computer-science" ]
How to split text into chunks minimizing the solution?
39,750,879
<p><strong>OVERVIEW</strong> </p> <p>I got a set of possible valid chunks I can use to split a text (if possible).</p> <p>How can i split a given text using these chunks such as the result will be optimized (minimized) in terms of the number of resulting chunks?</p> <p><strong>TEST SUITE</strong></p> <pre><code>if ...
8
2016-09-28T14:47:06Z
39,892,785
<pre><code>def find_shortest_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if start not in graph: return None shortest = None for node in graph[start]: if node not in path: newpath = find_shortest_path(graph, node, end, path)...
-3
2016-10-06T09:49:49Z
[ "python", "string", "algorithm", "split", "computer-science" ]
How to split text into chunks minimizing the solution?
39,750,879
<p><strong>OVERVIEW</strong> </p> <p>I got a set of possible valid chunks I can use to split a text (if possible).</p> <p>How can i split a given text using these chunks such as the result will be optimized (minimized) in terms of the number of resulting chunks?</p> <p><strong>TEST SUITE</strong></p> <pre><code>if ...
8
2016-09-28T14:47:06Z
39,904,054
<p>Sorry, the implementation is a bit hacky. But I think it always returns the optimal answer. (Did not proove, though.) It is a fast and complete implementation in python and returns the correct answers for all proposed use cases.</p> <p>The algorithm is recursive and works as follows:</p> <ol> <li>start at the begi...
4
2016-10-06T19:20:05Z
[ "python", "string", "algorithm", "split", "computer-science" ]
Python rewriting instead of appending
39,751,095
<p>I have two csv files result.csv and sample.csv.</p> <p>result.csv</p> <pre><code>M11251TH1230 M11543TH4292 M11435TDS144 </code></pre> <p>sample.csv</p> <pre><code>M11435TDS144,STB#1,Router#1 M11543TH4292,STB#2,Router#1 M11509TD9937,STB#3,Router#1 M11543TH4258,STB#4,Router#1 </code></pre> <p>I have a python ...
0
2016-09-28T14:57:07Z
39,751,361
<p>you write to the <code>sample.csv</code> and then you use it as input file, with the additional column. That's why you have more and more 1's and 0's in this file. Regards, Grzegorz</p>
0
2016-09-28T15:09:39Z
[ "python", "csv", "fileappender" ]
Early stopping with tflearn
39,751,113
<p>I'm having a hard time to figure out how to implement early stopping with tflearn. Supposedly it works by using callbacks in the model.fit() function but I don't quite get how it's done... This is the example on the website but it still needs a Monitor class that I can't get to work:</p> <pre><code>class MonitorCal...
0
2016-09-28T14:58:08Z
39,927,599
<p>Which version of tflearn are you using? Most probably you will need to download the repo to leverage the feature right now. <a href="https://github.com/tflearn/tflearn/pull/288" rel="nofollow">Early commits for the feature are dated on Aug 17 2016</a> but latest release (<a href="https://github.com/tflearn/tflearn/c...
0
2016-10-08T00:54:02Z
[ "python", "machine-learning", "tensorflow" ]
How to select a span element using selenium in python?
39,751,153
<p>I am trying to select month which is a table element using the below code where I am finding the table element using <code>xpath</code>. </p> <p>This code works:</p> <pre><code>month = driver.find_element_by_xpath('/html/body/div[11]/div[3]/table/tbody/tr/td/span[text()="Aug"]) month.click() </code></pre> <p>Here...
0
2016-09-28T14:59:55Z
39,754,392
<p>Actually your question is not much clear, I think you want to append <code>year</code> variable value into your <code>xpath</code> to locate an element with input text, to achieve this you should try as below :-</p> <pre><code>year = str(raw_input("Enter year") month = driver.find_element_by_xpath("/html/body/div[1...
0
2016-09-28T17:47:23Z
[ "python", "html", "python-2.7", "selenium-webdriver", "html-table" ]
Python: Trying to restart script not working
39,751,206
<p>Tried to restart my python script within itself. Python 2.7.11</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys os.execv(__file__, sys.argv) sys.exit() </code></pre> <p>Result:</p> <pre><code>Traceback (most recent call last): File "...\foo.py", line 3, in &lt;module&gt; o...
0
2016-09-28T15:02:42Z
39,752,046
<p>Your error message <code>C:\...\python.exe</code> suggests that you're running a Windows system. </p> <p>Your first script fails because under Windows, <code>os.execv()</code> doesn't know how to handle Python scripts because the first line (<code>#!/usr/bin/python</code>) is not evaluated nor does it point to a va...
0
2016-09-28T15:40:58Z
[ "python", "exec", "restart" ]
Regex to extract titles from the text
39,751,242
<p>Can anyone help with the regex to extract the text phrases after 'Title:' from the following text: (have just bolded the text to clearly depict the portion to be extracted)</p> <pre>Title: <b>Anorectal Fistula (Fistula-in-Ano)</b> Procedure Code(s): Effective date: 7/1/07 Title: <b>2003247</b> or previous e...
2
2016-09-28T15:04:08Z
39,809,089
<p>I suggest using</p> <pre><code> Title:\s*(.*?)\s*Procedure|Title:\s*(.*) </code></pre> <p>See the <a href="https://regex101.com/r/a8DXbK/1" rel="nofollow">regex demo</a>.</p> <p><em>Details</em>:</p> <ul> <li><code>Title:</code> - literal text <code>Title:</code></li> <li><code>\s*</code> - 0+ whitespaces</li> <...
0
2016-10-01T16:43:24Z
[ "python", "regex", "python-2.7", "text-extraction" ]
REGEX formulating conditions
39,751,262
<p>Just started learning python and regex. </p> <pre><code>My regex: \b\d+\s+([A-Za-z]* |[A-Za-z]*\s+[A-Za-z]*)\s+\D+.. </code></pre> <p>using <a href="https://regex101.com/" rel="nofollow">https://regex101.com/</a> </p> <p><strong>string 1:</strong> <a href="https://i.imgur.com/XNuXftW.jpg" rel="nofollow">https://i...
0
2016-09-28T15:05:20Z
39,751,529
<p>Try this:</p> <pre><code>\d+\s+([A-Za-z ]*)\b *\D+ </code></pre> <p>See on <a href="https://regex101.com/r/rlFheb/2" rel="nofollow">regex101</a>.</p>
1
2016-09-28T15:17:56Z
[ "python", "regex" ]
REGEX formulating conditions
39,751,262
<p>Just started learning python and regex. </p> <pre><code>My regex: \b\d+\s+([A-Za-z]* |[A-Za-z]*\s+[A-Za-z]*)\s+\D+.. </code></pre> <p>using <a href="https://regex101.com/" rel="nofollow">https://regex101.com/</a> </p> <p><strong>string 1:</strong> <a href="https://i.imgur.com/XNuXftW.jpg" rel="nofollow">https://i...
0
2016-09-28T15:05:20Z
39,751,542
<p>You could use this regex, which takes advantage of look-behind (<code>?&lt;=</code>) and look-ahead <code>(?=</code>) so it only captures the product names:</p> <pre><code>(?&lt;=\s\s)\w+(?:\s\w+)*(?=\s\s) </code></pre> <p>See demo on <a href="https://regex101.com/r/rtIXLK/2" rel="nofollow">regex101.com</a>.</p> ...
1
2016-09-28T15:18:52Z
[ "python", "regex" ]
REGEX formulating conditions
39,751,262
<p>Just started learning python and regex. </p> <pre><code>My regex: \b\d+\s+([A-Za-z]* |[A-Za-z]*\s+[A-Za-z]*)\s+\D+.. </code></pre> <p>using <a href="https://regex101.com/" rel="nofollow">https://regex101.com/</a> </p> <p><strong>string 1:</strong> <a href="https://i.imgur.com/XNuXftW.jpg" rel="nofollow">https://i...
0
2016-09-28T15:05:20Z
39,751,854
<p>I guess the the space before "|" is the one causes it captures "beer " in <strong>string 1 case</strong> "Chocolate cake" does not happen as "beer " as it is matched with the second regex which is </p> <pre><code>[A-Za-z]*\s+[A-Za-z]* </code></pre> <p>for <strong>string 2</strong> [A-Za-z]<em>\s+[A-Za-z]</em>...
1
2016-09-28T15:31:51Z
[ "python", "regex" ]
How to use a refresh_token for youtube python api?
39,751,307
<p>So i got a refresh token in this way and can I keep it?</p> <p>And if so, how do I use it next time, so that there is no need for me to open browser?</p> <p>Right now I'm thinking about creating OAuth2Credentials object directly, is this the right way?</p> <pre><code>from urllib.parse import urlparse, parse_qs fr...
0
2016-09-28T15:07:01Z
39,774,370
<p>If the user consents to authorize your application to access those resources, Google will return a token to your application. Depending on your application's type, it will either validate the token or exchange it for a different type of token. Check this <a href="https://developers.google.com/youtube/2.0/developers_...
0
2016-09-29T15:26:59Z
[ "python", "youtube-api", "google-api-client" ]
Update MongoDB collection with python script
39,751,341
<p>I want to be able to create a new empty collection that will update any time a python script is called. I know that to create the collection i can simply use pymongo as follows:</p> <pre><code>from pymongo import MongoClient db = MongoClient('my.ip.add.ress', 27017)['xxxx'] #connect to client db.createCollection(...
0
2016-09-28T15:08:39Z
39,793,714
<p>I suppose you know which collection you like to modify. If you do, you can just add the collection as another argument to your command:</p> <p>After that you can fetch the command line arguments by using sys.argv or a library specifically written to parse command line arguments. The python 3 standard library includ...
0
2016-09-30T14:19:53Z
[ "python", "mongodb", "teamcity", "pymongo" ]
Python reading a file line by line and sending it to another Python script
39,751,523
<p>Good day.</p> <p>Today i was trying to practice python and Im trying to make a script that reads the lines from a file containing only numbers and using said numbers as a parameter in another Python script.</p> <p>Here at work i sometimes need to execute a python script called Suspend.py, ever time i excute this s...
1
2016-09-28T15:17:44Z
39,751,620
<p>If I understand you correctly:</p> <pre><code>import subprocess with open("file_with_numbers.txt") as f: for line in f: subprocess.call(["python", "Suspend.py", "suspend", line.strip()]) </code></pre>
2
2016-09-28T15:22:19Z
[ "python" ]
select dict object based on value
39,751,545
<p>This is how my JSON object looks like:</p> <pre><code>[{ 'Description': 'Description 1', 'OutputKey': 'OutputKey 1', 'OutputValue': 'OutputValue 1' }, { 'Description': 'Description 2', 'OutputKey': 'OutputKey 2', 'OutputValue': 'OutputValue 2' }, { 'Description': 'Description 3', 'Ou...
1
2016-09-28T15:18:58Z
39,751,615
<p>You can use <code>next</code>:</p> <pre><code>next(key for key in myJSON if key['OutputKey'] == 'OutputKey 4') </code></pre> <p>However, if the "key" isn't present, then you'll get a <code>StopIteration</code> exception. You can handle that as you normally would handle any other exception, or you can supply a "de...
5
2016-09-28T15:22:04Z
[ "python" ]
select dict object based on value
39,751,545
<p>This is how my JSON object looks like:</p> <pre><code>[{ 'Description': 'Description 1', 'OutputKey': 'OutputKey 1', 'OutputValue': 'OutputValue 1' }, { 'Description': 'Description 2', 'OutputKey': 'OutputKey 2', 'OutputValue': 'OutputValue 2' }, { 'Description': 'Description 3', 'Ou...
1
2016-09-28T15:18:58Z
39,751,623
<pre><code>try: next(key for key in myJSON if key['OutputKey'] == 'OutputKey 4') except StopIteration: #code for the case where there is no such dictionary </code></pre>
1
2016-09-28T15:22:22Z
[ "python" ]
select dict object based on value
39,751,545
<p>This is how my JSON object looks like:</p> <pre><code>[{ 'Description': 'Description 1', 'OutputKey': 'OutputKey 1', 'OutputValue': 'OutputValue 1' }, { 'Description': 'Description 2', 'OutputKey': 'OutputKey 2', 'OutputValue': 'OutputValue 2' }, { 'Description': 'Description 3', 'Ou...
1
2016-09-28T15:18:58Z
39,751,655
<p>A JSON Object is essentially a list of dictionaries. Therefore you need to use index notation to access one of the dictionaries, in this case myJSON[3]. Then inside the dictionary, call that dictionary's key so that it will return its value. So:</p> <p><code>myJSON[3]['OutputKey']</code></p> <p>will return OutputK...
0
2016-09-28T15:23:39Z
[ "python" ]
select dict object based on value
39,751,545
<p>This is how my JSON object looks like:</p> <pre><code>[{ 'Description': 'Description 1', 'OutputKey': 'OutputKey 1', 'OutputValue': 'OutputValue 1' }, { 'Description': 'Description 2', 'OutputKey': 'OutputKey 2', 'OutputValue': 'OutputValue 2' }, { 'Description': 'Description 3', 'Ou...
1
2016-09-28T15:18:58Z
39,751,677
<p>You have a list of dicts. If you know the index of the required dict, then you can index that list:</p> <pre><code>output_4 = myJSON[3] </code></pre> <p>Otherwise, you'll be looping through, even if the loop is not obvious (as with your <code>any</code> approach):</p> <pre><code>for d in myJSON: if d['OutputK...
0
2016-09-28T15:24:23Z
[ "python" ]
select dict object based on value
39,751,545
<p>This is how my JSON object looks like:</p> <pre><code>[{ 'Description': 'Description 1', 'OutputKey': 'OutputKey 1', 'OutputValue': 'OutputValue 1' }, { 'Description': 'Description 2', 'OutputKey': 'OutputKey 2', 'OutputValue': 'OutputValue 2' }, { 'Description': 'Description 3', 'Ou...
1
2016-09-28T15:18:58Z
39,751,741
<p>Perhaps you should consider using some kind of in-memory database to store the info in order to perform that kind of queries on your data.</p> <p>For instance, I have used <a href="https://pypi.python.org/pypi/tinydb" rel="nofollow">TinyDB</a> in the past, which save the data in a file in JSON format. This is the c...
0
2016-09-28T15:26:53Z
[ "python" ]
python ipaddress, get first usable host only?
39,751,563
<p>I am using pythons ipaddress module and im trying to get the first usable host only, not all usable hosts</p> <p>the below gives me all hosts, and when i try to index it i get the below error.</p> <p>is is possible any other way to just get the first usable host?</p> <p>Thanks</p> <pre><code>n = ipaddress.ip_net...
0
2016-09-28T15:19:59Z
39,751,684
<p><code>hosts()</code> returns a generator object, which does not support indexing. You must iterate through it.</p> <p>If you only want the first element, just use <code>next()</code>:</p> <pre><code>n = ipaddress.ip_network(u'10.10.20.0/24') first_host = next(n.hosts()) </code></pre> <p>If you want to convert the...
4
2016-09-28T15:24:36Z
[ "python" ]
PyCharm - Python Strange behavior
39,751,570
<p>I dont know if I can post this here or not. But a strange thing happened recently. </p> <p>I use pycharm to run my python codes and surprisingly when I opened a piece of my code - it got deleted. The file is 0KB now - for some reason. I am using this file for over a month now and this happened when I opened it and ...
0
2016-09-28T15:20:21Z
39,751,646
<p>PyCharm has Local History feature, it might recover your deleted file...</p> <ul> <li>Right click on your file</li> <li>Click <code>Local History</code> </li> <li><p>Click <code>Show History</code></p> <p><a href="http://i.stack.imgur.com/82Fd6.png" rel="nofollow"><img src="http://i.stack.imgur.com/82Fd6.png" alt=...
0
2016-09-28T15:23:20Z
[ "python", "pycharm" ]
PyCharm - Python Strange behavior
39,751,570
<p>I dont know if I can post this here or not. But a strange thing happened recently. </p> <p>I use pycharm to run my python codes and surprisingly when I opened a piece of my code - it got deleted. The file is 0KB now - for some reason. I am using this file for over a month now and this happened when I opened it and ...
0
2016-09-28T15:20:21Z
39,753,232
<p>Seems like a problem with one of my network servers. It is fixed after talking with an IT professional</p>
0
2016-09-28T16:42:39Z
[ "python", "pycharm" ]
On the default/fill value for *multi-key* outer joins
39,751,636
<p>NB: The post below is the "multi-key" counterpart of an <a href="http://stackoverflow.com/q/39748976/559827">earlier question</a> of mine. The solutions to that earlier question work only for the case where the join is on a single key, and it is not clear to me how to generalize those solutions to the multi-key cas...
3
2016-09-28T15:22:55Z
39,754,322
<p>Set the <code>keys</code> to be the index of the two <code>DF's</code>:</p> <pre><code>def index_set(frame, keys=['key1', 'key2']): frame.set_index(keys, inplace=True) return frame </code></pre> <p>Subset the <code>DF's</code> containing <code>NaN</code> values:</p> <pre><code>def nulls(frame): nulls_...
2
2016-09-28T17:43:33Z
[ "python", "pandas" ]
python replace unicode characters
39,751,705
<p>I wrote a program to read in Windows DNS debugging log, but inside always got some funny characters in the domain field. </p> <p>Below is one of the example:</p> <pre>(13)\xc2\xb5\xc2\xb1\xc2\xbe\xc3\xa2p\xc3\xb4\xc2\x8d(5)example(3)com(0)'</pre> <p>I want to replace all the <code>\x..</code> with a <code>?</code...
4
2016-09-28T15:25:24Z
39,751,863
<p>There are better tools for this job than regex, you could try for example:</p> <pre><code>&gt;&gt;&gt; line '(13)\xc2\xb5\xc2\xb1\xc2\xbe\xc3\xa2p\xc3\xb4\xc2\x8d(5)example(3)com(0)' &gt;&gt;&gt; line.decode('ascii', 'ignore') u'(13)p(5)example(3)com(0)' </code></pre> <p>That skips non-ascii characters. Or with r...
2
2016-09-28T15:32:04Z
[ "python", "mojibake" ]
python replace unicode characters
39,751,705
<p>I wrote a program to read in Windows DNS debugging log, but inside always got some funny characters in the domain field. </p> <p>Below is one of the example:</p> <pre>(13)\xc2\xb5\xc2\xb1\xc2\xbe\xc3\xa2p\xc3\xb4\xc2\x8d(5)example(3)com(0)'</pre> <p>I want to replace all the <code>\x..</code> with a <code>?</code...
4
2016-09-28T15:25:24Z
39,752,163
<p>what about this?</p> <pre><code>line = '(13)\xc2\xb5\xc2\xb1\xc2\xbe\xc3\xa2p\xc3\xb4\xc2\x8d(5)example(3)com(0)' pattern = r'\\x.+' re.sub(pattern, r'?', line) </code></pre>
-2
2016-09-28T15:46:44Z
[ "python", "mojibake" ]
Mapping each element in list to different column in pandas dataframe
39,751,747
<p><strong>Background</strong>: I have a dataframe with individuals' names and addresses. I'm trying to catalog people associated with each person in my dataframe, so I'm running each row/record in the dataframe through an external API that returns a list of people associated with the individual. The idea is to write a...
0
2016-09-28T15:27:10Z
39,752,637
<pre><code>import pandas as pd def make_relatives_frame(relatives): return pd.DataFrame(data=[relatives], columns=["relative%i_name" % x for x in range(1, len(relatives) + 1)]) # example output from an API call df_names = pd.DataFrame(data=[["Kyle", "Smith"]], columns=["First_Name", "Las...
0
2016-09-28T16:10:02Z
[ "python", "list", "function", "pandas", "vectorization" ]
How to handle meta data associated with a pandas dataframe?
39,751,807
<p>What is the best practice for saving meta information to a dataframe? I know of the following coding practice</p> <pre><code>import pandas as pd df = pd.DataFrame([]) df.currency = 'USD' df.measure = 'Price' df.frequency = 'daily' </code></pre> <p>But as stated in this post <a href="http://stackoverflow.com/questi...
1
2016-09-28T15:29:50Z
39,755,663
<p>I think that MultiIndexes is the way to go, but this way:</p> <pre><code>daily_price_data = pd.DataFrame({'Apple': [90, 85, 30], 'MSFT':[20, 30, 25]}) daily_earnings_data = pd.DataFrame({'Apple': [5000, 58000, 5100], 'MSFT':[2000, 2200, 3000]}) data = pd.concat({'price':daily_price_data, 'earnings': daily_earnings_...
0
2016-09-28T19:01:37Z
[ "python", "pandas", "metadata", "finance", "divide" ]
Configure Visual Studio Code to run Python in bash on Windows
39,751,858
<p>I want to run python <code>.py</code> file in Visual Studio Code using Windows bash console.</p> <p>What I tried to do:</p> <p>Change default shell in <code>settings.json</code>:</p> <pre><code>{ "terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\bash.exe" } </code></pre> <p>Add task in <code>task...
0
2016-09-28T15:31:54Z
39,755,569
<p>I don't have Windows 10 with <code>bash</code> but I'd imagine the problem is that you're not actually trying to run Python. You're trying to run <code>bash</code> (and then run <code>python</code>). Try setting the command to <code>bash</code> with params <code>["python", "$file"]</code>.</p>
0
2016-09-28T18:55:48Z
[ "python", "vscode", "wsl" ]
expanding rows in pandas dataframe
39,751,866
<p>I have the following data:</p> <pre><code>product Sales_band Hour_id sales prod_1 HIGH 1 200 prod_1 HIGH 3 100 prod_1 HIGH 4 300 prod_1 VERY HIGH 2 100 prod_1 VERY HIGH 5 253 prod_1 VERY HIGH 6 234 </code></pre> <p>want to add rows based on the ...
2
2016-09-28T15:32:06Z
39,752,186
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a>:</p> <pre><code>print (df.groupby(['pro...
2
2016-09-28T15:48:06Z
[ "python", "python-3.x", "pandas", "expand", "reindex" ]