title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Python how to make class object shared across functions | 38,676,443 | <p>Lets say I created a class object someClassObject in function A, and threw that object into a function B:</p>
<pre><code>functionB(someClassObject)
</code></pre>
<p>How do I retain all the modifications I've made in function B to someClassObject so I can continue using someClassObject in function A if my function ... | 0 | 2016-07-30T17:05:15Z | 38,676,870 | <p>I presume you meant instance of a class when you meant class object, in Python even a class is an object and you can pass them like instances.
In Python all objects are passed by reference meaning when you pass an instance to a function you only pass a reference and all changes you make to the object will be preserv... | 0 | 2016-07-30T17:53:52Z | [
"python",
"oop"
] |
How to get the Average of a specific category via Python | 38,676,558 | <p>I was wondering how I could calculate the average of a specific category via Python? I have a csv file called demo.csv</p>
<pre><code> import pandas as pd
import numpy as np
#loading the data into data frame
X = pd.read_csv('demo.csv')
</code></pre>
<p>the two columns of interest are the <code>Category</code> an... | 0 | 2016-07-30T17:19:27Z | 38,676,751 | <p>You can restrict your dataframe to the subset of the rows you want(<code>Category=2</code>), followed by taking mean of the columns corresponding to <code>Totals</code> column as follows:</p>
<pre><code>df[df['Category'] == 2]['Totals'].mean()
2745.5
</code></pre>
| 2 | 2016-07-30T17:41:13Z | [
"python",
"csv",
"pandas",
"average"
] |
How to get the Average of a specific category via Python | 38,676,558 | <p>I was wondering how I could calculate the average of a specific category via Python? I have a csv file called demo.csv</p>
<pre><code> import pandas as pd
import numpy as np
#loading the data into data frame
X = pd.read_csv('demo.csv')
</code></pre>
<p>the two columns of interest are the <code>Category</code> an... | 0 | 2016-07-30T17:19:27Z | 38,677,486 | <blockquote>
<p>I'm interested in finding the average for the Totals corresponding with Category 2</p>
</blockquote>
<p>You may set the category as the index then calculate the mean for any category using the <code>.loc</code> or <code>.ix</code> indexers:</p>
<pre><code>df.set_index('Category').loc['2', 'Totals'].... | 0 | 2016-07-30T18:57:03Z | [
"python",
"csv",
"pandas",
"average"
] |
BeautifulSoup parsing returns None | 38,676,569 | <p>There are plenty of websites thats simply return <code>None</code> when I request a value from the website.</p>
<p>Example: </p>
<pre><code>import requests
from bs4 import BeautifulSoup
def spider():
url = 'https://poloniex.com/exchange'
source_code = requests.get(url)
plain_text = source_code.text
... | 0 | 2016-07-30T17:21:44Z | 40,120,977 | <p>The web page has JavaScript code, and because of this the request doesn't return a complete result (the JS code in this case is necessary to complete the page).</p>
<p>I'm using selenium to solve this kind of problem.</p>
| 0 | 2016-10-19T02:14:11Z | [
"python",
"parsing",
"web-scraping",
"beautifulsoup",
"web-crawler"
] |
BeautifulSoup parsing returns None | 38,676,569 | <p>There are plenty of websites thats simply return <code>None</code> when I request a value from the website.</p>
<p>Example: </p>
<pre><code>import requests
from bs4 import BeautifulSoup
def spider():
url = 'https://poloniex.com/exchange'
source_code = requests.get(url)
plain_text = source_code.text
... | 0 | 2016-07-30T17:21:44Z | 40,121,690 | <p>Download chromedriver from this link <a href="http://chromedriver.storage.googleapis.com/index.html?path=2.24/" rel="nofollow">http://chromedriver.storage.googleapis.com/index.html?path=2.24/</a> and uzip it & Put chromedriver.exe in C:\Python27\Scripts </p>
<p>try this code:</p>
<pre><code>from selenium impo... | 0 | 2016-10-19T03:37:27Z | [
"python",
"parsing",
"web-scraping",
"beautifulsoup",
"web-crawler"
] |
Refresh HTML page from python input | 38,676,583 | <p>NEW:</p>
<p>It worked without isseus for like 40 mins, then the code itself crashed:
this is the outpud in the console</p>
<pre><code>Gradi: 29.0 C Umidita: 35.0 %
Traceback (most recent call last):
File "temp.py", line 22, in <module>
valori='Gradi: {0:0.1f} C Umidita: {1:0.1f} %'.format(temperature... | 0 | 2016-07-30T17:24:03Z | 38,676,796 | <p>For making <em>really</em> sure the file never is empty or incomplete when reading from it with another program keep reading below the first code block.</p>
<p>If it is OK for you to <em>almost</em> never have an empty or incomplete file you would do</p>
<pre><code>import datetime
import sys
import Adafruit_DHT
im... | 0 | 2016-07-30T17:46:02Z | [
"python",
"html",
"raspberry-pi"
] |
Returning a PDF from S3 in Flask | 38,676,591 | <p>I'm trying to return a PDF in the browser in a Flask application. I'm using AWS S3 to store the files and boto3 as the SDK to interact with S3. My code so far is:</p>
<pre><code>s3 = boto3.resource('s3', aws_access_key_id=settings.AWS_ACCESS_KEY,
aws_secret_access_key=settings.AWS_SECRET_KEY)
file =... | 0 | 2016-07-30T17:25:25Z | 38,679,722 | <p>It turns out that boto3 doesn't have a <code>readLines()</code> method but they do have a <code>read()</code> method, so it worked by doing:</p>
<pre><code>response = make_response(file['Body'].read())
response.headers['Content-Type'] = 'application/pdf'
return response
</code></pre>
| 0 | 2016-07-31T00:26:56Z | [
"python",
"amazon-web-services",
"amazon-s3",
"flask",
"boto3"
] |
Tkinter Show splash screen and hide main screen until __init__ has finished | 38,676,617 | <p>I have a main tkinter window that can take up to a few seconds to load properly. Because of this, I wish to have a splash screen that shows until the <strong>init</strong> method of the main class has finished, and the main tkinter application can be shown. How can this be achieved?</p>
<p>Splash screen code:</p>
... | 0 | 2016-07-30T17:27:31Z | 38,678,891 | <p>a simple example for python3:</p>
<pre><code>#!python3
import tkinter as tk
import time
class Splash(tk.Toplevel):
def __init__(self, parent):
tk.Toplevel.__init__(self, parent)
self.title("Splash")
## required to make window show before the program gets to the mainloop
self.u... | 0 | 2016-07-30T22:03:15Z | [
"python",
"tkinter",
"splash-screen"
] |
Cant select a value from a drop down list using Selenium in python | 38,676,636 | <p>I'm trying to select the year 1989 in the drop down list on this sign up page.</p>
<pre><code>driver.get("https://club.pokemon.com/us/pokemon-trainer-club/sign-up/")
elem = driver.find_element_by_id("id_dob")
elem.send_keys(Keys.RETURN)
elem = driver.find_element_by_class_name("picker__footer")
find_element_by_xpa... | 1 | 2016-07-30T17:29:48Z | 38,676,846 | <p>You can actually avoid dealing with the date picker in the first place and set the "date of birth" <em>directly in the input</em>. For that, we can remove the <code>readonly</code> property from the "date of birth" input and <a href="http://stackoverflow.com/a/4386514/771848">replace the element with it's clone to r... | 0 | 2016-07-30T17:51:18Z | [
"python",
"selenium"
] |
How can I create an in-memory database with sqlite? | 38,676,691 | <p>I'm trying to create an in-memory database using <code>sqlite3</code> in Python.</p>
<p>I created a function to create a db database file and store information in to it and that is working 100%.</p>
<p>But trying to connect with <code>:memory:</code> I've faced some problems.</p>
<p>What I'm doing is:</p>
<pre><... | 0 | 2016-07-30T17:35:00Z | 38,676,728 | <p>You create a <strong>new</strong> connection each time you call the function. Each connection call produces a <strong>new</strong> in-memory database.</p>
<p>Create the connection outside of the function, and pass it into the function, or create a <a href="https://stackoverflow.com/questions/32681761/how-can-i-atta... | 2 | 2016-07-30T17:39:07Z | [
"python",
"python-2.7",
"sqlite",
"sqlite3"
] |
Checking if a list of tuples is a subset of another | 38,676,711 | <p>Firstly, note that I have gone through the other list-subset questions and they are not related to my problem here. </p>
<p>I have two lists</p>
<pre><code>>>> l1 = [[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]
>>>
>>> l2 = [(7, -1, '... | 0 | 2016-07-30T17:37:30Z | 38,676,750 | <p>You can just use sets and the <= operator (is subset of). </p>
<pre><code>>>> l1 = [2,4,6,8]
>>> l2 = [2,4,6,8,10]
>>> set(l1) <= set(l2)
True
</code></pre>
| 0 | 2016-07-30T17:41:09Z | [
"python",
"list",
"set"
] |
Checking if a list of tuples is a subset of another | 38,676,711 | <p>Firstly, note that I have gone through the other list-subset questions and they are not related to my problem here. </p>
<p>I have two lists</p>
<pre><code>>>> l1 = [[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]
>>>
>>> l2 = [(7, -1, '... | 0 | 2016-07-30T17:37:30Z | 38,676,757 | <p>Use <a href="https://docs.python.org/2/library/stdtypes.html#set.issubset" rel="nofollow"><code>issubset</code></a>,</p>
<pre><code>l1 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]
l2 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, '... | 0 | 2016-07-30T17:41:45Z | [
"python",
"list",
"set"
] |
Checking if a list of tuples is a subset of another | 38,676,711 | <p>Firstly, note that I have gone through the other list-subset questions and they are not related to my problem here. </p>
<p>I have two lists</p>
<pre><code>>>> l1 = [[(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, 'shocked', 'shocked')]]
>>>
>>> l2 = [(7, -1, '... | 0 | 2016-07-30T17:37:30Z | 38,676,781 | <p>The problem is that <code>l1</code> is a list of list of tuple (i.e. [[tuple]]), whereas <code>l2</code> is a list of tuple (i.e. [tuple]). If you change this the output from the list comprehensions are what you expect:</p>
<pre><code>l1 = [(7, -1, 'VBD', 'null', -1, 'looked', 'looked'), (8, 7, 'JJ', 'xcomp', -1, '... | 3 | 2016-07-30T17:44:12Z | [
"python",
"list",
"set"
] |
Fail to Launch Mozilla with selenium | 38,676,719 | <p>I am trying to launch <code>Mozilla</code> but still i am getting this error:</p>
<blockquote>
<p>Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see <a href="https://github.com/mozilla/g... | 8 | 2016-07-30T17:38:13Z | 38,676,858 | <p><em>The <code>Selenium</code> client bindings will try to locate the <code>geckodriver</code> executable from the system <code>PATH</code>. You will need to add the directory containing the executable to the system path.</em></p>
<ul>
<li><p>On <strong>Unix</strong> systems you can do the following to append it to ... | 11 | 2016-07-30T17:53:02Z | [
"java",
"python",
"selenium",
"firefox",
"mozilla"
] |
Fail to Launch Mozilla with selenium | 38,676,719 | <p>I am trying to launch <code>Mozilla</code> but still i am getting this error:</p>
<blockquote>
<p>Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see <a href="https://github.com/mozilla/g... | 8 | 2016-07-30T17:38:13Z | 40,048,585 | <p>Download gecko driver from the seleniumhq website and set the path for gecko driver as below</p>
<pre><code>System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
</code></pre>
| 0 | 2016-10-14T17:12:00Z | [
"java",
"python",
"selenium",
"firefox",
"mozilla"
] |
Cut off trailing group with regex | 38,676,726 | <p>I have a couple of strings which all terminate with some numerical digits, immediately preceeded by a number of non-numerical characters, e.g., <code>10.1002/0470868279-ch1</code>. I would like cut off exactly this group; for this example <code>-ch1</code>. I tried</p>
<pre><code>import re
str0 = '10.1002/047086... | -1 | 2016-07-30T17:38:46Z | 38,676,762 | <p>Add <code>?</code> to make first match non-greedy so it matches as little as possible. Also add <code>$</code> so that match will always go to end of string:</p>
<pre><code>a = re.match('(.*?)([^0-9]+[0-9]*)$', str0)
</code></pre>
| 3 | 2016-07-30T17:42:22Z | [
"python",
"regex"
] |
Cut off trailing group with regex | 38,676,726 | <p>I have a couple of strings which all terminate with some numerical digits, immediately preceeded by a number of non-numerical characters, e.g., <code>10.1002/0470868279-ch1</code>. I would like cut off exactly this group; for this example <code>-ch1</code>. I tried</p>
<pre><code>import re
str0 = '10.1002/047086... | -1 | 2016-07-30T17:38:46Z | 38,676,904 | <p>The following should match up to the end of what you want: <code>(-|\+)?\d+(\.\d*)?/(-|\+)?\d+(\.\d*)?</code> This would let you extract the numbers you are looking for.</p>
<p>This pattern would match just the end portion (<em>tested on your <code>-ch1</code> example</em>): <code>(?<=\d)[^\d\./][a-zA-Z0-9]*$</c... | 0 | 2016-07-30T17:57:40Z | [
"python",
"regex"
] |
how to know whether login is successfull or not? | 38,676,799 | <p>I am using roboBrowser to login into a website and this the code</p>
<pre><code>from robobrowser import RoboBrowser
browser = RoboBrowser(parser = "html5lib")
login_url = 'someUrl/login.php'
browser.open(login_url)
form = browser.get_form(id='form1')
form['Username'].value = "User"
form['Password'].value = "1234"
b... | 0 | 2016-07-30T17:46:16Z | 38,677,236 | <pre><code>p = browser.parsed()
f = open("file.txt","w+",encoding = 'UTF-8')
f.write(str(p))
f.flush()
f.close()
</code></pre>
<p>you can find the username or some data which is visible only after login to confirm the login</p>
| 1 | 2016-07-30T18:31:09Z | [
"python",
"python-3.x",
"beautifulsoup",
"python-requests",
"robobrowser"
] |
how to know whether login is successfull or not? | 38,676,799 | <p>I am using roboBrowser to login into a website and this the code</p>
<pre><code>from robobrowser import RoboBrowser
browser = RoboBrowser(parser = "html5lib")
login_url = 'someUrl/login.php'
browser.open(login_url)
form = browser.get_form(id='form1')
form['Username'].value = "User"
form['Password'].value = "1234"
b... | 0 | 2016-07-30T17:46:16Z | 38,678,700 | <p>As the website returns nothing could you use some like <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> to parse the HTML and find something in the site which confirms you are logged in?</p>
| -1 | 2016-07-30T21:34:04Z | [
"python",
"python-3.x",
"beautifulsoup",
"python-requests",
"robobrowser"
] |
how to keep a subprocess running and keep supplying output to it in python? | 38,676,839 | <p>I am not able to keep alive a tunnel created by subprocess to fire multiple commands.
<br>first i tried this to execute a subprocess</p>
<pre><code>command=['gdb']
process=subprocess.Popen(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
(out,err)=process.communicate("""file demo
b main
r
""")
print out
</code... | 1 | 2016-07-30T17:50:51Z | 38,676,962 | <p>I would use something along the lines of</p>
<pre><code>with Popen(command, stdin=PIPE, stdout=PIPE) as proc:
for line in proc.stdout:
proc.stdin.write("b main")
</code></pre>
<p>This will allow you to write lines to the process, while reading lines from the process.</p>
| 0 | 2016-07-30T18:03:15Z | [
"python",
"linux",
"ubuntu",
"gdb"
] |
how to keep a subprocess running and keep supplying output to it in python? | 38,676,839 | <p>I am not able to keep alive a tunnel created by subprocess to fire multiple commands.
<br>first i tried this to execute a subprocess</p>
<pre><code>command=['gdb']
process=subprocess.Popen(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
(out,err)=process.communicate("""file demo
b main
r
""")
print out
</code... | 1 | 2016-07-30T17:50:51Z | 38,865,633 | <p>As noticed, <code>communicate()</code> and <code>readlines()</code> are not fit for the task because they don't return before gdb's output has ended, i. e. gdb exited. We want to read gdb's output until it waits for input; one way to do this is to read until gdb's prompt appears - see below function <code>get_output... | 1 | 2016-08-10T06:18:49Z | [
"python",
"linux",
"ubuntu",
"gdb"
] |
Allow_Other with fusepy? | 38,676,937 | <p>I have a 16.04 ubuntu server with <a href="https://github.com/sondree/b2_fuse/issues" rel="nofollow">b2_fuse</a> mounting my b2 cloud storage bucket which uses pyfuse. The problem is, I have no idea how I can pass the allow_other argument like with FUSE! This is an issue because other services running under differ... | 0 | 2016-07-30T18:01:01Z | 39,031,709 | <p>inside of file <code>b2fuse.py</code>
if you change this line <code>FUSE(filesystem, mountpoint, nothreads=True, foreground=True)</code>
to
<code>FUSE(filesystem, mountpoint, nothreads=True, foreground=True,**{'allow_other': True})</code> the volume will be mounted with allow_other</p>
| 1 | 2016-08-19T05:30:43Z | [
"python",
"fuse"
] |
Nested list comprehension against .NET Arrays within Arrays | 38,676,956 | <p>I have a .NET structure that has arrays with arrays in it. I want to crete a list of members of items from a specific array in a specific array using list comprehension in IronPython, if possible.</p>
<p>Here is what I am doing now:</p>
<pre><code>tag_results = [item_result for item_result in results.ItemResults i... | 1 | 2016-07-30T18:02:47Z | 38,677,000 | <p><code>tag_results = [...][0]</code> builds a <em>whole new list</em> just to get one item. This is what <code>next()</code> on a generator expression is for:</p>
<pre><code>next(item_result for item_result in results.ItemResults if item_result.ItemId == tag_id)
</code></pre>
<p>which only iterates just enough to g... | 1 | 2016-07-30T18:07:14Z | [
"python",
"ironpython"
] |
Python: How to split a string column in a dataframe? | 38,676,968 | <p>I have a dataframe with two columns one is <code>Date</code> and the other one is <code>Location(Object)</code> datatype, below is the format of Location columns with values :</p>
<pre><code> Date Location
1 07/12/1912 AtlantiCity, New Jersey... | 2 | 2016-07-30T18:04:47Z | 38,677,071 | <p>A straight forward way is to <code>apply</code> the <code>split</code> method to each element of the column and pick up the last one:</p>
<pre><code>df.Location.apply(lambda x: x.split(",")[-1])
1 New Jersey
2 Canada
3 Over the North Sea
4 Germany
5 Bel... | 2 | 2016-07-30T18:14:40Z | [
"python",
"python-3.x",
"pandas"
] |
Python: How to split a string column in a dataframe? | 38,676,968 | <p>I have a dataframe with two columns one is <code>Date</code> and the other one is <code>Location(Object)</code> datatype, below is the format of Location columns with values :</p>
<pre><code> Date Location
1 07/12/1912 AtlantiCity, New Jersey... | 2 | 2016-07-30T18:04:47Z | 38,677,460 | <p>We could try with <code>str.extract</code></p>
<pre><code>print(df['Location'].str.extract(r'([^,]+$)'))
#0 New Jersey
#1 Canada
#2 Over the North Sea
#3 Germany
#4 Belgium
#5 Germany
#6 Bulgeria
#7 England
#8 ... | 1 | 2016-07-30T18:54:07Z | [
"python",
"python-3.x",
"pandas"
] |
python printing dictionary to csv gives blank file | 38,676,978 | <p>I am using the following code as a representation of a larger dictionary which needs to be printed to a csv file:</p>
<pre><code>import csv
dict1 = {"hello": 1}
w = csv.writer(open("C:\output.csv", "w"))
for key, val in dict1.items():
w.writerow([key, val])
</code></pre>
<p>But the <code>output.csv</code> is b... | 0 | 2016-07-30T18:05:26Z | 38,677,045 | <p>Files you open need to be closed. Inside a <code>with</code> block, that happens automatically, for example:</p>
<pre><code>import csv
dict1 = {"hello": "world"}
with open("C:\output.csv", "w") as fd:
w = csv.writer(fd)
for key, val in dict1.items():
w.writerow([key, val])
</code></pre>
| 1 | 2016-07-30T18:11:44Z | [
"python",
"csv",
"dictionary"
] |
working with NaN in a dataframe with if condition | 38,677,017 | <p>I have 2 columns in a dataframe and I am trying to enter into a condition based on if the second one is NaN and First one has some values, unsuccessfully using:</p>
<pre><code>if np.isfinite(train_bk['Product_Category_1']) and np.isnan(train_bk['Product_Category_2'])
</code></pre>
<p>and </p>
<pre><code> if not... | 1 | 2016-07-30T18:09:17Z | 38,682,987 | <p>I would use eval:</p>
<pre><code>df.eval(' ind = ((pc1==pc1) & (pc2!=pc2) )*2+((pc1==pc1)&(pc2==pc2))*3')
df.replace({'ind':{0:1})
</code></pre>
| 0 | 2016-07-31T10:23:36Z | [
"python",
"numpy",
"pandas"
] |
Can not upload file/image in flaskapp | 38,677,022 | <p>I have created a form in html/php, and using flask for backend. </p>
<p>Everything is working perfect except when I am trying to upload image I am always seeing the error: </p>
<pre><code>error is**"UnboundLocalError: local variable 'filename' referenced before assignment"**
</code></pre>
<p>my flaskapp code snip... | 0 | 2016-07-30T18:09:47Z | 38,677,208 | <p><code>filename</code> existence depends on couple of conditions:</p>
<p>1 - <code>file = request.files['file']</code> <br>
2 - <code>if file and allowed_file(file.filename):</code> <br>
3 - No <em>exception</em> is raised.</p>
<p>So, if any of the above didn't happen, then <code>filename</code> won't spring into e... | 0 | 2016-07-30T18:29:13Z | [
"python",
"flask",
"flask-wtforms",
"flask-appbuilder"
] |
OS.rename() not working with tkinter | 38,677,028 | <p>Folks I'm trying to make a tool which gets user path and file name in one entry and new file name with path in another entry, My aim is to use <code>os.rename(oldname, newname)</code> to rename the given file, but its throwing me some error.</p>
<p>My code</p>
<pre><code>from tkinter import *
import os
def Rename... | 0 | 2016-07-30T18:10:17Z | 38,677,331 | <p>To expand upon what @SuperSaiyan said in the comment(s).</p>
<p>You are using a <code>StringVar</code>, which has the method <code>.get()</code> available to it. When you pass the variable which is set to this stringvar you are just passing the reference to this object. You need to actually use the <code>.get()</co... | 2 | 2016-07-30T18:39:56Z | [
"python",
"function",
"tkinter",
"module"
] |
OS.rename() not working with tkinter | 38,677,028 | <p>Folks I'm trying to make a tool which gets user path and file name in one entry and new file name with path in another entry, My aim is to use <code>os.rename(oldname, newname)</code> to rename the given file, but its throwing me some error.</p>
<p>My code</p>
<pre><code>from tkinter import *
import os
def Rename... | 0 | 2016-07-30T18:10:17Z | 38,677,488 | <p>You are using <code>StringVar</code>, whereas <code>rename</code> needs Strings. Use <code>oldname.get()</code>:</p>
<pre><code>import tkinter as tk
import os
def rename(oldname, oldname2, newname):
os.rename(oldname2.get(),newname.get())
oldname.set("Renamed Successfully !!! ")
def main():
root = tk.... | 1 | 2016-07-30T18:57:09Z | [
"python",
"function",
"tkinter",
"module"
] |
Checking data in a file for duplicates (Python) | 38,677,037 | <p>I am trying to make a list of topics for another project to use and I am storing the topics in <code>Topics.txt</code>. However, when the topics are stored in the file, I do not want duplicate topics. So when I am saving my topics to my <code>Topics.txt</code> file, I also save them to a <code>Duplicates.txt</code> ... | 1 | 2016-07-30T18:10:39Z | 38,677,187 | <p>You can store your topics in a set. A set is collection of unique items.</p>
<pre><code>topics = {'Banjo', 'Guitar', 'Piano'}
</code></pre>
<p>You can check for membership using:</p>
<pre><code>>>> 'Banjo' in topics
True
</code></pre>
<p>You add new things to a set via <code>.add()</code></p>
<pre><cod... | 0 | 2016-07-30T18:27:06Z | [
"python",
"python-3.x",
"duplicates",
"keyword-search"
] |
Checking data in a file for duplicates (Python) | 38,677,037 | <p>I am trying to make a list of topics for another project to use and I am storing the topics in <code>Topics.txt</code>. However, when the topics are stored in the file, I do not want duplicate topics. So when I am saving my topics to my <code>Topics.txt</code> file, I also save them to a <code>Duplicates.txt</code> ... | 1 | 2016-07-30T18:10:39Z | 38,677,227 | <p>You can read a file line by line which would result in a solution like this one</p>
<pre><code>Entry = input("Enter topic: ")
Topic = Entry + "\n"
Readfilename = "Duplicates.txt"
found=False
with open(Readfilename, "r") as Readfile:
for line in Readfile:
if Topic==line:
found=True
... | 1 | 2016-07-30T18:30:31Z | [
"python",
"python-3.x",
"duplicates",
"keyword-search"
] |
Python - use AND or OR in this code? | 38,677,089 | <p>I'm writing a simple code to get some easy practice in Python, just to find the maximum out of three numbers, without using the max function.</p>
<p>I wrote this:</p>
<pre><code>num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: ")... | -3 | 2016-07-30T18:16:37Z | 38,677,132 | <p>Yes, there is a difference. Basically, if you replace <code>and</code> by <code>or</code>, your code no longer works correctly.</p>
<p>The problem is that in each <code>if</code> statement, you need both conditions fulfilled to ensure that the value you want to return is larger than any of the others.</p>
<p>Note ... | 0 | 2016-07-30T18:21:21Z | [
"python"
] |
Python - use AND or OR in this code? | 38,677,089 | <p>I'm writing a simple code to get some easy practice in Python, just to find the maximum out of three numbers, without using the max function.</p>
<p>I wrote this:</p>
<pre><code>num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: ")... | -3 | 2016-07-30T18:16:37Z | 38,677,199 | <p>Yes there is a difference. Say you used</p>
<pre><code>if num1>num2 or num1>num3:
return num1
</code></pre>
<p>and say we tried <code>print (max_of_three(2,1,3))</code> it would return 2, because when it tries <code>num1>num2 or num1>num3</code> which evaluates to <code>True or False</code> which e... | 0 | 2016-07-30T18:28:24Z | [
"python"
] |
Python - use AND or OR in this code? | 38,677,089 | <p>I'm writing a simple code to get some easy practice in Python, just to find the maximum out of three numbers, without using the max function.</p>
<p>I wrote this:</p>
<pre><code>num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: ")... | -3 | 2016-07-30T18:16:37Z | 38,677,362 | <p>First, you need to alter the operators to make them greater than or equal to <code>>=</code> because some numbers may be the same.</p>
<p>Yes there would be a difference if you used <code>or</code> instead of <code>and</code> because of short-circuiting.</p>
<p>When using <code>and</code> to return a boolean va... | 2 | 2016-07-30T18:42:29Z | [
"python"
] |
Python - use AND or OR in this code? | 38,677,089 | <p>I'm writing a simple code to get some easy practice in Python, just to find the maximum out of three numbers, without using the max function.</p>
<p>I wrote this:</p>
<pre><code>num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: ")... | -3 | 2016-07-30T18:16:37Z | 38,677,452 | <p>Yes there is a difference. The statement <strong>and</strong> requires both the conditions to be true. <strong>Or</strong> would only require one of them to be true. Lets take an example:</p>
<ol>
<li>Num 1 = 1</li>
<li>Num 2 = 2</li>
<li>Num 3 = 3</li>
</ol>
<p>Your code, using or, would:</p>
<p>Disregard the fi... | 1 | 2016-07-30T18:52:41Z | [
"python"
] |
Python - use AND or OR in this code? | 38,677,089 | <p>I'm writing a simple code to get some easy practice in Python, just to find the maximum out of three numbers, without using the max function.</p>
<p>I wrote this:</p>
<pre><code>num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: ")... | -3 | 2016-07-30T18:16:37Z | 38,677,476 | <p>We can get rid of the ANDs and ORs altogether, and eliminate the redundant test (once you've decided to neither return num1 nor num2, why test if you should return num3? There's nothing else left!) We end up with something overly Pythonish like:</p>
<pre><code>def max_of_three(num1, num2, num3):
if num2 <= ... | 2 | 2016-07-30T18:55:56Z | [
"python"
] |
Working efficiently with selected (query()) data from Pandas Dataframe | 38,677,102 | <p>After querying a pandas DataFrame, I want to get the 3 entries before the selected index in my query.</p>
<p>The code below works, but I think it's dirty and not efficient, I can only image there is a better way of doing it with Pandas.</p>
<p>Does someone could help me?</p>
<pre class="lang-py prettyprint-overri... | 2 | 2016-07-30T18:17:59Z | 38,678,588 | <p>AFAIK, <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-query-method-experimental" rel="nofollow">query()</a> method doesn't accept functions and methods, that can be applied on columns - at least i couldn't make it working</p>
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stabl... | 0 | 2016-07-30T21:18:21Z | [
"python",
"numpy",
"pandas",
"indexing",
"pandasql"
] |
How to dive into stacked dict gracefully | 38,677,125 | <p>Let's say I have a dict like</p>
<pre><code>{
"key_a": "value",
"key_b": {
"key_b_a": "value",
"key_b_b": {
"key_b_b_a": "value"
}
}
}
</code></pre>
<p>What I want is to create a method to delete the given key or change its value.</p>
<pre><code>def del_key(key):
... | 2 | 2016-07-30T18:20:51Z | 38,677,271 | <p>It assumes your input is valid key,otherwise you have to check.</p>
<pre><code>data = {
"key_a": "value",
"key_b": {
"key_b_a": "value",
"key_b_b": {
"key_b_b_a": "value"
}
}
}
def del_key(key):
key = key.split(':')
temp = data
for i in key[:-1]:
... | 4 | 2016-07-30T18:34:07Z | [
"python"
] |
Python: Int is object is not subscriptable | 38,677,130 | <p>I know this is a topic that there are already several threads for. I've reviewed them and understand what this error means, but for some reason cannot get it to work for my code. </p>
<p>I'm trying to code a simple Python function that takes a list of integers as input and outputs the integers in the list that are ... | -1 | 2016-07-30T18:21:19Z | 38,677,143 | <pre><code>if num == num[i + 1] / 2:
</code></pre>
<p>should be</p>
<pre><code>if num == lst[i + 1] / 2:
</code></pre>
<p>Also, I recommend using <a href="http://stackoverflow.com/a/522578/5699206">enumerate</a> to iterate over the list with indexes, but there are better ways of doing such a thing, as shown in <a hr... | 3 | 2016-07-30T18:22:34Z | [
"python"
] |
Python: Int is object is not subscriptable | 38,677,130 | <p>I know this is a topic that there are already several threads for. I've reviewed them and understand what this error means, but for some reason cannot get it to work for my code. </p>
<p>I'm trying to code a simple Python function that takes a list of integers as input and outputs the integers in the list that are ... | -1 | 2016-07-30T18:21:19Z | 38,677,167 | <p>You're attempting to subscript an item in the list, not the list itself. Instead of iterating the items, you could iterate the list's indexes:</p>
<pre><code>def doubles(lst):
for i in range(0, len(lst) - 1):
if lst[i] == lst[i + 1] / 2:
print(lst[i])
</code></pre>
| 0 | 2016-07-30T18:25:04Z | [
"python"
] |
Python: Int is object is not subscriptable | 38,677,130 | <p>I know this is a topic that there are already several threads for. I've reviewed them and understand what this error means, but for some reason cannot get it to work for my code. </p>
<p>I'm trying to code a simple Python function that takes a list of integers as input and outputs the integers in the list that are ... | -1 | 2016-07-30T18:21:19Z | 38,677,177 | <p>you can zip original list and list begin from second element,then compare two elements </p>
<pre><code>def doubles(lst):
return [ i for i,j in zip(lst,lst[1:]) if j==i*2 ]
</code></pre>
<p>example:</p>
<pre><code>lst = [1,2,3,5,66,2,4,5]
print doubles(lst)
[1, 2]
</code></pre>
| 1 | 2016-07-30T18:26:04Z | [
"python"
] |
SSH Python Script Closing Too Early | 38,677,439 | <p>Iâm trying to write a python script to SSH into a box and run a command using the paramiko library. I am still in the learning process when it comes to python but the aim of this exercise is to build upon this program and use it in the work place.
I have been testing the program and so far so good however when th... | -1 | 2016-07-30T18:51:32Z | 38,677,495 | <pre><code>print ssh_session.recv(99999)
</code></pre>
<p>Tells the program to receive the response up to that limit of characters. So if the length of the server's response was 100,000, then the program would receive only the first 99,999, and not the last character. If the response is less than or equal to 99,999, t... | 0 | 2016-07-30T18:57:46Z | [
"python",
"paramiko"
] |
SSH Python Script Closing Too Early | 38,677,439 | <p>Iâm trying to write a python script to SSH into a box and run a command using the paramiko library. I am still in the learning process when it comes to python but the aim of this exercise is to build upon this program and use it in the work place.
I have been testing the program and so far so good however when th... | -1 | 2016-07-30T18:51:32Z | 38,677,512 | <p>I'm not entirely familiar with paramiko, but it looks like you are getting some sort of wrapper to the lower level socket object, and doing operations manually, even though the <code>client</code> object you got has functions to take care of this for you. <code>recv</code> looks like the standard <code>Socket</code>... | 0 | 2016-07-30T19:00:20Z | [
"python",
"paramiko"
] |
SSH Python Script Closing Too Early | 38,677,439 | <p>Iâm trying to write a python script to SSH into a box and run a command using the paramiko library. I am still in the learning process when it comes to python but the aim of this exercise is to build upon this program and use it in the work place.
I have been testing the program and so far so good however when th... | -1 | 2016-07-30T18:51:32Z | 38,677,765 | <p>the <code>recv()</code> method used here is actually expecting 99999 bytes from the socket. If 99999 bytes are not provided within a certain amount of time (i.e. timeout) then the connection will be closed and you'll be given the bytes provided within this time.</p>
<p>This is probably what is happening in your sit... | 0 | 2016-07-30T19:31:42Z | [
"python",
"paramiko"
] |
How to annotate a range of the x axis in matplotlib? | 38,677,467 | <p>I want to make an annotation, something like <a href="http://matplotlib.org/users/annotations_intro.html" rel="nofollow">here</a>, but I need to show a <em>range in x</em> instead of a single point. It's something like the <a href="https://en.wikipedia.org/wiki/Engineering_drawing#/media/File:Line_types.png" rel="no... | 4 | 2016-07-30T18:54:43Z | 38,677,732 | <p>You could use two calls to <a href="http://matplotlib.org/users/annotations_guide.html#plotting-guide-annotation" rel="nofollow"><code>ax.annotate</code></a> - one to add the text and one to draw an arrow with flat ends spanning the range you want to annotate:</p>
<pre><code>import matplotlib.pyplot as plt
import n... | 1 | 2016-07-30T19:26:54Z | [
"python",
"numpy",
"matplotlib"
] |
How to annotate a range of the x axis in matplotlib? | 38,677,467 | <p>I want to make an annotation, something like <a href="http://matplotlib.org/users/annotations_intro.html" rel="nofollow">here</a>, but I need to show a <em>range in x</em> instead of a single point. It's something like the <a href="https://en.wikipedia.org/wiki/Engineering_drawing#/media/File:Line_types.png" rel="no... | 4 | 2016-07-30T18:54:43Z | 38,683,607 | <p>Using <a href="http://stackoverflow.com/a/38677732/776515">ali_m's answer</a>, I could define this function, maybe it can be useful for someone sometime :)</p>
<hr>
<p><strong>Function</strong></p>
<pre><code>def annotation_line( ax, xmin, xmax, y, text, ytext=0, linecolor='black', linewidth=1, fontsize=12 ):
... | 1 | 2016-07-31T11:41:42Z | [
"python",
"numpy",
"matplotlib"
] |
Finding specific strings within a column and finding the max corresponding to that string | 38,677,504 | <p>I was wondering: <br></p>
<p>1.) how do I find a specific string in a column <br>
2.) given that string, how would I find it's corresponding max <br>
3.) How do I count the number of strings for each row in that column</p>
<p>I have a csv file called sports.csv</p>
<pre><code> import pandas as pd
import numpy a... | 0 | 2016-07-30T18:59:15Z | 38,677,642 | <p>You can do it in one pass as you read the file:</p>
<pre><code>import csv
with open("sport.csv") as f:
mx, best = float("-inf"), None
for row in csv.reader(f, delimiter=" ", skipinitialspace=1):
row[1:] = row[1].split("|")
if "Baseball" in row and len(row[1:]) > 2 and int(row[0]) > mx:... | 0 | 2016-07-30T19:16:22Z | [
"python",
"csv",
"pandas",
"max"
] |
Finding specific strings within a column and finding the max corresponding to that string | 38,677,504 | <p>I was wondering: <br></p>
<p>1.) how do I find a specific string in a column <br>
2.) given that string, how would I find it's corresponding max <br>
3.) How do I count the number of strings for each row in that column</p>
<p>I have a csv file called sports.csv</p>
<pre><code> import pandas as pd
import numpy a... | 0 | 2016-07-30T18:59:15Z | 38,678,027 | <p>You can easily do this using <code>pandas</code></p>
<p>First, split the strings into a list on the tab delimiter followed by iterating over the list and choosing the ones with the length greater than 2 as you would want baseball along with two other sports as the criteria.</p>
<pre><code>In [4]: df['Gym'] = df['G... | 1 | 2016-07-30T20:05:59Z | [
"python",
"csv",
"pandas",
"max"
] |
Finding specific strings within a column and finding the max corresponding to that string | 38,677,504 | <p>I was wondering: <br></p>
<p>1.) how do I find a specific string in a column <br>
2.) given that string, how would I find it's corresponding max <br>
3.) How do I count the number of strings for each row in that column</p>
<p>I have a csv file called sports.csv</p>
<pre><code> import pandas as pd
import numpy a... | 0 | 2016-07-30T18:59:15Z | 38,678,917 | <p>Try This: </p>
<pre><code>df3.loc[(df3['Gym'].str.contains('Hockey') == True) & (df3["Gym"].str.count("\|")>1)].sort_values("Total").tail(1)
Total Gym
0 40 Football|Baseball|Hockey|Running|Basketball|Sw...
df3.loc[(df3['Gym'].str.contains('Baseball') =... | 0 | 2016-07-30T22:08:00Z | [
"python",
"csv",
"pandas",
"max"
] |
Python - Convert strings in column into categorical variable | 38,677,615 | <p>I'd like to transform columns filled with strings into categorical variables so that I could run statistics. However, I am having difficulty with this transformation because I'm fairly new to Python.</p>
<p>Here is a sample of my code:</p>
<pre><code># Open txt file and provide column names
data = pd.read_csv('sam... | 0 | 2016-07-30T19:12:33Z | 38,678,718 | <p>As @ayhan noted in the comments, you probably want to use <a href="http://www.socialresearchmethods.net/kb/dummyvar.php" rel="nofollow">dummy variables</a> here. This is because it seems highly unlikely from your data that there is really any ordering in your text labels. </p>
<p>This can easily be done via <a href... | 1 | 2016-07-30T21:36:36Z | [
"python",
"string",
"pandas",
"statistics",
"categorical-data"
] |
Character Usage Python | 38,677,659 | <p>Python 3.5.2</p>
<p>I am trying to find out how to use characters in python (!,@,$ etc), however i haven't been able to find anything to give any help or any detail about this.</p>
<p>Here is an example:</p>
<pre><code>>>> $
SyntaxError: invalid syntax
</code></pre>
<p>What i'm looking for is why this ... | -2 | 2016-07-30T19:18:12Z | 38,677,702 | <p>Generally, Python identifiers can only use <a href="https://docs.python.org/3/reference/lexical_analysis.html#identifiers" rel="nofollow">letters (from various languages), numbers, or underscores</a>. Unlike JavaScript, <code>$</code> isn't a valid identifier character. Likewise, most punctuation, including <code>... | 2 | 2016-07-30T19:23:24Z | [
"python",
"syntax"
] |
Character Usage Python | 38,677,659 | <p>Python 3.5.2</p>
<p>I am trying to find out how to use characters in python (!,@,$ etc), however i haven't been able to find anything to give any help or any detail about this.</p>
<p>Here is an example:</p>
<pre><code>>>> $
SyntaxError: invalid syntax
</code></pre>
<p>What i'm looking for is why this ... | -2 | 2016-07-30T19:18:12Z | 38,677,715 | <p>Naming convention rules in python only allow numbers, letters, and underscores. Here specifically are the rules</p>
<blockquote>
<pre><code>Variables names must start with a letter or an underscore, such as:
_underscore
underscore_
The remainder of your variable name may consist of letters, numbers and unde... | 2 | 2016-07-30T19:25:00Z | [
"python",
"syntax"
] |
python - how to simultaneously iterate and modify list, set, etc | 38,677,708 | <p>In my program I have <strong>many</strong> lines where I need to both iterate over a something <strong>and</strong> modify it in that same <code>for</code> loop.</p>
<p>However, I know that modifying the thing over which you're iterating is bad because it <em>may</em> - probably <strong>will</strong> - result in an... | 0 | 2016-07-30T19:24:26Z | 38,677,855 | <p>This is a conceptual misunderstanding. </p>
<p>It is dangerous to modify the list itself from within the iteration, because of the way Python translates the loop to lower level code. This can cause unexpected side effects during the iteration, there's a good example here : </p>
<p><a href="https://unspecified.word... | 1 | 2016-07-30T19:43:07Z | [
"python"
] |
python - how to simultaneously iterate and modify list, set, etc | 38,677,708 | <p>In my program I have <strong>many</strong> lines where I need to both iterate over a something <strong>and</strong> modify it in that same <code>for</code> loop.</p>
<p>However, I know that modifying the thing over which you're iterating is bad because it <em>may</em> - probably <strong>will</strong> - result in an... | 0 | 2016-07-30T19:24:26Z | 38,677,860 | <p>you could get index first </p>
<pre><code>idx = [ el_idx for el_idx, el in enumerate(theList) if el.IsSomething() ]
[ theList[i].SetIt(False) for i in idx ]
</code></pre>
| -1 | 2016-07-30T19:44:05Z | [
"python"
] |
python - how to simultaneously iterate and modify list, set, etc | 38,677,708 | <p>In my program I have <strong>many</strong> lines where I need to both iterate over a something <strong>and</strong> modify it in that same <code>for</code> loop.</p>
<p>However, I know that modifying the thing over which you're iterating is bad because it <em>may</em> - probably <strong>will</strong> - result in an... | 0 | 2016-07-30T19:24:26Z | 38,678,397 | <p>Your problem seems to be unclear to me. But if we talk about harmful of modifying list during a <code>for</code> loop iteration in Python. I can think about two scenarios.</p>
<p><strong>First</strong>, You modify some elements in list that suppose to be used on the next round of computation as its original value.<... | 0 | 2016-07-30T20:53:11Z | [
"python"
] |
Matching up iterables in lists, having significant difficulty | 38,677,714 | <p>For a personal project I have three lists. One of these contains a set of arrays (l2) the size of which is always determined by a setting l2_size and always contains random members of l1. The next array, l3, on the other hand will always be a set of 0's of quantity len(l1).</p>
<p>This means...</p>
<pre><code>l1 =... | 0 | 2016-07-30T19:24:55Z | 38,677,794 | <p>get sublist first, then using sublist's element get l1's index. increase 1 for l3 element based on l1's index</p>
<pre><code>l1 = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
l2 = [[3, 4, 5, 2, 4],[3, 5, 1, 2, 4], [4, 3, 2, 1, 5]]
l3 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
def combinList( lst ):
''' put list of list together bas... | 2 | 2016-07-30T19:34:51Z | [
"python",
"arrays",
"iterable"
] |
Matching up iterables in lists, having significant difficulty | 38,677,714 | <p>For a personal project I have three lists. One of these contains a set of arrays (l2) the size of which is always determined by a setting l2_size and always contains random members of l1. The next array, l3, on the other hand will always be a set of 0's of quantity len(l1).</p>
<p>This means...</p>
<pre><code>l1 =... | 0 | 2016-07-30T19:24:55Z | 38,706,624 | <p>Still a little hazy on the specs but try this - it works for the simple case of <code>l1 = [1,2,3,4,5,1,2,3,4,5]</code> and <code>l2 = [[1,2,3,4,5],[1,2,3,4,5]]</code>.</p>
<pre><code>used_indices = set()
def get_next_index(card, l1 = l1, used_indices = used_indices):
try:
# find the next index that ha... | 0 | 2016-08-01T19:25:01Z | [
"python",
"arrays",
"iterable"
] |
Matching up iterables in lists, having significant difficulty | 38,677,714 | <p>For a personal project I have three lists. One of these contains a set of arrays (l2) the size of which is always determined by a setting l2_size and always contains random members of l1. The next array, l3, on the other hand will always be a set of 0's of quantity len(l1).</p>
<p>This means...</p>
<pre><code>l1 =... | 0 | 2016-07-30T19:24:55Z | 38,806,985 | <p>I simplified the solution by creating two arrays extra arrays called a "configuration space" which are assigned boolean true (represented by the integer 1) depending on a number (a card) has been assigned to a hand or a member of the subset (a hand) has already been assigned to a card. </p>
<p>This solution makes o... | 0 | 2016-08-06T17:32:37Z | [
"python",
"arrays",
"iterable"
] |
Display Web cam Python | 38,677,741 | <p>I have this code for web cam and should be displayed in the window (designed in Qt designer) this code works well but now i have two cam windows, one in my Main window (form designed in Qt Designer) and one out of the Main window. </p>
<pre><code>def b1_clicked(self):
mycam = cv2.VideoCapture(0)
if mycam.i... | 0 | 2016-07-30T19:28:03Z | 38,689,244 | <p>Comment out cv2.imshow which opens its own window.</p>
| 0 | 2016-07-31T23:27:32Z | [
"python",
"opencv",
"qt-designer"
] |
heroku does not load jquery on https | 38,677,808 | <p>i have an app deployed to heroku and i request the jquery to be loaded</p>
<pre><code><script src="//www.highcharts.com/lib/jquery-1.7.2.js" type="text/javascript"></script>
</code></pre>
<p>in order to use highcharts. But when running my app on http the charts are not loaded,whereas when running the a... | 0 | 2016-07-30T19:37:05Z | 38,677,829 | <p>www.highcharts.com doesn't seem to support HTTPS, so you'll need to load jQuery from somewhere else.</p>
<p>Try one of the options here: <a href="http://code.jquery.com/" rel="nofollow">http://code.jquery.com/</a>. Or you could download the copy of jQuery you're using and just include it in your app.</p>
<p><stron... | 2 | 2016-07-30T19:39:53Z | [
"javascript",
"python",
"html",
"heroku",
"highcharts"
] |
How to sort half of the 2d array in descending order (numpy) | 38,678,057 | <p>I'm trying to create an array (10000, 50) size (I'm mentioning the size because efficiency is important), and then : </p>
<ul>
<li>Sort the first 5000 rows in ascending order </li>
<li>Sort the next 5000 rows in descending order.</li>
</ul>
<p>Here is my code : </p>
<pre><code>samples = 10 # I'm going to increas... | 3 | 2016-07-30T20:10:05Z | 38,678,185 | <p>It would probably be faster to sort the array in place using its <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sort.html" rel="nofollow"><code>.sort</code></a> method, rather than <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html" rel="nofollow"><code>np.sort</... | 4 | 2016-07-30T20:25:24Z | [
"python",
"arrays",
"sorting",
"numpy"
] |
Showing both the value and index in the x-ticks in a plot | 38,678,085 | <p>I want to plot something using <code>plot(x,y)</code> and be able to see on the plot the index of the value in <code>x</code></p>
<p>For example.</p>
<pre><code>x = [10,30,100,120]
y = [16,17,19,3]
plot(x,y)
</code></pre>
<p>will show </p>
<p><a href="http://i.stack.imgur.com/C2IKz.png" rel="nofollow"><img src="... | 1 | 2016-07-30T20:13:35Z | 38,679,797 | <p>Here's my solution:</p>
<pre><code>import matplotlib.pyplot as plt
x = [10,30,100,120]
y = [16,17,19,3]
plt.plot(x,y);
for i, (a, b) in enumerate(zip(x, y)):
plt.annotate(str(i), xy=(a, b), textcoords="offset points", xytext=(0, 12),
horizontalalignment='center', verticalalignment='center')
plt... | 1 | 2016-07-31T00:45:26Z | [
"python",
"matplotlib",
"plot"
] |
Project Euler #18 in Python- Beginner | 38,678,131 | <p>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.</p>
<pre><code>3
7 4
2 4 6
8 5 9 3
</code></pre>
<p>That is, 3 + 7 + 4 + 9 = 23.</p>
<p>Find the maximum total from top to bottom of the triangle below:</p>
<pre><code>75
95 6... | 1 | 2016-07-30T20:17:59Z | 38,678,170 | <p>It looks like you always choose the larger number (of left and right) in the next line (This is called a <a href="https://en.wikipedia.org/wiki/Greedy_algorithm" rel="nofollow">greedy algorithm</a>.) But maybe choosing the smaller number first, you could choose larger numbers in the subsequent lines. (And indeed, by... | 0 | 2016-07-30T20:23:19Z | [
"python"
] |
Project Euler #18 in Python- Beginner | 38,678,131 | <p>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.</p>
<pre><code>3
7 4
2 4 6
8 5 9 3
</code></pre>
<p>That is, 3 + 7 + 4 + 9 = 23.</p>
<p>Find the maximum total from top to bottom of the triangle below:</p>
<pre><code>75
95 6... | 1 | 2016-07-30T20:17:59Z | 38,678,252 | <p>Your approach is incorrect. You can't just do a greedy algorithm. Consider the example:</p>
<pre><code>3
7 4
2 4 6
8 5 9 500
</code></pre>
<p>Clearly:</p>
<pre><code>3 + 7 + 4 + 9 = 23 < 500 + (other terms here)
</code></pre>
<p>Yet you follow this algorithm.</p>
<p>However if the triangle were just:</p>
<p... | 1 | 2016-07-30T20:36:07Z | [
"python"
] |
Project Euler #18 in Python- Beginner | 38,678,131 | <p>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.</p>
<pre><code>3
7 4
2 4 6
8 5 9 3
</code></pre>
<p>That is, 3 + 7 + 4 + 9 = 23.</p>
<p>Find the maximum total from top to bottom of the triangle below:</p>
<pre><code>75
95 6... | 1 | 2016-07-30T20:17:59Z | 38,679,464 | <p>You can reach each cell only from the adjacent (at most) three cells on the top line, and the most favorable will be the one with the highest number among these, you don't need to keep track of the others. </p>
<p>I put an example of the code. This works for the pyramid aligned to the left as in your question (the ... | 0 | 2016-07-30T23:34:37Z | [
"python"
] |
Use Pandas dataframe to add lag feature from MultiIindex Series | 38,678,246 | <p>I have a MultiIndex Series (3 indices) that looks like this:</p>
<pre><code>Week ID_1 ID_2
3 26 1182 39.0
4767 42.0
31393 20.0
31690 42.0
32962 3.0
....................................
</c... | 1 | 2016-07-30T20:34:57Z | 38,678,549 | <p>Increase the <code>Week</code> by 2:</p>
<pre><code>saved_groupby = df.groupby(['Week', 'ID_1', 'ID_2'])['Target'].median()
saved_groupby = saved_groupby.reset_index()
saved_groupby['Week'] = saved_groupby['Week'] + 2
</code></pre>
<p>and then merge <code>df</code> with <code>saved_groupby</code>:</p>
<pre><code>... | 3 | 2016-07-30T21:13:30Z | [
"python",
"pandas",
"dataframe",
"data-science"
] |
SqlAlchemy: How to implement DROP TABLE ... CASCADE? | 38,678,336 | <p>I need to drop tables in a PostgreSQL database that have foreign key constraints and require <code>DROP TABLE ... CASCADE</code>.</p>
<p>I could execute raw SQL: <code>engine.execute("DROP TABLE %s CASCADE;" % table.name)</code>.
However, I would like to implement this behaviour such that I can do <code>table.drop(... | 1 | 2016-07-30T20:45:17Z | 38,678,459 | <p>You need the data in <code>pg_constraint</code>, which is <a href="https://www.postgresql.org/docs/current/static/catalog-pg-constraint.html" rel="nofollow">a rather complicated table</a>, that handles all constraints, including check constraints and foreign keys. Fortunately, what you want is fairly straightforward... | 1 | 2016-07-30T21:01:32Z | [
"python",
"postgresql",
"sqlalchemy"
] |
SqlAlchemy: How to implement DROP TABLE ... CASCADE? | 38,678,336 | <p>I need to drop tables in a PostgreSQL database that have foreign key constraints and require <code>DROP TABLE ... CASCADE</code>.</p>
<p>I could execute raw SQL: <code>engine.execute("DROP TABLE %s CASCADE;" % table.name)</code>.
However, I would like to implement this behaviour such that I can do <code>table.drop(... | 1 | 2016-07-30T20:45:17Z | 38,679,457 | <p>You can <a href="http://docs.sqlalchemy.org/en/latest/core/compiler.html#changing-compilation-of-types" rel="nofollow">customize the compilation of constructs</a> like this:</p>
<pre><code>from sqlalchemy.schema import DropTable
from sqlalchemy.ext.compiler import compiles
@compiles(DropTable, "postgresql")
def _c... | 2 | 2016-07-30T23:34:18Z | [
"python",
"postgresql",
"sqlalchemy"
] |
Python 3 parse PDF from web | 38,678,377 | <p>I was trying to get a PDF from a webpage, parse it and print the result to the screen using <a href="https://github.com/mstamy2/PyPDF2" rel="nofollow">PyPDF2</a>. I got it working without issues with the following code:</p>
<pre><code>with open("foo.pdf", "wb") as f:
f.write(requests.get(buildurl(jornal, date, ... | 0 | 2016-07-30T20:50:59Z | 38,678,451 | <p>Use io to fake the use of a file (Python 3):</p>
<pre><code>import io
output = io.BytesIO()
output.write(requests.get(buildurl(jornal, date, page)).content)
output.seek(0)
pdf_reader = PyPDF2.PdfFileReader(output)
</code></pre>
<p>I did not test in your context but I tested this simple example and it worked:</p>
... | 0 | 2016-07-30T21:00:22Z | [
"python",
"pdf",
"python-requests",
"pypdf2"
] |
Python 3 parse PDF from web | 38,678,377 | <p>I was trying to get a PDF from a webpage, parse it and print the result to the screen using <a href="https://github.com/mstamy2/PyPDF2" rel="nofollow">PyPDF2</a>. I got it working without issues with the following code:</p>
<pre><code>with open("foo.pdf", "wb") as f:
f.write(requests.get(buildurl(jornal, date, ... | 0 | 2016-07-30T20:50:59Z | 38,678,468 | <p>You have to convert the returned <code>content</code> to a file-like object using <code>BytesIO</code>:</p>
<pre><code>import io
pdf_content = io.BytesIO(requests.get(buildurl(jornal, date, page)).content)
pdf_reader = PyPDF2.PdfFileReader(pdf_content)
</code></pre>
| 1 | 2016-07-30T21:03:11Z | [
"python",
"pdf",
"python-requests",
"pypdf2"
] |
How to wait for response from modal window before continuing using tkinter? | 38,678,415 | <p>I have a python program in which I've created a few custom modal windows that are children of a top level tkinter window. An example of such a window is below, but I have other, more complicated ones. What I would like to do, but cannot determine how, is to have somewhere that I call this and wait for a response. I'... | 0 | 2016-07-30T20:55:22Z | 38,679,126 | <p>After some further digging, I found my own answer. The following does what I want. The function <code>wait_window</code> accepts a tkinter window and pauses until that window has been closed.</p>
<pre><code>root = tk.Tk()
modal = ModalWindow(root, 'Title', 'Text')
root.wait_window(modal.modalWindow)
if modal.choice... | 1 | 2016-07-30T22:39:20Z | [
"python",
"tkinter",
"modal-dialog"
] |
How to wait for response from modal window before continuing using tkinter? | 38,678,415 | <p>I have a python program in which I've created a few custom modal windows that are children of a top level tkinter window. An example of such a window is below, but I have other, more complicated ones. What I would like to do, but cannot determine how, is to have somewhere that I call this and wait for a response. I'... | 0 | 2016-07-30T20:55:22Z | 38,679,640 | <p>I am missing something fundamental here. If the window is application-modal, you're forced to wait: there's nothing programmatic to be done. If you're trying to wait for an event that transpires in a window belonging to ANOTHER application, you're hosed unless you write some thorny OLE code (I assume Windows here,... | 0 | 2016-07-31T00:11:34Z | [
"python",
"tkinter",
"modal-dialog"
] |
Pyplot: changing color depending on class | 38,678,431 | <p>I have an array of values with their associated class labels (0 or 1). I'd like to change the colour of the plotted values based on their class labels.
I'm using the matplotlib.pyplot plot function to plot the values:</p>
<pre><code>plt.plot(data[0])
</code></pre>
<p>For each value the associated class labels are... | 0 | 2016-07-30T20:56:51Z | 38,678,560 | <p>You could split it in two different data sets:</p>
<pre><code>xx0 = class_labels == 0
xx1 = class_labels == 1
data_class_0 = data[0].copy()
data_class_0[xx1] = np.nan
data_class_1 = data[0].copy()
data_class_1[xx0] = np.nan
plt.plot(data_class_0, 'b')
plt.plot(data_class_1, 'r')
</code></pre>
| 1 | 2016-07-30T21:15:22Z | [
"python",
"matplotlib",
"classification"
] |
Random list generates as blocks not individual lines | 38,678,465 | <p>I am attempting to write a piece of code which does probability calculations based on the National lottery.
But I am having an issue with the way the code runs.<br>
It prints out each one 5 times rather than creating a new set of random numbers, does anyone know why?</p>
<pre><code>gen = True
while gen == True:
#... | 1 | 2016-07-30T21:02:36Z | 38,678,522 | <p>i'm not sure i understood the purpose of this program, However i saw you printed the <code>g,h,i,j,k,l</code> variables in the second loop, causing the last iteration values to be printed with the same value.</p>
<p>If the purpose is to print these values, place the ticket print in the tickets for loop:</p>
<pre><... | 0 | 2016-07-30T21:09:40Z | [
"python",
"loops",
"numbers"
] |
Combining lists from function that returns lists using list comprehensions | 38,678,486 | <p>I want to populate three lists: <code>A</code>, <code>B</code> and <code>C</code></p>
<p>I have a function that based on a singular input returns N objects that should append to each list. That is, <code>f</code> returns <code>stuff_for_A</code>, <code>stuff_for_B</code>, <code>stuff_for_C</code> where each <code>s... | 0 | 2016-07-30T21:04:43Z | 38,678,652 | <p>Extend A, B, C directly, without returning things?</p>
<pre><code>iterable = range(10)
A, B, C = [], [], []
def f(item):
A.extend([item * 2])
B.extend([item * 3])
C.extend([item * 4])
map(f, iterable)
print A
print B
print C
</code></pre>
<p><a href="https://repl.it/Chl6" rel="nofollow">https://repl.... | 0 | 2016-07-30T21:26:35Z | [
"python",
"python-2.7"
] |
Combining lists from function that returns lists using list comprehensions | 38,678,486 | <p>I want to populate three lists: <code>A</code>, <code>B</code> and <code>C</code></p>
<p>I have a function that based on a singular input returns N objects that should append to each list. That is, <code>f</code> returns <code>stuff_for_A</code>, <code>stuff_for_B</code>, <code>stuff_for_C</code> where each <code>s... | 0 | 2016-07-30T21:04:43Z | 38,678,664 | <p>It appears that you want the same result as</p>
<pre><code>A = [create_A_list(input) for input in iterable]
B = [create_B_list(input) for input in iterable]
C = [create_C_list(input) for input in iterable]
</code></pre>
<p>but with only one pass over <code>iterable</code>. With an explicit <code>for</code> loop, y... | 1 | 2016-07-30T21:28:39Z | [
"python",
"python-2.7"
] |
Combining lists from function that returns lists using list comprehensions | 38,678,486 | <p>I want to populate three lists: <code>A</code>, <code>B</code> and <code>C</code></p>
<p>I have a function that based on a singular input returns N objects that should append to each list. That is, <code>f</code> returns <code>stuff_for_A</code>, <code>stuff_for_B</code>, <code>stuff_for_C</code> where each <code>s... | 0 | 2016-07-30T21:04:43Z | 38,678,670 | <p>To create the lists from the <em>returned</em> tuples, you can use that multiple assignment with <code>zip</code> and <em>unpacking</em> on a generator expression:</p>
<pre><code>def f(input):
...
return stuff_for_A,stuff_for_B,stuff_for_C
A, B, C = zip(*(f(input) for input in iterable))
</code></pre>
<p>... | 1 | 2016-07-30T21:29:07Z | [
"python",
"python-2.7"
] |
Combining lists from function that returns lists using list comprehensions | 38,678,486 | <p>I want to populate three lists: <code>A</code>, <code>B</code> and <code>C</code></p>
<p>I have a function that based on a singular input returns N objects that should append to each list. That is, <code>f</code> returns <code>stuff_for_A</code>, <code>stuff_for_B</code>, <code>stuff_for_C</code> where each <code>s... | 0 | 2016-07-30T21:04:43Z | 38,678,672 | <p>If <code>A</code>, <code>B</code>, and <code>C</code> exist, the following will update them with the returned values from <code>f</code>:</p>
<p><code>list(map(lambda x: x[0].extend(x[1]), zip([A,B,C], f())))</code></p>
<p><code>list</code> is called, cause <code>map</code> is lazy in python 3.</p>
| 1 | 2016-07-30T21:29:30Z | [
"python",
"python-2.7"
] |
Merge every dataframe in a folder | 38,678,520 | <p>I have <code>.csv</code> files within multiple folders which look like this:</p>
<p>File1</p>
<pre><code>Count 2002_Crop_1 2002_Crop_2 Ecoregion
20 Corn Soy 46
15 Barley Oats 46
</code></pre>
<p>File 2</p>
<pre><code>Count 2003_Crop_1 2003_Crop_2 Ecoreg... | 1 | 2016-07-30T21:09:00Z | 38,678,829 | <ul>
<li><p>Use <code>glob.glob</code> to <a href="http://stackoverflow.com/a/7159726/190597">traverse a directory at a fixed depth</a>.</p></li>
<li><p>Try to avoid calling <code>pd.merge</code> repeatedly if you can help it. Each call to <code>pd.merge</code> creates a new DataFrame. So all the data in each intermedi... | 2 | 2016-07-30T21:54:52Z | [
"python",
"csv",
"pandas"
] |
Saving Add to cart items in django models | 38,678,623 | <p>So I am creating something like an e-commerce platform. I am building the project using Django.</p>
<p>Now I have to make an Add to Cart feature. How should I make the model so that I can store the things added to the cart in my table that is connected to user table using foreignkey.</p>
<p>Specifically, I want to... | 0 | 2016-07-30T21:23:00Z | 38,678,798 | <p>There is no sense to store such information on a backend. I most cases you can use <code>cookies</code> or <code>localstorage</code>.</p>
<p>But if you want store this information for registered users, device independent, you should create Model with FK to users table and Use that.</p>
<p><strong>Answer:</strong>
... | 0 | 2016-07-30T21:48:36Z | [
"python",
"django",
"django-models",
"e-commerce",
"cart"
] |
Iterate in 2 different dictionaries simultaneously in Python | 38,678,686 | <p>---EDIT 2---
So I get the question Why I use dictionaries?,
this question is a follow up on this one: <a href="http://stackoverflow.com/questions/38647250/csv-file-compression-without-using-existing-libraries-in-python/38662750#38662750">csv file compression without using existing libraries in Python</a></p>
<p>I ... | 1 | 2016-07-30T21:32:11Z | 38,678,779 | <p>You can speed up the lookup by inverting the keys and values in the <code>ticks</code> and <code>symbs</code> dicts and then just looking up the right values instead of iterating and comparing all the values in the dicts:</p>
<pre><code>ticks_inv = {v: k for k, v in ticks.items()}
symbs_inv = {v: k for k, v in symb... | 0 | 2016-07-30T21:45:35Z | [
"python",
"list",
"for-loop",
"dictionary",
"iteration"
] |
Iterate in 2 different dictionaries simultaneously in Python | 38,678,686 | <p>---EDIT 2---
So I get the question Why I use dictionaries?,
this question is a follow up on this one: <a href="http://stackoverflow.com/questions/38647250/csv-file-compression-without-using-existing-libraries-in-python/38662750#38662750">csv file compression without using existing libraries in Python</a></p>
<p>I ... | 1 | 2016-07-30T21:32:11Z | 38,678,794 | <p>So first of all you want to <strong>reverse</strong> the mapping, you are currently looking by value, which is wrong and slow:</p>
<pre><code>ticks = {0: '6NH8', 1: '6AH8', 2: 'QMH8'}
symbs = {0: 'F,A', 1: 'F,B'}
</code></pre>
<p>Using <code>ticks = {v: k for k, v in ticks.items()}</code> (same for <code>symbs</co... | 1 | 2016-07-30T21:48:16Z | [
"python",
"list",
"for-loop",
"dictionary",
"iteration"
] |
Iterate in 2 different dictionaries simultaneously in Python | 38,678,686 | <p>---EDIT 2---
So I get the question Why I use dictionaries?,
this question is a follow up on this one: <a href="http://stackoverflow.com/questions/38647250/csv-file-compression-without-using-existing-libraries-in-python/38662750#38662750">csv file compression without using existing libraries in Python</a></p>
<p>I ... | 1 | 2016-07-30T21:32:11Z | 38,678,817 | <p>Your dictionary is backwards; it's not using the dictionary's key-lookup feature. Instead of </p>
<pre><code>for ticksKey, ticksValue in ticks.items():
if values[0] == ticksValue:
values[0] = ticksKey
</code></pre>
<p>try</p>
<pre><code>ticks = {'6NH8': 0, '6AH8': 1, 'QMH8': 2}
...
if values[0] in ti... | 0 | 2016-07-30T21:52:36Z | [
"python",
"list",
"for-loop",
"dictionary",
"iteration"
] |
'module' object has no attribute 'questiоn'. Class name considered an attribute? | 38,678,740 | <p>I'm trying to make a quiz for my project and I'm getting this error: <code>AttributeError: 'module' object has no attribute 'question'</code>. I don't understand why it thinks my class is an attribute. </p>
<ul>
<li><p>questionbf.py is where I made the binary file.</p></li>
<li><p>quizbf.py is where I'm trying to m... | 0 | 2016-07-30T21:40:35Z | 38,679,161 | <p>When you pickle an instance of a class the class name is saved in the pickle to allow the reading program to import the necessary module and gain access to the required class. Unfortunately the class whose elements you are pickling is in the <code>__main__</code> module, which is the name Python gives to the module ... | 0 | 2016-07-30T22:44:46Z | [
"python",
"python-2.7"
] |
Batch executed by Python script is acting like it is in the script's folder | 38,678,745 | <p>I run the batch(it is in different folder than the python script) the using following line of code:</p>
<pre><code>subprocess.Popen("the_bat.bat", creationflags=subprocess.CREATE_NEW_CONSOLE)
</code></pre>
<p>The job of the batch is to launch a .jar(same directory as batch) which creates folders and files in it's ... | -2 | 2016-07-30T21:40:53Z | 38,679,019 | <p>This is because the bash script is executed in Python's working directory, which makes the bash script's working directory the same one as Python's. You can fix this by passing a current working directory to the <code>subprocess.Popen</code>.</p>
<p><code>subprocess.Popen(r'your script', cwd=r'd:\the\working\direct... | 0 | 2016-07-30T22:23:22Z | [
"python",
"windows",
"batch-file",
"jar"
] |
AttributeError: 'unicode' object has no attribute 'isPalindrome' | 38,678,784 | <p>I'm new to Python thus the question,</p>
<p>I'm trying to solve a simple algorithmic problem of finding the longest palindromic substring given a string.</p>
<p>This is my code.</p>
<pre><code>class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
... | 0 | 2016-07-30T21:46:27Z | 38,678,799 | <p>You should call the method using the <em>self</em> reference. That would be:</p>
<pre><code>if self.isPalindrome(sub):
curr = max(curr, len(sub))
</code></pre>
<p><code>sub.isPalindrome()</code> will not work because the method is not bound to the unicode/string object</p>
| 1 | 2016-07-30T21:48:49Z | [
"python"
] |
Close a tkinter GUI after a period of time | 38,678,859 | <p>I want to create a GUI that shows a message and it is automatically destroyed after some time. I saw this question in different posts but none of the solutions proposed worked out for my App. Here a small part of the code</p>
<pre><code>class MessageShort(tkSimpleDialog.Dialog):
def __init__(self, parent, text, ti... | 0 | 2016-07-30T21:58:12Z | 38,679,044 | <p>Create a timer and set destroying the root as it's callback:</p>
<pre><code>from threading import Timer
import time
def called_after_timer():
if(root != None):
root.destroy()
t = Timer(20 * 60, called_after_timeout)
t.start()
# do something else, such as
time.sleep(1500)
</code></pre>
| 0 | 2016-07-30T22:27:33Z | [
"python",
"tkinter",
"destroy"
] |
Close a tkinter GUI after a period of time | 38,678,859 | <p>I want to create a GUI that shows a message and it is automatically destroyed after some time. I saw this question in different posts but none of the solutions proposed worked out for my App. Here a small part of the code</p>
<pre><code>class MessageShort(tkSimpleDialog.Dialog):
def __init__(self, parent, text, ti... | 0 | 2016-07-30T21:58:12Z | 38,683,158 | <p>Finally I got something that seems to work</p>
<p>class MessageShort(tkSimpleDialog.Dialog):</p>
<pre><code> def __init__(self, parent, text, time):
self.top=Toplevel.__init__(self, parent)
self.transient(parent)
self.parent = parent
self.text=text
self.time=time
... | 0 | 2016-07-31T10:45:13Z | [
"python",
"tkinter",
"destroy"
] |
Middleware in flask | 38,678,864 | <p>I just stated using Flask and was trying to implement a small feature in my project. The objective is to set a cookie only if the request comes from a authenticated user.</p>
<p>I found two ways of doing this. </p>
<p>First method</p>
<pre><code>@app.before_request
def before_request():
# set cookie if user is... | 1 | 2016-07-30T21:58:58Z | 38,695,915 | <p>I've never used the second method you've mentioned. I'm sure that it can be done with it, but it's very uncommon. I would suggest to use more common features of flask. For sake of maintainers of your code :)
So the first method you've mentioned is fine.</p>
<p>Or you can use <a href="http://flask.pocoo.org/docs/0.1... | 0 | 2016-08-01T09:56:11Z | [
"python",
"cookies",
"flask",
"middleware"
] |
Error while reading Boston data from UCL website using pandas | 38,678,882 | <p>Any help please for reading this file from url website.</p>
<pre><code>eurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data'
data = pandas.read_csv(url, sep=',', header = None)
</code></pre>
<p>I tried sep=',', sep=';' and sep='\t' but the data read like this
<a href="http://i.st... | 0 | 2016-07-30T22:02:12Z | 38,678,908 | <p>There are multiple spaces used as a delimiter, that's why it's not working when you use a single space as a delimiter (<code>sep=' '</code>)</p>
<p>you can do it using <code>sep='\s+'</code>:</p>
<pre><code>In [171]: data = pd.read_csv(url, sep='\s+', header = None)
In [172]: data.shape
Out[172]: (506, 14)
In [1... | 1 | 2016-07-30T22:06:31Z | [
"python",
"python-2.7",
"csv",
"pandas"
] |
pandas time interval to time series | 38,678,955 | <p>How do i transform time interval data into time series data using Python (and pandas)? </p>
<p>Here's my before data frame as time intervals:</p>
<pre><code>code start_dt end_dt ent_value
156600 1960-01-01 2016-04-21 H:CXP
156600 1960-01-01 2016-01-03 46927
156600 ... | 1 | 2016-07-30T22:14:59Z | 38,679,444 | <p>First, try by yourself!
Then, if you do not succeed, this is a possible solution.</p>
<blockquote class="spoiler">
<p> <pre>
<code>data = pd.read_csv(open('/tmp/test.tab', 'r'), sep='\t')</code>
<code>tmp = [(e.code, pd.date_range(e.start_dt, e.end_dt, freq='1D'),</code>
<code>e.ent_value) for e in data.itertuple... | 1 | 2016-07-30T23:32:52Z | [
"python",
"pandas"
] |
pandas time interval to time series | 38,678,955 | <p>How do i transform time interval data into time series data using Python (and pandas)? </p>
<p>Here's my before data frame as time intervals:</p>
<pre><code>code start_dt end_dt ent_value
156600 1960-01-01 2016-04-21 H:CXP
156600 1960-01-01 2016-01-03 46927
156600 ... | 1 | 2016-07-30T22:14:59Z | 38,679,529 | <p>try this:</p>
<pre><code>In [17]: %paste
(df.groupby(['code','ent_value'])
.apply(lambda x: pd.DataFrame({'as_of_dt':pd.date_range(x.start_dt.min(), x.end_dt.max())}))
.reset_index()
.drop('level_2', 1)
)
## -- End pasted text --
Out[17]:
code ent_value as_of_dt
0 156600 4501242 1960-01-0... | 0 | 2016-07-30T23:47:38Z | [
"python",
"pandas"
] |
Running a python script from another script while passing args from another script/json generated by script? | 38,679,109 | <p>So I have 3 scripts, for the sake of simplicity lets call them a.py,b.py, and c.py</p>
<p>now a.py creates a json containing some data i want to pass to b which uses this data to create another json containing another related subset of data
and I want to do this action from c.py. how can I go about getting b to rea... | 0 | 2016-07-30T22:36:21Z | 38,679,477 | <p>(From comments to question)</p>
<p>Consider the following files:</p>
<pre><code>#-- b.py ----------------------------------------------------------------------------------
def main():
name = input("Enter your name: ") # Python 3, use raw_input for Python 2
print("Your name is:", name)
#-- a.py --... | 2 | 2016-07-30T23:37:34Z | [
"python"
] |
AttributeError: __exit__ while buffering downloaded image on python 2.7 | 38,679,194 | <p>I'm trying to automate captcha file recognition with a python script.
However, after several days of efforts my functions seems to be far from desired result. </p>
<p>Furthermore, the traceback I've got is not informative enough to help me investigate further.</p>
<p>Here is my function:</p>
<pre><code>def getmsg... | -2 | 2016-07-30T22:50:30Z | 38,679,217 | <p><code>imagebuf</code> is not a <a href="https://docs.python.org/2/library/stdtypes.html#context-manager-types" rel="nofollow">context manager</a>. You can't use it in a <code>with</code> statement, which tests for a context manager by first storing the <a href="https://docs.python.org/2/library/stdtypes.html#context... | 0 | 2016-07-30T22:53:02Z | [
"python",
"image",
"python-2.7",
"python-imaging-library",
"buffering"
] |
numpy diff weird behaviour | 38,679,215 | <p>I have a case of strange behaviour of numpy diff:</p>
<pre><code>a = list(img_arr[y_coord_1,:])
print a
print np.diff(a)
>>[62, 62, 62, 62, 62, 62, 62, 62, 63, 62, 96, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 9... | 3 | 2016-07-30T22:52:52Z | 38,679,528 | <p><code>.tolist()</code> is a better way of converting an array to a list (or nested lists). It carries the conversion all the way down. <code>list()</code> just iterates on one level. And since an array is already iterable, I don't think <code>list(anarray)</code> does anything useful.</p>
<p>start with an array:... | 2 | 2016-07-30T23:47:36Z | [
"python",
"numpy"
] |
Trying to capture a particular pattern with regular expressions (Python 3.4) | 38,679,238 | <p>The pattern I'm trying to capture is along the lines of:</p>
<pre><code>Coin: gp (3840)
</code></pre>
<p>"gp" can be replaced with "cp", "sp", or "pp", and there can be any string of digits inside the parentheses. The pattern I came up with is:</p>
<pre><code>"Coin: 'cp|sp|gp|pp' \(\d+\)"
</code></pre>
<p>Howeve... | 1 | 2016-07-30T22:55:51Z | 38,679,267 | <p>You have pattern matching different options wrong: <code>'cp|sp|gp|pp'</code> It's trying to match the literal character <code>'</code>.</p>
<p>Your regex should really be something like:</p>
<pre><code>>>> re.match("Coin: (?:cp|sp|gp|pp) \(\d+\)", "Coin: gp (3840)")
</code></pre>
<p>The expression <code... | 4 | 2016-07-30T22:59:43Z | [
"python",
"regex",
"python-3.x"
] |
using opencv with zbar in python on windows 8.1 to detect qr codes | 38,679,301 | <p>I am using opencv version 3.1.0 with zbar (latest version as of this post) and PIL (latest version as of this post)</p>
<pre><code>import zbar
import Image
import cv2
# create a reader
scanner = zbar.ImageScanner()
# configure the reader
scanner.parse_config('enable')
#create video capture feed
cap = cv2.VideoCapt... | 0 | 2016-07-30T23:05:27Z | 38,679,701 | <p>zbar works with grayscale images. Change <code>cv = cv2.cvtColor(cv, cv2.COLOR_BGR2RGB)</code> to <code>cv = cv2.cvtColor(cv, cv2.COLOR_BGR2GRAY)</code>.</p>
<p>I'm guessing you're using <a href="https://github.com/herbyme/zbar/blob/3687df80d2a9cd0f95bb293426827d5bf2f8dcbe/python/examples/scan_image.py" rel="nofoll... | 0 | 2016-07-31T00:22:12Z | [
"python",
"opencv",
"python-imaging-library",
"qr-code",
"zbar"
] |
python based IP address calculator (IPCALC) code | 38,679,383 | <p>I've the python CGI for user entered input for IP address calculation but python ipcalc is not taking input as a variable, for example I'm trying to run this code</p>
<pre><code>>>> import ipcalc
>>> ip='10.84.35.11'
>>> mask=24
>>> print ip
10.84.35.11
>>> print mas... | 1 | 2016-07-30T23:22:32Z | 38,679,403 | <p>You probably want a string representing a network:</p>
<pre><code>subnet = ipcalc.Network("%s/%d" % (ip, mask))
</code></pre>
<p>Right now you're trying to use the <code>/</code> operator on <code>str</code> and <code>int</code> which is not defined (as the error says).</p>
| 1 | 2016-07-30T23:25:53Z | [
"python",
"ip",
"ip-address"
] |
Adding nodes to a linked list in Python | 38,679,388 | <p>The addToList() function takes a value as an argument. Values are passed to the addToList() function many times consecutively. </p>
<pre><code>def addToList(value):
node = {}
node["data"] = value
node["next"] = None
head = node
</code></pre>
<p>The question is: how do I create many different nodes?... | 0 | 2016-07-30T23:23:11Z | 38,679,435 | <p>the easy answer to your question to make each node point to correct next is to make your function as</p>
<pre><code>def addToList(value):
node = {}
node["data"] = value
node["next"] = None
head[next] = node
head = node
</code></pre>
<p>but you need to keep track of the real head of your list so... | -1 | 2016-07-30T23:30:51Z | [
"python",
"linked-list",
"nodes"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.