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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Checking request get parameter in Django template | 38,276,225 | <p>I'm checking a request.GET parameter in Django template. I'm pasting a portion of it:</p>
<pre><code><dd>
<i class="fa fa-caret-right {% if request.GET.order %}{% ifequal request.GET.order 'price-asc' %}active{% endifequal %}{% endif %}"></i> <a href="{%url_add_replace request 'order' 'pric... | 1 | 2016-07-08T22:27:38Z | 38,276,830 | <p>I solved my problem with writing another custom tag:</p>
<pre><code>@register.simple_tag(name='active_request_get')
def active_request_get(request, key, value):
dict = request.GET.copy()
if dict.__contains__(key):
if dict.get(key, default=None) == value:
return 'active'
return ''... | 0 | 2016-07-08T23:41:36Z | [
"python",
"django",
"get",
"request"
] |
Checking request get parameter in Django template | 38,276,225 | <p>I'm checking a request.GET parameter in Django template. I'm pasting a portion of it:</p>
<pre><code><dd>
<i class="fa fa-caret-right {% if request.GET.order %}{% ifequal request.GET.order 'price-asc' %}active{% endifequal %}{% endif %}"></i> <a href="{%url_add_replace request 'order' 'pric... | 1 | 2016-07-08T22:27:38Z | 38,278,010 | <p>I think a custom template tag is overkill for this. The following template logic should work without triggering any debug logs:</p>
<pre><code>{% if 'order' in request.GET %}
{% ifequal request.GET.order 'price-asc' %}active{% endifequal %}
{% endif %}
</code></pre>
<p>The difference between this and your orig... | 0 | 2016-07-09T03:31:27Z | [
"python",
"django",
"get",
"request"
] |
Django render template not loading jquery events | 38,276,236 | <p>I'm trying to create a url preview similar like in facebook, with <a href="https://github.com/stephan-fischer/jQuery-LiveUrl" rel="nofollow">this</a> jquery plugin. In a stand alone template when I pass url, the preview of url is obtained, but when I try to render the template to a string, the jquery event is not ge... | 0 | 2016-07-08T22:29:05Z | 38,276,719 | <p>You need to call <code>jQuery</code> as you would normally within the script tag. All Django does with the static template linking is link to those files.</p>
<p>Wrap you javascript code to be called on document ready.</p>
<pre><code>$( document ).ready(function() {
// Handler for .ready() called.
// wrap the... | 0 | 2016-07-08T23:29:07Z | [
"jquery",
"python",
"django",
"render"
] |
Numpy: Finding the bounding box within a 2d array | 38,276,273 | <p>I have a bounding box that sits inside a 2-d array, where areas outside of the bounding box are marked as 'nan'. I am looking for a way to locate the 4 corners of the bounding box, aka, the indices of the values adjacent to the 'nan' value. I can do it in a 'for-loop' way, but just wonder if there are faster ways to... | 0 | 2016-07-08T22:33:01Z | 38,276,327 | <p>Have a look at <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a>:</p>
<pre><code>import numpy as np
a = [[nan,nan,nan,nan,nan,nan,nan],
[nan,nan,nan,nan,nan,nan,nan],
[nan, 0, 7, 3, 3, nan,nan],
[nan, 7, 6, 9, 9, nan,nan],
[... | 1 | 2016-07-08T22:38:52Z | [
"python",
"arrays",
"python-2.7",
"numpy",
"bounding-box"
] |
Numpy: Finding the bounding box within a 2d array | 38,276,273 | <p>I have a bounding box that sits inside a 2-d array, where areas outside of the bounding box are marked as 'nan'. I am looking for a way to locate the 4 corners of the bounding box, aka, the indices of the values adjacent to the 'nan' value. I can do it in a 'for-loop' way, but just wonder if there are faster ways to... | 0 | 2016-07-08T22:33:01Z | 38,276,356 | <p>This will give max and min of the two axes:</p>
<pre><code>xmax, ymax = np.max(np.where(~np.isnan(a)), 1)
xmin, ymin = np.min(np.where(~np.isnan(a)), 1)
</code></pre>
| 2 | 2016-07-08T22:43:05Z | [
"python",
"arrays",
"python-2.7",
"numpy",
"bounding-box"
] |
Numpy: Finding the bounding box within a 2d array | 38,276,273 | <p>I have a bounding box that sits inside a 2-d array, where areas outside of the bounding box are marked as 'nan'. I am looking for a way to locate the 4 corners of the bounding box, aka, the indices of the values adjacent to the 'nan' value. I can do it in a 'for-loop' way, but just wonder if there are faster ways to... | 0 | 2016-07-08T22:33:01Z | 38,276,386 | <p>You must check for matrix with all nans</p>
<pre><code>row, col = np.where(~np.isnan(matrix))
r1, c1 = row[ 0], col[ 0]
r2, c2 = row[-1], col[-1]
</code></pre>
| 1 | 2016-07-08T22:46:12Z | [
"python",
"arrays",
"python-2.7",
"numpy",
"bounding-box"
] |
Error models.py Django | 38,276,301 | <p>I have an error when creating migrations in django</p>
<p>models.py</p>
<pre><code>class StateBuyers(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Meta:
db_table = "states"
class CountiesBuyers (models.Model):
state = models.... | 1 | 2016-07-08T22:35:33Z | 38,276,993 | <p>slightly off-topic, but why do you not follow the conventions?</p>
<ul>
<li>simple model names using <em>singular</em> form</li>
<li>no need for extra parameters if they are same as defaults</li>
<li>why duplicate State if there is State for county? any performance gains?</li>
</ul>
<pre><code>class NameAsReprMi... | 1 | 2016-07-09T00:10:06Z | [
"python",
"django",
"migrate",
"makemigrations"
] |
Bulk XML to JSON conversion | 38,276,326 | <p>Can anyone recommend some good XML to JSON conversion tools/scripts for converting over 1 million XML records?</p>
| -1 | 2016-07-08T22:38:41Z | 38,276,456 | <p>You don't need Python for this.</p>
<p>You should be able to use <a href="http://www.w3schools.com/xsl/" rel="nofollow">XSLT</a> to achieve this pretty easily.</p>
| 1 | 2016-07-08T22:54:08Z | [
"python",
"json",
"xml",
"parsing"
] |
Bulk XML to JSON conversion | 38,276,326 | <p>Can anyone recommend some good XML to JSON conversion tools/scripts for converting over 1 million XML records?</p>
| -1 | 2016-07-08T22:38:41Z | 38,276,595 | <p>One way to do this is to convert xml to dict and then dict to JSON . Here is a quick example </p>
<pre><code>import json
import xmltodict
def convertXmlToJSON(xmlFile, xml_attribs=True):
with open(xmlFile, "rb") as file:
my_dict = xmltodict.parse(file, xml_attribs=xml_attribs)
return json.dumps... | 0 | 2016-07-08T23:11:42Z | [
"python",
"json",
"xml",
"parsing"
] |
Using Django pipeline browserify on Windows | 38,276,360 | <p>I'm trying to follow <a href="http://gregblogs.com/how-django-reactjs-and-browserify/" rel="nofollow">http://gregblogs.com/how-django-reactjs-and-browserify/</a>.
I went through some hoops to get <code>collectstatic</code> working but it runs without error now. However when I try to load the page which contains my r... | 1 | 2016-07-08T22:43:51Z | 38,338,412 | <p>My co-worker tried to get it working on OSX too, but we gave up. We just short-circuited the <code>is_outdated</code> to always return true. The <code>is_outdated</code> contains some info in the comments about that anyway (<a href="https://github.com/j0hnsmith/django-pipeline-browserify/blob/master/pipeline_browser... | 0 | 2016-07-12T20:34:03Z | [
"python",
"django",
"reactjs",
"browserify",
"pipeline"
] |
Do an inner join in python pandas using criteria | 38,276,374 | <p>Iâm trying to replicate in python/pandas what would be fairly straightforward in SQL, but am stuck.</p>
<p>I want to take a data frame with three columns:</p>
<pre><code>dataframe1
Org Des Score
0 A B 10
1 A B 11
2 A B 15
3 A C 4
4 A C 4.5
5 A C 6
6 A D 100
7 A ... | 1 | 2016-07-08T22:45:21Z | 38,276,560 | <p>You can set up the join criteria as this. For the original data frame, set the join columns as <code>['Org', 'Des']</code>, and for the aggregated data frame the grouped columns become index so you will need to set <code>right_index</code> to be true, then it should work as expected:</p>
<pre><code>import pandas as... | 2 | 2016-07-08T23:06:56Z | [
"python",
"pandas",
"join",
"merge",
"group-by"
] |
Do an inner join in python pandas using criteria | 38,276,374 | <p>Iâm trying to replicate in python/pandas what would be fairly straightforward in SQL, but am stuck.</p>
<p>I want to take a data frame with three columns:</p>
<pre><code>dataframe1
Org Des Score
0 A B 10
1 A B 11
2 A B 15
3 A C 4
4 A C 4.5
5 A C 6
6 A D 100
7 A ... | 1 | 2016-07-08T22:45:21Z | 38,279,391 | <p>I did it like this:</p>
<pre><code>df[df.groupby(['Org', 'Des']).Score.apply(lambda x: x < x.min() * 1.2)]
</code></pre>
<p><a href="http://i.stack.imgur.com/yyj2Q.png" rel="nofollow"><img src="http://i.stack.imgur.com/yyj2Q.png" alt="enter image description here"></a></p>
| 2 | 2016-07-09T07:18:50Z | [
"python",
"pandas",
"join",
"merge",
"group-by"
] |
sqlalchemy: Call STR_TO_DATE on column | 38,276,487 | <p>I am moving some of my code onto sqlalchemy from using raw MySQL queries.</p>
<p>The current issue I am having is that the datetime was saved in a string format by a C# tool. Unfortunately, the representation does not match up with Python's (as well as that it has an extra set of single quotes), thus making filteri... | 2 | 2016-07-08T22:57:38Z | 38,277,347 | <p>In the <code>cast()</code> you should be using <code>sqlalchemy.DateTime</code>, not (what I assume is) a <code>datetime.date</code> - that is the cause of the exception.</p>
<p>However, fixing that will not really help because of the embedded single quotes.</p>
<p>You are fortunate that the dates stored in your t... | 1 | 2016-07-09T01:20:24Z | [
"python",
"mysql",
"sqlalchemy"
] |
sqlalchemy: Call STR_TO_DATE on column | 38,276,487 | <p>I am moving some of my code onto sqlalchemy from using raw MySQL queries.</p>
<p>The current issue I am having is that the datetime was saved in a string format by a C# tool. Unfortunately, the representation does not match up with Python's (as well as that it has an extra set of single quotes), thus making filteri... | 2 | 2016-07-08T22:57:38Z | 38,294,820 | <p>You can try to use <code>func.str_to_date(COLUMN, FORMAT_STRING)</code> instead of <code>cast</code></p>
| 1 | 2016-07-10T17:50:23Z | [
"python",
"mysql",
"sqlalchemy"
] |
Window-Leveling in python | 38,276,495 | <p>I would like to change the window-level of my dicom images from lung window to chest window. I know the values need for the window-leveling. But how to implement it in python? Or else anyone can provide me with an detailed description of this process would be highly appreciated. </p>
| 0 | 2016-07-08T22:58:27Z | 38,341,345 | <p>I have already implemented this in Python. Take a look at the function GetImage in <a href="https://github.com/dicompyler/dicompyler-core/blob/master/dicompylercore/dicomparser.py" rel="nofollow">dicomparser</a> module in the <a href="https://github.com/dicompyler/dicompyler-core" rel="nofollow">dicompyler-core</a> ... | 0 | 2016-07-13T01:38:58Z | [
"python",
"image",
"dicom"
] |
Config file to define JSON Schema Struture in pyspark | 38,276,588 | <p>I have created a pyspark application that reads the json file in a dataframe through a defined Schema. code sample below</p>
<pre><code>schema = StructType([
StructField("domain", StringType(), True),
StructField("timestamp", LongType(), True),
])
df= sqlContext.read.json(file, ... | 1 | 2016-07-08T23:10:42Z | 38,276,795 | <p><code>StructType</code> provides <code>json</code> and <code>jsonValue</code> methods which can be used to obtain <code>json</code> and <code>dict</code> representation respectively and <code>fromJson</code> which can be used to convert Python dictionary to <code>StructType</code>.</p>
<pre><code>schema = StructTyp... | 0 | 2016-07-08T23:38:30Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-sql",
"spark-dataframe"
] |
Tkinter NameError only when running script from shell | 38,276,691 | <p>I've got a Tkinter Python program, a reduced version of which can be found below:</p>
<pre><code>from tkinter import *
from tkinter.ttk import *
filedialog.askopenfilename()
</code></pre>
<p>When I run this script from IDLE, I do not get any errors. </p>
<p>However, when run from PowerShell, using <code>python ... | 1 | 2016-07-08T23:25:24Z | 38,277,204 | <p>IDLE is probably importing it already, but in general since <code>filedialog</code> is a <code>tkinter</code> module it won't get imported with the bare:</p>
<pre><code>from tkinter import *
</code></pre>
<p>Include an extra:</p>
<pre><code>from tkinter import filedialog
</code></pre>
<p>and you should be good t... | 1 | 2016-07-09T00:54:02Z | [
"python",
"tkinter",
"python-idle",
"nameerror",
"filedialog"
] |
Multiple if and else statements | 38,276,703 | <p>I'm trying to make some plots using matplotlib in python.</p>
<p>I then have a loop going through:</p>
<pre><code>structure = ['CTV', 'ITV', 'PTV', 'Index']
</code></pre>
<p>Now, some stuff is going on in the loop (<code>for voi in structure</code>) like getting data from .txt-files, subplots and formatting the p... | 2 | 2016-07-08T23:26:46Z | 38,276,737 | <p>Use a dictionary:</p>
<pre><code>poss_voi = {'Index':40,'PTV':75,'ITV':15, 'CTV': 92 etc....}
</code></pre>
<p>Then just get do a lookup:</p>
<pre><code>plt.axis([0, 180, poss_voi[voi]])
</code></pre>
<p>If you want a default use <em>dict.get</em>:</p>
<pre><code> plt.axis([0, 180, poss_voi.get(voi, some_defaul... | 4 | 2016-07-08T23:31:40Z | [
"python",
"matplotlib"
] |
Having errors working with com ports using pyserial | 38,276,704 | <p>I am trying to interface with my com ports, specifically an XBee connected to thi using this code.</p>
<pre><code>from xbee import XBee
from serial import Serial
PORT = 'COM3'
BAUD = 9600
ser = Serial(PORT, BAUD)
xbee = XBee(ser)
# Send the string 'Hello World' to the module with MY set to 1
xbee.tx(dest_addr='\... | 1 | 2016-07-08T23:26:55Z | 38,276,864 | <p>A serial port can be "open" in only one application at a time. Once application "A" opens the port, application "B" will get an Access Denied error when it tries to open the same port. In your case, you need to figure out what other application is holding the port and close it first.</p>
| 1 | 2016-07-08T23:46:12Z | [
"python"
] |
Scapy and sniff. how can I filter TCP SYN? | 38,276,770 | <pre><code>pkts=sniff(offline="/home/jaghanata/Desktop/amostra.pcap", filter='tcp')
</code></pre>
<p>how can I filter TCP SYN ?</p>
| 1 | 2016-07-08T23:35:23Z | 38,277,174 | <p><code>scapy</code> filters are full <a href="https://en.wikipedia.org/wiki/Berkeley_Packet_Filter" rel="nofollow">Berkeley Packet Filters</a>, therefore you can do:</p>
<pre><code>pkts = sniff(offline="amostra.pcap", filter='tcp and tcp.flags.syn==1')
</code></pre>
<p>Or, more likely, you want this:</p>
<pre><cod... | 2 | 2016-07-09T00:46:01Z | [
"python",
"scapy"
] |
numpy.where : how to delay evaluating parameters? | 38,276,813 | <p>I am using <code>numpy.where</code>, and I was wondering if there was a simply way to avoid calling the unused parameter. Example:</p>
<pre><code>import numpy as np
z = np.array([-2, -1, 0, 1, -2])
np.where(z!=0, 1/z, 1)
</code></pre>
<p>returns:</p>
<pre><code>array([-0.5, -1. , 1. , 1. , -0.5])
</code></pre>
... | 0 | 2016-07-08T23:40:16Z | 38,277,975 | <p>You can apply a mask:</p>
<pre><code>out = numpy.ones_like(z)
mask = z != 0
out[mask] = 1/z[mask]
</code></pre>
| 1 | 2016-07-09T03:25:22Z | [
"python",
"numpy",
"divide-by-zero"
] |
numpy.where : how to delay evaluating parameters? | 38,276,813 | <p>I am using <code>numpy.where</code>, and I was wondering if there was a simply way to avoid calling the unused parameter. Example:</p>
<pre><code>import numpy as np
z = np.array([-2, -1, 0, 1, -2])
np.where(z!=0, 1/z, 1)
</code></pre>
<p>returns:</p>
<pre><code>array([-0.5, -1. , 1. , 1. , -0.5])
</code></pre>
... | 0 | 2016-07-08T23:40:16Z | 38,278,222 | <p>You can also turn off the warning and turn it back on after you are done
using the context manager <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.errstate.html#numpy.errstate" rel="nofollow"><code>errstate</code></a>:</p>
<pre><code>with np.errstate(divide='ignore'):
np.where(z!=0, 1/z, 1)
<... | 1 | 2016-07-09T04:09:33Z | [
"python",
"numpy",
"divide-by-zero"
] |
numpy.where : how to delay evaluating parameters? | 38,276,813 | <p>I am using <code>numpy.where</code>, and I was wondering if there was a simply way to avoid calling the unused parameter. Example:</p>
<pre><code>import numpy as np
z = np.array([-2, -1, 0, 1, -2])
np.where(z!=0, 1/z, 1)
</code></pre>
<p>returns:</p>
<pre><code>array([-0.5, -1. , 1. , 1. , -0.5])
</code></pre>
... | 0 | 2016-07-08T23:40:16Z | 38,315,673 | <p>scipy has a little utility just for this purpose:
<a href="https://github.com/scipy/scipy/blob/master/scipy/_lib/_util.py#L26" rel="nofollow">https://github.com/scipy/scipy/blob/master/scipy/_lib/_util.py#L26</a></p>
<p>It's basically a matter of allocating the output array and using <code>np.place</code> (or putma... | 0 | 2016-07-11T20:28:44Z | [
"python",
"numpy",
"divide-by-zero"
] |
True + True = 2. Elegantly perform boolean arithmetic? | 38,276,843 | <p>I have nested lists of truth values representing SAT forumlas, like this:</p>
<pre><code>[[[0, True, False], [0, True, False], [0, True, 1]], [[0, True, True], [2, True, True], [3, False, True]], [[1, False, False], [1, False, False], [3, False, True]]]
</code></pre>
<p>representing</p>
<pre><code>([x0=0] + [x0=0... | 0 | 2016-07-08T23:43:03Z | 38,276,859 | <p>There is a way to do boolean arithmetic. That way is to use boolean operators. </p>
<ul>
<li>and, as you call "*", is <code>and</code>. </li>
<li>or, as you call "+", is <code>or</code>.</li>
</ul>
| 2 | 2016-07-08T23:45:44Z | [
"python",
"boolean",
"boolean-operations"
] |
True + True = 2. Elegantly perform boolean arithmetic? | 38,276,843 | <p>I have nested lists of truth values representing SAT forumlas, like this:</p>
<pre><code>[[[0, True, False], [0, True, False], [0, True, 1]], [[0, True, True], [2, True, True], [3, False, True]], [[1, False, False], [1, False, False], [3, False, True]]]
</code></pre>
<p>representing</p>
<pre><code>([x0=0] + [x0=0... | 0 | 2016-07-08T23:43:03Z | 38,276,885 | <p>In Python, <code>True == 1</code> and <code>False == 0</code>, as <code>True</code> and <code>False</code> are type <code>bool</code>, which is a subtype of <code>int</code>. When you use the operator <code>+</code>, it is implicitly adding the integer values of <code>True</code> and <code>False</code>.</p>
<pre><c... | 2 | 2016-07-08T23:49:11Z | [
"python",
"boolean",
"boolean-operations"
] |
Opencv: How to stitch four trapezoid images to make a square image? | 38,276,857 | <p>I am currently trying very hard to figure out a way to make these four trapezoid images into one nice image. The final image should look something like this(used photoshop to make it):
<a href="http://i.stack.imgur.com/JlDu5.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/JlDu5.jpg" alt="enter image descripti... | 0 | 2016-07-08T23:45:23Z | 38,601,613 | <p>I did actually figure it out. I did it with these steps:</p>
<ul>
<li>Create two SAME SIZED black backgrounds with numpy zeros</li>
<li>Put one image in each background where you want them(for me, it was left and top)</li>
<li>Then all you need to do is cv.add(first, second) </li>
</ul>
<p>The reason it works is b... | 0 | 2016-07-26T23:49:11Z | [
"python",
"image",
"python-2.7",
"opencv"
] |
Django REST framework serializer error when instantiating | 38,276,893 | <p>I'm having an strange issue with DRF ans some serializers.</p>
<p>Here is my model:</p>
<pre><code>class Accommodation(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
product = models.OneToOneField(
Product,
on_delete=model... | 0 | 2016-07-08T23:50:54Z | 38,284,053 | <p>Using the <code>data</code> field would be the right way since the keywords in the DRF Serializer hierarchy are not generic. If the dictionary you specifiy for <code>data</code> is valid you could create a model instance with <code>.save()</code> (after calling <code>.is_valid()</code>). The dictionary could of cour... | 1 | 2016-07-09T16:46:56Z | [
"python",
"django",
"django-rest-framework",
"drf-nested-routers"
] |
Python: Why is my base64 filename encode not matching what it should be? | 38,276,902 | <p>I have a base64 situation in Python I can't quite figure out -- when I run my script:</p>
<pre><code>import rebus
import os
# Set directory
os.chdir('/Users/Ryan/')
# Filename from folder
filename = 'Ryan20160708.txt'
# Create the base64 of the filename
filenameenc = rebus.urlsafe_b64encode(filename)
filebase64 ... | 1 | 2016-07-08T23:52:31Z | 38,277,278 | <p>If you read the PyPI on it: <a href="https://pypi.python.org/pypi/rebus/0.2" rel="nofollow">https://pypi.python.org/pypi/rebus/0.2</a></p>
<p>You'll see that rebus is used to:</p>
<blockquote>
<p>Generate base64-encoded strings consisting of alphanumeric symbols
only.</p>
</blockquote>
<p>I doubt this is what... | 0 | 2016-07-09T01:07:41Z | [
"python",
"base64"
] |
pip install package location issues | 38,276,908 | <p>I have made a package and install it with pip (have created a sdist package). However when I execute the script that was at the same time install too <code>/usr/local/bin/</code> it errors because the modules it is trying to import are installed too <code>/usr/local/lib/python2.7/site-packages/MyApplication/Modules/... | 0 | 2016-07-08T23:53:10Z | 38,287,478 | <p>I have answered this myself and for brevity am putting the answer up incase someone else comes across the same problem.</p>
<p>Before my module imports happen I do a check of the install location for my modules directory. I am then adding this to the <code>sys.path</code>. This has worked perfectly.</p>
<pre><code... | 1 | 2016-07-10T00:22:01Z | [
"python",
"pip",
"sdist"
] |
Removing a list item until the list is empty | 38,276,953 | <p>I currently have a grid displaying on my screen and one block being filled. I would like every block to be filled with a random color. So I would like to remove the <code>coords_list(random_coord)</code> from the list when its called so my <code>pygame.draw.rect</code> doesn't try to print a new color over top of ... | 0 | 2016-07-09T00:02:25Z | 38,277,004 | <p>The problem is that <code>1065</code> in an out of range index</p>
<pre><code>>>> coords_list = list(product(range(30,1170,30), range(30,870, 30)))
>>> len(coords_list)
1064
</code></pre>
<p>This means the maximum index is <code>1063</code> (python list indexes start at <code>0</code>)</p>
<p>Yo... | 1 | 2016-07-09T00:11:50Z | [
"python",
"loops",
"random",
"rect"
] |
Removing a list item until the list is empty | 38,276,953 | <p>I currently have a grid displaying on my screen and one block being filled. I would like every block to be filled with a random color. So I would like to remove the <code>coords_list(random_coord)</code> from the list when its called so my <code>pygame.draw.rect</code> doesn't try to print a new color over top of ... | 0 | 2016-07-09T00:02:25Z | 38,277,089 | <p>I see two ways of solving this. The main issue is with this block of code:</p>
<pre><code>random_coord = random.randint(0,1065)
coord_location = coords_list[random_coord]
coord_loc_x = coord_location[0]
coord_loc_y = coord_location[1]
</code></pre>
<p>Way one is not dependent on squares being filled in a random or... | 0 | 2016-07-09T00:25:16Z | [
"python",
"loops",
"random",
"rect"
] |
check which features scikitlearn imputer discards | 38,277,014 | <p>The <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Imputer.html" rel="nofollow">docs</a> for scikit-learn's Imputation transformer says </p>
<blockquote>
<p>When axis=0, columns which only contained missing values at fit are discarded upon transform.</p>
</blockquote>
<p>Since im... | 0 | 2016-07-09T00:13:33Z | 38,278,362 | <p><strong>How do I check which features were discarded during imputation?</strong></p>
<p>Columns containing all <code>NaN</code>s will be discarded. You could check this without going through the <code>fit</code> and <code>transform</code> process with <code>df.isnull().all()</code>. Where <code>True</code>, those a... | 3 | 2016-07-09T04:33:18Z | [
"python",
"python-3.x",
"scikit-learn"
] |
Python: Create Nomograms from Data (using PyNomo) | 38,277,062 | <p>I am working on <code>Python 2.7</code>. I want to create nomograms based on the data of various variables in order to predict one variable. I am looking into and have installed <code>PyNomo</code> package. </p>
<p>However, the from the documentation <a href="http://lefakkomies.github.io/pynomo-doc/" rel="nofollow"... | 1 | 2016-07-09T00:20:19Z | 38,409,891 | <p>The term "nomogram" has become somewhat confused of late as it now refers to two entirely different things.</p>
<p>A classic nomogram performs a full calculation - you mark two scales, draw a straight line across the marks and read your answer from a third scale. This is the type of nomogram that pynomo produces, a... | 0 | 2016-07-16T09:53:39Z | [
"python"
] |
selenium not able to retrieve/read part of the website | 38,277,064 | <p>I was trying to do a automated script to download some foreign exchange price historical data. These data are available at </p>
<p><a href="https://www.dukascopy.com/swiss/english/marketwatch/historical/" rel="nofollow">https://www.dukascopy.com/swiss/english/marketwatch/historical/</a></p>
<p>However, if I just u... | 0 | 2016-07-09T00:21:02Z | 38,277,095 | <p><a href="http://selenium-python.readthedocs.org/waits.html#explicit-waits" rel="nofollow">Wait for the presence</a> of the frame and then <em>switch to it</em>. Then, you can look for the elements inside:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriv... | 0 | 2016-07-09T00:26:39Z | [
"python",
"selenium",
"web-crawler"
] |
interleave multiple files with 2 or more consecutive lines at a time from each file | 38,277,065 | <p>I've searched and found code below that can interleave 2 files line by line into new one.</p>
<pre><code>from itertools import izip_longest
from contextlib import nested
with nested(open('foo'), open('bar')) as (foo, bar):
for line in (line for pair in izip_longest(foo, bar)
for line in p... | 3 | 2016-07-09T00:21:20Z | 38,277,242 | <p>This should work:</p>
<pre><code>from itertools import islice
# number of sequential lines to read from each file
N = 2
# files that are read
files = [open(n) for n in ['foo', 'bar', 'baz']]
line = ''.join([''.join(islice(f, N)) for f in files])[:-1]
while line:
print(line)
line = ''.join([''.join(islice(... | 1 | 2016-07-09T01:01:54Z | [
"python"
] |
How do I resolve the "TypeError: unorderable types: str() < int()" error? | 38,277,151 | <p>I'm a newbie to Python (I'm only 14), and I want to create a bubble sorter for a random list of integers. The following is my code:</p>
<pre><code>list = input("Please put in a random set of integers, in any order you like (unlimited range), separated by spaces:")
list = list.split()
indexcounter = 0
def sorter... | 0 | 2016-07-09T00:40:44Z | 38,280,592 | <p>That Exception is most likely raised here:</p>
<pre><code>int(list[indexcounter2]) <= list[indexcounter2 + 1]
</code></pre>
<p>If you are certain you will only be working with numbers you can change all elements in the list to <code>int</code>s by using the following after the call to <code>input</code>:</p>
<... | 0 | 2016-07-09T09:58:39Z | [
"python",
"python-3.x"
] |
Splitting Numpy array based on value | 38,277,182 | <p>Suppose I have this NumPy array: </p>
<pre><code>a = np.array([0, 3, 5, 5, 0, 10, 14, 15, 56, 0, 12, 23, 45, 23, 12, 45,
0, 1, 0, 2, 3, 4, 0, 0 ,0])
</code></pre>
<p>I would like to print all the numbers between 0s and automatically add them to a new <code>np.array</code> (see below):</p>
<pre><cod... | 7 | 2016-07-09T00:47:54Z | 38,277,298 | <p>You can get the indices of zeros with np.where:</p>
<pre><code>zeros = np.where(a == 0)[0]
</code></pre>
<p>And iterate over every pair to slice the array:</p>
<pre><code>[a[i+1:j] for i, j in zip(zeros, zeros[1:]) if len(a[i+1:j])>0]
Out[46]:
[array([3, 5]),
array([10, 14, 15, 56]),
array([12, 23, 45, 23,... | 3 | 2016-07-09T01:10:54Z | [
"python",
"numpy"
] |
Splitting Numpy array based on value | 38,277,182 | <p>Suppose I have this NumPy array: </p>
<pre><code>a = np.array([0, 3, 5, 5, 0, 10, 14, 15, 56, 0, 12, 23, 45, 23, 12, 45,
0, 1, 0, 2, 3, 4, 0, 0 ,0])
</code></pre>
<p>I would like to print all the numbers between 0s and automatically add them to a new <code>np.array</code> (see below):</p>
<pre><cod... | 7 | 2016-07-09T00:47:54Z | 38,277,460 | <p>You can use <code>groupby()</code> function from <code>itertools</code>, and specify the <code>key</code> as the boolean condition of zero or nonzero. In such a way, all consecutive zeros and nonzeros will be grouped together. Use <code>if</code> filter to pick up groups of nonzeros and use <code>list</code> to conv... | 6 | 2016-07-09T01:43:10Z | [
"python",
"numpy"
] |
Splitting Numpy array based on value | 38,277,182 | <p>Suppose I have this NumPy array: </p>
<pre><code>a = np.array([0, 3, 5, 5, 0, 10, 14, 15, 56, 0, 12, 23, 45, 23, 12, 45,
0, 1, 0, 2, 3, 4, 0, 0 ,0])
</code></pre>
<p>I would like to print all the numbers between 0s and automatically add them to a new <code>np.array</code> (see below):</p>
<pre><cod... | 7 | 2016-07-09T00:47:54Z | 38,277,925 | <p>No need for numpy, this lambda function works on a list, but we can convert your numpy array to and from a list on the way in and out:</p>
<pre><code>cut = lambda x: [j for j in [cut(x[:x.index(0)])]+cut(x[x.index(0)+1:]) if j] if x.count(0) else x
numpy.array(cut(list(a)))
# array([[3, 5, 5], [10, 14, 15, 56], [... | 0 | 2016-07-09T03:15:32Z | [
"python",
"numpy"
] |
Splitting Numpy array based on value | 38,277,182 | <p>Suppose I have this NumPy array: </p>
<pre><code>a = np.array([0, 3, 5, 5, 0, 10, 14, 15, 56, 0, 12, 23, 45, 23, 12, 45,
0, 1, 0, 2, 3, 4, 0, 0 ,0])
</code></pre>
<p>I would like to print all the numbers between 0s and automatically add them to a new <code>np.array</code> (see below):</p>
<pre><cod... | 7 | 2016-07-09T00:47:54Z | 38,278,031 | <p>NumPy's <code>split()</code> and <code>where()</code> in a list compehension:</p>
<pre><code>[x[x!=0] for x in np.split(a, np.where(a==0)[0]) if len(x[x!=0])]
[array([3, 5, 5]),
array([10, 14, 15, 56]),
array([12, 23, 45, 23, 12, 45]),
array([1]),
array([2, 3, 4])]
</code></pre>
| 2 | 2016-07-09T03:36:51Z | [
"python",
"numpy"
] |
Splitting Numpy array based on value | 38,277,182 | <p>Suppose I have this NumPy array: </p>
<pre><code>a = np.array([0, 3, 5, 5, 0, 10, 14, 15, 56, 0, 12, 23, 45, 23, 12, 45,
0, 1, 0, 2, 3, 4, 0, 0 ,0])
</code></pre>
<p>I would like to print all the numbers between 0s and automatically add them to a new <code>np.array</code> (see below):</p>
<pre><cod... | 7 | 2016-07-09T00:47:54Z | 38,278,327 | <p>Here's a vectorized approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow"><code>np.split</code></a> -</p>
<pre><code>idx = np.where(a!=0)... | 2 | 2016-07-09T04:27:09Z | [
"python",
"numpy"
] |
Python - Input from user is not recognized as "Y" or "N" | 38,277,231 | <p>I'm trying to write a simple program to get myself back into python after a long break caused by my personal life. The purpose of the program is to do as follows:</p>
<ul>
<li>Ask the user to enter a number equal to 5 (very simple, I know)</li>
<li>Check if what the user inputs is valid</li>
<li>Check if the user's... | 1 | 2016-07-09T00:59:07Z | 38,277,261 | <p>Instead of <code>if again == "y" or "Y":</code>, you need:</p>
<pre><code>if again == "y" or again == "Y":
</code></pre>
<p>or:</p>
<pre><code>if again.lower() == 'y':
</code></pre>
<p>However, you might be better off with a raw_input setup like this:</p>
<pre><code>while True:
entry = raw_input("Enter a nu... | 3 | 2016-07-09T01:05:40Z | [
"python",
"raw-input"
] |
Python - Input from user is not recognized as "Y" or "N" | 38,277,231 | <p>I'm trying to write a simple program to get myself back into python after a long break caused by my personal life. The purpose of the program is to do as follows:</p>
<ul>
<li>Ask the user to enter a number equal to 5 (very simple, I know)</li>
<li>Check if what the user inputs is valid</li>
<li>Check if the user's... | 1 | 2016-07-09T00:59:07Z | 38,277,295 | <pre><code>if again == again.isalpha():
</code></pre>
<p>I don't think this is what you want. <code>again.isalpha()</code> returns True or False, so it doesn't make sense to compare that to the value of <code>again</code>.
You probably intended:</p>
<pre><code>if again.isalpha():
</code></pre>
<p>Also,</p>
<pre><c... | -1 | 2016-07-09T01:10:15Z | [
"python",
"raw-input"
] |
Travis CI not recognizing API key environment variables | 38,277,271 | <p>I am trying to store API keys (two of them) in two encrypted environment variables for Travis and it says that they're imported, then doesn't recognize them. The two variables are <code>TWILIO_TOKEN</code> and <code>TWILIO_ACCT</code>. I also have these stored in a <code>.env</code> variable for Heroku. I have tried... | 0 | 2016-07-09T01:06:51Z | 38,277,632 | <p>Although I didn't figure out why, I found what was wrong. First, I decided to store the API keys through the UI. Second, I wasn't using the variables as bash environment variables. Rather, I was using heroku's suggestion of having a .env file. </p>
| 0 | 2016-07-09T02:17:36Z | [
"python",
"heroku",
"environment-variables",
"travis-ci"
] |
Insert variable inside string in python | 38,277,304 | <p>I'm new to python and I was wondering how to put a variable inside a string to show the contents of such variable in an LCD 20x4 display (2004A).</p>
<p>The code I have looks as follows:</p>
<pre><code>with open("temperature.txt") as myfile:
currenttemp=myfile.readlines()
lcd_string("%(currenttemp)" ,LCD_LINE_1,2... | 1 | 2016-07-09T01:12:25Z | 38,277,379 | <p>An example of string formatting in Python:</p>
<p><strong>Code:</strong></p>
<pre><code>a = "one line file"
print("this file contains: %s" %a)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>this file contains: one line file
</code></pre>
<p>For performance comparison of various string formatting techn... | 1 | 2016-07-09T01:25:40Z | [
"python",
"string",
"variables"
] |
Read in year, DOY and microsecond data as datetime | 38,277,336 | <p>I have a data file formatted like this:</p>
<pre class="lang-none prettyprint-override"><code>year doy milliseconds data
2000 103 272220 1.123
2000 103 373058 1.342
2000 103 471764 0.743
2000 103 573509 1.666
2000 103 664624 1.736
2000 103 ... | 0 | 2016-07-09T01:18:17Z | 38,304,082 | <p>use <code>pandas</code>:</p>
<pre><code>import pandas as pd
f = r"df2dt.txt"
df = pd.read_csv(f, delim_whitespace=True)
td_ms = pd.to_timedelta(df['milliseconds'], unit='ms')
td_D = pd.to_timedelta(df['doy'] - 1, unit='D')
date_str = df['year'].astype(str)
date = pd.to_datetime(date_str, format="%Y", yearfirst=True... | 0 | 2016-07-11T09:59:42Z | [
"python",
"datetime",
"numpy"
] |
Read in year, DOY and microsecond data as datetime | 38,277,336 | <p>I have a data file formatted like this:</p>
<pre class="lang-none prettyprint-override"><code>year doy milliseconds data
2000 103 272220 1.123
2000 103 373058 1.342
2000 103 471764 0.743
2000 103 573509 1.666
2000 103 664624 1.736
2000 103 ... | 0 | 2016-07-09T01:18:17Z | 38,318,906 | <p>Using plain old Python's <code>datetime</code>:</p>
<pre><code>import datetime
dates = []
with open('datafile.txt','r') as fp:
fp.readline()
lines = fp.readlines()
for line in lines:
line = line.rstrip('\n').split()
data = float(line[3])
line = map(int, line[0:3])
line.append(data)
da... | 0 | 2016-07-12T02:05:33Z | [
"python",
"datetime",
"numpy"
] |
Autosummary with toctree not creating documentation for methods | 38,277,358 | <p>I'm using sphinx with the numpydoc extension and autosummary. After some experimentation, I added the following options to my conf.py file.</p>
<pre><code>autosummary_generate = True
numpydoc_show_class_members = False
</code></pre>
<p>This is giving me a new file for each class referenced like below, and it also... | 0 | 2016-07-09T01:22:31Z | 38,277,688 | <p>First, make sure that in your conf.py file, the strings 'sphinx.ext.autodoc' and 'sphinx.ext.autosummary' are in the <em>extensions</em> list.</p>
<p>Second, you can either manually make the file with name <em>mymodule.MyClass.rst</em> inside the generate/ directory, which can be something like this:</p>
<pre><cod... | 0 | 2016-07-09T02:27:00Z | [
"python",
"numpy",
"python-sphinx",
"autodoc"
] |
Can't print object, despite _str_ method in a class | 38,277,408 | <p>I defined the method <code>_str_</code> in my <code>Book</code> class with attributes <code>title</code> and <code>author</code>:</p>
<pre><code>def _str_(self):
book_line = "{title} by {author}".format(title=self.title, author=self.author)
return book_line
</code></pre>
<p>Now, when I create an instance o... | 0 | 2016-07-09T01:30:34Z | 38,277,414 | <p>You need two underscores for "magic" methods. It should be:</p>
<pre><code>def __str__(self):
#stuff
</code></pre>
<p>A single underscore it used to denote a "private" (or semi-private) method.</p>
<p>A double underscore invokes name mangling. Usually used to prevent overriding a method in a subclass.</p>
... | 2 | 2016-07-09T01:32:20Z | [
"python",
"python-2.7"
] |
ValueError: too many values to unpack (sin/cos graph with Python 2.7) | 38,277,418 | <p>I am trying to plot sin and cos on the same graph using Spyder (Python 2.7). I am able to plot a waving sin curve with this code:</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig ... | -1 | 2016-07-09T01:33:08Z | 38,289,607 | <p>One cannot <code>set_data</code> to a line with four arguments. You need another line. See solution below:</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt... | 0 | 2016-07-10T07:19:37Z | [
"python",
"animation",
"numpy",
"matplotlib"
] |
What's the right algorithm for finding isolated subsets | 38,277,491 | <p>Picture is worth a thousand words, so:</p>
<p><a href="http://i.stack.imgur.com/I0tIh.png" rel="nofollow"><img src="http://i.stack.imgur.com/I0tIh.png" alt="enter image description here"></a></p>
<p>My input is the matrix on the left, and what I need to find is the sets of nodes that are maximum one step away from... | 2 | 2016-07-09T01:49:35Z | 38,286,209 | <p>What you are trying to do is searching for "connected components" and
NetworX has itself a method for doing exactly that as can be seen in the first example on this <a href="https://networkx.readthedocs.io/en/stable/tutorial/tutorial.html#analyzing-graphs" rel="nofollow">documentation page</a> as others has already ... | 0 | 2016-07-09T20:45:43Z | [
"python",
"algorithm",
"networkx"
] |
Why does my if statement say that two strings are in a list when its not? | 38,277,501 | <p>Basically I am creating a calculator, and the program so far asks the user for an operation involving addition, subtraction, multiplication and/or division. Then the program proceeds in creating two list, one containing the full numbers and another one containing the operators. The next part of the code is supposed ... | 0 | 2016-07-09T01:50:50Z | 38,277,522 | <p>Given:</p>
<pre><code>if ("*") or ("/") in Oper_NAN: print("POSITIVE") else print("NEGATIVE")
</code></pre>
<p>Each side of your <code>or</code> is evaluated individually. So you are considering whether either of these is true:</p>
<pre><code>("*")
("/") in Oper_NAN
</code></pre>
<p>The first, being a non-zero-... | 6 | 2016-07-09T01:54:19Z | [
"python",
"python-3.x"
] |
Why does my if statement say that two strings are in a list when its not? | 38,277,501 | <p>Basically I am creating a calculator, and the program so far asks the user for an operation involving addition, subtraction, multiplication and/or division. Then the program proceeds in creating two list, one containing the full numbers and another one containing the operators. The next part of the code is supposed ... | 0 | 2016-07-09T01:50:50Z | 38,277,524 | <p>This if statement basically breaks down to the following:</p>
<pre><code>if True or (condition): #code
</code></pre>
<p>Everything in python has a truth value and a non-empty string will evaluate to <code>True</code>. </p>
<p>Your <code>if</code> condition is evaluated lazily. The left side is evaluated first and... | 2 | 2016-07-09T01:54:36Z | [
"python",
"python-3.x"
] |
MRJob same key gets sent to different reducers | 38,277,503 | <p>So I have Hadoop 2.7.1 installed on a 3 machine cluster. I'm trying to run an inverted index mapreduce job using MRJob and Hadoop Streaming. </p>
<p>Here's my configuration:</p>
<pre><code>MRJob.SORT_VALUES = True
def steps(self):
JOBCONF_STEP1 = {
"mapred.map.tasks":20,
"mapred.reduce.task... | 0 | 2016-07-09T01:51:07Z | 38,282,381 | <p>As I Don't Have Your Code, So, I'm Not Providing a Code. Simple Answer:</p>
<p>You Just Need To Use a <a href="https://pythonhosted.org/mrjob/job.html" rel="nofollow">Combiner</a></p>
| 0 | 2016-07-09T13:36:43Z | [
"python",
"hadoop",
"partitioning",
"hadoop-streaming",
"mrjob"
] |
MRJob same key gets sent to different reducers | 38,277,503 | <p>So I have Hadoop 2.7.1 installed on a 3 machine cluster. I'm trying to run an inverted index mapreduce job using MRJob and Hadoop Streaming. </p>
<p>Here's my configuration:</p>
<pre><code>MRJob.SORT_VALUES = True
def steps(self):
JOBCONF_STEP1 = {
"mapred.map.tasks":20,
"mapred.reduce.task... | 0 | 2016-07-09T01:51:07Z | 38,472,340 | <p>Figured it out. THe problem was that MRJob was setting the following by default:</p>
<pre><code>'stream.num.map.output.key.fields': '2'
</code></pre>
<p>I resolved the problem by explicitly setting in jobconf:</p>
<pre><code>'stream.num.map.output.key.fields': '1'
</code></pre>
<p>I don't know how 2 got to be t... | 0 | 2016-07-20T04:29:21Z | [
"python",
"hadoop",
"partitioning",
"hadoop-streaming",
"mrjob"
] |
IPython run magic: How create an alias for "run -i"? | 38,277,669 | <p>I am programming a python user interface to control various instruments in a lab. If a script is not run interactively, the connection with instruments is lost at the end of the script, which can be very bad. I want to help the user to 'remember' running the script interactively.</p>
<p>I'm thinking of two possible... | 2 | 2016-07-09T02:23:49Z | 38,277,783 | <p>You can define your own magic function and use <code>%run -i</code> in it:</p>
<pre><code>from IPython.core.magic import register_line_magic
@register_line_magic
def r(line):
get_ipython().magic('run -i ' + line)
del r
</code></pre>
<p><strong>EDIT</strong></p>
<p>As hpaulj points out <code>magic</code> is ... | 3 | 2016-07-09T02:48:46Z | [
"python",
"ipython",
"ipython-magic"
] |
Add item to stack in game inventory | 38,277,792 | <p>I've tried working on this problem for over an hour and a half and I've finally capitulated. Try as I might, I cannot get like items to stack in an inventory.</p>
<p>In detail, I randomly generate a 'drop', which has a name and a quantity stored in an array. 'drops' is a 2d array which holds these sub-arrays. I'm t... | 1 | 2016-07-09T02:51:00Z | 38,277,857 | <p>A better data type for this kind of thing would be to use <code>dict</code> for the inventory because it can keep track of quantities given a key (item):</p>
<pre><code>import random as rd
inventory = {}
items = ["gunk","gear","bolt","wheel","pinion"]
drops = []
while True:
enter = input("")
if enter =... | 3 | 2016-07-09T03:02:55Z | [
"python"
] |
Add item to stack in game inventory | 38,277,792 | <p>I've tried working on this problem for over an hour and a half and I've finally capitulated. Try as I might, I cannot get like items to stack in an inventory.</p>
<p>In detail, I randomly generate a 'drop', which has a name and a quantity stored in an array. 'drops' is a 2d array which holds these sub-arrays. I'm t... | 1 | 2016-07-09T02:51:00Z | 38,281,612 | <p>You didn't state which Python version you're using. Based on your <code>print()</code> syntax, I assume it's Python 3.x, right? </p>
<p>If so, this might be an ideal use case for the <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code> class</a> from t... | 0 | 2016-07-09T12:02:34Z | [
"python"
] |
Linear Approximate of Data Frame | 38,277,852 | <pre><code>Block DF
0 1.2
1 2.3
4 4.2
5 5.6
6 4.3
10 2.2
</code></pre>
<p>How to find out linear approx. value DF of Block 7 </p>
<pre><code>(7,???)
</code></pre>
<p>using the closest two data point</p>
<pre><code>(6, 4.3)
(10, 2.2)?
</code></pre>
<p>How to implement to find the two closes... | 1 | 2016-07-09T03:02:13Z | 38,277,935 | <p>You can use <code>numpy.interp</code> function to find interpolations:</p>
<pre><code>import numpy as np
np.interp(7, df.block, df.DF)
# >>> 3.775
</code></pre>
<p>More info <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html" rel="nofollow">here</a>.</p>
<p>You could also use ... | 1 | 2016-07-09T03:17:21Z | [
"python",
"pandas"
] |
Linear Approximate of Data Frame | 38,277,852 | <pre><code>Block DF
0 1.2
1 2.3
4 4.2
5 5.6
6 4.3
10 2.2
</code></pre>
<p>How to find out linear approx. value DF of Block 7 </p>
<pre><code>(7,???)
</code></pre>
<p>using the closest two data point</p>
<pre><code>(6, 4.3)
(10, 2.2)?
</code></pre>
<p>How to implement to find the two closes... | 1 | 2016-07-09T03:02:13Z | 38,278,844 | <p>I saw the tag 'pandas' on the question and I tried to use Pandas for this implementation. Check out the code:</p>
<pre><code>import pandas as pd
import numpy as np
s = pd.Series([1.2,2.3,np.nan,np.nan,4.2,5.6,4.3,np.nan,np.nan,np.nan,2.2], index=[0,1,2,3,4,5,6,7,8,9,10])
ans = s.interpolate(method='linear')
print(... | 1 | 2016-07-09T05:53:56Z | [
"python",
"pandas"
] |
Obtain location of largest rectangle | 38,277,859 | <p>I'm trying to follow the code in the answer here: <a href="http://stackoverflow.com/questions/2478447/find-largest-rectangle-containing-only-zeros-in-an-n%C3%97n-binary-matrix">Find largest rectangle containing only zeros in an N×N binary matrix</a></p>
<p>I'm having difficulty understanding how to find the or... | 1 | 2016-07-09T03:03:10Z | 38,401,244 | <p>Here a solution that modifies the <a href="https://gist.github.com/zed/776423" rel="nofollow">Gist version</a> of J.F. Sebastian's <a href="http://stackoverflow.com/a/4671342/1628638">answer</a>:</p>
<pre><code>from collections import namedtuple
Info = namedtuple('Info', 'start height')
# returns height, width, a... | 2 | 2016-07-15T16:43:34Z | [
"python",
"algorithm"
] |
Django Heroku Profile | 38,277,899 | <p>I am having trouble running my django app on Heroku. Following is my file structures:</p>
<pre><code>---django_blog
---media_cdn
---static_cdn
---Procfile
---requirements.txt
---runtime.txt
---src
---blog
---...
---settings.py
---manage.py
---...
</code></pre>
... | 0 | 2016-07-09T03:11:01Z | 38,278,194 | <p>From <code>Heroku</code> documentation:</p>
<blockquote>
<p>First, and most importantly, Heroku web applications require a
Procfile.</p>
<p>This file (named Procfile) is used to explicitly declare your
applicationâs process types and entry points. It is located in the
root of your repository.</p>
</b... | 0 | 2016-07-09T04:03:44Z | [
"python",
"django",
"heroku",
"procfile"
] |
Django can't be found in a Heroku Python Virtualenv | 38,277,904 | <p>Update: Problem solved. See the answer in the answers section.</p>
<hr>
<p>Today is the first day I'm working on Heroku with Python, and I have successfully worked through <a href="https://devcenter.heroku.com/articles/getting-started-with-python#introduction" rel="nofollow">this tutorial</a> to set things up on m... | 1 | 2016-07-09T03:11:53Z | 38,286,744 | <p>Thanks to cdunklau from irc #python. The solution was because my MacBook (OS X El Capitan)'s brew was too outdated for Django, that <code>brew doctor</code> said:</p>
<pre><code>Homebrew requires Leopard or higher. For Tiger support, see:
http://github.com/sceaga/homebrew/tree/tiger
</code></pre>
<p>My Python was ... | 1 | 2016-07-09T22:05:27Z | [
"python",
"django",
"heroku",
"virtualenv"
] |
Python Cryptography Multibackend cannot be innitialized | 38,277,915 | <pre><code>Traceback (most recent call last):
File "ENCDEC.py", line 96, in decrypt
File "site-packages\cryptography\fernet.py", line 32, in __init__
File "site-packages\cryptography\hazmat\backends\__init__.py", line 35, in def
ault_backend
File "site-packages\cryptography\hazmat\backends\multibackend.py", lin... | 1 | 2016-07-09T03:14:07Z | 38,285,941 | <p>I also faced this very same problem while freezing the Python scripts. I solved the problem using a patch to the cryptography.hazmat.backends as suggested here
<a href="https://github.com/pyca/cryptography/issues/2039" rel="nofollow">github#issues</a></p>
<pre><code> # file: pyenv\lib\site-packages\cryptography... | 1 | 2016-07-09T20:11:02Z | [
"python",
"cryptography"
] |
Remove special characters in pandas dataframe | 38,277,928 | <p>This seems like an inherently simple task but I am finding it very difficult to remove the '<em>' from my entire data frame and return the numeric values in each column, including the numbers that did not have '</em>'. The dateframe includes hundreds of more columns and looks like this in short:</p>
<pre><code>Time... | 2 | 2016-07-09T03:16:10Z | 38,277,932 | <p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow">replace</a> which applies on whole dataframe :</p>
<pre><code>df
Out[14]:
Time A1 A2
0 2.000255 1499 1592
1 2.176470 2096 1942
2 2.765405 *7639* *8196*
3 2.765856 *70... | 3 | 2016-07-09T03:17:14Z | [
"python",
"numpy",
"pandas"
] |
How do I get data into the ndarray format for SKLearn? | 38,277,938 | <p>Scikit-Learn is a great Python module that supplies a <a href="https://en.wikipedia.org/wiki/Support_vector_machine" rel="nofollow">support vector machine</a> with many algorithms. I've been learning how to use the module for the past few days, and I've noticed it relies heavily on the separate <a href="https://pypi... | 0 | 2016-07-09T03:17:28Z | 38,283,335 | <p>For each sample(e.g each Forum Post) you must have a vector(in python a list). For example if you have 200 post and their respective category, you must have 200 list for training data and exactly one list that has 200 element for each 200 category.
each list of traning category can be a model(e.g Bag Of Word. see he... | 0 | 2016-07-09T15:25:16Z | [
"python",
"scikit-learn",
"classification",
"svm"
] |
Python - Global Name is not defined | 38,278,026 | <p>I promise I have read through the other versions of this question, but I was unable to find a relevant one to my situation. If there is one, I apologize, I've been staring at this for a few hours now.</p>
<p>I've been toying with this a lot and actually got results on one version, so know it's close.</p>
<p>The 's... | 2 | 2016-07-09T03:35:02Z | 38,278,041 | <p>use <code>spider1.start_urls</code> instead of just <code>start_urls</code>.</p>
| 2 | 2016-07-09T03:38:33Z | [
"python",
"xpath",
"scrapy",
"scrapy-spider"
] |
Python - Global Name is not defined | 38,278,026 | <p>I promise I have read through the other versions of this question, but I was unable to find a relevant one to my situation. If there is one, I apologize, I've been staring at this for a few hours now.</p>
<p>I've been toying with this a lot and actually got results on one version, so know it's close.</p>
<p>The 's... | 2 | 2016-07-09T03:35:02Z | 38,278,091 | <p>You need to fix your <code>start_requests()</code> method:</p>
<ul>
<li>you meant to use <code>listing_url_list</code> instead of <code>start_urls</code></li>
<li>you meant to use <code>listing_url</code> instead of <code>listing_url_list</code> as a loop variable</li>
<li>there is no need to instantiate <code>Sele... | 2 | 2016-07-09T03:46:03Z | [
"python",
"xpath",
"scrapy",
"scrapy-spider"
] |
How do you save a function's data to a csv file | 38,278,084 | <p>Let's say I want to take function <code>test_function</code> and write it's data to a csv file that can be read by python later. How can I do that?</p>
<p>Just a sample function:</p>
<pre><code>def test_function():
games_won = 4
games_lost = 5
average_time_sec = 6.0
some_list = [1,2,3,4]
some_... | 0 | 2016-07-09T03:45:06Z | 38,278,195 | <p>Here is one way </p>
<pre><code>import csv
import os.path
resultFile = open("path to your destination file" , 'wb')
wr = csv.writer(resultFile, dialect='excel')
some_list = [1,2,3,4]
wr.writerow(some_list)
</code></pre>
| 1 | 2016-07-09T04:03:52Z | [
"python",
"python-3.x",
"csv"
] |
Error with links in scrapy | 38,278,136 | <p>I want to scrape some links to a news site and get the full news. However the links are relative</p>
<p>The news site is <a href="http://www.puntal.com.ar/v2/" rel="nofollow">http://www.puntal.com.ar/v2/</a></p>
<p>And the links are as well</p>
<pre><code><div class="article-title">
<a href="... | 0 | 2016-07-09T03:54:48Z | 38,278,147 | <p>That <code>i[1:]</code> is strange and is the key problem. There is no need in slicing:</p>
<pre><code>def parse(self, response):
urls = response.xpath('//div[@class="article-title"]/a/@href').extract()
for url in urls:
yield Request(urlparse.urljoin(response.url, url), callback=self.parse_url)
</co... | 0 | 2016-07-09T03:55:58Z | [
"python",
"scrapy",
"web-crawler",
"scrapy-spider"
] |
how do djangos field instances work in models | 38,278,141 | <p>Something I'm confused about in Django is how the model's fields work.</p>
<p>You define them as class variables.</p>
<p>So, a class like this:</p>
<pre><code>class Foo:
avar = "something here"
</code></pre>
<p>And if you created two instances.</p>
<pre><code>f1 = Foo()
f2 = Foo()
</code></pre>
<p>And you ... | -1 | 2016-07-09T03:55:18Z | 38,278,205 | <p>A few things are going on here. First, all you are doing is creating a string in your Foo object just like any other python object. If you want it to be a field in the database, you need to use a type from models. Something like</p>
<pre><code>from django.db import models
class Foo(models.Model):
avar = models... | 0 | 2016-07-09T04:05:51Z | [
"python",
"django",
"python-3.x",
"django-models"
] |
how do djangos field instances work in models | 38,278,141 | <p>Something I'm confused about in Django is how the model's fields work.</p>
<p>You define them as class variables.</p>
<p>So, a class like this:</p>
<pre><code>class Foo:
avar = "something here"
</code></pre>
<p>And if you created two instances.</p>
<pre><code>f1 = Foo()
f2 = Foo()
</code></pre>
<p>And you ... | -1 | 2016-07-09T03:55:18Z | 38,278,219 | <p>A regular class variable is a property of the class. It is not stored in the database (only <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/" rel="nofollow">model fields</a> are). In your case, <code>avar</code> is not a model field. It is just a simple python class variable.</p>
<p>If you change t... | 1 | 2016-07-09T04:08:38Z | [
"python",
"django",
"python-3.x",
"django-models"
] |
how do djangos field instances work in models | 38,278,141 | <p>Something I'm confused about in Django is how the model's fields work.</p>
<p>You define them as class variables.</p>
<p>So, a class like this:</p>
<pre><code>class Foo:
avar = "something here"
</code></pre>
<p>And if you created two instances.</p>
<pre><code>f1 = Foo()
f2 = Foo()
</code></pre>
<p>And you ... | -1 | 2016-07-09T03:55:18Z | 38,280,621 | <p>Django uses a <a href="https://github.com/django/django/blob/ba53da894fc713629ae4d3fbdd14eff98c808389/django/db/models/base.py#L78" rel="nofollow">metaclass</a> to gather all fields, and collects them in <code>Model._meta</code>. After the class is created, fields are no longer part of the model class itself:</p>
<... | 1 | 2016-07-09T10:02:06Z | [
"python",
"django",
"python-3.x",
"django-models"
] |
does npartitions influence the result of dask.dataframe.head()? | 38,278,157 | <p>When running the following code, the result of dask.dataframe.head() depends on npartitions:</p>
<pre><code>import dask.dataframe as dd
import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [2,3,4]})
ddf = dd.from_pandas(df, npartitions = 3)
print(ddf.head())
</code></pre>
<p>This yields the following result:<... | 6 | 2016-07-09T03:58:07Z | 38,283,697 | <p>According to the documentation <a href="http://dask.pydata.org/en/latest/dataframe-api.html#dask.dataframe.DataFrame.head" rel="nofollow"><code>dd.head()</code></a> only checks the first partition:</p>
<blockquote>
<p><code>head(n=5, compute=True)</code></p>
<p>First n rows of the dataset</p>
<p>Caveat,... | 3 | 2016-07-09T16:03:53Z | [
"python",
"pandas",
"dask"
] |
How to issue commands on remote hosts in parallel using Fabric without using a fabfile? | 38,278,266 | <p>I have a Python script that uses Fabric to launch tests on remote hosts, get the otuput file of the tests, and do some parsing. The Python script is not a fabfile.</p>
<p>I would like to launch and run the tests in parallel. I've read about using the "@parallel" decorator but all the examples I've read has the sc... | 0 | 2016-07-09T04:17:35Z | 38,353,766 | <p>I can't comment so i'll put an answer change your main to :</p>
<pre><code>if __name__ == '__main__':
HOSTS = ['10.10.10.10', '10.10.10.11', '10.10.10.12', '10.10.10.13']
testfile_name = "foo.py"
execute(copy_test,HOSTS, testfile_name)
# I would like to launch run_test() in parallel
execute(... | 0 | 2016-07-13T13:56:44Z | [
"python",
"parallel-processing",
"fabric"
] |
Fastest way to get the index of the first sublist that contains value | 38,278,313 | <p>I have a list of lists in python of the form</p>
<pre><code>A=[[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
</code></pre>
<p>I need to get a fast way to get the row index of an element in that structure.</p>
<p>method(2) = 0</p>
<p>method(8) = 1</p>
<p>method(12) = 2</p>
<p>and so on. As always, the fastest the m... | 0 | 2016-07-09T04:25:37Z | 38,278,344 | <p>In this state, <em>the data structure (list of lists) is not quite convenient and efficient for the queries you want to make on it</em>. Restructure it to have it in a form:</p>
<pre><code>item -> list of sublist indexes # assuming items can be present in multiple sublists
</code></pre>
<p>This way the lookups... | 1 | 2016-07-09T04:29:56Z | [
"python",
"list",
"multidimensional-array"
] |
Fastest way to get the index of the first sublist that contains value | 38,278,313 | <p>I have a list of lists in python of the form</p>
<pre><code>A=[[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
</code></pre>
<p>I need to get a fast way to get the row index of an element in that structure.</p>
<p>method(2) = 0</p>
<p>method(8) = 1</p>
<p>method(12) = 2</p>
<p>and so on. As always, the fastest the m... | 0 | 2016-07-09T04:25:37Z | 38,278,351 | <p>It is very simple using <code>next()</code> with a generator expression:</p>
<pre><code>def method(lists, value):
return next(i for i, v in enumerate(lists) if value in v)
</code></pre>
<p>The problem with that is that it will have an error if <code>value</code> does not occur. With a slightly longer function... | 1 | 2016-07-09T04:31:35Z | [
"python",
"list",
"multidimensional-array"
] |
Fastest way to get the index of the first sublist that contains value | 38,278,313 | <p>I have a list of lists in python of the form</p>
<pre><code>A=[[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
</code></pre>
<p>I need to get a fast way to get the row index of an element in that structure.</p>
<p>method(2) = 0</p>
<p>method(8) = 1</p>
<p>method(12) = 2</p>
<p>and so on. As always, the fastest the m... | 0 | 2016-07-09T04:25:37Z | 38,278,381 | <p>Here is another way using numpy</p>
<pre><code>import numpy
A = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
my_array = numpy.array(A)
numpy.where(my_array==2) ## will return both the list and the index within the list
numpy.where(my_array==12)
## As a follow up if we want only the index we can always do :
numpy.where(my... | 0 | 2016-07-09T04:36:24Z | [
"python",
"list",
"multidimensional-array"
] |
Fastest way to get the index of the first sublist that contains value | 38,278,313 | <p>I have a list of lists in python of the form</p>
<pre><code>A=[[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
</code></pre>
<p>I need to get a fast way to get the row index of an element in that structure.</p>
<p>method(2) = 0</p>
<p>method(8) = 1</p>
<p>method(12) = 2</p>
<p>and so on. As always, the fastest the m... | 0 | 2016-07-09T04:25:37Z | 38,278,418 | <p>find operation in list is linear. Following is simple code in python to find an element in list of lists.</p>
<pre><code>A=[[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
def method(value):
for idx, list in enumerate(A):
if value in list:
return idx
return -1
print (method(12))
</code></pre... | 0 | 2016-07-09T04:43:41Z | [
"python",
"list",
"multidimensional-array"
] |
Convert string in python from no quote with quote | 38,278,385 | <p>I have tried:</p>
<pre><code>a = '%s' % (John)
</code></pre>
<p>and</p>
<pre><code>a = '%s' % John
</code></pre>
<p>but its not correct.</p>
<p>I need this </p>
<p>John -> "John"</p>
<p>The converted "John" has double quotes.</p>
| -1 | 2016-07-09T04:36:34Z | 38,278,703 | <pre><code>>>> foo = '"{name}"'.format(name="John")
>>> foo
'"John"'
</code></pre>
<p>OR </p>
<pre><code>>>> bar = '"{0}"'.format("John")
>>> bar
'"John"'
</code></pre>
| 0 | 2016-07-09T05:28:17Z | [
"python"
] |
(Python) How to give a quiz 2 right answers | 38,278,419 | <p>I'm new to Python so sorry if I've screwed up some code in any way, for the month of February I am trying to make it so it has 3 correct answers for the number of days in the month 28,29 29 28 but it doesn't seem to be working when I try to change</p>
<pre><code>user = int(input(""))
if month == "January":
answ... | 1 | 2016-07-09T04:43:42Z | 38,278,473 | <p>I believe "or" is only used for boolean or comparison operations.
i.e.</p>
<p><code>if month == "Janurary" or month == "Feburary":
do_something</code></p>
<p>if the quiz is looking for the possible "last days" of a month, I'm assuming the function would want a list of options.</p>
<p><code>if month == "Janura... | 0 | 2016-07-09T04:52:30Z | [
"python",
"question-answering"
] |
(Python) How to give a quiz 2 right answers | 38,278,419 | <p>I'm new to Python so sorry if I've screwed up some code in any way, for the month of February I am trying to make it so it has 3 correct answers for the number of days in the month 28,29 29 28 but it doesn't seem to be working when I try to change</p>
<pre><code>user = int(input(""))
if month == "January":
answ... | 1 | 2016-07-09T04:43:42Z | 38,279,819 | <p>You will likely want to use a <code>list</code> to check if the <code>user</code> answer was in the list of possible answers for the number of days in a month. you can then use the <code>in</code> keyword in python check if <code>user</code> is in the possible answers list.</p>
<p>The code would look a bit like the... | 0 | 2016-07-09T08:13:54Z | [
"python",
"question-answering"
] |
Python tkinter wont display diagonal lines | 38,278,420 | <p>I recently started using Arch Linux, and after transferring a python file from my mac to the Linux, and running it, it did not work. This is pretty common, but, the way in which it didn't work was very strange. The program is one that graphs equations of lines, but on Linux, the tkinter Canvas object's create_line... | 0 | 2016-07-09T04:43:49Z | 38,279,010 | <p>I was able to fix it by installing the correct driver, in my case xf86-video-intel, and rebooting. I think it was just a newbie mistake, but its still sort of interesting that the missing driver only affected diagonal lines in tkinter.</p>
| 1 | 2016-07-09T06:20:22Z | [
"python",
"linux",
"tkinter"
] |
How to create a business side inventory manager | 38,278,459 | <p>I am creating my first website for a friend using python, flask, and mysql. The goal of the website is to display and sell shoes (like a much simpler/smaller eastbay or nike). </p>
<p>I am at the point where I have created a database of inventory and have added some of the items myself via INSERT commands in the my... | -1 | 2016-07-09T04:49:19Z | 38,278,549 | <p>Basically, you're going to need to create an admin interface that runs those <code>INSERT</code>, <code>UPDATE</code>, and <code>DELETE</code> queries. With Flask, a lot of people will reach for sqlalchemy to handle the data access layer.</p>
<p>If you're not completely sold on Flask, one of Django's major selling ... | 1 | 2016-07-09T05:04:00Z | [
"python",
"mysql",
"flask"
] |
BeautifulSoup grabbing text | 38,278,467 | <p>I'm a bit confused as to how to get something with BeautifulSoup, the html that I'm trying to grab looks like this:</p>
<pre><code><div class="txt-block">
<h4 class="inline">Gross:</h4>
$408,992,272
</div>
</code></pre>
<p>I want to grab the dollar number.
So far I have this, but ... | 2 | 2016-07-09T04:51:12Z | 38,280,787 | <p>If you just want the dollar amount, find_all the text from the <em>txt-block</em> <em>div</em> setting <em>recursive=False</em> so you don't get any text from its children and strip any whitespace:</p>
<pre><code>In [27]:h = """<div class="txt-block">
<h4 class="inline">Gross:</h4&... | 1 | 2016-07-09T10:22:13Z | [
"python",
"beautifulsoup"
] |
How to take out text from the following HTML TEXT using HTMLParser in Python? | 38,278,578 | <p>Given below is the extract from html file. I want to get only the text part from it using HTMLParser. </p>
<pre><code><html>
<div class="js-tweet-text-container">
<p class="TweetTextSize js-tweet-text tweet-text" data-aria-label-part=
"0" lang="en"><a class="twitter-atreply... | -1 | 2016-07-09T05:08:12Z | 38,279,916 | <p>Let's use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">BeautifulSoup</a> instead. First let's install it:</p>
<pre><code>pip install beautifulsoup4
</code></pre>
<p>Then our code:</p>
<pre><code>from bs4 import BeautifulSoup
html = """
<html>
<div class="js-tweet-t... | 1 | 2016-07-09T08:28:50Z | [
"python"
] |
Use groupby in Pandas to count things in one column in comparison to another | 38,278,603 | <p>Maybe groupby is the wrong approach. Seems like it should work but I'm not seeing it...</p>
<p>I want to group an event by it's outcome. Here is my DataFrame (df):</p>
<pre><code>Status Event
SUCCESS Run
SUCCESS Walk
SUCCESS Run
FAILED Walk
</code></pre>
<p>Here is my desired result:</p>
<pre><code>Event SUC... | 4 | 2016-07-09T05:12:58Z | 38,279,262 | <p>try this: </p>
<pre><code> pd.crosstab(df.Event, df.Status)
Status FAILED SUCCESS
Event
Run 0 2
Walk 1 1
len("df.groupby('Event').Status.value_counts().unstack().fillna(0)")
61
len("df.pivot_table(index='Event', columns='Status', aggfunc=len, fill_value=0)")
... | 6 | 2016-07-09T06:59:10Z | [
"python",
"pandas",
"dataframe"
] |
Use groupby in Pandas to count things in one column in comparison to another | 38,278,603 | <p>Maybe groupby is the wrong approach. Seems like it should work but I'm not seeing it...</p>
<p>I want to group an event by it's outcome. Here is my DataFrame (df):</p>
<pre><code>Status Event
SUCCESS Run
SUCCESS Walk
SUCCESS Run
FAILED Walk
</code></pre>
<p>Here is my desired result:</p>
<pre><code>Event SUC... | 4 | 2016-07-09T05:12:58Z | 38,279,370 | <p>An alternative solution, using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table()</a> method:</p>
<pre><code>In [5]: df.pivot_table(index='Event', columns='Status', aggfunc=len, fill_value=0)
Out[5]:
Status FAILED SUCCESS
Event
Run 0 ... | 7 | 2016-07-09T07:16:08Z | [
"python",
"pandas",
"dataframe"
] |
Use groupby in Pandas to count things in one column in comparison to another | 38,278,603 | <p>Maybe groupby is the wrong approach. Seems like it should work but I'm not seeing it...</p>
<p>I want to group an event by it's outcome. Here is my DataFrame (df):</p>
<pre><code>Status Event
SUCCESS Run
SUCCESS Walk
SUCCESS Run
FAILED Walk
</code></pre>
<p>Here is my desired result:</p>
<pre><code>Event SUC... | 4 | 2016-07-09T05:12:58Z | 38,279,447 | <p>I'd do:</p>
<pre><code>df.groupby('Event').Status.value_counts().unstack().fillna(0)
</code></pre>
<p><a href="http://i.stack.imgur.com/Hqo2T.png"><img src="http://i.stack.imgur.com/Hqo2T.png" alt="enter image description here"></a></p>
<hr>
<h3>Timing</h3>
<p><a href="http://i.stack.imgur.com/VhokL.png"><img s... | 5 | 2016-07-09T07:27:29Z | [
"python",
"pandas",
"dataframe"
] |
Use groupby in Pandas to count things in one column in comparison to another | 38,278,603 | <p>Maybe groupby is the wrong approach. Seems like it should work but I'm not seeing it...</p>
<p>I want to group an event by it's outcome. Here is my DataFrame (df):</p>
<pre><code>Status Event
SUCCESS Run
SUCCESS Walk
SUCCESS Run
FAILED Walk
</code></pre>
<p>Here is my desired result:</p>
<pre><code>Event SUC... | 4 | 2016-07-09T05:12:58Z | 38,280,018 | <p>Here's a NumPy based approach -</p>
<pre><code># Get unique header strings for input dataframes
unq1,ID1 = np.unique(df['Event'],return_inverse=True)
unq2,ID2 = np.unique(df['Status'],return_inverse=True)
# Get linear indices/tags corresponding to grouped headers
tag = ID1*(ID2.max()+1) + ID2
# Setup 2D Numpy arr... | 3 | 2016-07-09T08:46:06Z | [
"python",
"pandas",
"dataframe"
] |
Conditional based on slope between two rows in Pandas DataFrame | 38,278,664 | <p>I am trying to create a program that will select rows in a large time series dataframe and return only the rows where the slope (row2-row1)/(Time2-Time1) is >= the slope of the previous two rows (row1-row0)/(Time1-Time0). I have gone through some very heavy loop operations only to meet the extent for loops. </p>
<p... | 2 | 2016-07-09T05:22:45Z | 38,279,310 | <p>Let's start by calculating the dataframe of slopes:</p>
<pre><code>slopes = df.iloc[:, 1:].diff().div(df.Time.diff(), axis=0)
</code></pre>
<p>This uses <code>diff</code> or difference of every row with the one prior and divides each column that isn't the first by the first.</p>
<p>And we might as well calculate ... | 3 | 2016-07-09T07:06:30Z | [
"python",
"numpy",
"pandas"
] |
Spliting uneven spaced column in Python | 38,278,689 | <p>I tried to use the below program</p>
<pre><code>import os
HOME= os.getcwd()
STORE_INFO_FILE = os.path.join(HOME,'storeInfo')
def searchStr(STORE_INFO_FILE, storeId):
with open (STORE_INFO_FILE, 'r') as storeInfoFile:
for storeLine in storeInfoFile:
## print storeLine.split(r'\s+')[0]
... | 0 | 2016-07-09T05:25:55Z | 38,278,752 | <p>Code has an issue if split method returns an empty list.
You can change code that calls split method and add error handling code.</p>
<p>Following can be done</p>
<pre><code>storeLineWords = storeLine.split()
if len(storeLineWords) > 0 and storeLineWords[0] == storeId:
</code></pre>
| 0 | 2016-07-09T05:40:13Z | [
"python",
"split"
] |
Spliting uneven spaced column in Python | 38,278,689 | <p>I tried to use the below program</p>
<pre><code>import os
HOME= os.getcwd()
STORE_INFO_FILE = os.path.join(HOME,'storeInfo')
def searchStr(STORE_INFO_FILE, storeId):
with open (STORE_INFO_FILE, 'r') as storeInfoFile:
for storeLine in storeInfoFile:
## print storeLine.split(r'\s+')[0]
... | 0 | 2016-07-09T05:25:55Z | 38,278,759 | <p>It looks like you have an empty or blank line in your file:</p>
<pre><code>>>> 'abc def hij\n'.split()
['abc', 'def', 'hij']
>>> ' \n'.split() # a blank line containing white space
[]
>>> '\n'.split() # an empty line
[]
</code></pre>
<p>The last 2 cases show that an empty ... | 2 | 2016-07-09T05:41:02Z | [
"python",
"split"
] |
How to get pyPdf to work with os or glob | 38,278,720 | <p>My goal is to read a directory with several PDF files and return the number of pages in each file using Python. I'm trying to use the pyPdf library but it fails. </p>
<p>If I do this:</p>
<pre><code>from pyPdf import PdfFileReader
testFile = "C:\\path\\file.pdf"
pdfFile = PdfFileReader(file(testFile, 'rb'))
print... | 0 | 2016-07-09T05:32:35Z | 38,278,922 | <p>Issue is due to using name, file as variable.
You are using file as variable name in first for loop.
And as a function call in statement, targetPdf = PdfFileReader(file(item,'rb')).</p>
<p>Try changing variable name in first for loop from file to fileName.
Hope that helps</p>
| 1 | 2016-07-09T06:06:32Z | [
"python",
"parsing",
"pypdf"
] |
Removing a row from CSV with python if data wasn't recorded in a column | 38,278,870 | <p>I'm trying to import a batch of CSV's into PostgreSQL and constantly run into an issue with missing data:</p>
<blockquote>
<p>psycopg2.DataError: missing data for column "column_name" CONTEXT:<br>
COPY table_name, line <em>where ever in the CSV that data wasn't<br>
recorded, and here are data values up to the... | -1 | 2016-07-09T05:57:42Z | 38,278,889 | <p>Unfortunately, you <em>cannot parameterize table or column names</em>. Use string formatting, but make sure to validate/escape the value properly:</p>
<pre><code>cursor.execute("COPY table_name FROM {column_name} WITH CSV HEADER DELIMITER ','".format(column_name=arc_csv))
</code></pre>
| 0 | 2016-07-09T06:00:28Z | [
"python",
"postgresql",
"csv",
"psycopg2"
] |
Removing a row from CSV with python if data wasn't recorded in a column | 38,278,870 | <p>I'm trying to import a batch of CSV's into PostgreSQL and constantly run into an issue with missing data:</p>
<blockquote>
<p>psycopg2.DataError: missing data for column "column_name" CONTEXT:<br>
COPY table_name, line <em>where ever in the CSV that data wasn't<br>
recorded, and here are data values up to the... | -1 | 2016-07-09T05:57:42Z | 38,280,460 | <p>You could use pandas to remove rows with missing values:</p>
<pre><code>import glob, os, pandas
file_list = glob.glob(path)
for f in file_list:
filename = os.path.basename(f)
arc_csv = arc_path + filename
data = pandas.read_csv(f, index_col=0)
ind = data.apply(lambda x: not pandas.isnull(x.values)... | 0 | 2016-07-09T09:44:23Z | [
"python",
"postgresql",
"csv",
"psycopg2"
] |
numpy.sum on range and range_iterator objects | 38,278,881 | <p>Consider this performance test on Ipython under python 3:</p>
<p>Create a range, a range_iterator and a generator</p>
<pre><code>In [1]: g1 = range(1000000)
In [2]: g2 = iter(range(1000000))
In [3]: g3 = (i for i in range(1000000))
</code></pre>
<p>Measure time for summing using python native sum</p>
<pre><cod... | 0 | 2016-07-09T05:59:25Z | 38,279,232 | <p>Did you look at the results of repeated sums on the iter?</p>
<pre><code>95:~/mypy$ g2=iter(range(10))
96:~/mypy$ sum(g2)
Out[96]: 45
97:~/mypy$ sum(g2)
Out[97]: 0
98:~/mypy$ sum(g2)
Out[98]: 0
</code></pre>
<p>Why the 0s? Because <code>g2</code> can be use only once. Same goes for the generator expression.</p>
... | 2 | 2016-07-09T06:55:56Z | [
"python",
"python-3.x",
"numpy",
"ipython"
] |
Read last valid rows in csv using python | 38,278,992 | <p>I am working on reading from my csv file using python. But I want to read only specific(last valid) rows from the tail in csv also there is a catch that function should return the entire row only when it is valid. Can anyone help me out with this?</p>
<p>Below is my csv file looks like:</p>
<pre><code>Sr. Ad... | 0 | 2016-07-09T06:17:35Z | 38,279,544 | <p>With pandas it would look like this:</p>
<p>Note: python 2.7. code. Change the import for the StringIo on Python3.</p>
<pre><code>import pandas as pd
from StringIO import StringIO
input = """Sr. Add A B C D
0 0013A20040D6A141 -308.1 -307.6 -307.7 -154.063
1 0013... | 1 | 2016-07-09T07:41:54Z | [
"python",
"csv",
"tail"
] |
Inner scope changing value of variable defined in outer scope | 38,278,998 | <p>I did a coding practice about symmetric square.</p>
<p>Here is the instruction:
A list is symmetric if the first row is the same as the first column,
the second row is the same as the second column and so on. Write a
procedure, symmetric, which takes a list as input, and returns the
boolean True if the list is symm... | 0 | 2016-07-09T06:18:22Z | 38,279,057 | <p><code>j</code> is defined outside the scope of the while loop, so as you increment <code>j</code> in the loop, you are incrementing the variable defined in the outer scope.</p>
<p>For what it's worth, this is a slightly more terse way to do that:</p>
<pre><code>def symmetric(inval):
return map(tuple, inval) ==... | 0 | 2016-07-09T06:28:12Z | [
"python",
"global-variables"
] |
How to decode encode e-mail subject line in python? | 38,279,038 | <p>How do I detect encode e-mail subject in python and also decode it? I see code in PHP mb_decode_mimeheader(); but not map code in python.</p>
<p>This is my code:</p>
<pre><code>print "=============Subject==============="
print mystr = email_message['Subject']
</code></pre>
<p>This is output:</p>
<pre><code>====... | 1 | 2016-07-09T06:25:37Z | 38,279,580 | <p>Maybe you can use <a href="https://docs.python.org/2/library/email.header.html#email.header.decode_header" rel="nofollow">decode_header</a> like:</p>
<pre><code>>>> from email.header import decode_header
>>> decode_header(email_message['Subject'])
[(b"Fry's-Day Deal Alert! More Smokin", '... | 0 | 2016-07-09T07:46:14Z | [
"python",
"email",
"utf-8",
"decode"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.