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
Getting child attributes from an XML document using element tree
39,475,897
<p>I have an xml pom file like the following:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&g...
0
2016-09-13T17:34:06Z
39,476,557
<p>Your XML has a small mistake. There should be a closing tag <code>&lt;/project&gt;</code> which you probably missed in the question.</p> <p>The following works for me:</p> <pre><code>from xml.etree import ElementTree tree = ElementTree.parse('pomFile.xml') root = tree.getroot() namespace = '{http://maven.apache.or...
0
2016-09-13T18:16:04Z
[ "python", "maven", "elementtree" ]
Aligning pandas DataFrames that don't have a common index
39,475,968
<p>I have DataFrames that represent data from two different sensors:</p> <pre><code>In[0]: df0 Out[0]: time foo 0 0.1 123 1 1.0 234 2 2.1 345 3 3.1 456 4 3.9 567 5 5.1 678 In[0]: df1 Out[0]: time bar 0 -0.9 876 1 -0.1 765 2 0.7 654 3 2.1 543 4 3.0 432 </c...
2
2016-09-13T17:39:16Z
39,476,878
<p><a href="http://stackoverflow.com/questions/39475968/aligning-pandas-dataframes-that-dont-have-a-common-index?noredirect=1#comment66271493_39475968">@Kartik posted a perfect links</a> to start with...</p> <p>Here is a starting point:</p> <pre><code>df0.set_index('time', inplace=True) df1.set_index('time', inplace=...
1
2016-09-13T18:35:43Z
[ "python", "pandas", "indexing", "dataframe" ]
Apply function to each cell in DataFrame
39,475,978
<p>I have a dataframe that may look like this:</p> <pre><code>A B C foo bar foo bar bar foo foo bar </code></pre> <p>I want to look through every element of each row (or every element of each column) and apply the following function to get the subsequent DF:</p> <pre><code>def foo_bar(x...
0
2016-09-13T17:39:45Z
39,476,023
<p>You can do <code>df%2</code>, with the old question about finding the even numbers in the data frame:</p> <pre><code>df%2 == 0 # A B C #0 True False True #1 False True False </code></pre> <p><em>Update</em>:</p> <p>Since the question has been updated, as per @ayhan suggested, you can ...
4
2016-09-13T17:42:24Z
[ "python", "pandas", "dataframe", "apply" ]
Get feature and class names into decision tree using export graphviz
39,476,020
<p>Good Afternoon,</p> <p>I am working on a decision tree classifier and am having trouble visualizing it. I can output the decision tree, however I cannot get my feature or class names/labels into it. My data is in a pandas dataframe format which I then move into a numpy array and pass to the classifier. I've tried a...
0
2016-09-13T17:42:14Z
39,481,669
<p>The class names are stored in <code>decision_tree_classifier.classes_</code>, i.e. the <code>classes_</code> attribute of your <code>DecisionTreeClassifier</code> instance. And the feature names should be the columns of your input dataframe. For your case you will have </p> <pre><code>classe_names = decision_tree_c...
2
2016-09-14T02:34:48Z
[ "python", "scikit-learn", "decision-tree" ]
what does the -1 mean in Scipy's voronoi algorithm?
39,476,094
<p>I am trying to custom plot the <a href="http://scipy.github.io/devdocs/generated/scipy.spatial.Voronoi.html" rel="nofollow">Voronoi</a> regions of random points in 2D</p> <pre><code>import matplotlib.pyplot as plt %matplotlib inline from scipy.spatial import Voronoi pt = np.random.random((10,2)) x = sp.spatial.Vor...
1
2016-09-13T17:46:21Z
39,476,507
<p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Voronoi.html" rel="nofollow"><code>scipy.spatial.Voronoi</code></a> uses the Qhull library underneath. In my experience Qhull contains several usability bugs. You hit <a href="http://www.qhull.org/html/qvoronoi.htm#outputs" rel="nofollow">one...
3
2016-09-13T18:13:00Z
[ "python", "graphics", "scipy", "computational-geometry", "voronoi" ]
search a file for text using input from another file with a twist [Python]
39,476,150
<p>I want to use a queryfile.txt as the source file, which will be used for searching and matching each line to a datafile.txt. But the datafile.txt has a different structure.</p> <p>queryfile.txt should look like this:</p> <pre><code>Gina Cooper Asthon Smith Kim Lee </code></pre> <p>while the datafile.txt looks l...
0
2016-09-13T17:49:33Z
39,476,299
<p>Rewrite this:</p> <pre><code>with open('datafile.txt', 'r') as data_file: data_addresses = set(names.rstrip() for names in data_file) </code></pre> <p>To this:</p> <pre><code>with open('datafile.txt', 'r') as data_file: data = data_file.readlines() data_addresses = list(filter(None, [line for line ...
0
2016-09-13T17:59:47Z
[ "python" ]
search a file for text using input from another file with a twist [Python]
39,476,150
<p>I want to use a queryfile.txt as the source file, which will be used for searching and matching each line to a datafile.txt. But the datafile.txt has a different structure.</p> <p>queryfile.txt should look like this:</p> <pre><code>Gina Cooper Asthon Smith Kim Lee </code></pre> <p>while the datafile.txt looks l...
0
2016-09-13T17:49:33Z
39,476,306
<p>Loop through the options instead and then you can just grab the next index:</p> <pre><code>for i in range(len(data_addresses): for entry in input_addresses: if entry==data_addresses[i]: output.write(data_address[i] + data_address[i+1]) </code></pre> <p>This might not have great time complexity, but you...
0
2016-09-13T18:00:02Z
[ "python" ]
Django upload image to cdn using an API
39,476,243
<p>I am building a website in Django on Pythonanywhere.com and I am using Backblaze's B2 cloud storage to store all the static and media files. My css and images that I have uploaded to Backblaze are working but I can't figure out how everything should fit together, so here is where I am (minimalized):</p> <p>In this ...
0
2016-09-13T17:56:15Z
39,476,527
<p>Using these commands in settings, You can set MEDIA_URL as well as where image is to be stored. Here image is stored in src/media_cdn</p> <pre><code>MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media_cdn") </code></pre> <p>You have to tell the path where upload_to should save the image inside media_c...
0
2016-09-13T18:14:15Z
[ "python", "django", "file-upload", "cdn" ]
picking a file and reading the words from it python
39,476,255
<p>I need help with this, I'm a total beginner at python. my assignment is to create a program that has the user pick a category, then scramble words from a file that are in that category. I just want to figure out why this first part isn't working, the first part being the first of four different methods that run depe...
-3
2016-09-13T17:57:17Z
39,476,342
<p>The first problem is that you're reading only 1-5 letters from the file. Please read the (documentation)[<a href="https://docs.python.org/2/tutorial/inputoutput.html]" rel="nofollow">https://docs.python.org/2/tutorial/inputoutput.html]</a> on how the <strong>read</strong> function works. The number in parentheses i...
2
2016-09-13T18:02:01Z
[ "python" ]
work around for former CStringIO and String IO function in Python 3 Pdfinterp (Pdfminer)
39,476,291
<p>I am using the pdfminer tool to convert pdf to .csv (text) and one of the subcommands in the tool <code>pdfinterp.py</code> still uses the CStringIO and StringIO for string to string translation -</p> <pre><code>import re try: from CStringIO import StringIO except ImportError: from StringIO import StringIO...
0
2016-09-13T17:59:14Z
39,476,413
<p>you could extend your import block to make it compatible with all versions (Python 2.x or 3.x). Ugly because of all try/except blocks but would work</p> <pre><code>try: from CStringIO import StringIO except ImportError: try: from StringIO import StringIO except ImportError: from io impo...
0
2016-09-13T18:06:20Z
[ "python", "c-strings", "pdfminer" ]
Why "class Meta" is necessary while creating a model form?
39,476,334
<pre><code>from django import forms from .models import NewsSignUp class NewsSignUpForm(forms.ModelForm): class Meta: model = NewsSignUp fields = ['email', 'first_name'] here </code></pre> <p>This code works perfectly fine. But, when I remove <strong>"class Meta:"</strong> as below, it throws a Va...
0
2016-09-13T18:01:21Z
39,476,404
<p>You are creating a <em><code>ModelForm</code></em> subclass. A model form <strong>has</strong> to have a model to work from, and the <code>Meta</code> object configures this.</p> <p>Configuration like this is grouped into the <code>Meta</code> class to avoid name clashes; that way you can have a <code>model</code> ...
3
2016-09-13T18:05:52Z
[ "python", "django", "django-models", "django-forms" ]
scikit-learn decision tree node depth
39,476,414
<p>My goal is to identify at what depth two samples separate within a decision tree. In the development version of scikit-learn you can use the <code>decision_path()</code> method to identify to last common node:</p> <pre><code>from sklearn import tree import numpy as np clf = tree.DecisionTreeClassifier() clf.fit(da...
3
2016-09-13T18:06:22Z
39,501,867
<p>Here is a function that you could use to recursively traverse the nodes and calculate the node depths</p> <pre><code>def get_node_depths(tree): """ Get the node depths of the decision tree &gt;&gt;&gt; d = DecisionTreeClassifier() &gt;&gt;&gt; d.fit([[1,2,3],[4,5,6],[7,8,9]], [1,2,3]) &gt;&gt;&...
1
2016-09-15T01:18:54Z
[ "python", "scikit-learn", "decision-tree" ]
Find all occurences of a specified match of two numbers in numpy array
39,476,430
<p>what i need to achieve is to get array of all indexes, where in my data array filled with zeros and ones is step from zero to one. I need very quick solution, because i have to work with milions of arrays of hundrets milions length. It will be running in computing centre. For instance..</p> <pre><code>data_array = ...
2
2016-09-13T18:07:40Z
39,476,537
<p>try this:</p> <pre><code>In [23]: np.where(np.diff(a)==1)[0] + 1 Out[23]: array([ 3, 9, 13], dtype=int64) </code></pre> <p>Timing for 100M element array:</p> <pre><code>In [46]: a = np.random.choice([0,1], 10**8) In [47]: %timeit np.nonzero((a[1:] - a[:-1]) == 1)[0] + 1 1 loop, best of 3: 1.46 s per loop In [4...
3
2016-09-13T18:14:49Z
[ "python", "arrays", "performance", "numpy" ]
Find all occurences of a specified match of two numbers in numpy array
39,476,430
<p>what i need to achieve is to get array of all indexes, where in my data array filled with zeros and ones is step from zero to one. I need very quick solution, because i have to work with milions of arrays of hundrets milions length. It will be running in computing centre. For instance..</p> <pre><code>data_array = ...
2
2016-09-13T18:07:40Z
39,476,555
<p>Here's the procedure:</p> <ol> <li>Compute the diff of the array</li> <li>Find the index where the diff == 1</li> <li>Add 1 to the results (b/c <code>len(diff) = len(orig) - 1</code>)</li> </ol> <p>So try this:</p> <pre><code>index = numpy.nonzero((data_array[1:] - data_array[:-1]) == 1)[0] + 1 index # [3, 9, 13]...
1
2016-09-13T18:15:55Z
[ "python", "arrays", "performance", "numpy" ]
Find all occurences of a specified match of two numbers in numpy array
39,476,430
<p>what i need to achieve is to get array of all indexes, where in my data array filled with zeros and ones is step from zero to one. I need very quick solution, because i have to work with milions of arrays of hundrets milions length. It will be running in computing centre. For instance..</p> <pre><code>data_array = ...
2
2016-09-13T18:07:40Z
39,478,145
<p>Well thanks a lot to all of you. Solution with nonzero is probably better for me, because I need to know steps from 0->1 and also 1->0 and finally calculate differences. So this is my solution. Any other advice appreciated .)</p> <pre><code>i_in = np.nonzero( (data_array[1:] - data_array[:-1]) == 1 )[0] +1 i_o...
0
2016-09-13T20:03:10Z
[ "python", "arrays", "performance", "numpy" ]
Find all occurences of a specified match of two numbers in numpy array
39,476,430
<p>what i need to achieve is to get array of all indexes, where in my data array filled with zeros and ones is step from zero to one. I need very quick solution, because i have to work with milions of arrays of hundrets milions length. It will be running in computing centre. For instance..</p> <pre><code>data_array = ...
2
2016-09-13T18:07:40Z
39,479,474
<p>Since it's an array filled with <code>0s</code> and <code>1s</code>, you can benefit from just comparing rather than performing arithmetic operation between the one-shifted versions to directly give us the boolean array, which could be fed to <code>np.flatnonzero</code> to get us the indices and the final output. </...
0
2016-09-13T21:45:05Z
[ "python", "arrays", "performance", "numpy" ]
Add context to every Django Admin page
39,476,439
<p>How do I add extra context to all admin webpages?</p> <p>I use default Django Admin for my admin part of a site.</p> <p>Here is an url entry for admin:</p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), ] </code></pre> <p>And my apps register their standard view models using:</p> <pre><code>ad...
1
2016-09-13T18:08:17Z
39,476,707
<p>Found the solution, url registration has to be:</p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls, {'extra_context': {'mycontext': '123'}}), ] </code></pre> <p>Its a context dictionary inside of a dictionary with <code>'extra_context'</code> as a key.</p>
1
2016-09-13T18:25:14Z
[ "python", "django", "django-admin", "django-views" ]
Authorization error when parsing data from router
39,476,591
<p>I want to scrap the data from my router for some home automation, but im facing some trouble I cannot solve/crack.</p> <p>I have managed to successfully login into the router, but when accessing the data with python script (opening links in router web interface) I recieve an error saying: You have no authority to a...
3
2016-09-13T18:18:29Z
39,477,096
<p>I have solved the issue by adding this:</p> <pre><code>br.addheaders.append( ('Referer', "http://192.168.1.1/userRpm/LoginRpm.htm?Save=Save") ) </code></pre> <p>Reason:</p> <p>Searching the message on web I navigated to a forum where users with firefox version (old) complained about the same warning. The fix ...
1
2016-09-13T18:52:45Z
[ "python", "mechanize", "router" ]
print jsonfile key that it's value is selected by input
39,476,609
<p>I have following codes and problems , Any idea would help. Thanks...</p> <p><strong>Nouns.json :</strong></p> <pre><code>{ "hello":["hi","hello"], "beautiful":["pretty","lovely","handsome","attractive","gorgeous","beautiful"], "brave":["fearless","daring","valiant","valorous","brave"], "big":["huge","large","big"]...
1
2016-09-13T18:19:13Z
39,476,888
<p>This looks massively over-complicated. Why not do something like:</p> <pre><code>import json def allnouns(xinput): nouns = json.load(open('Nouns.json')) for key, synonyms in nouns.items(): if xinput in synonyms: print(key) return; xinput = input(' input : ') allnouns(xinput...
2
2016-09-13T18:36:53Z
[ "python", "json", "python-3.x" ]
Remove first characters from a list
39,476,617
<p>I'm working on a program to have a user input what they want for dinner and then output a shopping list. Currently user can enter which meals they want and it will print out the list sorted in order from produce, meat, and other. </p> <p>I want the program to output the material without the category number in front...
-2
2016-09-13T18:20:12Z
39,476,758
<p>Your code has some other issues, but you can use (for example) <code>strog[0][2:]</code> to get one item in strog or the entire list by doing <code>new_strog = [x[2:] for x in strog]</code> to parse out the category number and space.</p>
0
2016-09-13T18:28:44Z
[ "python" ]
Remove first characters from a list
39,476,617
<p>I'm working on a program to have a user input what they want for dinner and then output a shopping list. Currently user can enter which meals they want and it will print out the list sorted in order from produce, meat, and other. </p> <p>I want the program to output the material without the category number in front...
-2
2016-09-13T18:20:12Z
39,476,768
<p>Seems like you just need to learn normal python <a href="https://developers.google.com/edu/python/strings" rel="nofollow">string manipulation</a> and list&lt;->string conversion (<code>split</code> and <code>join</code>).</p> <p>Try something like this:</p> <pre><code>strog = ["3 egg noddles", "3 beef broth", "2 s...
0
2016-09-13T18:29:15Z
[ "python" ]
Http requests freezes after severel requests
39,476,633
<p>Okay, here is my code:</p> <pre><code>from lxml import html from lxml import etree from selenium import webdriver import calendar import math import urllib import progressbar import requests </code></pre> <p><em>Using selenium</em></p> <pre><code>path_to_driver = '/home/vladislav/Shit/geckodriver' browser = webdr...
0
2016-09-13T18:21:16Z
39,478,718
<p>Okay, the problem was in an advertising banner, which appeared after several requests. Solution is just to wait (<code>time.sleep</code>), untill the banner disapeares, and the send request again!:</p> <pre><code> try: browser.get(url) try: news_list = browser.fi...
0
2016-09-13T20:46:00Z
[ "python", "html", "selenium" ]
Is it possible for django-rest-framework view to be called without a request object?
39,476,672
<p>I've inherited a Django code base using Django REST Framework that has many views that check for the existence of a <code>request</code> argument at the top, like this:</p> <pre><code>class ExampleViewSet(viewsets.GenericViewSet): def create(self, request): if not request: return Response(st...
0
2016-09-13T18:23:08Z
39,477,032
<p>They are required. This is how <a href="https://docs.djangoproject.com/en/1.10/topics/http/urls/#how-django-processes-a-request" rel="nofollow">Django processes the urls</a>. You'll likely have an issue if you remove it as other part of the code expects this argument.</p>
0
2016-09-13T18:47:51Z
[ "python", "django", "django-rest-framework" ]
Is it possible for django-rest-framework view to be called without a request object?
39,476,672
<p>I've inherited a Django code base using Django REST Framework that has many views that check for the existence of a <code>request</code> argument at the top, like this:</p> <pre><code>class ExampleViewSet(viewsets.GenericViewSet): def create(self, request): if not request: return Response(st...
0
2016-09-13T18:23:08Z
39,477,362
<p>That particular if statement is indeed probably useless; you are right that the method can never be called without a request. The only exception would be if some other methods called this method directly, passing an empty or falsey value for the request parameter, but that does seem unlikely.</p>
1
2016-09-13T19:11:32Z
[ "python", "django", "django-rest-framework" ]
Python returns nothing after recursive call
39,476,732
<p>I am working on a python script that calculates an individual's tax based on their income.</p> <p>The system of taxation requires that people are taxed based on how rich they are or how much they earn.</p> <p>The first <strong>1000</strong> is not taxed,<br> The next <strong>9000</strong> is taxed 10% The next <s...
-3
2016-09-13T18:26:50Z
39,476,752
<p>It's returning nothing because you're not <code>return</code>ing.</p> <p><code>return get_tax(income, current_level, total_tax)</code>.</p> <p>Now that it's returning something, you need to do something with the returned value. </p>
3
2016-09-13T18:28:27Z
[ "python", "recursion", "return-value" ]
Python compiled file generated even though wrong syntax
39,476,828
<p>I wrote a small program 'test1.py'</p> <pre><code>print abc print 'the above is invalid' </code></pre> <p>Now i write a different python program 'test2.py'</p> <pre><code>import test1 print 'this line will not get executed' </code></pre> <p>Q1:To my surprise,i can see test1.pyc file is successfully generated. Wh...
3
2016-09-13T18:32:14Z
39,477,760
<p><h2>Q1:</h2> Neither file contains any syntax errors. The module test1 can therefore successfully be compiled into instructions the interpreter can read. The *compiling however has no code introspection that can determine ahead of time whether a variable is defined at any given point or not. </p> <p>*I like to thin...
1
2016-09-13T19:37:47Z
[ "python", "python-2.7", "compilation" ]
Return from canvas.get_group() call in kivy
39,476,837
<p>Calling <code>get_group()</code> from an instruction group yields back more that what I wanted.</p> <p>I have the following code:</p> <pre><code>for widget in self.selected: dx, dy = ( widget.pos[0] - self.pos[0], widget.pos[1] - self.pos[1] ) self.shadows.add(Rectangle(size=widget.size...
0
2016-09-13T18:32:38Z
39,480,009
<p>Maybe you've already noticed that with <code>Rectangle</code> you can set a background image of a Widget. That's what <a href="https://kivy.org/docs/api-kivy.graphics.html#kivy.graphics.BindTexture" rel="nofollow"><code>BindTexture</code></a> is for as it provides <code>source</code> parameter for a path to an image...
0
2016-09-13T22:37:24Z
[ "python", "kivy", "kivy-language" ]
Python: Create a user and send email with account details to the user
39,476,840
<p>Here is a script I have written which will create a new user account. I am trying to get help in adding a bit more to it. </p> <p>I want to have it also send an email to the new user that is created. Ideally, the program will ask the user creating the new account, what their email is, and then it will use the user ...
0
2016-09-13T18:32:41Z
39,476,938
<p>You can easily send mails with gmail and smtplib (you maybe need to install it first). This way you can send any message you want. </p> <pre><code>import smtplib toaddrs = raw_input('what is your e mail?') fromaddr = '[email protected]' msg = 'the message you want to send' server.starttls() server.login(fromadd...
1
2016-09-13T18:40:22Z
[ "python", "linux", "email" ]
Use Flask current_app.logger inside threading
39,476,889
<p>I am using <code>current_app.logger</code> and when I tried to log inside thread it says "working outside of application context". How do I log a message from a method running in a thread?</p> <pre><code>def background(): current_app.logger.debug('logged from thread') @app.route('/') def index(): Thread(ta...
3
2016-09-13T18:36:54Z
39,477,756
<p>You use the standard <code>logging</code> module in the standard way: get the logger for the current module and log a message with it.</p> <pre><code>def background(): logging.getLogger(__name__).debug('logged from thread') </code></pre> <hr> <p><code>app.logger</code> is mostly meant for internal Flask loggi...
4
2016-09-13T19:37:34Z
[ "python", "multithreading", "logging", "flask" ]
Variable as statement in python?
39,476,937
<p>I was reading some python code and come across this. Since I mostly write C and Java (And variable as statement doesn't even compile in these language) I'm not sure what it is about in python.</p> <p>What does <code>self.current</code>, the "variable as statement", means here? Is it just some way to print the varia...
3
2016-09-13T18:40:22Z
39,477,040
<p>It really doesn't do anything, the only way it can do anything in particular, as @Daniel said in the comments, is if <code>self.current</code> refers to a <a href="https://docs.python.org/2/library/functions.html#property" rel="nofollow">property method</a>. Something like the following:</p> <pre><code>class X(): ...
3
2016-09-13T18:48:26Z
[ "python" ]
Variable as statement in python?
39,476,937
<p>I was reading some python code and come across this. Since I mostly write C and Java (And variable as statement doesn't even compile in these language) I'm not sure what it is about in python.</p> <p>What does <code>self.current</code>, the "variable as statement", means here? Is it just some way to print the varia...
3
2016-09-13T18:40:22Z
39,904,090
<p>I realized that this can be used for checking whether the attribute/method actually exist in the passed parameter. May be useful for input sanity check.</p> <pre><code>def test(value): try: value.testAttr except AttributeError: print "No testAttr attribute found" </code></pre>
0
2016-10-06T19:22:25Z
[ "python" ]
python subprocess.Popen hanging
39,477,003
<pre><code> child = subprocess.Popen(command, shell=True, env=environment, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, ...
1
2016-09-13T18:45:29Z
39,477,247
<p>You're likely hitting the deadlock that's <a href="https://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait" rel="nofollow">explained in the documentation</a>:</p> <blockquote> <p><code>Popen.wait()</code>:</p> <p>Wait for child process to terminate. Set and return <code>returncode</code> attr...
2
2016-09-13T19:03:25Z
[ "python", "subprocess" ]
Error "mach-o, but wrong architecture" after installing anaconda on mac
39,477,023
<p>I am getting an architecture error while importing any package, i understand my Python might not be compatible, can't understand it. Current Python Version - 2.7.10</p> <blockquote> <p>`MyMachine:desktop *********$ python pythonmath.py Traceback (most recent call last): File "pythonmath.py", line 1, in ...
0
2016-09-13T18:47:15Z
39,477,667
<p>you are mixing 32bit and 64bit versions of python. probably you installed 64bit python version on a 32bit computer. go on and uninstall python and reinstall it with the right configuration.</p>
0
2016-09-13T19:31:55Z
[ "python", "osx", "python-2.7" ]
Convert GroupBy Object to Ordered List in Pyspark
39,477,027
<p>I'm using Spark 2.0.0 and dataframe. Here is my input dataframe as</p> <pre><code>| id | year | qty | |----|-------------|--------| | a | 2012 | 10 | | b | 2012 | 12 | | c | 2013 | 5 | | b | 2014 | 7 | | c | 2012 | 3 | </code></pre> <p>What I...
0
2016-09-13T18:47:24Z
39,477,680
<p>The first one can be easily achieved using <code>pivot</code>:</p> <pre><code>from itertools import chain years = sorted(chain(*df.select("year").distinct().collect())) df.groupBy("id").pivot("year", years).sum("qty") </code></pre> <p>which can be further converted to array form:</p> <pre><code>from pyspark.sql....
2
2016-09-13T19:32:35Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql", "spark-dataframe" ]
Python - Searching .csv file with rows from a different .csv file
39,477,061
<p>All -</p> <p>I am attempting to read a single row from a csv file and then have it search another csv file.</p> <p>I have a masterlist.csv that has a single column called empID. It contains thousands of rows of 9 digit numbers. As well I have ids.csv that also contains a single column called number. It contains ...
3
2016-09-13T18:50:17Z
39,477,319
<p>You could easily find the numbers that are common to both by using the <em>intersection of sets</em> and the <code>csv.DictReader</code> as your reader object (not sure if the file actually contains a single column):</p> <pre><code>with open("masterlist.csv") as f1, open("ids.csv") as f2: masterReader = csv.Dic...
0
2016-09-13T19:09:05Z
[ "python", "csv" ]
Python - Searching .csv file with rows from a different .csv file
39,477,061
<p>All -</p> <p>I am attempting to read a single row from a csv file and then have it search another csv file.</p> <p>I have a masterlist.csv that has a single column called empID. It contains thousands of rows of 9 digit numbers. As well I have ids.csv that also contains a single column called number. It contains ...
3
2016-09-13T18:50:17Z
39,477,387
<p><strong>Content of master.csv</strong></p> <pre><code>EmpId 111111111 222222222 333333333 444444444 </code></pre> <p><strong>Content of ids.csv:</strong></p> <pre><code>Number 111111111 999999999 444444444 555555555 222222222 </code></pre> <p><strong>Code:</strong></p> <pre><code>import csv f1 = file('master.c...
1
2016-09-13T19:12:47Z
[ "python", "csv" ]
PyQt - trouble with reimplementing data method of QSqlTableModel
39,477,070
<p>I'm a newbie with python and mainly with pyqt. The problem is simple: I have a <code>QTableView</code> and I want to "simply" change the color of some rows. Reading all around I found that the simplest solution should be to override the data method in the model in such a way:</p> <pre><code>class MyModel(QtSql.QSql...
0
2016-09-13T18:50:51Z
39,477,501
<p>Your implementation is broken in a couple of ways: (1) it always returns <code>None</code> for any unspecified roles, (2) it creates a new instance of <code>QSqlTableModel</code> every time the display role is requested, instead of calling the base-class method.</p> <p>The implementation should probably be somethin...
0
2016-09-13T19:20:29Z
[ "python", "pyqt", "override", "qsqltablemodel" ]
Python Calculate log(1+x)/x for x near 0
39,477,176
<p>Is there a way to correctly calculate the value of log(1+x)/x in python for values of x close to 0? When I do it normally using np.log1p(x)/x, I get 1. I somehow seem to get the correct values when I use np.log(x). Isn't log1p supposed to be more stable?</p>
1
2016-09-13T18:58:14Z
39,477,218
<pre><code>np.log1p(1+x) </code></pre> <p>That gives you <code>log(2+x)</code>. Change it to <code>np.log1p(x)</code>. </p>
1
2016-09-13T19:01:38Z
[ "python", "numerical-stability" ]
Python Calculate log(1+x)/x for x near 0
39,477,176
<p>Is there a way to correctly calculate the value of log(1+x)/x in python for values of x close to 0? When I do it normally using np.log1p(x)/x, I get 1. I somehow seem to get the correct values when I use np.log(x). Isn't log1p supposed to be more stable?</p>
1
2016-09-13T18:58:14Z
39,885,108
<p>So I found one answer to this. I used a library called decimal.</p> <pre><code>from decimal import Decimal x = Decimal('1e-13') xp1 = Decimal(1) + x print(xp1.ln()/x) </code></pre> <p>This library seems to be much more stable than numpy.</p>
0
2016-10-05T23:15:18Z
[ "python", "numerical-stability" ]
Python using Pyodbc connecting to Sql 2012 calling up a stored procedure
39,477,214
<p>I have a stored procedure that works 100% when run from the Sql server. It updates at least 5 different tables. When I run it from Python it only updates the first two tables. Does not complete on the remaining tables. The parameters passed are exactly the same as run from the sql server directly. The data is r...
-1
2016-09-13T19:01:08Z
39,479,209
<p>I found it by stepping through piece by piece of what it was doing. Having a "Print Statement" in the stored procedure ends the execution of the stored procedure at that step. Make sure you don't use print statements in stored procedures if you are using Python 3.5 with Pyodbc with MSSql 2012 on a Winderz platform...
0
2016-09-13T21:23:57Z
[ "python", "sql-server-2012", "pyodbc" ]
How to disable log file for py2exe?
39,477,242
<p>I've created a small script using <code>Python</code> and <code>PyQt4</code>, I converted it to <code>exe</code>. But there's some cases in my script that I'm not handling so a <code>log</code> file being created while using the program. So I wanna disable creating this <code>log</code> file.</p> <p>How can I do th...
0
2016-09-13T19:03:14Z
39,478,211
<p>I finally found how to do that.</p> <p>I went to <code>C:\Python27\Lib\site-packages\py2exe</code> and then opened <code>boot_common.py</code> file and commented the 56, 57, 58, 59, 60, 63, 64,65 lines and saved it.</p> <p>I run py2exe again and tried the program works great. It makes a log file but doesn't run it...
0
2016-09-13T20:08:33Z
[ "python", "python-2.7", "pyqt4", "py2exe" ]
Python Mysql class to call a stored procedure
39,477,316
<p>I am very new. All of my experience is on the DB side so I am lost on the Python side of things. That said I am trying to create a class that I can use to execute stored procedures. I am using Python 3.4.3. I found a mysql class on github and simplified/modified it to make a proc call and it is not working. </p...
0
2016-09-13T19:08:46Z
39,477,423
<p><code>mysql.connector.connect()</code> takes named arguments, not positional arguments, and you're missing the names.</p> <pre><code>cnx = mysql.connector.connect(host=self.__host, user=self.__user, password=self.__password, database=self.__database) </code></pre>
1
2016-09-13T19:15:04Z
[ "python", "mysql", "stored-procedures", "typeerror" ]
Conditionally extracting Pandas rows based on another Pandas dataframe
39,477,328
<p>I have two dataframes:</p> <p><code>df1:</code></p> <pre><code>col1 col2 1 2 1 3 2 4 </code></pre> <p><code>df2:</code></p> <pre><code>col1 2 3 </code></pre> <p>I want to extract all the rows in <code>df1</code> where <code>df1</code>'s <code>col2</code> <code>not in</code> <code>df2</code>...
1
2016-09-13T19:09:22Z
39,477,357
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a> with <code>~</code> for inverting boolean mask:</p> <pre><code>print (df1['col2'].isin(df2['col1'])) 0 True 1 True 2 False Name: col2, dtype: bool print (~df1['col2']....
1
2016-09-13T19:11:09Z
[ "python", "pandas", "indexing", "dataframe", "condition" ]
Conditionally extracting Pandas rows based on another Pandas dataframe
39,477,328
<p>I have two dataframes:</p> <p><code>df1:</code></p> <pre><code>col1 col2 1 2 1 3 2 4 </code></pre> <p><code>df2:</code></p> <pre><code>col1 2 3 </code></pre> <p>I want to extract all the rows in <code>df1</code> where <code>df1</code>'s <code>col2</code> <code>not in</code> <code>df2</code>...
1
2016-09-13T19:09:22Z
39,477,421
<p>using <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-query-method-experimental" rel="nofollow">.query()</a> method:</p> <pre><code>In [9]: df1.query('col2 not in @df2.col1') Out[9]: col1 col2 2 2 4 </code></pre> <p>Timing for bigger DFs:</p> <pre><code>In [44]: df1.shape Out[44...
1
2016-09-13T19:14:59Z
[ "python", "pandas", "indexing", "dataframe", "condition" ]
Finding the average of two consecutive rows in pandas
39,477,393
<p>I am trying to find the average of two consecutive rows in each column</p> <pre><code>In[207]: df = DataFrame({"A": [9, 4, 2, 1, 4], "B": [12, 7, 5, 4,8]}) In[208]: df Out[207]: A B 0 9 12 1 4 7 2 2 5 3 1 4 4 4 8 </code></pre> <p>The result should be: </p> <pre><code>Out[207]: A B 0 6.5...
2
2016-09-13T19:13:09Z
39,477,558
<p>try this:</p> <pre><code>In [29]: idx = len(df) - 1 if len(df) % 2 else len(df) In [30]: df[:idx].groupby(df.index[:idx] // 2).mean() Out[30]: A B 0 6.5 9.5 1 1.5 4.5 </code></pre>
4
2016-09-13T19:24:08Z
[ "python", "pandas", "dataframe" ]
Python 3 regex word boundary unclear
39,477,394
<p>I am using a regex to find the string 'my car' and detect up to four words before it. My reference text is:</p> <pre><code>my house is painted white, my car is red. A horse is galloping very fast in the road, I drive my car slowly. </code></pre> <p>if I use the regex:</p> <pre><code>re.finditer(r'(?:\w+[ \t,]+){0...
3
2016-09-13T19:13:10Z
39,477,472
<p>Because <code>\b</code> is a <em>zero-width assertion</em> <a href="http://www.regular-expressions.info/wordboundaries.html" rel="nofollow"><strong>word boundary</strong></a> matching a <em>location</em> between the start of string and a word char, between a non-word char and a word char, between a word char and a n...
1
2016-09-13T19:18:01Z
[ "python", "regex", "python-3.x" ]
Python 3 regex word boundary unclear
39,477,394
<p>I am using a regex to find the string 'my car' and detect up to four words before it. My reference text is:</p> <pre><code>my house is painted white, my car is red. A horse is galloping very fast in the road, I drive my car slowly. </code></pre> <p>if I use the regex:</p> <pre><code>re.finditer(r'(?:\w+[ \t,]+){0...
3
2016-09-13T19:13:10Z
39,477,490
<p>You could use:</p> <pre><code>(?:\b\w+\W+){4} \b(?:my\ car)\b </code></pre> <p>See <a href="https://regex101.com/r/iB6xL0/3" rel="nofollow"><strong>a demo on regex101.com</strong></a>.<hr> In <code>Python</code> this will be:</p> <pre><code>import re rx = re.compile(r''' (?:\b\w+\W+){0,4} ...
2
2016-09-13T19:19:30Z
[ "python", "regex", "python-3.x" ]
How to Access Pandas dataframe columns when the number of columns are unknown before hand
39,477,397
<p>I am new to python and data science altogether. I am writing a program to read and analyze a csv with pandas. The problem is that the csv will be supplied by the user and it can have variable number of columns depending on the user. I do not have a prior knowledge of the column names. I went about the problem by ...
1
2016-09-13T19:13:25Z
39,477,470
<p>Better is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow"><code>iloc</code></a>:</p> <pre><code>df.iloc[:, 0] </code></pre> <p>output is same as:</p> <pre><code>coln = df.columns print (df.ix[:, coln[0]]) </code></pre>
2
2016-09-13T19:17:52Z
[ "python", "pandas", "data-science" ]
How to Access Pandas dataframe columns when the number of columns are unknown before hand
39,477,397
<p>I am new to python and data science altogether. I am writing a program to read and analyze a csv with pandas. The problem is that the csv will be supplied by the user and it can have variable number of columns depending on the user. I do not have a prior knowledge of the column names. I went about the problem by ...
1
2016-09-13T19:13:25Z
39,477,528
<p>You can use <code>iloc</code></p> <pre><code>df.iloc[:,0] </code></pre> <p>Btw, <code>df.coln</code> does not exist you created <code>coln</code> as separate variable. </p>
0
2016-09-13T19:22:05Z
[ "python", "pandas", "data-science" ]
How to Access Pandas dataframe columns when the number of columns are unknown before hand
39,477,397
<p>I am new to python and data science altogether. I am writing a program to read and analyze a csv with pandas. The problem is that the csv will be supplied by the user and it can have variable number of columns depending on the user. I do not have a prior knowledge of the column names. I went about the problem by ...
1
2016-09-13T19:13:25Z
39,477,625
<p>You should be using iloc and not the method I corrected below as the other answers show, but to fix your original error:</p> <pre><code>coln = df.columns df.ix[:, coln[0]] # to access the first column of the dataframe. </code></pre> <p>You wrote df.coln[0] instead of coln[0]. coln is a list, there is no such thin...
0
2016-09-13T19:28:59Z
[ "python", "pandas", "data-science" ]
Unable to run psql commands on remote server from local python script
39,477,545
<p>I'm writing a script that is called locally to run psql queries on a remote server. I'm writing the script in Python 2.7 using the subprocess module. I'm using subprocess.Popen to ssh into the remote server and directly run a psql command. My local machine is osx and I think the server is CentOS.</p> <p>When I call...
0
2016-09-13T19:23:20Z
39,478,596
<p>When you run ssh for an interactive session on a remote system, ssh requests a PTY (pseudo TTY) for the remote system. When you run ssh to run a command on a remote system, ssh doesn't allocate a PTY by default.</p> <p>Having a TTY/PTY changes the way your shell initializes itself. Your actual problem is you need t...
1
2016-09-13T20:37:32Z
[ "python", "python-2.7", "ssh", "subprocess", "psql" ]
Pandas: what is the data-type of object passed to the agg function
39,477,618
<p>I have been curious about what exactly is passed to the agg function </p> <pre><code>Id NAME SUB_ID 276956 A 5933 276956 B 5934 276956 C 5935 287266 D 1589 </code></pre> <p>So when I call an agg function, what exactly is the datatype of x.</p> <pre><code>df.groupby('Id').agg(lambda ...
1
2016-09-13T19:28:25Z
39,477,645
<p>You working with <code>Series</code>:</p> <pre><code>print (df.groupby('Id').agg(lambda x: print(x))) 0 A 1 B 2 C Name: NAME, dtype: object 3 D Name: NAME, dtype: object 0 5933 1 5934 2 5935 Name: SUB_ID, dtype: int64 3 1589 Name: SUB_ID, dtype: int64 </code></pre> <p>You can working with c...
4
2016-09-13T19:30:30Z
[ "python", "pandas", "numpy" ]
Pandas: what is the data-type of object passed to the agg function
39,477,618
<p>I have been curious about what exactly is passed to the agg function </p> <pre><code>Id NAME SUB_ID 276956 A 5933 276956 B 5934 276956 C 5935 287266 D 1589 </code></pre> <p>So when I call an agg function, what exactly is the datatype of x.</p> <pre><code>df.groupby('Id').agg(lambda ...
1
2016-09-13T19:28:25Z
39,477,776
<pre><code>&gt;&gt;&gt; df[['Id', 'NAME']].groupby('Id').agg(lambda x: ', '.join(x)) NAME Id 276956 A, B, C 287266 D </code></pre> <p>The <code>x</code> in this case will be the series for each relevant grouping on <code>Id</code>.</p> <p>To actually get a list of values:</p> <pre><co...
3
2016-09-13T19:38:43Z
[ "python", "pandas", "numpy" ]
Pop from empty list error ONLY on lists with even number of elements
39,477,629
<p>So this is just an exercise I'm doing for fun on codewars.com. The point is to take a string and pull it apart by taking the last character and adding it to a string, taking the first character and adding it to another string until you have either 1 (for a string with an odd number of letters) or 0 (for a string wit...
1
2016-09-13T19:29:25Z
39,477,685
<p>Your loop is checking to see if the length of the list isn't 1; for an even length list, since you always pop 2 items at a time, it will never see a length of 1.</p>
0
2016-09-13T19:33:02Z
[ "python", "list", "pop" ]
Pop from empty list error ONLY on lists with even number of elements
39,477,629
<p>So this is just an exercise I'm doing for fun on codewars.com. The point is to take a string and pull it apart by taking the last character and adding it to a string, taking the first character and adding it to another string until you have either 1 (for a string with an odd number of letters) or 0 (for a string wit...
1
2016-09-13T19:29:25Z
39,478,086
<p>Instead of <code>while len(testList) != 1</code>, you need: <code>while len(testList) &gt; 1</code>, since <code>len(testList)</code> will jump from <code>2</code> to <code>0</code> on "even" strings:</p> <pre><code>def pop_shift(test): firstSol = [] secondSol = [] testList = list(test) while len(te...
0
2016-09-13T19:59:15Z
[ "python", "list", "pop" ]
Scrapy csv file has uniform empty rows?
39,477,662
<p>here is the spider:</p> <pre><code>import scrapy from danmurphys.items import DanmurphysItem class MySpider(scrapy.Spider): name = 'danmurphys' allowed_domains = ['danmurphys.com.au'] start_urls = ['https://www.danmurphys.com.au/dm/navigation/navigation_results_gallery.jsp?params=fh_location%3D%2F%2Fca...
0
2016-09-13T19:31:28Z
39,477,789
<p>This output shows the typical symptom of csv file handle opened using <code>"w"</code> mode on windows (to fix Python 3 compatibility maybe) but omitting <code>newline</code>.</p> <p>While this has no effect on Linux/Unix based systems, on Windows, 2 carriage return chars are issued, inserting a fake blank line aft...
1
2016-09-13T19:39:29Z
[ "python", "scrapy" ]
Scrapy csv file has uniform empty rows?
39,477,662
<p>here is the spider:</p> <pre><code>import scrapy from danmurphys.items import DanmurphysItem class MySpider(scrapy.Spider): name = 'danmurphys' allowed_domains = ['danmurphys.com.au'] start_urls = ['https://www.danmurphys.com.au/dm/navigation/navigation_results_gallery.jsp?params=fh_location%3D%2F%2Fca...
0
2016-09-13T19:31:28Z
39,489,264
<p>Thanks everybody especially (Jean-François)</p> <p>the problem was that I've installed another scrapy version 1.1.0 installed from conda for python 3.5 once I added python 2.7 in system path ,the original scrapy 1.1.2 returned to work as default . and everything works just fine .</p>
0
2016-09-14T11:26:16Z
[ "python", "scrapy" ]
How do i mount a usb device or a hard drive partition using python
39,477,682
<p>I have been trying to write a program that would mount a device in a specified location, everything will be done by the user inputs.</p> <p>I have used <strong>ctypes</strong>. The place where I'm stuck is at this part </p> <pre><code> def mount(source, target, fs, options=''): ret = ctypes.CDLL('libc.so.6', us...
-2
2016-09-13T19:32:42Z
39,477,913
<p>I would just use the command line mount. </p> <pre><code>import os os.system("mount /dev/sd(x) /mountpoint") </code></pre>
0
2016-09-13T19:47:43Z
[ "python", "linux", "python-2.7", "ctypes", "mount" ]
AWS Lambda read contents of file in zip uploaded as source code
39,477,729
<p>I have two files:</p> <pre><code>MyLambdaFunction.py config.json </code></pre> <p>I zip those two together to create <em>MyLambdaFunction.zip</em>. I then upload that through the AWS console to my lambda function. </p> <p>The contents of <em>config.json</em> are various environmental variables. I need a way t...
0
2016-09-13T19:35:58Z
39,479,685
<p>Try this. The file you uploaded can be accessed like:</p> <pre><code>import os os.environ['LAMBDA_TASK_ROOT']/config.json </code></pre>
2
2016-09-13T22:04:38Z
[ "python", "amazon-web-services", "aws-lambda", "amazon-lambda" ]
AWS Lambda read contents of file in zip uploaded as source code
39,477,729
<p>I have two files:</p> <pre><code>MyLambdaFunction.py config.json </code></pre> <p>I zip those two together to create <em>MyLambdaFunction.zip</em>. I then upload that through the AWS console to my lambda function. </p> <p>The contents of <em>config.json</em> are various environmental variables. I need a way t...
0
2016-09-13T19:35:58Z
39,550,486
<p>Figured it out with the push in the right direction from @helloV.</p> <p>At the top of the python file put "import os"</p> <p>Inside your function handler put the following:</p> <pre><code>configPath = os.environ['LAMBDA_TASK_ROOT'] + "/config.json" print("Looking for config.json at " + configPath) configContents...
0
2016-09-17T18:45:55Z
[ "python", "amazon-web-services", "aws-lambda", "amazon-lambda" ]
running python script with an ECS task
39,477,751
<p>I have an ECS task setup which, when with a Command override <strong>ls</strong>, produces expected results with my CloudWatch log stream: <strong>test.py</strong>. my script <strong>test.py</strong> takes one parameter. I am wondering how I can execute this script with python3 (which exists in my container) using...
0
2016-09-13T19:37:09Z
39,478,393
<p>Here's how I did something similar:</p> <p>In your docker build file, make the command you want to run as the last instruction. In your case:</p> <pre><code>CMD python3 test.py hello </code></pre> <p>To make it more extensible, use environment variables. For instance, do something like:</p> <pre><code>CMD ["pyth...
1
2016-09-13T20:21:08Z
[ "python", "amazon-ecs" ]
How to rename the date stamp portion of a csv file in python
39,477,778
<p>I have created a script which should remove the date stamp portion from a file. For example, rename the file from existing name_2016-09-13.csv to name.csv. The problem is that the filename changes everyday. So, I need to rename and overwrite the existing file when it gets renamed the next day.</p> <pre><code>import...
0
2016-09-13T19:38:43Z
39,478,526
<p>If your question is how to grab the 'name' portion of the filename, here is a capturing regular expression that does the trick: <code>r'(\S+)_\d\d\d\d-\d\d-\d\d\.csv'</code>. Since you <code>import re</code> but then never use it, I imagine someone told you that you can accomplish your task using regular expressions...
0
2016-09-13T20:32:32Z
[ "python", "csv" ]
Python 3 Requests or urllib - how to always add a header?
39,477,838
<p>Title says it all: is there a 'best' way to always add a header to every request? I've got an internal tool that wants to send request ids to other internal tools; I'm looking for a blessed solution. I've skimmed the docs of both and it seems that this isn't a popular thing to ask for as I can't find a cookbook exam...
0
2016-09-13T19:43:10Z
39,477,977
<p>Create a <a href="http://docs.python-requests.org/en/master/user/advanced/#session-objects" rel="nofollow">session object</a>, which is the 1st thing shown under <a href="http://docs.python-requests.org/en/master/user/advanced/" rel="nofollow">advanced usage</a>:</p> <pre><code>s = requests.Session() s.headers.upda...
2
2016-09-13T19:52:12Z
[ "python", "python-requests", "urllib" ]
MySQL On Update not triggering for Django/TastyPie REST API
39,477,897
<p>We have a resource table which has a field <code>last_updated</code> which we setup with mysql-workbench to have the following properties:</p> <p>Datatype: <code>TIMESTAMP</code></p> <p>NN (NotNull) is <code>checked</code></p> <p>Default: <code>CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP</code></p> <p>When I m...
0
2016-09-13T19:46:26Z
39,478,144
<p>I suspect that the UPDATE statement issued by Django may be including an assignment to the <code>last_updated</code> column. This is just a guess, there's not enough information provided.</p> <p>But if the Django model contains the <code>last_updated</code> column, and that column is fetched from the database into ...
1
2016-09-13T20:03:08Z
[ "python", "mysql", "django", "mysql-workbench", "tastypie" ]
MySQL On Update not triggering for Django/TastyPie REST API
39,477,897
<p>We have a resource table which has a field <code>last_updated</code> which we setup with mysql-workbench to have the following properties:</p> <p>Datatype: <code>TIMESTAMP</code></p> <p>NN (NotNull) is <code>checked</code></p> <p>Default: <code>CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP</code></p> <p>When I m...
0
2016-09-13T19:46:26Z
39,499,796
<p>With the added information from spencer7593's <a href="http://stackoverflow.com/a/39478144/3579910">answer</a>, I was able to track down how to do this through tastypie:</p> <p>The <code>BaseModelResource.save()</code> (from <code>tastypie/resources.py</code>):</p> <pre><code>def save(self, bundle, skip_errors=Fal...
0
2016-09-14T21:19:44Z
[ "python", "mysql", "django", "mysql-workbench", "tastypie" ]
Check for very specified numbers padding
39,477,931
<p>I am trying to check for a list of items in my scene to see if they bear 3 (version) paddings at the end of their name - eg. <code>test_model_001</code> and if they do, that item will be pass and items that do not pass the condition will be affected by a certain function..</p> <p>Suppose if my list of items is as f...
0
2016-09-13T19:48:53Z
39,478,021
<p>You can use the <code>{3}</code> to ask for 3 consecutive digits only and prepend underscore:</p> <pre><code>eg_list = ['test_model_01', 'test_romeo_005', 'test_charlie_rig'] for item in eg_list: match = re.search(r'_([0-9]{3})$', item) if match: print(match.group(1)) </code></pre> <p>This would pr...
3
2016-09-13T19:54:50Z
[ "python", "maya" ]
Check for very specified numbers padding
39,477,931
<p>I am trying to check for a list of items in my scene to see if they bear 3 (version) paddings at the end of their name - eg. <code>test_model_001</code> and if they do, that item will be pass and items that do not pass the condition will be affected by a certain function..</p> <p>Suppose if my list of items is as f...
0
2016-09-13T19:48:53Z
39,478,039
<pre><code>for item in eg_list: if re.match(".*_\d{3}$", item): print item.split('_')[-1] </code></pre> <p>This matches anything which ends in: <code>_</code> and underscore, <code>\d</code> a digit, <code>{3}</code> three of them, and <code>$</code> the end of the line.</p> <p><img src="https://www.debug...
1
2016-09-13T19:56:28Z
[ "python", "maya" ]
Check for very specified numbers padding
39,477,931
<p>I am trying to check for a list of items in my scene to see if they bear 3 (version) paddings at the end of their name - eg. <code>test_model_001</code> and if they do, that item will be pass and items that do not pass the condition will be affected by a certain function..</p> <p>Suppose if my list of items is as f...
0
2016-09-13T19:48:53Z
39,478,042
<p>The asterisk after the [0-9] specification means that you are expecting any random number of occurrences of the digits 0-9. Technically this expression matches test_charlie_rig as well. You can test that out here <a href="http://pythex.org/" rel="nofollow">http://pythex.org/</a></p> <p>Replacing the asterisk with ...
1
2016-09-13T19:56:44Z
[ "python", "maya" ]
Check for very specified numbers padding
39,477,931
<p>I am trying to check for a list of items in my scene to see if they bear 3 (version) paddings at the end of their name - eg. <code>test_model_001</code> and if they do, that item will be pass and items that do not pass the condition will be affected by a certain function..</p> <p>Suppose if my list of items is as f...
0
2016-09-13T19:48:53Z
39,481,623
<p>I usually don't like regex unless needed. This should work and be more readable.</p> <pre><code>def name_validator(name, padding_count=3): number = name.split("_")[-1] if number.isdigit() and number == number.zfill(padding_count): return True return False name_validator("test_model_01") # Retur...
1
2016-09-14T02:27:59Z
[ "python", "maya" ]
SyntaxError: invalid syntax - python 2.7 - Odoo v9 community
39,478,005
<p>I have this code which checks if there's a provider specified, and a pem key, in order to send over an xml to a server:</p> <pre><code> @api.multi def send_xml_file(self, envio_dte=None, file_name="envio",company_id=False): if not company_id.dte_service_provider: raise UserError(_("Not Service provider ...
0
2016-09-13T19:53:33Z
39,498,297
<p>Logger needs to be tabbed over, to be in the try block.</p> <pre><code>@api.multi def send_xml_file(self, envio_dte=None, file_name="envio",company_id=False): if not company_id.dte_service_provider: raise UserError(_("Not Service provider selected!")) try: signature_d = self.get_digital_sign...
1
2016-09-14T19:32:59Z
[ "python", "logging", "openerp", "odoo-9" ]
launch selenium from python on ubuntu
39,478,101
<p>I have the following script</p> <pre><code>from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title </code></pre> <p>I get the following error</p> <pre><code>$ python3 functional_tests.py Traceback (most recent call last): File "functi...
1
2016-09-13T20:00:05Z
39,479,712
<p>The last version of Firefox is not working properly with selenium. Try with 46 or 45. </p> <p>You can download here: ftp.mozilla.org/pub/firefox/releases</p> <p>or <code>sudo apt-get install firefox=45.0.2+build1-0ubuntu1</code></p>
0
2016-09-13T22:08:11Z
[ "python", "selenium", "ubuntu" ]
launch selenium from python on ubuntu
39,478,101
<p>I have the following script</p> <pre><code>from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title </code></pre> <p>I get the following error</p> <pre><code>$ python3 functional_tests.py Traceback (most recent call last): File "functi...
1
2016-09-13T20:00:05Z
39,536,091
<p>I struggled with this problem as well, and I was unhappy with having to use older versions of Firefox. Here's my solution that uses the latest version of Firefox. It however involves several steps</p> <p><strong>Step 1.</strong> Download v0.9.0 <em>Marionette</em>, the next generation of FirefoxDriver, from this ...
3
2016-09-16T16:21:41Z
[ "python", "selenium", "ubuntu" ]
python scikit-learn TfidfVectorizer: why ValueError when input is 2 single-character strings?
39,478,120
<p>I am trying to run something like this:</p> <pre><code>from sklearn.feature_extraction.text import TfidfVectorizer test_text = ["q", "r"] vect = TfidfVectorizer(min_df=1, stop_words=None, lowercase=False) tfidf = vect.fit_transform(test_text) print vect.get_feature...
0
2016-09-13T20:01:15Z
39,478,863
<p>The error is because of the min_df parameter. When you set the value of min_df =0, it will work fine as it will not be bounded by the 'minimum threshold' which is currently set to 1 and each of your word also appears for once only.</p>
0
2016-09-13T20:57:54Z
[ "python", "scikit-learn", "nlp", "tf-idf" ]
Calculate the number of combinations of unique positive integers with minimum and maximum differences between each other?
39,478,125
<p>How do I write a Python program to calculate the number of combinations of unique sorted positive integers over a range of integers that can be selected where the minimum difference between each of the numbers in the set is one number and the maximum difference is another number?</p> <p>For instance, if I want to c...
0
2016-09-13T20:01:32Z
39,480,253
<p>You can use a recursive function with caching to get your answer. This method will work even if you have a large array because some positions are repeated many times with the same parameters.<br> Here is a code for you (forgive me if I made any mistakes in python cause I don't normally use it). If there is any flow ...
1
2016-09-13T23:07:19Z
[ "python", "algorithm", "combinatorics", "itertools" ]
Calculate the number of combinations of unique positive integers with minimum and maximum differences between each other?
39,478,125
<p>How do I write a Python program to calculate the number of combinations of unique sorted positive integers over a range of integers that can be selected where the minimum difference between each of the numbers in the set is one number and the maximum difference is another number?</p> <p>For instance, if I want to c...
0
2016-09-13T20:01:32Z
39,480,350
<p>Here is a very simple (and non-optimized) recursive approach:</p> <h3>Code</h3> <pre><code>import numpy as np from time import time """ PARAMETERS """ SET = range(50) # Set of elements to choose from N = 6 # N elements to choose MIN_GAP = 4 # Gaps MAX_GAP = 7 # "" def count(N, CHOSEN=[]): "...
0
2016-09-13T23:20:02Z
[ "python", "algorithm", "combinatorics", "itertools" ]
Chrome webdriver cannot connect to the service chromedriver.exe on Windows
39,478,170
<p>Hello !</p> <p>I am currently using Selenium with Python on Windows 7, and I tried to use the Chrome webdriver for the hide function <code>--no-startup-window</code>. After I installed Chrome (x86), copied chromedriver.exe on path <code>C:\Python27\Scripts\</code> and added it on PATH environment, I tried to launch...
0
2016-09-13T20:04:41Z
39,478,225
<p>first , instead of using <strong>Options()</strong> method you should use <strong>webdriver.ChromeOptions()</strong> method to have the result that you want, secondly you should specify the <strong>path to the Chromedriver</strong> installed on your computer.</p> <p>for example put chormedriver.exe file on drive C:...
2
2016-09-13T20:10:01Z
[ "python", "google-chrome", "selenium", "selenium-webdriver", "webdriver" ]
Trouble running lighttpd with webpy
39,478,190
<p>This is what my lighttpd.conf file looks like:</p> <pre><code>server.modules = ( "mod_access", "mod_alias", "mod_compress", "mod_accesslog", ) server.document-root = "/home/ashley/leagueratings" server.upload-dirs = ( "/var/cache/lighttpd/uploads" ) server.errorlog = "/v...
1
2016-09-13T20:06:53Z
39,485,273
<blockquote> <p>2016-09-13 19:49:50: (mod_fastcgi.c.1112) the fastcgi-backend /home/ashley/leagueratings.py failed to start:</p> </blockquote> <p>This does not appear to be a web server issue.</p> <p>Have you tried manually starting up leagueratings.py? It is possible that a needed python module is missing (and ne...
0
2016-09-14T07:57:17Z
[ "python", "lighttpd", "web.py" ]
Python while loop closing console
39,478,204
<p>My console is closing every time I start the loop and I don't get why...</p> <pre><code>index = "" while not index: index = int(input("Enter the index that you want: ")) </code></pre>
-2
2016-09-13T20:08:02Z
39,478,311
<p>I think your issue is that your loop is executing only once and is exiting after that (<em>that's what I can think of based on your code</em>).</p> <p><strong>The reason is:</strong> at the start, your index is <code>""</code>. Hence <code>not index</code> is evaluated as <code>True</code> since python considers em...
1
2016-09-13T20:15:47Z
[ "python", "loops", "console" ]
Python while loop closing console
39,478,204
<p>My console is closing every time I start the loop and I don't get why...</p> <pre><code>index = "" while not index: index = int(input("Enter the index that you want: ")) </code></pre>
-2
2016-09-13T20:08:02Z
39,478,443
<p>a) your code seems fine.</p> <pre><code>$ python Python 2.7.10 (default, Oct 14 2015, 16:09:02) [GCC 5.2.1 20151010] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; index="" &gt;&gt;&gt; while not index: ... index=int(input("blabla: ")) ... blabla: 2 &gt;&gt;&gt; ...
0
2016-09-13T20:25:18Z
[ "python", "loops", "console" ]
nested absolute_imports python
39,478,271
<p>I am a bit confused on getting imports done properly. I have a project as follows</p> <pre><code>mainpackge/ packageone/ __init__.py file.py file2.py file3.py subpackageone/ __init__.py submodule1.py submodule2.py packagetwo/ __init__.py file.py file...
0
2016-09-13T20:13:02Z
39,479,751
<p>Figured it out. Basically, the import here:</p> <pre><code>from __future__ import absolute_import from subpackageone.submodule1 import ClassSubmodule1 </code></pre> <p>needs to be moved up to <code>packageone/__init__.py</code>. After i did that i was able to import into packagetwo no problem.</p>
0
2016-09-13T22:12:11Z
[ "python", "python-import" ]
How to convert convert csv to list of dictionaries (UTF-8)?
39,478,281
<p>I have a csv file (in.csv)</p> <pre><code>col1, col2, col3 Kapitän, Böse, Füller ... </code></pre> <p>and I want to create a list of dictionaries:</p> <pre><code>a = [{'col1': 'Kapitän', 'col2': 'Böse', 'col3': 'Füller'},{...}] </code></pre> <p>With Python 3 it's working with</p> <pre><code> import co...
0
2016-09-13T20:13:42Z
39,478,500
<p>for print use <code>print line</code> instead <code>print repr(line)</code></p> <p>and for dict i use this solution </p> <p><a href="https://docs.python.org/2/library/csv.html#csv-examples" rel="nofollow">https://docs.python.org/2/library/csv.html#csv-examples</a></p> <p>The csv module doesn’t directly support ...
0
2016-09-13T20:29:51Z
[ "python", "list", "python-2.7", "csv", "dictionary" ]
How to convert convert csv to list of dictionaries (UTF-8)?
39,478,281
<p>I have a csv file (in.csv)</p> <pre><code>col1, col2, col3 Kapitän, Böse, Füller ... </code></pre> <p>and I want to create a list of dictionaries:</p> <pre><code>a = [{'col1': 'Kapitän', 'col2': 'Böse', 'col3': 'Füller'},{...}] </code></pre> <p>With Python 3 it's working with</p> <pre><code> import co...
0
2016-09-13T20:13:42Z
39,478,754
<p>you can leverage the csv lib for the job.</p> <pre><code>import csv li_of_dicts = [] with open('in.csv', 'r') as infile: reader = csv.DictReader(infile, encoding='utf-8') for row in reader: li_of_dicts.append(row) </code></pre>
1
2016-09-13T20:48:51Z
[ "python", "list", "python-2.7", "csv", "dictionary" ]
python linear regression implementation
39,478,437
<p>I've been trying to do my own implementation of a simple linear regression algorithm, but I'm having some trouble with the gradient descent.</p> <p>Here's how I coded it:</p> <pre><code>def gradientDescentVector(data, alpha, iterations): a = 0.0 b = 0.0 X = data[:,0] y = data[:,1] m = data.shap...
2
2016-09-13T20:25:02Z
39,488,807
<p>It is clear that the parameters are diverging from the optimum ones. One possible reason may be that you are using too large a value for the learning rate ("alpha"). Try decreasing the learning rate. Here is a rule of thumb. Start always from a small value like 0.001. Then try increasing the learning rate by taking ...
1
2016-09-14T11:01:59Z
[ "python", "numpy", "machine-learning", "linear-regression" ]
Python Bigger is Greater optimization
39,478,440
<p>Thank you all. I found below function which is perfect, I mark this question closed</p> <p><a href="https://www.nayuki.io/page/next-lexicographical-permutation-algorithm" rel="nofollow">https://www.nayuki.io/page/next-lexicographical-permutation-algorithm</a></p> <pre><code>def next_permutation(arr): # Find n...
-4
2016-09-13T20:25:07Z
39,479,648
<p>Your instinct is right, so I'll try to help.</p> <p>Step1: You're iterating in reverse looking for a case where a[i] &lt; a[i+n], then you know you have a solution. Step2: Then you paste everything (the prefix, the character, and the sorted suffix junk.) </p> <p>Just make it easy on yourself: find the solution po...
1
2016-09-13T22:01:28Z
[ "python", "algorithm" ]
Jenkins user unable to run python script
39,478,448
<p>I have a boto python script that lives in /var/lib/jenkins/workspace/project/python-script.py that is being ran in the execute shell of a jenkins build. </p> <p>When I ssh into my jenkins server and execute the command python python-script.py arg1 arg2 as root or the ec2-user the python script runs exactly how I wi...
0
2016-09-13T20:25:54Z
39,479,237
<p>Ended up that I just needed to put my .boto file that contains my access and secret keys in the root of the jenkins user. Once I created the file in the root of the jenkins user it began to work.</p>
0
2016-09-13T21:26:27Z
[ "python", "python-2.7", "jenkins", "amazon-ec2", "boto" ]
Best Design Pattern to execute steps in python
39,478,460
<p>I have to execute multiple actions sequentially in an order dependant manner. </p> <pre><code>StepOne(arg1, arg2).execute() StepTwo(arg1, arg2).execute() StepThree(arg1, arg2).execute() StepFour(arg1, arg2).execute() StepFive(arg1, arg2).execute() </code></pre> <p>They all inherit from the same <code>Step</code> c...
2
2016-09-13T20:26:54Z
39,478,489
<p>You could create a list of the step classes, then instantiate and call them in a loop.</p> <pre><code>step_classes = [StepOne, StepTwo, StepThree, ...] for c in step_classes: c(arg1, arg2).execute() </code></pre>
6
2016-09-13T20:29:15Z
[ "python", "oop", "design-patterns" ]
Change django object name
39,478,510
<p>I have <code>UserDetailsSerializer</code> class as shown below. I would like to change it's object name from user to data to meet API endpoint requirements on my front-end application. I tried searching through internet but wasn't quite sure how to get such result. </p> <pre><code>class UserDetailsSerializer(serial...
0
2016-09-13T20:30:58Z
39,478,782
<p>You haven't provided the content of your view. I believe currently the response dict that your are returning is something like:</p> <pre><code>{'user': UserDetailsSerializer(your_object).data} </code></pre> <p>In this replace the key <code>user</code> with <code>data</code>.</p> <p>If that is not the case, please...
0
2016-09-13T20:51:03Z
[ "python", "django", "django-rest-framework", "django-rest-auth" ]
Nested list comprehension where inner loop range is dependent on outer loop
39,478,528
<p>I am trying to represent the following as a list comprehension:</p> <pre><code>L = [] for x in range(n): for y in range(x): L.append( (x, y) ) </code></pre> <p>I have done nested list comprehension in the more typical matrix scenario where the inner loop range is not dependent on the outer loop.</p> <...
0
2016-09-13T20:32:39Z
39,478,566
<p>Remember to wrap the <code>x, y</code> in parentheses this is the only slight caveat that if omitted leads to a <code>SyntaxError</code>. </p> <p>Other than that, the translation is pretty straightforward; the order of the <code>for</code>s inside the comprehension is similar to that with the nested statements:</p>...
3
2016-09-13T20:35:19Z
[ "python", "python-3.x", "list-comprehension", "nested-loops" ]
Nested list comprehension where inner loop range is dependent on outer loop
39,478,528
<p>I am trying to represent the following as a list comprehension:</p> <pre><code>L = [] for x in range(n): for y in range(x): L.append( (x, y) ) </code></pre> <p>I have done nested list comprehension in the more typical matrix scenario where the inner loop range is not dependent on the outer loop.</p> <...
0
2016-09-13T20:32:39Z
39,478,568
<p>Below is the example to convert your code to list comprehension.</p> <pre><code>&gt;&gt;&gt; n = 10 &gt;&gt;&gt; [ (x,y) for x in range(n) for y in range(x)] [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4...
0
2016-09-13T20:35:37Z
[ "python", "python-3.x", "list-comprehension", "nested-loops" ]
Nested list comprehension where inner loop range is dependent on outer loop
39,478,528
<p>I am trying to represent the following as a list comprehension:</p> <pre><code>L = [] for x in range(n): for y in range(x): L.append( (x, y) ) </code></pre> <p>I have done nested list comprehension in the more typical matrix scenario where the inner loop range is not dependent on the outer loop.</p> <...
0
2016-09-13T20:32:39Z
39,478,597
<p>List comprehensions are designed to make a straightforward translation of that loop possible:</p> <pre><code>[ (x,y) for x in range(3) for y in range(x) ] </code></pre> <p>Is that not what you wanted?</p>
0
2016-09-13T20:37:39Z
[ "python", "python-3.x", "list-comprehension", "nested-loops" ]
Why doesn't OrderedDict use super?
39,478,747
<p>We can create an <code>OrderedCounter</code> trivially by using multiple inheritance:</p> <pre><code>&gt;&gt;&gt; from collections import Counter, OrderedDict &gt;&gt;&gt; class OrderedCounter(Counter, OrderedDict): ... pass ... &gt;&gt;&gt; OrderedCounter('Mississippi').items() [('M', 1), ('i', 4), ('s', 4), ...
4
2016-09-13T20:48:11Z
39,478,934
<p>It's a microoptimization. Looking up a <code>dict_setitem</code> argument is slightly faster than looking up <code>dict.__setitem__</code> or <code>super().__setitem__</code>.</p> <p>This might cause problems with multiple inheritance if you have another class that overrides <code>__setitem__</code>, but <code>Orde...
0
2016-09-13T21:02:10Z
[ "python", "oop", "multiple-inheritance", "super", "python-collections" ]
Create process remotely by Supervisord API
39,478,769
<p>I'm creating an application to manage my supervisord process. I want to create process remotely by this application using the API.</p> <p>I've checked the <a href="http://supervisord.org/api.html" rel="nofollow">supervisord XML-RPC API</a> but doesn't helped.</p>
-2
2016-09-13T20:49:59Z
39,519,716
<p>I used this interface to create process by API: <a href="https://github.com/mnaberez/supervisor_twiddler" rel="nofollow">https://github.com/mnaberez/supervisor_twiddler</a></p>
0
2016-09-15T20:21:57Z
[ "python", "supervisord" ]
Unable to correctly use Pandas Interpolate over a series
39,478,838
<p>I am trying to use the interpolation functionality provided by Pandas, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.interpolate.html" rel="nofollow">here</a> but for some reason, cannot get my Series to adjust to the correct values. I casted them to a float64, but that did not appea...
1
2016-09-13T20:55:42Z
39,478,926
<p>The problem is that there is nothing to interpolate. I'm assuming you want to interpolate the value where zero is. In that case, replace the zero with <code>np.nan</code> then interpolate. One way to do this is</p> <pre><code>price_data.where(price_data != 0, np.nan).interpolate() 0 178.90 1 178.51 2 1...
0
2016-09-13T21:01:34Z
[ "python", "python-2.7", "pandas", "interpolation", "series" ]
Django Makemigrations not working in version 1.10 after adding new table
39,478,845
<p>I added some table models in <code>models.py</code> for the first time running the app and then ran <code>python manage.py makemigrations</code> followed by <code>python manage.py migrate</code>. This works well but after adding two more tables it doesn't work again. </p> <p>It created <em>migrations</em> for the c...
0
2016-09-13T20:56:32Z
39,481,262
<p>You could try:</p> <ol> <li>Deleted everything in the django-migrations table.</li> <li>Deleted all files in migrations folder and then run python manage.py makemigrations followed by python manage.py migrate as you said.</li> </ol> <p>If this doesn't work, try:</p> <ol> <li>Deleted everything in the django-migra...
-1
2016-09-14T01:36:44Z
[ "python", "django", "python-2.7" ]
Django Makemigrations not working in version 1.10 after adding new table
39,478,845
<p>I added some table models in <code>models.py</code> for the first time running the app and then ran <code>python manage.py makemigrations</code> followed by <code>python manage.py migrate</code>. This works well but after adding two more tables it doesn't work again. </p> <p>It created <em>migrations</em> for the c...
0
2016-09-13T20:56:32Z
39,481,477
<p>I have run into this problem before and found that running <code>manage.py</code> for specific tables in this fashion worked:</p> <pre><code>python manage.py schemamigration mytablename --auto python manage.py migrate </code></pre> <p>Also make sure that your new table is listed under <code>INSTALLED_APPS</code> i...
1
2016-09-14T02:07:01Z
[ "python", "django", "python-2.7" ]
Django Makemigrations not working in version 1.10 after adding new table
39,478,845
<p>I added some table models in <code>models.py</code> for the first time running the app and then ran <code>python manage.py makemigrations</code> followed by <code>python manage.py migrate</code>. This works well but after adding two more tables it doesn't work again. </p> <p>It created <em>migrations</em> for the c...
0
2016-09-13T20:56:32Z
39,482,630
<p>Can you post your models?</p> <p>Have you edited manage.py in any way?</p> <p>Try deleting the migrations and the database again after ensuring that your models are valid, then run manage.py makemigrations appname and then manage.py migrate.</p>
0
2016-09-14T04:45:46Z
[ "python", "django", "python-2.7" ]
Pandas pct change from initial value
39,478,853
<p>I want to find the pct_change of <code>Dew_P Temp (C)</code> from the initial value of -3.9. I want the pct_change in a new column.</p> <p>Source here:</p> <pre><code>weather = pd.read_csv('https://raw.githubusercontent.com/jvns/pandas-cookbook/master/data/weather_2012.csv') weather[weather.columns[:4]].head() D...
5
2016-09-13T20:57:16Z
39,479,039
<p>IIUC you can do it this way:</p> <pre><code>In [88]: ((weather['Dew Point Temp (C)'] - weather.ix[0, 'Dew Point Temp (C)']).abs() / weather.ix[0, 'Dew Point Temp (C)']).abs() * 100 Out[88]: 0 0.000000 1 5.128205 2 12.820513 3 17.948718 4 15.384615 5 15.384615 6 20....
4
2016-09-13T21:09:29Z
[ "python", "python-3.x", "pandas", "dataframe" ]
Pandas pct change from initial value
39,478,853
<p>I want to find the pct_change of <code>Dew_P Temp (C)</code> from the initial value of -3.9. I want the pct_change in a new column.</p> <p>Source here:</p> <pre><code>weather = pd.read_csv('https://raw.githubusercontent.com/jvns/pandas-cookbook/master/data/weather_2012.csv') weather[weather.columns[:4]].head() D...
5
2016-09-13T20:57:16Z
39,479,042
<p>You can use <code>iat</code> to access the scalar value (e.g. <code>iat[0]</code> accesses the first value in the series).</p> <pre><code>df = weather df['pct_diff'] = df['Dew_P Temp (C)'] / df['Dew_P Temp (C)'].iat[0] - 1 </code></pre>
6
2016-09-13T21:09:51Z
[ "python", "python-3.x", "pandas", "dataframe" ]
Pandas pct change from initial value
39,478,853
<p>I want to find the pct_change of <code>Dew_P Temp (C)</code> from the initial value of -3.9. I want the pct_change in a new column.</p> <p>Source here:</p> <pre><code>weather = pd.read_csv('https://raw.githubusercontent.com/jvns/pandas-cookbook/master/data/weather_2012.csv') weather[weather.columns[:4]].head() D...
5
2016-09-13T20:57:16Z
39,479,091
<p>I find this more graceful</p> <pre><code>weather['Dew_P Temp (C)'].pct_change().fillna(0).add(1).cumprod().sub(1) 0 0.000000 1 -0.051282 2 -0.128205 3 -0.179487 4 -0.153846 Name: Dew_P Temp (C), dtype: float64 </code></pre> <hr> <p>To get your expected output with absolute values</p> <pre><code>weath...
3
2016-09-13T21:15:03Z
[ "python", "python-3.x", "pandas", "dataframe" ]
BeautifulSoup, findAll after findAll?
39,478,865
<p>I'm pretty new to Python and mainly need it for getting information from websites. Here I tried to get the short headlines from the bottom of the website, but cant quite get them.</p> <pre><code>from bfs4 import BeautifulSoup import requests url = "http://some-website" r = requests.get(url) soup = BeautifulSoup(r....
1
2016-09-13T20:58:01Z
39,479,047
<p>Use a <em>css selector</em> with select if you want all the links in a single list:</p> <pre><code>anchors = soup.select('ul.list a') </code></pre> <p>If you want individual lists:</p> <pre><code>anchors = [ ul.find_all(a) for a in soup.find_all('ul', {'class':'list'})] </code></pre> <p>Also if you want the href...
0
2016-09-13T21:10:14Z
[ "python", "beautifulsoup", "python-requests" ]