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 |
|---|---|---|---|---|---|---|---|---|---|
file name is variable - does not write to file | 37,554,500 | <p>I have a large file about some populations (columns and rows). And I want to read the file and extract some information and write a script to create a single file for each population.</p>
<p>The issue now when I want to write to each population file "variable name"
just <strong>the last row</strong> of the large fi... | 0 | 2016-05-31T19:52:46Z | 37,554,891 | <p>Your code will write a file only when the name stored in 'item' is the same as the one stored in 'pop'. Probably you want to generate several files so the code, maybe, should be:</p>
<pre><code>if item == 'population': # exclude the header of the column
continue
else:
with ...
</code></pre>
| 0 | 2016-05-31T20:17:06Z | [
"python",
"file"
] |
NameError: global name 'x' is not defined | 37,554,618 | <p>i'm getting</p>
<pre><code>NameError: global name 'Ontologia' is not defined
</code></pre>
<p>The class Ontologia is defined on ontologia.py and I also used</p>
<pre><code>import ontologia
</code></pre>
<p>This is the line that i'm getting the problem</p>
<pre><code>onto = Ontologia()
</code></pre>
<p>The full... | -4 | 2016-05-31T19:58:33Z | 37,555,132 | <p>Python's <a href="https://docs.python.org/3/reference/simple_stmts.html#the-import-statement" rel="nofollow"><code>import</code></a> statement works a bit different from for example Java's <code>import</code> statement.</p>
<p>It's possible to import every public name from a module. If you're interested, the <a hr... | 3 | 2016-05-31T20:33:13Z | [
"python"
] |
got TypeError when running linear regression with tensorflow. ' Op has type float64 that does not match type float32 of argument' | 37,554,633 | <p>I'm pretty new to tensorflow. I did a linear regression with tensorflow.
when I ran the codes below, I got typeError like this:</p>
<p>TypeError: Input 'y' of 'Mul' Op has type float64 that does not match type float32 of argument 'x'.</p>
<p>Spent hours but could not figure out why.
where did it go wrong? help ... | 0 | 2016-05-31T19:59:35Z | 37,554,788 | <p><strong>TL;DR:</strong> The placeholder <code>X</code> and variable <code>w</code> have different element types, and TensorFlow does not automatically cast op arguments, so the <code>tf.mul()</code> op fails.</p>
<p>Your placeholder <code>X</code> has type <code>tf.float32</code> because it is defined to have dtype... | 0 | 2016-05-31T20:09:47Z | [
"python",
"tensorflow"
] |
Thumbor On Heroku causes heroku time out when fetching URL returns 404 | 37,554,692 | <p>We are hosting our thumbor image resizing service on Heroku, with image store in aws s3. The Thumbor service access s3 via the aws plugin.
Recently we observe a behavior on our thumbor service which I don't understand.</p>
<p>Use case: our client application was sending a resize request to resize an image that does... | 0 | 2016-05-31T20:03:45Z | 37,598,908 | <p>This issue on the tc_aws library we are using. It wasn't executing callback functions when 404 is returned from S3. We were at version 2.0.10. After upgrade the library, the problem is fixed.</p>
| 0 | 2016-06-02T17:52:21Z | [
"python",
"heroku",
"amazon-s3",
"timeout",
"thumbor"
] |
How to update QLabel in while loop | 37,554,696 | <p>It feels like I should just be able to set up an event listener that runs an AJAX like call to update a qlabel but this seems to be endlessly complicated with QT.</p>
<p>Basically what I'm attempting to do is update the text in a QLabel. This happens on an infinite loop that breaks when a button is clicked (AKA som... | 0 | 2016-05-31T20:03:56Z | 37,555,978 | <p>In <code>Qt/PyQt</code>, the method for triggering callbacks is the Signal/Slot system. Generally, if you need to continuously do some operation, and occasionally update the GUI based on that operation, you would create a worker thread that sends updates back to the main thread using <code>Signals</code>. For exam... | 4 | 2016-05-31T21:31:58Z | [
"python",
"qt",
"pyqt",
"pyside"
] |
Implementation of a function that finds the minimum of two values | 37,554,726 | <pre><code>def minimum (pNum1,pNum2):
#subprogram here
return ()
inNum = int (input ("Please enter a number. 0 to quit."))
minNum = inNum
maxNum = inNum
while (inNum !=0):
# ===> minNum = # here is where I will call the subprogram.
# ===> maxNum =
# ===> theSum =
inNum = int (input ("Please enter a numbe... | -4 | 2016-05-31T20:05:55Z | 37,554,942 | <p>It's not clear why you want to do that.
You could test which of the variable is the lower :</p>
<pre><code>def minimum (pNum1,pNum2):
if pNum1 < pNum2:
return pNum1
else:
return pNum2
</code></pre>
| 0 | 2016-05-31T20:20:13Z | [
"python",
"function"
] |
Implementation of a function that finds the minimum of two values | 37,554,726 | <pre><code>def minimum (pNum1,pNum2):
#subprogram here
return ()
inNum = int (input ("Please enter a number. 0 to quit."))
minNum = inNum
maxNum = inNum
while (inNum !=0):
# ===> minNum = # here is where I will call the subprogram.
# ===> maxNum =
# ===> theSum =
inNum = int (input ("Please enter a numbe... | -4 | 2016-05-31T20:05:55Z | 37,555,082 | <p>This is an implementation of a function that finds the minimum of two values:</p>
<pre><code>def minimum(pNum1, pNum2):
if pNum1 < pNum2:
return pNum1
else:
return pNum2
</code></pre>
<p>A program to find the minimum, maximum, and the sum:</p>
<pre><code>inNum = int(input("Please enter ... | 0 | 2016-05-31T20:29:25Z | [
"python",
"function"
] |
how to group elements in a list based on frequency into a tuple | 37,554,832 | <p>I'm trying to group the similar numbers into one tuple of the form (number,frequency).</p>
<pre><code>l1=[2,2,2,5,5,7]
</code></pre>
<p>How do I convert this list into the list below</p>
<pre><code>l1=[(2,3),(5,2),(7,1)]
</code></pre>
| 2 | 2016-05-31T20:12:48Z | 37,554,875 | <p>You can do this using <a href="https://docs.python.org/2/library/collections.html#counter-objects" rel="nofollow"><code>Counter()</code></a>:</p>
<pre><code>from collections import Counter
l1 = [2, 2, 2, 5, 5, 7]
l1 = Counter(l1).items()
</code></pre>
<p>The "key" is the list element, and the "value" is the occu... | 3 | 2016-05-31T20:16:06Z | [
"python",
"list",
"tuples"
] |
how to group elements in a list based on frequency into a tuple | 37,554,832 | <p>I'm trying to group the similar numbers into one tuple of the form (number,frequency).</p>
<pre><code>l1=[2,2,2,5,5,7]
</code></pre>
<p>How do I convert this list into the list below</p>
<pre><code>l1=[(2,3),(5,2),(7,1)]
</code></pre>
| 2 | 2016-05-31T20:12:48Z | 37,554,920 | <p>Use a <code>Counter</code> like so:</p>
<pre><code>>>> from collections import Counter
>>> l1=[2,2,2,5,5,7]
>>> c = Counter(l1)
>>> c.items()
dict_items([(2, 3), (5, 2), (7, 1)])
</code></pre>
| 2 | 2016-05-31T20:18:58Z | [
"python",
"list",
"tuples"
] |
Trouble retrieving text from XML with ElementTree with tags | 37,554,842 | <p>Right now I have some code which uses Biopython and NCBI's "Entrez" API to get XML strings from Pubmed Central. I'm trying to parse the XML with ElementTree to just have the text from the page. Although I have BeautifulSoup code that does exactly this when I scrape the lxml data from the site itself, I'm switching t... | 0 | 2016-05-31T20:13:29Z | 37,555,515 | <p>root.get() is the wrong method, as it will retrieve an attribute of the root tag not a subtag.
root.find() is correct as it will find the first matching subtag (alternatively one can use root.findall() for <strong>all</strong> matching subtags).</p>
<p>If you want to find not only direct subtags but also indirect s... | 1 | 2016-05-31T20:59:56Z | [
"python",
"xml",
"elementtree"
] |
Plotting DataFrame columns against each other | 37,554,859 | <p>How do I plot <code>DataFrame</code> columns against each other ignoring indices? e.g.</p>
<p>Let a <code>DataFrame</code> <code>df1</code> be as follows:</p>
<pre><code> x y
0 0 5
1 1 10
2 2 15
3 3 20
4 4 25
</code></pre>
<p>I've tried:</p>
<pre><code>import matplotlib.pyplot as plt
import pandas... | 0 | 2016-05-31T20:14:52Z | 37,554,909 | <p>You could:</p>
<pre><code>df1.set_index('x').plot()
</code></pre>
| 1 | 2016-05-31T20:18:28Z | [
"python",
"pandas",
"matplotlib",
"dataframe"
] |
Error in numpy nanmean | 37,554,962 | <p>I have an array with floats and NaNs yet when I call <code>numpy.nanmean()</code> on the array I get <code>NaN</code>as result. How is this possible?</p>
<p>This is a sample of the array <code>ages</code></p>
<pre><code>[22.0 38.0 26.0 35.0 35.0 nan 54.0 2.0 27.0 14.0 4.0 58.0 20.0 39.0 14.0
55.0 2.0 nan 31.0 nan... | 2 | 2016-05-31T20:21:26Z | 37,556,228 | <p>As we figured out in the comments above, having a dtype of <code>numpy.ndarray</code> in a one dimensional list is strange when it appears you only have floats and <code>NaN</code>s in there. This makes me think that you are generating your data in a flawed manner, something like manually creating an array from a f... | 1 | 2016-05-31T21:53:05Z | [
"python",
"python-3.x",
"numpy",
null
] |
How to write a python script that can communicate with the input and output of a swift executable? | 37,555,051 | <p>So, I have a simple swift program, a one file, <code>main.swift</code> program, that looks like this.</p>
<pre><code>import Foundation
var past = [String]()
while true {
let input = readLine()!
if input == "close" {
break
}
else {
past.append(input)
print(past)
}
}
</co... | 3 | 2016-05-31T20:27:18Z | 37,555,230 | <p>I think the following code is what you're looking for. It uses a pipe so you can programmically send data without using command line arguments.</p>
<pre><code>process = subprocess.Popen("./Recommender", shell=True, stdin=subprocess.PIPE)
process.stdin.write(('close').encode())
process.stdin.flush()
</code></pre>
| 2 | 2016-05-31T20:39:38Z | [
"python",
"linux",
"swift",
"shell"
] |
Possible to wrap ActionChains move_to_element() in a method? | 37,555,116 | <p>Using Python and webdriver-- I'm trying to wrap a selenium call for move_to_element() so I can call it in a page object to be used in a test script.</p>
<p>For example, I have:</p>
<pre><code>def find_element(self, locatorMode, Locator):
element = None
if locatorMode == LocatorMode.ID:
element = self.driver.... | 1 | 2016-05-31T20:31:32Z | 37,669,617 | <p>Following advice from <a href="http://stackoverflow.com/a/37576260/5471457">http://stackoverflow.com/a/37576260/5471457</a></p>
<p>I was able to get this working:</p>
<pre><code> def hover_over(self, waitTime, locatorMode, Locator):
element = self.wait_for_element_visibility(waitTime, locatorMode, Locator)
... | 0 | 2016-06-07T02:33:56Z | [
"python",
"selenium"
] |
Is it possible to stream video from https:// (e.g. YouTube) into python with OpenCV? | 37,555,195 | <p><a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html" rel="nofollow">This link</a> has a tidy little example of how to use python's OpenCV library, <code>cv2</code> to stream data from a camera into your python shell. I'm looking to do some experi... | 3 | 2016-05-31T20:37:18Z | 37,823,233 | <p>@incBrain's suggestion to download the youtube video to local mp4 was the way to go here. Here were the steps that I used to set up a remote server environment on EC2, with output piped into my local computer via X11 forwarding: </p>
<ul>
<li><code>ssh -X -i "<ssh_key.pem>" ubuntu@<IP-address>.compute-1... | 1 | 2016-06-14T22:35:28Z | [
"python",
"opencv",
"video",
"youtube"
] |
Python>openCV>numpy>image processing | 37,555,286 | <p>could you please look at this code, and tell me what is wrong with it:</p>
<pre><code>import cv2
import numpy as np
import os
OrigLenna = cv2.imread('Lenna.jpg', 1)
Lenna = cv2.imread('Lenna.jpg',0)
cv2.imshow('Original Lenna', OrigLenna) # <3
cv2.waitKey(0)
cv2.imshow('gray Lenna', Lenna)
cv2.waitKey(0)
cv2.de... | 0 | 2016-05-31T20:44:16Z | 37,555,353 | <p>Sorry I cannot comment. New to Stack overflow and don't have 50 reputations yet.
Either your i or j is going to a value of 512. Array with size 512 has indices 0 to 511. That's what I think. </p>
| 0 | 2016-05-31T20:48:47Z | [
"python",
"image",
"opencv",
"numpy"
] |
How to set a height to some buttons of GridLayout in Kivy Python? | 37,555,377 | <p>I'm working in an app with kivy and I have an issue that involve the <code>GridLayout</code>. I have a screen with different rows and I want the buttons of the last row to have always the same <code>height</code> (11,1% of the height of the Screen). I have tried to modify the attribute height in the buttons but does... | 0 | 2016-05-31T20:50:25Z | 37,555,742 | <p>Try this</p>
<pre><code>class LoginScreen(GridLayout):
def __init__(self,**kwargs):
super(LoginScreen, self).__init__(**kwargs)
self.cols=2
self.add_widget(Label(text='Subject'))
self.add_widget(Label(text=''))
self.add_widget(Label(text='1'))
self.add_widget(TextInput(multiline=False))
... | 0 | 2016-05-31T21:14:34Z | [
"python",
"button",
"height",
"kivy",
"grid-layout"
] |
How to set a height to some buttons of GridLayout in Kivy Python? | 37,555,377 | <p>I'm working in an app with kivy and I have an issue that involve the <code>GridLayout</code>. I have a screen with different rows and I want the buttons of the last row to have always the same <code>height</code> (11,1% of the height of the Screen). I have tried to modify the attribute height in the buttons but does... | 0 | 2016-05-31T20:50:25Z | 37,562,853 | <p>If you want a widget in a grid/box layout to have a fixed size, you should set its <code>size_hint</code> to <code>None</code> first. And always use kivy lang at such tasks - no exceptions.</p>
<pre><code>from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.lang import Builder
gui = '''
Lo... | 1 | 2016-06-01T08:04:10Z | [
"python",
"button",
"height",
"kivy",
"grid-layout"
] |
Unicode arabic string to user it | 37,555,473 | <p>i have a variable holding a value like <code>x='Ù
صطÙÙ'</code> and i want to convert it to the form of <code>u'Ù
صطÙÙ'</code> to user it again in some functions .. when i try to do <code>u''+x</code> it alawys give me an error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in posi... | 0 | 2016-05-31T20:57:31Z | 37,555,596 | <p>thanks I solved it :) </p>
<p>the solution will be to do so </p>
<pre><code>u''.encode('utf-8')+x
</code></pre>
| 0 | 2016-05-31T21:05:20Z | [
"python",
"python-2.7",
"unicode",
"decode"
] |
Unicode arabic string to user it | 37,555,473 | <p>i have a variable holding a value like <code>x='Ù
صطÙÙ'</code> and i want to convert it to the form of <code>u'Ù
صطÙÙ'</code> to user it again in some functions .. when i try to do <code>u''+x</code> it alawys give me an error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in posi... | 0 | 2016-05-31T20:57:31Z | 37,557,748 | <p>There's two things.</p>
<p>First the meaning of <code>x='Ù
صطÙÙ'</code> is ill-defined, and changes if you save your source file in another encoding. On the other hand <code>x=u'Ù
صطÙÙ'.encode('utf-8')</code> unambiguously means âthe bytes you get when you encode that text with UTF-8â.</p>
<p>Second, e... | 1 | 2016-06-01T00:42:48Z | [
"python",
"python-2.7",
"unicode",
"decode"
] |
Unicode arabic string to user it | 37,555,473 | <p>i have a variable holding a value like <code>x='Ù
صطÙÙ'</code> and i want to convert it to the form of <code>u'Ù
صطÙÙ'</code> to user it again in some functions .. when i try to do <code>u''+x</code> it alawys give me an error:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in posi... | 0 | 2016-05-31T20:57:31Z | 37,558,309 | <p>You have to know what encoding those bytes are in, and them <code>.decode(encoding)</code> them to get a Unicode string. If you received them from some API, <code>utf8</code> is a good guess. If you read the bytes from a file typed in Windows Notepad, it is more likely some Arabic(?) code page.</p>
<pre><code>Pyt... | 1 | 2016-06-01T02:05:16Z | [
"python",
"python-2.7",
"unicode",
"decode"
] |
How to extract a list of items using scrapely? | 37,555,487 | <p>I'm using scrapely to extract data from some HTML, but I'm having difficulties extracting a list of items.</p>
<p>The <a href="https://github.com/scrapy/scrapely" rel="nofollow">scrapely github project</a> describes only a simple example:</p>
<pre><code>from scrapely import Scraper
s = Scraper()
s.train(url, data... | 2 | 2016-05-31T20:58:27Z | 37,654,635 | <p>Scrapely can extract lists of items from structures lists (e.g. <code><ul></code> or <code><ol></code>) â see <a href="http://stackoverflow.com/a/37654688/754456">the other answer</a>. However, because it extracts content using HTML/document fragments it is not able to extract text-formatted data conta... | 3 | 2016-06-06T10:04:46Z | [
"python",
"data-extraction",
"scrapely"
] |
How to extract a list of items using scrapely? | 37,555,487 | <p>I'm using scrapely to extract data from some HTML, but I'm having difficulties extracting a list of items.</p>
<p>The <a href="https://github.com/scrapy/scrapely" rel="nofollow">scrapely github project</a> describes only a simple example:</p>
<pre><code>from scrapely import Scraper
s = Scraper()
s.train(url, data... | 2 | 2016-05-31T20:58:27Z | 37,654,688 | <p>Scrapely <strong>can</strong> be trained to extract a list of items. The trick is to pass the first and last items of the list to be extracted as a Python list when training. Here an example inspired by the question: (Training: 10-item ingredient list from <a href="http://www.sabormediterraneo.com/recetas/postres... | 3 | 2016-06-06T10:07:28Z | [
"python",
"data-extraction",
"scrapely"
] |
appending multiple values to CSV file | 37,555,512 | <p>I am trying to append two variables tonename and score to the CSV output (code below will only append tone_name) but not sure how to do it, I would really appreciate any help here:</p>
<pre><code>for fle in file:
# open the file and then call .read() to get the text
with open(fle) as f:
text = f.re... | -1 | 2016-05-31T20:59:50Z | 37,555,598 | <p>Instead of iterating through tonename you could find the len of tonename and iterate through both tonename & score</p>
<pre><code>for x in range(len(tonename)):
writer.writerow(tonename[x] + ',' + tonescore[x])
</code></pre>
| 0 | 2016-05-31T21:05:31Z | [
"python",
"csv"
] |
Scrapy output to json file | 37,555,513 | <p><a href="http://i.stack.imgur.com/mDyJA.png" rel="nofollow"><img src="http://i.stack.imgur.com/mDyJA.png" alt="enter image description here"></a> </p>
<p>After working through the official tut I decided to try to build my own spider in the same project. I created parker_spider.py in the spiders directory. which con... | 0 | 2016-05-31T20:59:54Z | 37,555,637 | <p>Your <code>parse_method</code> needs to return an instance of <code>scrapy.item.Item</code>, or a subclass. As it is, it returns <code>None</code>, which Scrapy interprets as no item could be extracted from the response received.</p>
| 1 | 2016-05-31T21:07:45Z | [
"python",
"scrapy"
] |
Scrapy output to json file | 37,555,513 | <p><a href="http://i.stack.imgur.com/mDyJA.png" rel="nofollow"><img src="http://i.stack.imgur.com/mDyJA.png" alt="enter image description here"></a> </p>
<p>After working through the official tut I decided to try to build my own spider in the same project. I created parker_spider.py in the spiders directory. which con... | 0 | 2016-05-31T20:59:54Z | 37,556,970 | <pre><code>def parse_method(self, response):
j = json.loads(response.body_as_unicode())
item = ParkerItem()
item['account'] = j['d'][0]
yield item
</code></pre>
| 1 | 2016-05-31T22:57:09Z | [
"python",
"scrapy"
] |
Repeating rows and columns in Python | 37,555,524 | <p>I'm trying to make two 600x800 matrices (<code>X</code> and <code>Y</code>) that look like the following:<br>
- <code>X</code> has 0 to 600 in every row<br>
- <code>Y</code> has 800 to 0 in every column</p>
<p>My idea was to do something along these lines:</p>
<pre><code>N = np.arange(0, 600, 1)
M = np.arange(0,... | 1 | 2016-05-31T21:00:39Z | 37,555,577 | <p>You are in luck as NumPy has a built-in for exactly that task in <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.meshgrid.html" rel="nofollow"><code>np.meshgrid</code></a> -</p>
<pre><code>X,Y = np.meshgrid(N,M[::-1])
</code></pre>
<p>Sample run -</p>
<pre><code>In [2]: N
Out[2]: array([... | 2 | 2016-05-31T21:04:22Z | [
"python",
"numpy",
"matrix",
"numpy-broadcasting"
] |
How can I add iteration information between iterations? | 37,555,534 | <p>I am working with this code, feeding it in a chunk of obfuscated java script and having it spit out a bunch of iterations of it passing through and xor function. My problem is I need to know which XOR value, or which iteration of the loop, was the right one. How can I add some line breaks-ideally 4-inbetween iterati... | 0 | 2016-05-31T21:01:34Z | 37,555,696 | <p>Python 3 has the <em>print function</em> which includes a named argument called <code>end='\n'</code> by default.</p>
<p>You can try changing your print statement to something like:</p>
<pre><code> print(subprocess.Popen(next(brute), shell=True), end='\n\n\n\n')
</code></pre>
| 0 | 2016-05-31T21:11:59Z | [
"python",
"python-3.x"
] |
How can I add iteration information between iterations? | 37,555,534 | <p>I am working with this code, feeding it in a chunk of obfuscated java script and having it spit out a bunch of iterations of it passing through and xor function. My problem is I need to know which XOR value, or which iteration of the loop, was the right one. How can I add some line breaks-ideally 4-inbetween iterati... | 0 | 2016-05-31T21:01:34Z | 37,557,896 | <p>I figured it out, i stored the output into a variable using check_output() and then I printed that variable after the string, and iteration number.</p>
<pre><code>#!/usr/bin/python
import os,sys
import subprocess
import re
import glob
from subprocess import check_output
from os import path
perl = "perl -pe 's/(\d+... | 0 | 2016-06-01T01:04:22Z | [
"python",
"python-3.x"
] |
Changing values in a pandas dataframe multiindex | 37,555,548 | <p>I have a list of dataframes, each has a multi-index. one column is a varName, the other is 'round'. </p>
<p>The values in the varName column are numbers. I have another dataframe that is a mapping of the numbers to labels. I want to use map() on the varName column, but since it's part of the index, there IS no varN... | 1 | 2016-05-31T21:02:29Z | 37,555,667 | <p>If <code>varName</code> is the <code>name</code> of one of the <code>MultiIndex</code> levels, you should be able to:</p>
<pre><code>df.reset_index(level='varName')
</code></pre>
<p>to convert <code>varName</code> to a <code>column</code> and then use <code>map()</code>. If <code>varName</code> is not the <code>na... | 1 | 2016-05-31T21:09:42Z | [
"python",
"pandas",
"dataframe",
"multi-index"
] |
Changing values in a pandas dataframe multiindex | 37,555,548 | <p>I have a list of dataframes, each has a multi-index. one column is a varName, the other is 'round'. </p>
<p>The values in the varName column are numbers. I have another dataframe that is a mapping of the numbers to labels. I want to use map() on the varName column, but since it's part of the index, there IS no varN... | 1 | 2016-05-31T21:02:29Z | 37,580,598 | <p>maybe you can do something like:</p>
<pre><code>df.reset_index(level=1).merge(df2)
</code></pre>
<p>this is assuming level=1 is your common column (eg 'varName') between two dfs. if you wish you can than set_index for the label name, like:</p>
<pre><code>df.reset_index(level=1).merge(df2).set_index(['labels'],app... | 0 | 2016-06-01T23:53:27Z | [
"python",
"pandas",
"dataframe",
"multi-index"
] |
Manipulating fields and values in dict and transforming into tuples in Python | 37,555,677 | <p>I have a dict that looks like </p>
<pre><code>{'2016-05-30':{
'go':((1, 2, 3, 4),),
'stop':((5, 6, 7, 8),)},
'2016-05-31': {
'go':((11, 12, 13, 14),),
'stop':((15, 16, 17, 18),)}}
</code></pre>
<p>and I have a list of state: <code>['state1', 'state2', 'state3', 'state4']</code></p>
<p>I'm tryi... | 2 | 2016-05-31T21:10:49Z | 37,556,014 | <p>Here is what I think that you want, using list comprehensions,</p>
<pre><code>some_list = [[s, d, v] for d in data for vals in data[d]['go'] for s, v in zip(state, vals)]
# [['state1', '2016-05-31', 11],
# ['state2', '2016-05-31', 12],
# ['state3', '2016-05-31', 13],
# ['state4', '2016-05-31', 14],
# ['state1'... | 1 | 2016-05-31T21:34:49Z | [
"python",
"dictionary"
] |
Python pillow automated image editing | 37,555,691 | <p>I am new to pillow but as far as my knowledge goes I understand that pillow can help me. I want to automatically edit picture that a user uploads.</p>
<p>for example automatically edit this <a href="http://i.stack.imgur.com/KPK42.png" rel="nofollow"><img src="http://i.stack.imgur.com/KPK42.png" alt="enter image des... | -1 | 2016-05-31T21:11:38Z | 37,555,811 | <p>You can try using the <code>.blend</code> method.</p>
<p>For two images <code>image1</code> and <code>image2</code>:</p>
<pre><code>from PIL import Image
image1 = Image.open(path1)
image2 = Image.open(path2)
new_image = Image.blend(image1, image2, alpha)
#save / do stuff
</code></pre>
<p>Alternatively, if you wan... | 0 | 2016-05-31T21:19:23Z | [
"python",
"pillow"
] |
Optical Character Recognition with Python - Auto Cropping | 37,555,707 | <p>I am working on various OCR tasks, pre-processing with Python and analyzing with Tesseract.</p>
<p>The latest problem is how to crop an image with images within e.g. a scanned image of 6 business cards or a photo of a board with two distinct sections. I would like to turn said business cards on one image (.jpg, .p... | -1 | 2016-05-31T21:12:26Z | 37,556,699 | <p>By using opencv you may be abile to find their contours, like they do in <a href="http://docs.opencv.org/2.4/doc/tutorials/imgproc/shapedescriptors/find_contours/find_contours.html" rel="nofollow">their documentation about finding contours</a> or <a href="http://docs.opencv.org/3.1.0/d4/d73/tutorial_py_contours_begi... | 0 | 2016-05-31T22:30:48Z | [
"python",
"image",
"ocr",
"photos"
] |
Is it possible to iterate over a list and skip certain elements? | 37,555,756 | <p>I imported a .xml with two columns (name, quantity). I want to write a function that groups the names into groups whose quantity equals 50. For example given: x - 10, y - 35, z - 42, n - 5, m - 3, and p - 5. The program would return "x,y,n" and "z,m,p". It would not return "x,y,p" since n occurs first. Additionally,... | -4 | 2016-05-31T21:15:37Z | 37,555,971 | <p>Since your goal is to find tuples that exactly add up to 50, the solution will be a bit more complicated than your current approach.
Consider these numbers:</p>
<pre><code>x 20
y 25
z 10
m 15
n 8
p 22
</code></pre>
<p>Your algorithm would first add x=20 and y=25 and then walk through the rest of the list wi... | 0 | 2016-05-31T21:31:21Z | [
"python",
"loops",
"iteration"
] |
Python - Plotting text file returns 'ValueError: invalid literal for float():' | 37,555,827 | <p>So I have this text file that i'm trying to plot. It has 5 columns of simulated data and im trying to plot each column from 2 - 5 to the 1st column.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
with open('SampleData.txt') as f:
data = f.read()
data = data.split('\n')
x = [row.split(' ')[0... | 0 | 2016-05-31T21:20:06Z | 37,555,880 | <pre><code>import matplotlib.pyplot as plt
import numpy as np
with open('SampleData.txt') as f:
data = f.read()
data = data.split('\n')
x = [float(row.split(' ')[0]) for row in data]
y = [float(row.split(' ')[1]) for row in data]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
ax.legend()
plt.show()
</... | 3 | 2016-05-31T21:23:44Z | [
"python",
"numpy",
"text",
"matplotlib"
] |
Python - Plotting text file returns 'ValueError: invalid literal for float():' | 37,555,827 | <p>So I have this text file that i'm trying to plot. It has 5 columns of simulated data and im trying to plot each column from 2 - 5 to the 1st column.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
with open('SampleData.txt') as f:
data = f.read()
data = data.split('\n')
x = [row.split(' ')[0... | 0 | 2016-05-31T21:20:06Z | 37,555,888 | <p>Try typcasting your split to an integer before using the add_subplot</p>
| 0 | 2016-05-31T21:24:22Z | [
"python",
"numpy",
"text",
"matplotlib"
] |
Python - Plotting text file returns 'ValueError: invalid literal for float():' | 37,555,827 | <p>So I have this text file that i'm trying to plot. It has 5 columns of simulated data and im trying to plot each column from 2 - 5 to the 1st column.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
with open('SampleData.txt') as f:
data = f.read()
data = data.split('\n')
x = [row.split(' ')[0... | 0 | 2016-05-31T21:20:06Z | 37,556,024 | <p>The type of the data you obtained from the text file is <strong>string</strong>. That is to say, before you plot it, you first need to convert it into <strong>float</strong> type. It can be easily done by <strong>float()</strong>.</p>
<pre class="lang-py prettyprint-override"><code>x = [float(row.split(' ')[0]) for... | 2 | 2016-05-31T21:35:33Z | [
"python",
"numpy",
"text",
"matplotlib"
] |
python mysqldb insert data evaporating without error | 37,555,843 | <p>first post; i've been helped many times by others' questions but now i'm completely stuck.</p>
<p>i am working in python, using MySQLdb (imported as 'mysql' below) and am trying to do an insert. this code, isolated with its own connection for debugging, immediately follows a completely successful insert to a differ... | 2 | 2016-05-31T21:21:02Z | 37,557,067 | <p>i found the answer in two parts:</p>
<p><a href="http://laviefrugale.blogspot.com/2011/03/python-and-mysql-autocommit.html" rel="nofollow">http://laviefrugale.blogspot.com/2011/03/python-and-mysql-autocommit.html</a></p>
<p>which then refers to this local answer:</p>
<p><a href="http://stackoverflow.com/questions... | 2 | 2016-05-31T23:11:04Z | [
"python",
"mysql"
] |
Python OpenCV import error with python 3.5 | 37,555,890 | <p>I am having some difficulties installing opencv with python 3.5.</p>
<p>I have linked the cv files, but upon <code>import cv2</code> I get an error saying <code>ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/cv2.so, 2): Symbol not found: _PyCObject_Type</code> or m... | 1 | 2016-05-31T21:24:39Z | 37,565,922 | <p>Found an answer - follow the instructions on <a href="http://www.pyimagesearch.com/2015/06/29/install-opencv-3-0-and-python-3-4-on-osx/" rel="nofollow">this website</a> BUT you have to change to the version of python you are using.</p>
<p>Also, I didn't bother with the virtual environments.</p>
<p>And lastly cv2.s... | 1 | 2016-06-01T10:22:08Z | [
"python",
"opencv"
] |
Python- How to show the selections in an Excel AutoFilter | 37,555,944 | <p>This may be a simple task but for the life of me I cannot find a solution. I have an excel document that has a table. The Columns in this table all have autofilters applied. All I want to do is to be able to select all the entries in that autofilter (for the 9th column) and store it in an array. I'm using Win32Co... | 0 | 2016-05-31T21:29:28Z | 37,556,368 | <p>I remember my first script....</p>
<p>are you married to win32?</p>
<p><a href="https://mail.python.org/pipermail/python-list/2011-October/613213.html" rel="nofollow">https://mail.python.org/pipermail/python-list/2011-October/613213.html</a></p>
<p><a href="http://stackoverflow.com/questions/11957420/python-how-t... | 0 | 2016-05-31T22:03:12Z | [
"python",
"win32com",
"autofilter"
] |
Python- How to show the selections in an Excel AutoFilter | 37,555,944 | <p>This may be a simple task but for the life of me I cannot find a solution. I have an excel document that has a table. The Columns in this table all have autofilters applied. All I want to do is to be able to select all the entries in that autofilter (for the 9th column) and store it in an array. I'm using Win32Co... | 0 | 2016-05-31T21:29:28Z | 37,562,495 | <p>You're trying to iterate over the method reference <code>Autofilter</code>, and not its return value(s) <code>Autofilter()</code>. By adding the brackets, you call the method. Without the brackets, you just have a reference to that method.</p>
| 0 | 2016-06-01T07:47:11Z | [
"python",
"win32com",
"autofilter"
] |
Python- How to show the selections in an Excel AutoFilter | 37,555,944 | <p>This may be a simple task but for the life of me I cannot find a solution. I have an excel document that has a table. The Columns in this table all have autofilters applied. All I want to do is to be able to select all the entries in that autofilter (for the 9th column) and store it in an array. I'm using Win32Co... | 0 | 2016-05-31T21:29:28Z | 37,602,903 | <p>I figured it out for anyone interested. Turns out the column I wanted to access was referenced as well as a Pivot Field in a Pivot Table. So once I was able to read the contents of that pivotfield I could then funnel it into an array (and then use that array to print out pdf invoices). Had some encoding weirdness... | 0 | 2016-06-02T22:03:42Z | [
"python",
"win32com",
"autofilter"
] |
Using split to populate a column in Pandas dataframe | 37,556,022 | <p>I'm working with text data and I would simply like to populate a new column based on an existing column.</p>
<p>Example: the column <code>sourceEncodedID</code> may have values like <code>a.b.c</code> and I'd like to extract only the second part of the string, <code>b</code>, if there's a second part available. Her... | 2 | 2016-05-31T21:35:25Z | 37,556,057 | <p><strong>UPDATE2:</strong> - i believe this will be bit faster:</p>
<pre><code>x['new'] = x.sourceEncodedID.str.replace(r'[^\.]*\.([^\.]*).*', r'\1')
</code></pre>
<p>Timing on 20K DF:</p>
<pre><code>In [155]: x.shape
Out[155]: (20000, 2)
In [156]: %timeit x['new'] = x.sourceEncodedID.str.replace(r'[^\.]*\.([^\.]... | 1 | 2016-05-31T21:38:20Z | [
"python",
"pandas",
"dataframe"
] |
Generating a tree that may have branches that terminate [Python] | 37,556,070 | <p>I'm trying to create a script that will generate a tree in the following way: if number is ever: split into 3 numbers: number // 2, number * 2, number + 15. If number is odd: split into 2 numbers: number +1, number * 4. These branches continue until a branch is either: greater than 100, equal to 6, a perfect square ... | 0 | 2016-05-31T21:39:18Z | 37,556,226 | <p>Why not use a list to keep the branch information? Then it can be rewritten into this way without adding a <strong>None</strong> type element in the two branch situation.</p>
<pre><code>daughters = make_daughters(node.number)
node.branch = [Node(d, node) for d in daughters]
</code></pre>
<p>Without worries about... | 0 | 2016-05-31T21:53:03Z | [
"python",
"tree"
] |
Generating a tree that may have branches that terminate [Python] | 37,556,070 | <p>I'm trying to create a script that will generate a tree in the following way: if number is ever: split into 3 numbers: number // 2, number * 2, number + 15. If number is odd: split into 2 numbers: number +1, number * 4. These branches continue until a branch is either: greater than 100, equal to 6, a perfect square ... | 0 | 2016-05-31T21:39:18Z | 37,556,277 | <p>The problem is in the odd case when you <code>make_daughters</code>: you're adding a <code>None</code> as the third parameter and later on you're creating a new <code>Node</code> and try to run the <code>sqrt</code> method on <code>None</code>.</p>
<p>The following parts were modified to fix this issue:</p>
<pre><... | 0 | 2016-05-31T21:56:28Z | [
"python",
"tree"
] |
What the purpose of the `pass` statement? | 37,556,091 | <p>Seems like <code>pass</code> is just a reserved word that isn't really needed. Python could use the convention of having a single line <code>None</code> statement to accomplish the same thing. </p>
<p>For example, I see very little difference between </p>
<pre><code>while doing_a_thing():
pass
</code></pre>
<p... | 0 | 2016-05-31T21:40:35Z | 37,556,111 | <p><code>None</code> already has meaning in Python. It is not a statement, but <a href="https://docs.python.org/2/library/constants.html" rel="nofollow">a value</a>. It can be used to flag a variable that does not yet have a standard value, or as the "return value" of a function that does not return anything.</p>
<p>S... | 7 | 2016-05-31T21:42:28Z | [
"python"
] |
What the purpose of the `pass` statement? | 37,556,091 | <p>Seems like <code>pass</code> is just a reserved word that isn't really needed. Python could use the convention of having a single line <code>None</code> statement to accomplish the same thing. </p>
<p>For example, I see very little difference between </p>
<pre><code>while doing_a_thing():
pass
</code></pre>
<p... | 0 | 2016-05-31T21:40:35Z | 37,556,160 | <p>I'm going to piggy-back off Rory a bit here.</p>
<p><code>None</code> is a value, whereas <code>pass</code> is a statement.</p>
<p>For instance if you want a default value for a function you would do</p>
<pre><code>def my_func(val1, val2=None):
# Some stuff here
</code></pre>
<p>Where <code>None</code> is us... | 4 | 2016-05-31T21:47:10Z | [
"python"
] |
changing each item in list of tuple to its integer value | 37,556,096 | <p>how can I change the following:</p>
<pre><code>from itertools import product
list1 = input().split()
list2 = input().split()
result = product(list1, list2)
for item in result:
print(item, end=" ")
</code></pre>
<p>to print:</p>
<pre><code>1 2
3 4
(1, 3) (1, 4) (2, 3) (2, 4)
</code></pre>
<p>instead of:</p>... | -1 | 2016-05-31T21:41:12Z | 37,556,125 | <p>Use <code>list(map(int, input().split()))</code> to transform your input strings into lists of integers. When you form the product of your lists, you'll get tuples of integers instead of tuples of numeric strings.</p>
| 2 | 2016-05-31T21:44:01Z | [
"python",
"list",
"python-3.x",
"tuples"
] |
changing each item in list of tuple to its integer value | 37,556,096 | <p>how can I change the following:</p>
<pre><code>from itertools import product
list1 = input().split()
list2 = input().split()
result = product(list1, list2)
for item in result:
print(item, end=" ")
</code></pre>
<p>to print:</p>
<pre><code>1 2
3 4
(1, 3) (1, 4) (2, 3) (2, 4)
</code></pre>
<p>instead of:</p>... | -1 | 2016-05-31T21:41:12Z | 37,556,126 | <p>Here's one way. You could just use the map separately, I just wanted to use a lambda.</p>
<pre><code> >>> from itertools import product
>>> list1 = input().split()
1 2
>>> list2 = input().split()
3 4
>>> to_int = lambda x: map(int, x)
#or, result = product(map(int, l... | 1 | 2016-05-31T21:44:15Z | [
"python",
"list",
"python-3.x",
"tuples"
] |
groupby multiple value columns | 37,556,145 | <p>I need to do a fuzzy <code>groupby</code> where a single record can be in one or more groups. </p>
<p>I have a <code>DataFrame</code> like this:</p>
<pre><code>test = pd.DataFrame({'score1' : pandas.Series(['a', 'b', 'c', 'd', 'e']), 'score2' : pd.Series(['b', 'a', 'k', 'n', 'c'])})
</code></pre>
<p>Output:</p>
... | 2 | 2016-05-31T21:46:02Z | 37,556,360 | <p>Combine the two <code>columns</code> in a single <code>column</code> using e.g. <code>pd.concat()</code>:</p>
<pre><code>s = pd.concat([test['score1'], test['score2'].rename(columns={'score2': 'score1'})]).reset_index()
s.columns = ['val', 'grp']
val grp
0 0 a
1 1 b
2 2 c
3 3 d
4 4 e
5 ... | 2 | 2016-05-31T22:02:18Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
groupby multiple value columns | 37,556,145 | <p>I need to do a fuzzy <code>groupby</code> where a single record can be in one or more groups. </p>
<p>I have a <code>DataFrame</code> like this:</p>
<pre><code>test = pd.DataFrame({'score1' : pandas.Series(['a', 'b', 'c', 'd', 'e']), 'score2' : pd.Series(['b', 'a', 'k', 'n', 'c'])})
</code></pre>
<p>Output:</p>
... | 2 | 2016-05-31T21:46:02Z | 37,556,416 | <p>Reorganizing your data for ease of manipulation (having multiple value columns for the same data will always cause you headaches).</p>
<pre><code>import pandas as pd
test = pd.DataFrame({'score1' : pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e']), 'score2' : pd.Series([2, 1, 8, 9, 3], index=['a', 'b', '... | 0 | 2016-05-31T22:07:39Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
groupby multiple value columns | 37,556,145 | <p>I need to do a fuzzy <code>groupby</code> where a single record can be in one or more groups. </p>
<p>I have a <code>DataFrame</code> like this:</p>
<pre><code>test = pd.DataFrame({'score1' : pandas.Series(['a', 'b', 'c', 'd', 'e']), 'score2' : pd.Series(['b', 'a', 'k', 'n', 'c'])})
</code></pre>
<p>Output:</p>
... | 2 | 2016-05-31T21:46:02Z | 37,557,337 | <p>Using <a href="http://stackoverflow.com/users/1494637/stefan">Stefan</a>'s help, I solved it like this. </p>
<pre><code>In (283): frame1 = test[['score1']]
frame2 = test[['score2']]
frame2.rename(columns={'score2': 'score1'}, inplace=True)
test = pandas.concat([frame1, frame2])
... | 1 | 2016-05-31T23:46:21Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Get all files and directories in current directory python | 37,556,251 | <p>I am writing a python package manager, and I am making it so that it generates the <code>__all__</code> object based on the programs/packages in the current directory, but I also want to ignore any non-packages.
i.e, if I had the following directory structure:</p>
<pre><code>project
|------__init__.py
|------prog1.... | 0 | 2016-05-31T21:54:22Z | 37,556,776 | <p>You want all .py-files and all directories with a <code>__init__.py</code> file of the given directory, use <code>glob</code>:</p>
<pre><code>def config_all(directory):
result = []
for filename in glob.iglob(os.path.join(directory, '*', '__init__.py')):
result.append(os.path.basename(os.path.dirname... | 1 | 2016-05-31T22:38:06Z | [
"python",
"file",
"packages"
] |
Continue not properly in loop | 37,556,291 | <p>I have python 2.7, this is my code and when I run it, I get this error: 'continue' not properly in loop.</p>
<p>I know that 'continue' should be inside the loop for, but I use it inside <code>if</code>, then what i have to do? </p>
<pre><code>from numpy import zeros
from scipy.linalg import svd
from math import l... | -2 | 2016-05-31T21:57:21Z | 37,556,330 | <p>It's totally unnecessary to use <code>continue</code> in that context, just use <code>pass</code>.</p>
| 1 | 2016-05-31T21:59:58Z | [
"python",
"arabic",
"lsa"
] |
Python DFS, can't figure out why return list is empty if using append/pop() but works for []+[] in recursive call | 37,556,304 | <p>can someone plz tell me why this code generate empty "res" variable? If uncomment the commented line and remove below will be working fine.</p>
<p>Codes not work:</p>
<pre><code>class Solution(object):
def dfs(self, nums, res, line):
if not nums:
print(line)
res.append(line)
... | 1 | 2016-05-31T21:58:23Z | 37,556,655 | <p>Your guessing is correct. Just like Java, list in python is copy-by-reference. Consider the following example:</p>
<pre><code>a = [1, 2, 3]
b = a
a.append(4)
print(b)
</code></pre>
<p>You will get</p>
<pre><code>[1, 2, 3, 4]
</code></pre>
<p>Thus, one easy way to fix the code is that replacing the <code>res.appe... | 0 | 2016-05-31T22:26:32Z | [
"python",
"algorithm",
"recursion",
"permutation",
"dfs"
] |
Python DFS, can't figure out why return list is empty if using append/pop() but works for []+[] in recursive call | 37,556,304 | <p>can someone plz tell me why this code generate empty "res" variable? If uncomment the commented line and remove below will be working fine.</p>
<p>Codes not work:</p>
<pre><code>class Solution(object):
def dfs(self, nums, res, line):
if not nums:
print(line)
res.append(line)
... | 1 | 2016-05-31T21:58:23Z | 37,557,685 | <p>Python function call semantics:</p>
<ul>
<li><p>Are <em>not pass-by-reference</em>. The receiving end does not need to de-reference it.</p></li>
<li><p>Are <em>not pass-by-value</em>. There is no copy made of the value.</p></li>
<li><p>May best be described as <strong>pass by object</strong>. The object itself is p... | 0 | 2016-06-01T00:33:45Z | [
"python",
"algorithm",
"recursion",
"permutation",
"dfs"
] |
Is there a way to prefilter data before using read_csv to download data into pandas dataframe? | 37,556,334 | <p>I'm working with the yelp dataset and of course it is millions of entries long so I was wondering if there was any way where you can just download what you need or do you have to pick away at it manually? For example, yelp has reviews on everything from auto repair to beauty salons but I only want the reviews on the... | 0 | 2016-05-31T22:00:34Z | 37,556,547 | <p>Assuming you are looking at a <code>.csv</code> file, you could read and preprocess <code>chunks</code> rather than reading the full dataset as in:</p>
<pre><code>df = pd.DataFrame()
chunksize = 100000
for chunk in pd.read_csv(filename, chunksize=chunksize):
process(chunk)
df = pd.concat([df, chunk])
</code... | 0 | 2016-05-31T22:17:40Z | [
"python",
"csv",
"pandas",
"dataframe",
"yelp"
] |
Is there a way to prefilter data before using read_csv to download data into pandas dataframe? | 37,556,334 | <p>I'm working with the yelp dataset and of course it is millions of entries long so I was wondering if there was any way where you can just download what you need or do you have to pick away at it manually? For example, yelp has reviews on everything from auto repair to beauty salons but I only want the reviews on the... | 0 | 2016-05-31T22:00:34Z | 37,556,551 | <p>Typically yes, load everything, then filter your dataset.</p>
<p>But if you really want to pre-filter, and you're on a unix like system, you can prefilter using <code>grep</code> before even starting Python.</p>
<p>A compromise between them is to write the prefilter using Python and Pandas, this way you download t... | 0 | 2016-05-31T22:18:20Z | [
"python",
"csv",
"pandas",
"dataframe",
"yelp"
] |
How can I get pyyaml to correctly display structure in output? | 37,556,363 | <p>Instead of getting normal line breaks like I'd expect it's just printing '\n'. How can I make the line break actually happen?</p>
<pre><code>>>> test2 = [{'A':['a', 'b']}, {'B':'b'}]
>>> yaml.dump(test2)
'- A: [a, b]\n- {B: b}\n'
>>>
</code></pre>
| 4 | 2016-05-31T22:02:52Z | 37,556,429 | <p>You can get the line breaks to render using <code>print</code>. Strings displayed in the interactive prompt in this manner never render line breaks. You can tell how your string is displaying by the quotation marks (<code>'</code>) displayed around the string, these won't appear with <code>print</code>.</p>
<pre><c... | 0 | 2016-05-31T22:08:40Z | [
"python",
"pyyaml"
] |
How can I get pyyaml to correctly display structure in output? | 37,556,363 | <p>Instead of getting normal line breaks like I'd expect it's just printing '\n'. How can I make the line break actually happen?</p>
<pre><code>>>> test2 = [{'A':['a', 'b']}, {'B':'b'}]
>>> yaml.dump(test2)
'- A: [a, b]\n- {B: b}\n'
>>>
</code></pre>
| 4 | 2016-05-31T22:02:52Z | 37,559,787 | <p>The <code>dump()</code> routines in PyYAML have several optional arguments, the first of which being the stream the data will be serialized to ( <code>stream=</code> ). </p>
<p>If you don't specify this stream a file like object will be created (<code>StringIO()</code> or <code>BytesIO()</code>) to which the data i... | 2 | 2016-06-01T05:01:05Z | [
"python",
"pyyaml"
] |
How to perform a natural join on two tables using SQLAlchemy and Flask? | 37,556,373 | <p>I have two tables Entry and Group defined in Python using Flask SQLAlchemy connected to a PostgresSQL database: </p>
<pre><code>class Entry (db.Model):
__tablename__ = "entry"
id = db.Column('id', db.Integer, primary_key = True)
group_title = db.Column('group_title', db.Unicode, db.ForeignKey('group.gro... | 0 | 2016-05-31T22:03:28Z | 37,556,738 | <p>Since you have already performed the basic join by using the <a href="http://docs.sqlalchemy.org/en/latest/orm/relationship_api.html#sqlalchemy.orm.relationship" rel="nofollow"><code>relationship()</code></a> call.
We can focus on getting the data you want, a query such as <code>db.session.query(Entry, Group).all()... | 0 | 2016-05-31T22:34:56Z | [
"python",
"database",
"postgresql",
"flask",
"flask-sqlalchemy"
] |
How to perform a natural join on two tables using SQLAlchemy and Flask? | 37,556,373 | <p>I have two tables Entry and Group defined in Python using Flask SQLAlchemy connected to a PostgresSQL database: </p>
<pre><code>class Entry (db.Model):
__tablename__ = "entry"
id = db.Column('id', db.Integer, primary_key = True)
group_title = db.Column('group_title', db.Unicode, db.ForeignKey('group.gro... | 0 | 2016-05-31T22:03:28Z | 37,732,525 | <p>I used the following query to perform a natuaral join for Group and Entry Table:
<code>db.session.query(Entry, Group).join(Group).filter(Group.group_start_id == Entry.id).order_by(Group.order.asc())</code></p>
<p>I did this using the <code>.join</code> function in my query which allowed me to join the Group table t... | 0 | 2016-06-09T17:23:53Z | [
"python",
"database",
"postgresql",
"flask",
"flask-sqlalchemy"
] |
Advice on how to predict future time series data | 37,556,600 | <p>Data:
I have time series data for different countries and factors, e.g. birth rate for "Afghanistan" for years from 1972 up until 2007 (<a href="https://www.drivendata.org/competitions/1/" rel="nofollow">source</a>).</p>
<p>Goal:
Predict e.g. birth rate for 2008 and 2012</p>
<p>Question:
I am familiar with linea... | 0 | 2016-05-31T22:22:01Z | 37,556,640 | <p>Take a look at the <code>statsmodels</code> <a href="http://statsmodels.sourceforge.net/devel/tsa.html" rel="nofollow">Time Series Analysis</a> module. Time series models are often based around autocorrelation, and the module has the standard univariate (for individual time series) <code>AR(p)</code> and <code>MA(p)... | 1 | 2016-05-31T22:25:21Z | [
"python",
"pandas",
"machine-learning",
"scikit-learn",
"time-series"
] |
Advice on how to predict future time series data | 37,556,600 | <p>Data:
I have time series data for different countries and factors, e.g. birth rate for "Afghanistan" for years from 1972 up until 2007 (<a href="https://www.drivendata.org/competitions/1/" rel="nofollow">source</a>).</p>
<p>Goal:
Predict e.g. birth rate for 2008 and 2012</p>
<p>Question:
I am familiar with linea... | 0 | 2016-05-31T22:22:01Z | 37,556,703 | <p>you can use <code>ARIMA</code> model and <code>VAR</code> Model in R. </p>
<p><code>ARIMA</code>: Auto Regressive Integrated Moving Average model</p>
<p><code>VAR</code>: Vector Auto Regressive model</p>
<p>For <code>ARIMA</code> model: <a href="https://stat.ethz.ch/R-manual/R-devel/library/stats/html/arima.html... | 0 | 2016-05-31T22:31:23Z | [
"python",
"pandas",
"machine-learning",
"scikit-learn",
"time-series"
] |
Shuffle DataFrame rows except the first row | 37,556,616 | <p>I am trying to randomize all rows in a data frame except for the first. I would like for the first row to always appear first, and the remaining rows can be in any randomized order. </p>
<p>My data frame is:</p>
<pre><code> df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
</code></pre>
... | 1 | 2016-05-31T22:23:31Z | 37,556,654 | <p>try this:</p>
<pre><code>df = pd.concat([df[:1], df[1:].sample(frac=1)]).reset_index(drop=True)
</code></pre>
<p>test:</p>
<pre><code>In [38]: df
Out[38]:
a b c d e
0 2.070074 2.216060 -0.015823 0.686516 -0.738393
1 -1.213517 0.994057 0.634805 0.517844 -0.128375
2 ... | 3 | 2016-05-31T22:26:27Z | [
"python",
"pandas",
"dataframe",
"shuffle"
] |
Shuffle DataFrame rows except the first row | 37,556,616 | <p>I am trying to randomize all rows in a data frame except for the first. I would like for the first row to always appear first, and the remaining rows can be in any randomized order. </p>
<p>My data frame is:</p>
<pre><code> df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
</code></pre>
... | 1 | 2016-05-31T22:23:31Z | 37,557,437 | <p>Use <code>numpy</code>'s <code>shuffle</code></p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(100).reshape(20, 5), columns=list('ABCDE'))
np.random.shuffle(df.values[1:, :])
print df
A B C D E
0 0 1 2 3 4
1 55 56 57 58 59
2 10 11 12 13 14
3 ... | 2 | 2016-05-31T23:59:46Z | [
"python",
"pandas",
"dataframe",
"shuffle"
] |
Problems installing Pandas | 37,556,742 | <p>I am unable to install Pandas on my Linux server. I am using virtualenv but I tried installing Pandas without that but no luck.</p>
<pre><code> root@host:~# uname -a
Linux host 3.13.0-61-generic #100-Ubuntu SMP Wed Jul 29 11:21:34 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
</code></pre>
<p>Numpy installs with ... | -1 | 2016-05-31T22:35:07Z | 37,664,172 | <p>I noticed that my errors started with this:</p>
<pre><code>You are using pip version 6.0.8, however version 8.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting numpy
Using cached numpy-1.11.0.tar.gz
Running from numpy source directory.
Installing collected... | 0 | 2016-06-06T18:13:49Z | [
"python",
"pandas"
] |
Having trouble with being selective in list comprehension | 37,556,830 | <p>I need to use a list comprehension to convert certain items in a list from Celsius to Fahrenheit. I have a list of temperatures. What my best guess is at this point looks like this:</p>
<pre><code>good_temps = [c_to_f(temp) for temp in temperatures if 9 < temperatures[temp] <32.6]
</code></pre>
<p>However I'... | -1 | 2016-05-31T22:42:17Z | 37,556,848 | <p>An alternative solution to the one pointed in another answer is to use filter to get the subset:</p>
<pre><code>filter(lambda temp: 9 < temp < 32.6, temperatures)
</code></pre>
<p>Then a list comprehension to make the transformations:</p>
<pre><code>[c_to_f(temp) for temp in temperatures]
</code></pre>
<p... | 2 | 2016-05-31T22:44:18Z | [
"python",
"list-comprehension"
] |
Having trouble with being selective in list comprehension | 37,556,830 | <p>I need to use a list comprehension to convert certain items in a list from Celsius to Fahrenheit. I have a list of temperatures. What my best guess is at this point looks like this:</p>
<pre><code>good_temps = [c_to_f(temp) for temp in temperatures if 9 < temperatures[temp] <32.6]
</code></pre>
<p>However I'... | -1 | 2016-05-31T22:42:17Z | 37,556,930 | <p>You're very close. What you need is:</p>
<pre><code>good_temps = [c_to_f(temp) for temp in temperatures if 9 < temp < 32.6]
</code></pre>
<p>This code will only convert <code>temp</code> if it's greater than 9 and less than 32.6. For <code>temp</code> values outside that range nothing will get added to <code... | 2 | 2016-05-31T22:51:39Z | [
"python",
"list-comprehension"
] |
Getting the rotation of a face normal from the Axis | 37,556,880 | <p>I have been trying to get the Euler angles to each axis of a face normal vector but I haven't been successful so far.
I tried using the direction cosines for each axis, but I haven't been successful as the returned value was completely off.
Here's my code so far, I'm pretty sure there's a problem with my logic, spe... | 0 | 2016-05-31T22:46:47Z | 37,668,288 | <p>There are a few ways to interpret the data but if given a vector you want the respective rotations per major axis you take the inverse tangents of the components of the vector. The choice of components determines the axis of rotation:</p>
<pre><code>inVec = /(input vector)/
rotZ = atan(inVec.y/inVec.x)
rotY = atan(... | 0 | 2016-06-06T23:23:35Z | [
"python",
"maya"
] |
Getting TypeError when trying to concatenate 'str' and 'NoneType' objects | 37,556,886 | <p>I have the following code:
import requests
from bs4 import BeautifulSoup</p>
<pre><code>def hltvmatch_spider(max_offset):
offset = 0
while offset < max_offset:
url = 'http://www.hltv.org/?pageid=188&offset=' + str(offset)
source_code = requests.get(url)
plain_text = so... | 2 | 2016-05-31T22:47:10Z | 37,556,954 | <p>You should set <em>href=True</em> so you only get anchors with href attributes, calling <code>.get("href")</code> will return None when the anchor has no href attribute:</p>
<pre><code>for link in soup.findAll('a', href=True):
</code></pre>
<p>As I commented getting all anchors is not probably what you want as joi... | 1 | 2016-05-31T22:55:04Z | [
"python",
"beautifulsoup",
"typeerror"
] |
Apparently inconsistent behavior when copying numpy arrays | 37,556,896 | <p>Consider the following minimal example. Can somebody explain the apparently inconsistent logic of <code>numpy</code> when it comes to copying list elements of varying nesting depths?</p>
<pre><code>import numpy as np
L = [[[[1, 1], 2, 3]]]
A1 = np.array(L)
A2 = A1.copy()
A1[0][0][2] = 'xx'
A1[0][0][0][0] = 'yy'
... | 0 | 2016-05-31T22:48:15Z | 37,575,547 | <p>Look at your array, and understand its structure first:</p>
<pre><code>In [139]: A1
Out[139]: array([[[[1, 1], 2, 3]]], dtype=object)
In [140]: A1.shape
Out[140]: (1, 1, 3)
</code></pre>
<p>It's a <code>dtype=object</code> array; that is the elements are object pointers, not numbers. Also it is 3d, with 3 elemen... | 1 | 2016-06-01T17:48:08Z | [
"python",
"arrays",
"numpy",
"copy",
"deep"
] |
How do I import a CSV file into sqlite3 in Python without knowing ahead of time the number of columns? | 37,557,005 | <p>I am currently trying to import, using Python, a CSV file into a SQLite database using the top fields as column names, but I need to be able to import any CSV file, regardless of how many columns it has. I know how to use the csv top row to create the column names, but every example I have seen with regards to impo... | 0 | 2016-05-31T23:01:33Z | 37,557,102 | <p>If you are willing to use the pandas library, this could easily be achieved using two functions:</p>
<pre><code>pandas.read_csv
</code></pre>
<p>which will return a dataframe object, and then use the Dataframe method</p>
<pre><code>Dataframe.to_sql
</code></pre>
<p>to create your database. Pandas should be prett... | 3 | 2016-05-31T23:15:37Z | [
"python",
"csv",
"sqlite3"
] |
How do I import a CSV file into sqlite3 in Python without knowing ahead of time the number of columns? | 37,557,005 | <p>I am currently trying to import, using Python, a CSV file into a SQLite database using the top fields as column names, but I need to be able to import any CSV file, regardless of how many columns it has. I know how to use the csv top row to create the column names, but every example I have seen with regards to impo... | 0 | 2016-05-31T23:01:33Z | 37,557,145 | <pre><code>import csv, sqlite3
con = sqlite3.connect(":memory:")
with closing(con.cursor()) as cur:
with open('data.csv','rb') as fin:
data_csv = csv.read(fin)
column_count = len(list(list(data_csv)[0])
create_table_statement = "CREATE TABLE t ("
for column in xrange(1, column_count... | 1 | 2016-05-31T23:21:27Z | [
"python",
"csv",
"sqlite3"
] |
Python: Running a script A that handles argparser inside script B | 37,557,027 | <p>I have a script_A that handles different inputs using argparser that I use to perform a function. I now need script B to call and have all of script A run (have it handle different inputs) from inside. I am using Windows.</p>
<p><strong>Goal:</strong> Script_B is going to do further analysis based on the output of ... | 3 | 2016-05-31T23:04:58Z | 37,559,824 | <pre><code>p = subprocess.Popen("your_a_code_with_args_here",
shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(stdoutput, erroutput) = p.communicate()
</code></pre>
<p>Then your B code could do things according to the output of A code.</p>
| 1 | 2016-06-01T05:03:30Z | [
"python",
"shell",
"command-line",
"argparse"
] |
Python: Running a script A that handles argparser inside script B | 37,557,027 | <p>I have a script_A that handles different inputs using argparser that I use to perform a function. I now need script B to call and have all of script A run (have it handle different inputs) from inside. I am using Windows.</p>
<p><strong>Goal:</strong> Script_B is going to do further analysis based on the output of ... | 3 | 2016-05-31T23:04:58Z | 37,559,931 | <p>Version 3 is almost correct. Although you have so many missing <code>'</code> and <code>"</code> in your examples that I'm not sure if your code is working on your side...</p>
<pre><code>from subprocess import call
# you need pass the name + all the arguments as a vector here
process = call(["script_A.py", "-i", ... | 0 | 2016-06-01T05:14:14Z | [
"python",
"shell",
"command-line",
"argparse"
] |
Python: Running a script A that handles argparser inside script B | 37,557,027 | <p>I have a script_A that handles different inputs using argparser that I use to perform a function. I now need script B to call and have all of script A run (have it handle different inputs) from inside. I am using Windows.</p>
<p><strong>Goal:</strong> Script_B is going to do further analysis based on the output of ... | 3 | 2016-05-31T23:04:58Z | 37,580,481 | <p>I've condensed your <code>A</code> to:</p>
<pre><code>import argparse
def function_1():
print('function 1')
def function_2():
print('function 2')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--id', choices=['A','B'], default='A')
parser.add_argument... | 1 | 2016-06-01T23:40:34Z | [
"python",
"shell",
"command-line",
"argparse"
] |
post() takes exactly 1 argument (2 given) django | 37,557,058 | <p>I've been coding this, so i wanted to create like a forum, and this is the comments part, if you guys can help me i will be really thankfull.</p>
<blockquote>
<p>views.py</p>
</blockquote>
<pre><code>class createComment(View):
form_class = CommentForm
template_name = "createComment.html"
def get(sel... | 1 | 2016-05-31T23:09:47Z | 37,557,083 | <pre><code>def get(self, request):
...
def post(request):
...
</code></pre>
<p>You forgot the <code>self</code> argument.</p>
| 2 | 2016-05-31T23:13:13Z | [
"python",
"django"
] |
How to extract data from nested structure? | 37,557,097 | <p>I'm extremely new to Python 3 and I've been trying to get some info from a webpage for the last days without proper results. I've replicated several examples from the web, but the structure of the webpage I want to get the data from is quite complicated to me. </p>
<p>From this webpage: <a href="https://www.leafly.... | -1 | 2016-05-31T23:14:33Z | 37,557,238 | <p>Using selenium and python</p>
<p>To install selenium in python: <code>pip install selenium</code></p>
<p>For details:<a href="https://pypi.python.org/pypi/selenium" rel="nofollow">click here</a></p>
<pre><code>import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = ... | -1 | 2016-05-31T23:34:31Z | [
"python",
"python-3.x",
"nested"
] |
Python Pandas Only Compare Identically Labeled DataFrame Objects | 37,557,131 | <p>I tried all the solutions here:
<a href="http://stackoverflow.com/questions/18548370/pandas-can-only-compare-identically-labeled-dataframe-objects-error">Pandas "Can only compare identically-labeled DataFrame objects" error</a> </p>
<p>Didn't work for me. Here's what I've got. I have two data frames. O... | 0 | 2016-05-31T23:19:53Z | 37,557,510 | <p>In order to get around this, you want to compare the underlying numpy arrays.</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'], index=['One', 'Two'])
df2 = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'], index=['one', 'two'])
df1.values == df2.values
array([[ True, ... | 0 | 2016-06-01T00:07:02Z | [
"python",
"pandas"
] |
Python Pandas Only Compare Identically Labeled DataFrame Objects | 37,557,131 | <p>I tried all the solutions here:
<a href="http://stackoverflow.com/questions/18548370/pandas-can-only-compare-identically-labeled-dataframe-objects-error">Pandas "Can only compare identically-labeled DataFrame objects" error</a> </p>
<p>Didn't work for me. Here's what I've got. I have two data frames. O... | 0 | 2016-05-31T23:19:53Z | 37,568,879 | <p>Replicated with some fake data to achieve the end goal of removing duplicates. Note this is not the answer to the original question, but what the answer was to what I was attempting to do that caused the question.</p>
<pre><code>b = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
'B': ['B4', 'B5',... | 0 | 2016-06-01T12:38:48Z | [
"python",
"pandas"
] |
parameters from variable? | 37,557,151 | <p>I am new to python and i am trying to read each line of file with comma <code>','</code> separated values. like this line: </p>
<pre><code>435,567,897,905,6,56,22,90.
</code></pre>
<p>My existing code</p>
<pre><code>#!/usr/bin/python
class Line():
def __init__(self, val1, val2, val3, val4, val5, val6, val7, ... | 2 | 2016-05-31T23:22:03Z | 37,557,192 | <p>To unpack the values in a list into all the arguments of a function (in this case <code>Line.__init__</code>), use the <code>*</code> operator, like so:</p>
<pre><code>lin = Line(*li)
</code></pre>
| 0 | 2016-05-31T23:28:44Z | [
"python",
"python-2.7",
"python-3.x"
] |
parameters from variable? | 37,557,151 | <p>I am new to python and i am trying to read each line of file with comma <code>','</code> separated values. like this line: </p>
<pre><code>435,567,897,905,6,56,22,90.
</code></pre>
<p>My existing code</p>
<pre><code>#!/usr/bin/python
class Line():
def __init__(self, val1, val2, val3, val4, val5, val6, val7, ... | 2 | 2016-05-31T23:22:03Z | 37,557,311 | <p>You need to pass each of the items in each <code>line</code> to the <code>Line</code> constructor. One way to do it would be to write:</p>
<pre><code>li = Line(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]))
</code></pre>
<p>but that's a lot of writing. Python has a shortcut:</p>
<pre><co... | 1 | 2016-05-31T23:42:39Z | [
"python",
"python-2.7",
"python-3.x"
] |
First element of series to cross threshold in numpy, with handling of series that never cross | 37,557,173 | <p>I have a numpy array of N time series of length T. I want the index at which each first crosses some threshold, and a -1 or something similar if it never crosses. Take <code>ts_array = np.randn(N, T)</code></p>
<p><code>np.argmax(ts_array > cutoff, axis=1)</code> gets close, but it returns a 0 for both time ser... | 0 | 2016-05-31T23:24:57Z | 37,557,384 | <p>It's not too bad with <code>np.where</code>. I would use the following as a starting point:</p>
<pre><code>ts_array = np.random.rand(10, 10)
cutoff = 0.5
# Get a list of all indices that satisfy the condition
rows, cols = np.where(ts_array > cutoff)
if len(rows) > 0:
index = (rows[0], cols[0])
else:
... | 1 | 2016-05-31T23:52:42Z | [
"python",
"numpy"
] |
First element of series to cross threshold in numpy, with handling of series that never cross | 37,557,173 | <p>I have a numpy array of N time series of length T. I want the index at which each first crosses some threshold, and a -1 or something similar if it never crosses. Take <code>ts_array = np.randn(N, T)</code></p>
<p><code>np.argmax(ts_array > cutoff, axis=1)</code> gets close, but it returns a 0 for both time ser... | 0 | 2016-05-31T23:24:57Z | 37,558,509 | <p>One liner:</p>
<pre><code>(ts > c).argmax() if (ts > c).any() else -1
</code></pre>
<p>assuming <code>ts = ts_array</code> and <code>c = cutoff</code></p>
<p>Otherwise:</p>
<p>Use <code>argmax()</code> and <code>any()</code></p>
<pre><code>np.random.seed([3,1415])
def xover(ts, cut):
x = ts > cut
... | 1 | 2016-06-01T02:36:17Z | [
"python",
"numpy"
] |
How do I get python to import pandas? | 37,557,174 | <p>I installed Python 3.5.1 from www.python.org. Everything works great. Except that you can't install pandas using pip (it needs visualstudio to compile, which I don't have). So I installed Anaconda (www.continuum.io/downloads). Now I can see pandas as part of the list of installed modules, but when I run python progr... | 0 | 2016-05-31T23:24:57Z | 37,557,227 | <p>Anaconda has included one version of Python with it. You have to change your system environment path with Anaconda's instead of the former one to avoid conflict. Also, if you want to make the whole process easy, it is recommended to use PyCharm, and it will ask you to choose the Python interpreter you want.</p>
| -1 | 2016-05-31T23:33:32Z | [
"python",
"python-3.x",
"pandas",
"packages"
] |
How do I get python to import pandas? | 37,557,174 | <p>I installed Python 3.5.1 from www.python.org. Everything works great. Except that you can't install pandas using pip (it needs visualstudio to compile, which I don't have). So I installed Anaconda (www.continuum.io/downloads). Now I can see pandas as part of the list of installed modules, but when I run python progr... | 0 | 2016-05-31T23:24:57Z | 37,557,638 | <p>I have successfully installed pandas for a Windows 32 bit version Python 3.4 with pre-complied code (no Visual Studio required) using the website:</p>
<pre><code>http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyyaml
</code></pre>
<p>There is link for Python 3.5 pre-complied code at this site as well, but I have not te... | 1 | 2016-06-01T00:26:41Z | [
"python",
"python-3.x",
"pandas",
"packages"
] |
Does the order in which dynamic libraries are loaded matter? | 37,557,261 | <p>I am on OS X and installed the Gtk+3 package with Homebrew.</p>
<pre><code>brew install gtk+3
</code></pre>
<p>I can load the installed libraries in Python with the <code>ctypes</code> module.</p>
<pre><code>$ python2.6
Python 2.6.9 (unknown, Oct 23 2015, 19:19:20)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-70... | 4 | 2016-05-31T23:37:09Z | 38,824,073 | <p>Here's the same problem shown at the command line level with C. Here, I've made a main.c which calls foo() in foo.so, which calls bar() in bar.so, which calls (for fun) g_free and g_malloc in glib.</p>
<pre><code>$ ls -Flas main.o libfoo.so libbar.so | cut -c3-13,34-37,51-
-rwxrwxr-x 2976 libbar.so* # has bar(),... | 1 | 2016-08-08T08:04:27Z | [
"python",
"ctypes",
"dylib"
] |
How can I get the pathname of the folder two directories upstream of a file? | 37,557,308 | <p>Using glob2 and os I would like the directory <code>'/a/b/'</code> given the file path <code>'/a/b/c/xyz.txt'</code></p>
<p>I have been able to (recursively) move forward through directories using <code>/*</code> and <code>/**</code> in glob2, but not backwards through parent directories. I don't want to use reg... | 0 | 2016-05-31T23:42:33Z | 37,557,370 | <p>Why glob?</p>
<pre><code>dir_path = file_path.split('/')
what_i_want = '/' + dir_path[10] + '/' + dir_path[1] + '/'
</code></pre>
<p>You can also do this by finding the index of the 3rd slash, using the return of each call as the "start" argument to the next.</p>
<pre><code>third_slash = file_path.index('/', file... | 2 | 2016-05-31T23:50:16Z | [
"python",
"glob"
] |
Correctly test with pytest | 37,557,339 | <p>So I want to start using tests with pytest in my python programs. </p>
<p><strong>EDIT:</strong> I'm only trying to test the response because it seemed like the easiest thing to test. I now understand that there are multiple ways to test the response, but I'm more looking to just get a general grip on building test... | 1 | 2016-05-31T23:46:38Z | 37,557,586 | <p>Is your goal to write a unit test?</p>
<p>If so, testing <code>requests.get</code> is already covered by rhe tests inside <code>requests</code>. It's considered unpythonic (and redundant) to re-check something that Python or your library already test for you. Instead, you should focus on testing the unique part o... | 0 | 2016-06-01T00:18:21Z | [
"python",
"python-2.7",
"automated-tests",
"python-requests",
"py.test"
] |
Correctly test with pytest | 37,557,339 | <p>So I want to start using tests with pytest in my python programs. </p>
<p><strong>EDIT:</strong> I'm only trying to test the response because it seemed like the easiest thing to test. I now understand that there are multiple ways to test the response, but I'm more looking to just get a general grip on building test... | 1 | 2016-05-31T23:46:38Z | 37,586,928 | <pre><code>*test_main.py**
from main import get_page
def test_page_response():
test_url = "https://www.google.com/search?q=weather+results&oq=weather+results&aqs=chrome..69i57.4626j0j1&sourceid=chrome&ie=UTF-8"
response = get_page(test_url2) # get_page() returns a response object
assert r... | 1 | 2016-06-02T08:48:03Z | [
"python",
"python-2.7",
"automated-tests",
"python-requests",
"py.test"
] |
Pandas - replacing NaN values using values from other columns | 37,557,396 | <p>I've started to work with pandas recently and I am trying to do some simple cleaning in data. So far I've learned that there are a lot of one-liners when using pandas. So I am looking also for one in my case. I have <code>DataFrame</code> like this:</p>
<pre><code> C0 C1 C2 C3 C4
3... | 0 | 2016-05-31T23:55:32Z | 37,557,766 | <p>Pandas has some methods to backfill and forwardfill missing values, so you can do:</p>
<pre><code>df['C1'] = df.bfill(axis='columns')['C1']
df
Out[10]:
C0 C1 C2 C3 C4
0 3789507 2010.0 NaN NaN NaN
1 3789508 2010.0 NaN 2010.0 NaN
2 3789509 2016.0 NaN 2016.... | 1 | 2016-06-01T00:45:00Z | [
"python",
"pandas"
] |
Why does defining the argument types for __eq__ throw a MyPy type error? | 37,557,411 | <p>I'm using Python 3.5.1 and the newly released <a href="http://mypy-lang.org/" rel="nofollow">MyPy</a> v0.4.1 static type analyzer.</p>
<p>I have some more complex code that I've reduced down to this simplest possible python class needed to reproduce the error:</p>
<pre><code>class MyObject(object):
def __init_... | 3 | 2016-05-31T23:56:34Z | 37,557,540 | <p><code>==</code> is supposed to take arbitrary other objects, not just objects of your type. If it doesn't recognize the other object, it should return <code>NotImplemented</code>:</p>
<pre><code>class MyObject(object):
def __init__(self, value: int=5) -> None:
self.value = value
def __eq__(self,... | 2 | 2016-06-01T00:10:33Z | [
"python",
"python-3.x",
"types",
"typechecking",
"mypy"
] |
Why does defining the argument types for __eq__ throw a MyPy type error? | 37,557,411 | <p>I'm using Python 3.5.1 and the newly released <a href="http://mypy-lang.org/" rel="nofollow">MyPy</a> v0.4.1 static type analyzer.</p>
<p>I have some more complex code that I've reduced down to this simplest possible python class needed to reproduce the error:</p>
<pre><code>class MyObject(object):
def __init_... | 3 | 2016-05-31T23:56:34Z | 37,557,966 | <p>Your reading of the docs is right -- you need to give the method (<code>__eq__</code>) the same signature as it has already in the base class (<code>object</code>), or else a more permissive one.</p>
<p>The reason for that is that because your <code>MyObject</code> is a subtype of <code>object</code>, a <code>MyObj... | 2 | 2016-06-01T01:15:58Z | [
"python",
"python-3.x",
"types",
"typechecking",
"mypy"
] |
Python list comprehension in Go | 37,557,427 | <p>I'm translating below Python function to Go. It's using list comprehension which I don't think is available in Go. What's the best way to translate it to Go ?</p>
<pre><code>def list1s():
return ["10." + str(x) + "." + str(y) + ".1" for x in range(192, 256) for y in range(0, 256)]
</code></pre>
| 1 | 2016-05-31T23:58:23Z | 37,557,493 | <p>Simply use explicit for loops. However, you should not try to simply translate what you do in a language into another.</p>
<pre><code>func list1s() []string {
res := make([]string, 0, 256*64)
for x := 192; x < 256; x++ {
for y := 0; y < 256; y++ {
res = append(res, fmt.Sprintf("10.... | 1 | 2016-06-01T00:05:05Z | [
"python",
"go"
] |
Divide rows of python pandas DataFrame | 37,557,485 | <p>I have a pandas DataFrame <code>df</code> like this</p>
<pre><code> mat time
0 101 20
1 102 7
2 103 15
</code></pre>
<p>I need to divide the rows so the column of time doesn't have any values higher than <code>t=10</code> to have something like this</p>
<pre><code> mat time
0 101 10
2 101 10... | 1 | 2016-06-01T00:04:37Z | 37,557,565 | <p>Use an <code>apply</code> function that loops until all are less than 10.</p>
<pre><code>def split_max_time(df):
new_df = df.copy()
while new_df.iloc[-1, -1] > 10:
temp = new_df.iloc[-1, -1]
new_df.iloc[-1, -1] = 10
new_df = pd.concat([new_df, new_df])
new_df.iloc[-1, -1] ... | 1 | 2016-06-01T00:15:09Z | [
"python",
"pandas",
"divide"
] |
Divide rows of python pandas DataFrame | 37,557,485 | <p>I have a pandas DataFrame <code>df</code> like this</p>
<pre><code> mat time
0 101 20
1 102 7
2 103 15
</code></pre>
<p>I need to divide the rows so the column of time doesn't have any values higher than <code>t=10</code> to have something like this</p>
<pre><code> mat time
0 101 10
2 101 10... | 1 | 2016-06-01T00:04:37Z | 37,559,236 | <p>You could <code>.groupby('mat')</code> and <code>.apply()</code> a combination of <code>integer</code> division and <code>modulo</code> operation using the <code>cutoff</code> (<code>10</code>) to decompose each <code>time</code> value into the desired components:</p>
<pre><code>cutoff = 10
def decompose(time):
... | 1 | 2016-06-01T04:05:18Z | [
"python",
"pandas",
"divide"
] |
Are ctype and ctypes different in python? | 37,557,625 | <p>I am learning python and am confused with ctype and ctypes. In the lecture, the instructor uses ctype and I searched it but only ctypes module result.
So I am not sure ctype and ctypes are same in python. In official documentation, I have to import <code>ctypes</code>, however I didn't import it.</p>
<p>This my cod... | 1 | 2016-06-01T00:24:49Z | 37,557,650 | <p>The ctypes module is a way of interfacing with C (language) types while the ctype you are referring to in your question stands for content-type. See here <a href="https://docs.python.org/2/library/cgi.html" rel="nofollow">https://docs.python.org/2/library/cgi.html</a></p>
| 3 | 2016-06-01T00:28:08Z | [
"python",
"cgi",
"ctypes",
"ctype"
] |
Are ctype and ctypes different in python? | 37,557,625 | <p>I am learning python and am confused with ctype and ctypes. In the lecture, the instructor uses ctype and I searched it but only ctypes module result.
So I am not sure ctype and ctypes are same in python. In official documentation, I have to import <code>ctypes</code>, however I didn't import it.</p>
<p>This my cod... | 1 | 2016-06-01T00:24:49Z | 37,557,986 | <blockquote>
<p>In the lecture, the instructor uses ctype and I searched it</p>
</blockquote>
<p>In what context? Just because a name appears in code somewhere doesn't mean you'll get meaningful results from a web search. You need to know why that name was chosen and what the intent <em>of that programmer</em> was.<... | 0 | 2016-06-01T01:18:40Z | [
"python",
"cgi",
"ctypes",
"ctype"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.