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 |
|---|---|---|---|---|---|---|---|---|---|
Removing the name of mulilevel index | 38,878,885 | <p>I created the mulitlevel DataFrame:</p>
<pre><code> Price
Country England Germany US
sys dis
23 0.8 300.0 300.0 800.0
24 0.8 1600.0 600.0 600.0
27 1.0 4000.0 4000.0 5500.0
30 1.0 1000.0 3000.0 1000.0
</code></pre>
<p>Right now I want to remove the name: Country, and add the index... | 1 | 2016-08-10T16:25:43Z | 38,879,140 | <p>for the index</p>
<pre><code>df.reset_index(inplace=True)
</code></pre>
<p>For the columns</p>
<pre><code> df.columns = df.columns.droplevel(1)
</code></pre>
| 1 | 2016-08-10T16:41:51Z | [
"python",
"pandas"
] |
Removing the name of mulilevel index | 38,878,885 | <p>I created the mulitlevel DataFrame:</p>
<pre><code> Price
Country England Germany US
sys dis
23 0.8 300.0 300.0 800.0
24 0.8 1600.0 600.0 600.0
27 1.0 4000.0 4000.0 5500.0
30 1.0 1000.0 3000.0 1000.0
</code></pre>
<p>Right now I want to remove the name: Country, and add the index... | 1 | 2016-08-10T16:25:43Z | 38,879,333 | <p>Best I've got for now:</p>
<pre><code>df.rename_axis([None, None], 1).reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/0mCtJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/0mCtJ.png" alt="enter image description here"></a></p>
| 2 | 2016-08-10T16:52:48Z | [
"python",
"pandas"
] |
Removing the name of mulilevel index | 38,878,885 | <p>I created the mulitlevel DataFrame:</p>
<pre><code> Price
Country England Germany US
sys dis
23 0.8 300.0 300.0 800.0
24 0.8 1600.0 600.0 600.0
27 1.0 4000.0 4000.0 5500.0
30 1.0 1000.0 3000.0 1000.0
</code></pre>
<p>Right now I want to remove the name: Country, and add the index... | 1 | 2016-08-10T16:25:43Z | 38,879,621 | <p>Try this:</p>
<pre><code>df.reset_index()
df.columns.names =[None, None]
df.columns
MultiIndex(levels=[[u'Price'], [u'England', u'Germany', u'US']],
labels=[[0, 0, 0], [0, 1, 2]],
names=[None, u'Country'])
</code></pre>
| 3 | 2016-08-10T17:09:30Z | [
"python",
"pandas"
] |
how to stop this while loop in python | 38,878,892 | <p>I want to generate a sequence of numbers starting from 2 and calculating each successive number in the sequence as the square of the previous number minus one. </p>
<pre><code>x = 2
while 0 <= x <= 10:
x ** 2 - 1
print(x)
</code></pre>
<p>note: Iam interested in finding the first number in the sequence ... | 0 | 2016-08-10T16:26:06Z | 38,878,913 | <p>you're not affecting x</p>
<pre><code>x = 2
while 0 <= x <= 10:
x = x ** 2 - 1
print(x)
</code></pre>
| 4 | 2016-08-10T16:27:30Z | [
"python",
"function",
"loops",
"while-loop"
] |
how to stop this while loop in python | 38,878,892 | <p>I want to generate a sequence of numbers starting from 2 and calculating each successive number in the sequence as the square of the previous number minus one. </p>
<pre><code>x = 2
while 0 <= x <= 10:
x ** 2 - 1
print(x)
</code></pre>
<p>note: Iam interested in finding the first number in the sequence ... | 0 | 2016-08-10T16:26:06Z | 38,878,929 | <p>You have to update the value of x so that the <code>while</code> statement will eventually be false.</p>
<pre><code>x = 2
while 0 <= x <= 10:
x = x ** 2 - 1
print(x)
</code></pre>
| 1 | 2016-08-10T16:28:34Z | [
"python",
"function",
"loops",
"while-loop"
] |
How to make a subquery in sqlalchemy | 38,878,897 | <pre><code>SELECT *
FROM Residents
WHERE apartment_id IN (SELECT ID
FROM Apartments
WHERE postcode = 2000)
</code></pre>
<p>I'm using sqlalchemy and am trying to execute the above query. I haven't been able to execute it as raw SQL using <code>db.engine.execute(sql)</code... | 1 | 2016-08-10T16:26:32Z | 38,880,249 | <p>You can create subquery with <a href="http://docs.sqlalchemy.org/en/rel_1_0/orm/query.html#sqlalchemy.orm.query.Query.subquery" rel="nofollow">subquery</a> method</p>
<pre><code>subquery = session.query(Apartments.id).filter(Apartments.postcode==2000).subquery()
query = session.query(Residents).filter(Residents.apa... | 2 | 2016-08-10T17:47:15Z | [
"python",
"sqlalchemy"
] |
Play and record sound using pyaudio simulataneously | 38,878,908 | <p>Im trying to create a program to talk back at once. I cant seem to get it to work. Some websites say use <code>numpy</code> arrays but I dont know how. Can anyone help me out??</p>
<pre><code>import pyaudio
import wave
import time
import multiprocessing as mp
import pyaudio
import numpy as np
import sounddevice as ... | 1 | 2016-08-10T16:27:11Z | 39,231,450 | <p>Not sure if you have requirement to use <code>pyaudio</code>, but here is an example using <code>sounddevice</code>.</p>
<p>Below example records audio from microphone for <code>#seconds</code> as per variable <code>duration</code> which you can modify as per your requirements. </p>
<p>Same contents are played ba... | 1 | 2016-08-30T15:21:39Z | [
"python",
"numpy",
"audio",
"talkback"
] |
syntax error in the file name when I run a python script twice? | 38,879,018 | <p>When I try to use the <code>run</code> command twice in IPython, I get a syntax error the second time:</p>
<pre><code>In [2]: run control.py
In [3]: run control.py
File "<ipython-input-3-3e54b0f85f39>", line 1
run control.py
^
SyntaxError: invalid syntax
</code></pre>
<p>In my script I i... | 0 | 2016-08-10T16:33:53Z | 38,879,073 | <p>The correct ipython command is <code>%run</code>, with the <code>%</code> prefix. Without the prefix <em>can</em> work, but <em>only</em> if you don't also have a Python global name <code>run</code> masking the command.</p>
<p>Because <code>%run script.py</code> runs the script <em>inside the IPython interpreter</e... | 3 | 2016-08-10T16:37:49Z | [
"python",
"windows",
"python-2.7",
"ipython"
] |
How to bind multiple mouse buttons to a widget? | 38,879,041 | <p>I'm trying to make the Minesweeper game. For each undifferentiated square I created a button.</p>
<pre><code>my_list = [[0 for i in range(9)] for j in range(9)]
all_buttons = []
def creaMatriz():
for y, row in enumerate(my_list):
buttons_row = []
for x, element in enumerate(row):
... | 1 | 2016-08-10T16:35:41Z | 38,879,390 | <p>You need to bind keys you wish in order to get this functionality. Here's a simple concept:</p>
<pre><code>from tkinter import *
root = Tk()
def left(event):
label.config(text="Left clicked")
def right(event):
label.config(text="Right clicked")
label = Label(root, text="Nothing")
label.pack()
label.foc... | 3 | 2016-08-10T16:55:42Z | [
"python",
"button",
"tkinter"
] |
How to bind multiple mouse buttons to a widget? | 38,879,041 | <p>I'm trying to make the Minesweeper game. For each undifferentiated square I created a button.</p>
<pre><code>my_list = [[0 for i in range(9)] for j in range(9)]
all_buttons = []
def creaMatriz():
for y, row in enumerate(my_list):
buttons_row = []
for x, element in enumerate(row):
... | 1 | 2016-08-10T16:35:41Z | 38,883,379 | <p>There's nothing special you need to do, you simply need to bind each mouse button separately rather than using the <code>command</code> attribute.</p>
<p>For example, let's create a callback for the left and right mouse buttons:</p>
<pre><code>def onLeftClick(x, y):
print("you clicked on %x,%y" % (x, y))
def ... | 0 | 2016-08-10T20:55:39Z | [
"python",
"button",
"tkinter"
] |
Read a non-conventional INI in python | 38,879,052 | <p>I coding a script in python to read a .INI file. I know there is a library called configparser, but my .INI is a little different from the "standard".</p>
<p>In general, the files should be like:</p>
<pre><code>[HEADER]
username = john
fruits = oranges, apples
</code></pre>
<p>but in my case, I have to read somet... | 0 | 2016-08-10T16:36:08Z | 38,880,518 | <p>This seems like the kind of thing you'll have to write your own parser to handle. I'd still drop it into a <code>ConfigParser</code> object, but only so it can be more easily used in the future. <code>configparser.ConfigParser</code> can do <em>almost</em> everything you need to do. I'm not aware of any way to tell ... | 0 | 2016-08-10T18:02:06Z | [
"python",
"ini",
"configparser"
] |
Python BST, change data of leaf nodes | 38,879,107 | <p>I'm trying create a function to change the data in the leaf nodes (the ones with no children nodes) in a binary search tree to "Leif". Currently I have this code for my BST:</p>
<pre><code>def add(tree, value, name):
if tree == None:
return {'data':value, 'data1':name, 'left':None, 'right':None}
eli... | 0 | 2016-08-10T16:39:22Z | 39,126,536 | <p>Split the problem into smaller problems which can be solved with simple functions.</p>
<pre><code>from itertools import ifilter
def is_leaf(tree):
return tree['left'] is None and tree['right'] is None
def traverse(tree):
if tree is not None:
yield tree
for side in ['left', 'right']:
... | 0 | 2016-08-24T14:46:27Z | [
"python",
"binary-search-tree"
] |
Python - Removing all numbers that are now smaller than the number behind them | 38,879,119 | <p>I made a function for this in my functions file:</p>
<pre><code>def removeNum(myList):
listSize = len(myList) -1
loop = 0
while loop < listSize:
if myList[loop] > myList[loop + 1]:
myList.remove(myList[loop + 1])
listSize = listSize - 1
loop = loop + 1
... | 1 | 2016-08-10T16:40:13Z | 38,879,497 | <p>One way to approach the problem is to <code>zip</code> the list with a copy of itself offset by 1 and then filter using a list comprehension as follows:</p>
<pre><code>ls = [1, 3, 0, 7, 9, 4]
zipped = zip(ls, ls[0:1] + ls[:-1])
ls_filtered = [p[0] for p in zipped if p[0] >= p[1]]
# ls_filtered is now [1, 3, 7, 9... | 4 | 2016-08-10T17:01:13Z | [
"python",
"arrays",
"list"
] |
Python - Removing all numbers that are now smaller than the number behind them | 38,879,119 | <p>I made a function for this in my functions file:</p>
<pre><code>def removeNum(myList):
listSize = len(myList) -1
loop = 0
while loop < listSize:
if myList[loop] > myList[loop + 1]:
myList.remove(myList[loop + 1])
listSize = listSize - 1
loop = loop + 1
... | 1 | 2016-08-10T16:40:13Z | 38,881,450 | <p>your function is broken, look</p>
<pre><code>>>> removeNum([9, 7, 4, 3, 1, 0])
[9, 4, 1]
</code></pre>
<p>it skip number, the reason is simple</p>
<pre><code>def removeNum(myList):
listSize = len(myList) -1
loop = 0
while loop < listSize:
if myList[loop] > myList[loop + 1]:
... | 1 | 2016-08-10T18:56:23Z | [
"python",
"arrays",
"list"
] |
Python - Removing all numbers that are now smaller than the number behind them | 38,879,119 | <p>I made a function for this in my functions file:</p>
<pre><code>def removeNum(myList):
listSize = len(myList) -1
loop = 0
while loop < listSize:
if myList[loop] > myList[loop + 1]:
myList.remove(myList[loop + 1])
listSize = listSize - 1
loop = loop + 1
... | 1 | 2016-08-10T16:40:13Z | 38,929,885 | <pre class="lang-py prettyprint-override"><code>my_list = [1, 0, 5, 9, 3, 8, 4]
return [item for index, item in enumerate(my_list) if index == 0 or my_list[index] >= my_list[index - 1]]
</code></pre>
<p>this code will iterate over <code>my_list</code> comparing current item to previous taking only ones which are gr... | 0 | 2016-08-13T06:25:34Z | [
"python",
"arrays",
"list"
] |
Python BeautifulSoup - Find all elements whose class names begin with some string | 38,879,133 | <p>Assume that we want to find all <code>li</code> elements whose class names all begin with a known string and end with an arbitrary id number.</p>
<p>That means that this approach doesn't work:</p>
<pre><code>soup.find_all("li", {"class": KNOWN_STRING})
</code></pre>
<p>I have also tried this approach without any ... | 1 | 2016-08-10T16:41:15Z | 38,879,460 | <p>I would use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-regular-expression" rel="nofollow">regex</a> in this approach.</p>
<pre><code>import re
soup.find_all('li', {'class': re.compile(r'regex_pattern')})
</code></pre>
<p>Because you have a known string but an arbitrary (I'm assuming unknown... | 1 | 2016-08-10T16:58:59Z | [
"python",
"html",
"string",
"css-selectors",
"beautifulsoup"
] |
Python BeautifulSoup - Find all elements whose class names begin with some string | 38,879,133 | <p>Assume that we want to find all <code>li</code> elements whose class names all begin with a known string and end with an arbitrary id number.</p>
<p>That means that this approach doesn't work:</p>
<pre><code>soup.find_all("li", {"class": KNOWN_STRING})
</code></pre>
<p>I have also tried this approach without any ... | 1 | 2016-08-10T16:41:15Z | 38,884,314 | <p>You select is incorrect, just use KNOWN_STRING, don't wrap it it quotes and make sure you use a closing bracket:</p>
<pre><code>soup.select("li[class^=KNOWN_STRING]")
</code></pre>
| 0 | 2016-08-10T22:03:32Z | [
"python",
"html",
"string",
"css-selectors",
"beautifulsoup"
] |
Python: Convert a text file multi-level JSON | 38,879,220 | <p>I am writing a script in <code>python</code> to go recursively through each file, create a JSON object from the file that looks like this:</p>
<pre><code>target_id length eff_length est_counts tpm
ENST00000619216.1 68 33.8839 2.83333 4.64528
ENST00000473358.1 712 428.88 0 0
ENST00000469289.1 535 306.... | 0 | 2016-08-10T16:45:52Z | 38,881,540 | <p>First, instead of setting the default value over and over, you should make use of <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a>.</p>
<p>Secondly, I think your proposed structure is off, and you should be using some arrays within (JSO... | 0 | 2016-08-10T19:00:59Z | [
"python",
"json"
] |
random flip m values from an array | 38,879,244 | <p>I have an array with length <code>n</code>, I want to randomly choose <code>m</code> elements from it and flip their value. What is the most efficient way? </p>
<p>there are two cases, <code>m=1</code> case is a special case. It can be discussed separately, and <code>m=/=1</code>.</p>
<p>My attempt is:</p>
<pre><... | 1 | 2016-08-10T16:47:02Z | 38,879,738 | <p>You need to change the index of the array from <code>m</code> to <code>i</code> to actually change the value.
Result:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
n = 20
m = 5
#generate an array a
a = np.random.randint(0,2,n)*2-1
print(a)
#random choose `i` element and flip it.
for i in np... | 0 | 2016-08-10T17:16:47Z | [
"python",
"arrays",
"performance",
"numpy"
] |
random flip m values from an array | 38,879,244 | <p>I have an array with length <code>n</code>, I want to randomly choose <code>m</code> elements from it and flip their value. What is the most efficient way? </p>
<p>there are two cases, <code>m=1</code> case is a special case. It can be discussed separately, and <code>m=/=1</code>.</p>
<p>My attempt is:</p>
<pre><... | 1 | 2016-08-10T16:47:02Z | 38,879,755 | <p>You can make a random permutation of the array indices, take the first <code>m</code> of them and flip their values:</p>
<pre><code>a[np.random.permutation(range(len(a)))[:m]]*=-1
</code></pre>
<p>Using <code>permutation</code> validate you don't choose the same index twice.</p>
| 1 | 2016-08-10T17:17:41Z | [
"python",
"arrays",
"performance",
"numpy"
] |
random flip m values from an array | 38,879,244 | <p>I have an array with length <code>n</code>, I want to randomly choose <code>m</code> elements from it and flip their value. What is the most efficient way? </p>
<p>there are two cases, <code>m=1</code> case is a special case. It can be discussed separately, and <code>m=/=1</code>.</p>
<p>My attempt is:</p>
<pre><... | 1 | 2016-08-10T16:47:02Z | 38,879,832 | <p>To make sure we are not flipping the same element twice or even more times, we can create unique indices in that length range with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html" rel="nofollow"><code>np.random.choice</code></a> using its optional <code>replace</code> argument s... | 3 | 2016-08-10T17:22:27Z | [
"python",
"arrays",
"performance",
"numpy"
] |
Python delete a node in linked list, given just access to that node | 38,879,291 | <p>This is a LeetCode question, I knew its solution, but wondering about why my code not work.</p>
<blockquote>
<p>Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.</p>
<p>Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node wit... | 0 | 2016-08-10T16:49:49Z | 38,879,344 | <p>You were almost there, but are doing way too much work shifting <em>all</em> <code>val</code> values up one node. You also failed to clear the last <code>next</code> reference, which is why you see <code>5</code> printed <em>twice</em>. I'll show you how to solve the problem properly first, then address removing the... | 7 | 2016-08-10T16:53:09Z | [
"python",
"algorithm",
"linked-list"
] |
Python delete a node in linked list, given just access to that node | 38,879,291 | <p>This is a LeetCode question, I knew its solution, but wondering about why my code not work.</p>
<blockquote>
<p>Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.</p>
<p>Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node wit... | 0 | 2016-08-10T16:49:49Z | 38,879,368 | <pre><code>def deleteNode(node):
node.val = node.next.val
node.next = node.next.next
</code></pre>
<p>Since you don't have a reference to your current node, you can't delete it.
But you do have a ref to your next node.
So give your current node the role that your next node previously had,
and then the garbage co... | 1 | 2016-08-10T16:54:26Z | [
"python",
"algorithm",
"linked-list"
] |
How do I use Jinja2 filter on a block with argumets | 38,879,318 | <p>I am trying to use <code>jinja2</code> templates. I have custom filter called <code>highlight</code>, that takes string and language name and passes them to <code>pyhments</code> for code highlightning. I am trying to use it like this:</p>
<pre><code>{% filter highlight("python") %}
import sys
def main():
pass... | 1 | 2016-08-10T16:51:37Z | 39,025,723 | <p>I am an idiot, that was <code>pygments</code> error. By some mistake, I didn't see that last entry in stacktrace was from there.</p>
<p>You should use:</p>
<pre><code>pygments.highlight(
code,
lexer=pygments.lexers.get_lexer_by_name(lang),
formatter=pygments.formatters.get_formatter_by_name('html')
)... | 1 | 2016-08-18T19:03:55Z | [
"python",
"jinja2"
] |
Upgrading to Python correctly on Mac OS X 10.11.6 - issue with the /etc/paths file | 38,879,385 | <p>Python being the new fashionable language, especially in Finance industry, I started learning it.
I downloaded it from the Python website - Python version 3.5.2 - and it successfully installed... in my Application folder.
Just so you know a little bit more about myself, I did an IT engineering school in France, so... | 1 | 2016-08-10T16:55:28Z | 38,883,637 | <p>Run the program from command line using <code>python3 my_script.py</code> or add shebang <code>#!/urs/bin/python3</code></p>
| 0 | 2016-08-10T21:12:21Z | [
"python",
"shell",
"python-3.x",
"osx-elcapitan"
] |
Returning the index in a list from a search hit | 38,879,398 | <p>I'm using a list of names (<code>cust_name</code>) to find if any names in the list are found in any email files located within a folder. I would like to then take the name that the search hit on and create a folder with their id <code>cust_id</code> as the folder name and copy the email file into the new folder. I ... | 0 | 2016-08-10T16:56:20Z | 38,879,557 | <p>Do you mean this? </p>
<pre><code>for index, line in enumerate(content):
</code></pre>
| 2 | 2016-08-10T17:05:11Z | [
"python"
] |
Returning the index in a list from a search hit | 38,879,398 | <p>I'm using a list of names (<code>cust_name</code>) to find if any names in the list are found in any email files located within a folder. I would like to then take the name that the search hit on and create a folder with their id <code>cust_id</code> as the folder name and copy the email file into the new folder. I ... | 0 | 2016-08-10T16:56:20Z | 38,879,758 | <p>You can use enumeration as dhdavvie suggests if you just want the index. For your use case, you can also consider first <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow">zipping</a> the cust_id and cust_name and arrays:</p>
<pre><code>cust_tuples = zip(cust_id, cust_name)
for root, dirs... | 2 | 2016-08-10T17:17:50Z | [
"python"
] |
Python - Should there be made an attempt to be consistent with the arg type in optional args? | 38,879,408 | <p>My doubt is simple. Should I do an effort to be consistent with argument types when using optional arguments?</p>
<p>An example:</p>
<pre><code>def example_method(str_arg_1=None):
if str_arg_1 is not None:
# do something
</code></pre>
<p>My <code>arg</code> is allways a <code>str</code>,except when it... | 0 | 2016-08-10T16:57:09Z | 38,879,744 | <p>Names don't have types; only the values they refer to have types. In this case, it is perfectly normal to document that <code>str_arg_1</code> will refer to a <code>str</code> object or <code>None</code>, with an explanation of what each means. As far as a docstring is concerned, it's safe to say everyone will under... | 4 | 2016-08-10T17:17:03Z | [
"python"
] |
Checking for a Happy number - else statement not working | 38,879,470 | <p>I'm trying to make a program which checks if an entered number is a <a href="https://en.wikipedia.org/wiki/Happy_number" rel="nofollow">happy number</a>.</p>
<p>My code finds each of the numbers after squaring and adding but when it reaches 1, i'd expect it to print "that is a happy number".</p>
<p>I cant see anyt... | -2 | 2016-08-10T16:59:42Z | 38,879,975 | <blockquote>
<p>I cant see anything wrong with the code but i could be missing something simple</p>
</blockquote>
<p>Yup, something simple <code>number = raw_input('What number?')</code> and <code>number = str(added)</code> are making <code>number</code> a string value, but yet you want to check if it is not the int... | 0 | 2016-08-10T17:32:14Z | [
"python"
] |
Evaluating a pandas series with a for loop and nested inequality statement | 38,879,552 | <p>I'm attempting to run a for loop through a pandas dataframe and apply a logic expression to a column in each of the elements of the dataframe. My code compiles without error, but there is no output. </p>
<p>Example code:</p>
<pre><code>for i in df:
if df['value'].all() >= 0.0 and df['value'].all() < 0.05... | 0 | 2016-08-10T17:04:40Z | 38,879,593 | <p><code>.all()</code> is going to return <code>True</code> or <code>False</code> and so based on the order of your checks, you're filtering everything out. I assume what you actually want is <code>(df['value'] >= 0.0).all() and (df['value'] < 0.05).all()</code>. </p>
<p>EDIT: You're also not actually iterating ... | 0 | 2016-08-10T17:07:31Z | [
"python",
"loops",
"pandas"
] |
Evaluating a pandas series with a for loop and nested inequality statement | 38,879,552 | <p>I'm attempting to run a for loop through a pandas dataframe and apply a logic expression to a column in each of the elements of the dataframe. My code compiles without error, but there is no output. </p>
<p>Example code:</p>
<pre><code>for i in df:
if df['value'].all() >= 0.0 and df['value'].all() < 0.05... | 0 | 2016-08-10T17:04:40Z | 38,879,651 | <p>Is this the result you are looking for?</p>
<pre><code>print(df.loc[(df['value'] >= 0.0) & (df['value'] < 0.05), 'value'])
</code></pre>
<p>For just the values, throw this in:</p>
<pre><code>print(df.loc[(df['value'] >= 0.0) & (df['value'] < 0.05), 'value'].values)
</code></pre>
<p>or</p>
<p... | 0 | 2016-08-10T17:11:10Z | [
"python",
"loops",
"pandas"
] |
Evaluating a pandas series with a for loop and nested inequality statement | 38,879,552 | <p>I'm attempting to run a for loop through a pandas dataframe and apply a logic expression to a column in each of the elements of the dataframe. My code compiles without error, but there is no output. </p>
<p>Example code:</p>
<pre><code>for i in df:
if df['value'].all() >= 0.0 and df['value'].all() < 0.05... | 0 | 2016-08-10T17:04:40Z | 38,879,982 | <p>If you are looking to see whether all elements in a column are satisfying that logical expression, this can be used:</p>
<pre><code>np.logical_and(df['value'] >= 0.0, df['value'] < 0.05).all()
</code></pre>
<p>This will return a single <code>True</code> or <code>False</code>.</p>
<p>By the way, I don't see ... | 1 | 2016-08-10T17:32:39Z | [
"python",
"loops",
"pandas"
] |
Log ALL errors without using python logging library | 38,879,601 | <p>I am trying to make a python program that others on my team can use without me having to make a GUI. Thus, it is important that the code they interface is super simple and intuitive to the users. I don't want to put logging code in the main program because I think it would confuse them and I don't know what kind of ... | 0 | 2016-08-10T17:07:57Z | 38,880,022 | <p>You may want to check this question: <a href="http://stackoverflow.com/questions/5136611/capture-stdout-from-a-script-in-python">Capture stdout from a script in Python</a></p>
<p>[edit]removed the code snippept, because it is all there (sorry missed the python 3 examples there)</p>
| -1 | 2016-08-10T17:34:32Z | [
"python",
"logging",
"error-handling"
] |
Setting value by slicing index and conditional rows | 38,879,647 | <p>Trying to set a col 'X' value by slicing on multindex and also accounting for a column 'Z' conditional value. I can set the col 'X' value pretty easily, but I'm getting stuck trying to figure out the conditional.</p>
<pre><code>import pandas as pd
FOOBAR = (['foo','foo','foo','foo','bar','bar','bar','bar'])
NUM1 =... | 4 | 2016-08-10T17:11:01Z | 38,880,451 | <p>This is actually kind of tricky. Feels like there could be a better way - but here's one approach that depends on a little knowledge of the indexing internals - building up the set of locations that that meet your criteria, then passing that all to <code>iloc</code>.</p>
<pre><code>In [80]: cond1 = df.index.get_lo... | 2 | 2016-08-10T17:57:52Z | [
"python",
"pandas",
"dataframe",
"multi-index"
] |
Setting value by slicing index and conditional rows | 38,879,647 | <p>Trying to set a col 'X' value by slicing on multindex and also accounting for a column 'Z' conditional value. I can set the col 'X' value pretty easily, but I'm getting stuck trying to figure out the conditional.</p>
<pre><code>import pandas as pd
FOOBAR = (['foo','foo','foo','foo','bar','bar','bar','bar'])
NUM1 =... | 4 | 2016-08-10T17:11:01Z | 38,880,707 | <p>If the DataFrame, <code>df</code>, had a unique index, then you could use</p>
<pre><code>index1 = df.loc[df['Z'] == 2].index
index2 = df.loc[idx['foo',5,1,:]].index
df.loc[index1.intersection(index2), 'X'] = 999
</code></pre>
<p>Since your <code>df</code> does not have a unique index, you could create a faux index... | 2 | 2016-08-10T18:13:40Z | [
"python",
"pandas",
"dataframe",
"multi-index"
] |
Setting value by slicing index and conditional rows | 38,879,647 | <p>Trying to set a col 'X' value by slicing on multindex and also accounting for a column 'Z' conditional value. I can set the col 'X' value pretty easily, but I'm getting stuck trying to figure out the conditional.</p>
<pre><code>import pandas as pd
FOOBAR = (['foo','foo','foo','foo','bar','bar','bar','bar'])
NUM1 =... | 4 | 2016-08-10T17:11:01Z | 38,907,495 | <p>Figured it out...</p>
<pre><code>mask = df.loc[idx[:],idx['Z']] == 2
df.loc[idx[mask,5,1,:],idx['X']] = 999
</code></pre>
| 0 | 2016-08-11T23:13:33Z | [
"python",
"pandas",
"dataframe",
"multi-index"
] |
Setting value by slicing index and conditional rows | 38,879,647 | <p>Trying to set a col 'X' value by slicing on multindex and also accounting for a column 'Z' conditional value. I can set the col 'X' value pretty easily, but I'm getting stuck trying to figure out the conditional.</p>
<pre><code>import pandas as pd
FOOBAR = (['foo','foo','foo','foo','bar','bar','bar','bar'])
NUM1 =... | 4 | 2016-08-10T17:11:01Z | 38,908,185 | <p>Try this: (one line) </p>
<pre><code>df.loc[idx[:,5,1,(df['Z'] == 2)],idx['X']] = 999
df
FL X Y Z
iFOOBAR iNUM1 iNUM2 iNUM3
bar 5 1 1004 0.1 6 G 7
1005 0.1 7 H 7
8 3 1003 0.4 4 E 5
... | 0 | 2016-08-12T00:45:25Z | [
"python",
"pandas",
"dataframe",
"multi-index"
] |
tensorflow.python.framework.errors.InvalidArgumentError: Field 0 in record 0 is not a valid int32: 1 0 | 38,879,779 | <p>My .<strong>CSV</strong> file contains the data look like this ...
1 0 0 0 0 0 0 0 0 0 0 0</p>
<p>I am trining to read this .CSV file by the following code</p>
<pre><code>filename = "alpha_test.csv"
#setup text reader
file_length = file_len(filename)
filename_queue = tf.train.string_input_pro... | 0 | 2016-08-10T17:19:18Z | 38,906,286 | <p>Most likely reason for the issue you see is that the 1 and 0 in the first line of your file are actually separated by 3 spaces, not a tab. Note how the <code>field_delim</code> is properly set to <code>\t</code> in your call to <code>decode_csv</code>, but the value it seems to read is <code>1 0</code>. This is pr... | 0 | 2016-08-11T21:16:25Z | [
"python",
"numpy",
"tensorflow",
"deep-learning"
] |
Python converting XML to dictionary with namespace names | 38,879,977 | <p>I am trying to figure out how to best parse XML with python in a way I can use. Basically namespaces are very important to the dictionary I need to create, and the ElementTree parser's <code>{http://somewebsite.org/xml/path}(Element)</code> way of doing it doesn't work for me since I need both the URL and the namspa... | 0 | 2016-08-10T17:32:22Z | 38,880,029 | <p>This is the <a href="https://pypi.python.org/pypi/xmljson" rel="nofollow">library</a> you need </p>
<pre><code>pip install xmljson
</code></pre>
<p><a href="https://pypi.python.org/pypi/xmljson" rel="nofollow">https://pypi.python.org/pypi/xmljson</a></p>
<pre><code>>>> from xmljson import badgerfish as b... | -1 | 2016-08-10T17:35:02Z | [
"python",
"xml",
"dictionary"
] |
python - is there a better way of writing this, shorter and easier to add more | 38,880,003 | <p>I'm creating a set of string numbers to be matched with another set of string numbers</p>
<p>this is the long and hard way, is there a better or shorter way where i can easily expand this list to say 500 more</p>
<pre><code> a = i
print 'grabing file',(a)
#print (a)
b = i+1
print 'grabing file',... | -2 | 2016-08-10T17:33:53Z | 38,880,229 | <p>Use a <code>for</code>-loop for the first part:</p>
<pre><code>for a in range(i, i + 93):
print 'grabing file', a
</code></pre>
<p>and the second part is a simple <code>if</code>:</p>
<pre><code>if i <= int(xyz) <= i + 92:
print int(xyz)
</code></pre>
| 3 | 2016-08-10T17:46:09Z | [
"python"
] |
python - is there a better way of writing this, shorter and easier to add more | 38,880,003 | <p>I'm creating a set of string numbers to be matched with another set of string numbers</p>
<p>this is the long and hard way, is there a better or shorter way where i can easily expand this list to say 500 more</p>
<pre><code> a = i
print 'grabing file',(a)
#print (a)
b = i+1
print 'grabing file',... | -2 | 2016-08-10T17:33:53Z | 38,880,242 | <p>Please refer to the python's <a href="https://docs.python.org/3/tutorial/controlflow.html" rel="nofollow">control flow</a> structures, particularly <a href="http://www.tutorialspoint.com/python/python_for_loop.htm" rel="nofollow"><code>for</code></a> loops.</p>
<h3>#1</h3>
<pre><code>i = 100 # Arbitrary Value... | 1 | 2016-08-10T17:46:50Z | [
"python"
] |
python - is there a better way of writing this, shorter and easier to add more | 38,880,003 | <p>I'm creating a set of string numbers to be matched with another set of string numbers</p>
<p>this is the long and hard way, is there a better or shorter way where i can easily expand this list to say 500 more</p>
<pre><code> a = i
print 'grabing file',(a)
#print (a)
b = i+1
print 'grabing file',... | -2 | 2016-08-10T17:33:53Z | 38,880,244 | <p>I would create a dictionary. The keys could just be numbers:</p>
<pre><code>i = 3 #or some other number
d = {}
for x in range(0,92): #you can also change the range to 500 etc
d[x]=i
i +=1
</code></pre>
<p>This creates a dictionary or a system of pairs in this case. A key and a value.</p>
<p>In order to pri... | 0 | 2016-08-10T17:46:57Z | [
"python"
] |
What is the sphinx directive for including a document into another document? | 38,880,277 | <p>In my documentation I have an <code>examples</code> directory where I can say,</p>
<pre><code>.. literalinclude:: examples/1_basic_usage.py
:language: python
:linenos:
</code></pre>
<p>..which works great, because they're code and they're formatted correctly as code.</p>
<p>However, I want to do a <code>lit... | 1 | 2016-08-10T17:48:34Z | 38,880,705 | <p>Apparently the way to do this is with the <code>.. include:: <path></code> directive.</p>
<p>It's no-where obvious in their documentation and doesn't have an example stub at all.</p>
<p>Full documentation can be found in the <a href="http://docutils.sourceforge.net/docs/ref/rst/directives.html#include" rel="... | 1 | 2016-08-10T18:13:37Z | [
"python",
"python-sphinx",
"restructuredtext"
] |
How does sympy simplify ln((exp(x)+1)/exp(x)) to log(1+exp(-x))? | 38,880,320 | <p>If I use <code>simplify()</code> function in sympy, <code>log((exp(x)+1)/exp(x))</code> does simplify to <code>log(1+exp(-x))</code>, however, as I read the doc, the simplify function is "can be unnecessarily slow", I tried other simplification methods, but non of them works, so I'm wondering how do I simplify <code... | 2 | 2016-08-10T17:50:58Z | 38,889,405 | <p>You can more directly just use <a href="http://docs.sympy.org/latest/modules/polys/reference.html?highlight=cancel#sympy.polys.polytools.cancel" rel="nofollow"><strong><code>sympy.polys.polytools.cancel()</code></strong></a>, which is available as a method on your expression with <code>.cancel()</code>. </p>
<pre><... | 3 | 2016-08-11T07:01:16Z | [
"python",
"sympy"
] |
How does sympy simplify ln((exp(x)+1)/exp(x)) to log(1+exp(-x))? | 38,880,320 | <p>If I use <code>simplify()</code> function in sympy, <code>log((exp(x)+1)/exp(x))</code> does simplify to <code>log(1+exp(-x))</code>, however, as I read the doc, the simplify function is "can be unnecessarily slow", I tried other simplification methods, but non of them works, so I'm wondering how do I simplify <code... | 2 | 2016-08-10T17:50:58Z | 38,905,278 | <p>The exact function you want to use depends on the general form of the expressions you are dealing with. <code>cancel</code> apparently works, but perhaps only by accident. In general, <code>cancel</code> cancels common factors from a numerator and denominator, like <code>cancel((x**2 - 1)/(x - 1))</code> -> <code>x ... | 4 | 2016-08-11T20:11:12Z | [
"python",
"sympy"
] |
How to select by categorical index of grouped data using Pandas | 38,880,340 | <p>I am trying to select the data from a grouped categorical index and am unable to select by group.</p>
<p>This data was amassed using pd.cut in bins of 60. The final goal is to select a range of the index then plot the data - however I can't select the data.</p>
<p>For example - I want to select a slice of (0,60] ... | 0 | 2016-08-10T17:51:45Z | 38,880,532 | <p><code>pd.cut</code> just creates string values, so you can give them in a list directly using <code>.ix</code> or just do location indexing with <code>.iloc</code>:</p>
<pre><code>In [7]: df
Out[7]:
0 1
1
(-1, 0] 0.00 0.0
(0, 1] 0.01 1.0
(1, 2] 0.02 2.0
(2, 4] 0.03 3.0
In [8]: df.ix[['(0,... | 2 | 2016-08-10T18:03:03Z | [
"python",
"pandas",
"group-by",
"slice",
"categorical-data"
] |
zipfile.extractall always gives exception | 38,880,384 | <p>Here is my script: </p>
<pre><code>import zipfile
zFile = zipfile.ZipFile('crack.zip')
passFile = open('passwords.txt')
for line in passFile.readlines():
password = line.strip('\n')
try:
zFile.extractall(pwd=password)
print password
except Exception, e:
print e
</code></pre>
<p>Thes... | 0 | 2016-08-10T17:54:07Z | 38,880,581 | <p>After you successfully unzip the file with the right password, you don't stop the loop. Therefore it continues and tries the other three passwords. There are five incorrect passwords in your file so you get five exceptions. To fix this, add a <code>break</code> statement. I rearranged your code a bit, because gener... | 0 | 2016-08-10T18:06:08Z | [
"python",
"python-2.7",
"zipfile"
] |
I have two sets of data and I need to build a data structure that organizers them into sets. (Python) | 38,880,410 | <p>Using Python 2.7. I have one set of data consisting of id tags: </p>
<pre><code>SET1=[{'MISC': u'2759'}, {'MISC': u'2759'}, {'MISC': u'2759'}, {'MISC': u'2758'},{'MISC': u'2758'}, {'MISC': u'1751'}]
</code></pre>
<p>and another set consisting of different id tags: </p>
<pre><code>SET2= [u'15672542c8ed280b', u'156... | 0 | 2016-08-10T17:55:15Z | 38,880,453 | <pre><code>zip([m['MISC'] for m in SET1], SET2)
</code></pre>
<p>That should give you what you want I think, assuming your "sets" (they are actually lists) are the same length.</p>
| 3 | 2016-08-10T17:57:54Z | [
"python",
"set"
] |
I have two sets of data and I need to build a data structure that organizers them into sets. (Python) | 38,880,410 | <p>Using Python 2.7. I have one set of data consisting of id tags: </p>
<pre><code>SET1=[{'MISC': u'2759'}, {'MISC': u'2759'}, {'MISC': u'2759'}, {'MISC': u'2758'},{'MISC': u'2758'}, {'MISC': u'1751'}]
</code></pre>
<p>and another set consisting of different id tags: </p>
<pre><code>SET2= [u'15672542c8ed280b', u'156... | 0 | 2016-08-10T17:55:15Z | 38,880,735 | <p>In one iteration, you could try:</p>
<pre><code>[{a['MISC'], b} for a, b in zip(SET1, SET2)]
</code></pre>
<p>This will produce the list of sets you specified.</p>
<p>This shows more clearly how to iterate both lists in one iteration:</p>
<pre><code>result = []
for i, a in enumerate(SET1):
result.append({a['... | 4 | 2016-08-10T18:15:09Z | [
"python",
"set"
] |
How to reinitialize a class in Python | 38,880,505 | <p>Suppose I have a class <code>Game</code> which plays a game. Once the game is over, I'd like to immediately start a new game. I thought this might possible in a recursive way by instantiating a new <code>Game()</code> within its own class definition. Is this possible?</p>
<p>To give a specific example, I'm writing ... | 0 | 2016-08-10T18:01:34Z | 38,884,212 | <p>In the end I simply did a 'manual' reset of the relevant attributes rather than 're-instantiate' the class. Here is the resulting code:</p>
<pre><code>import numpy as np
import Tkinter as tk
class Game:
def __init__(self, master, player1, player2):
frame = tk.Frame()
frame.grid()
self.m... | 0 | 2016-08-10T21:56:10Z | [
"python",
"tkinter"
] |
Is there a way to schedule sending an e-mail through Google App Engine Mail API (Python)? | 38,880,555 | <p>I want to be able to schedule an e-mail or more of them to be sent on a specific date, preferably using GAE Mail API if possible (so far I haven't found the solution). </p>
<p>Would using Cron be an acceptable workaround and if so, would I even be able to create a Cron task with Python? The dates are various with n... | 0 | 2016-08-10T18:04:32Z | 38,880,681 | <p>Here's a snippet to send mail directly using gmail smtp (just using standard python and smtplib, not google-app-engine but it works fine):</p>
<pre><code>from email.mime.text import MIMEText
import smtplib
msg=MIMEText('hi, sent by python.....','plain','utf-8')
from_addr='user@gmail.com'
password='psw'
to_addr='use... | 0 | 2016-08-10T18:11:36Z | [
"python",
"email",
"google-app-engine",
"cron"
] |
Is there a way to schedule sending an e-mail through Google App Engine Mail API (Python)? | 38,880,555 | <p>I want to be able to schedule an e-mail or more of them to be sent on a specific date, preferably using GAE Mail API if possible (so far I haven't found the solution). </p>
<p>Would using Cron be an acceptable workaround and if so, would I even be able to create a Cron task with Python? The dates are various with n... | 0 | 2016-08-10T18:04:32Z | 38,881,529 | <p>Yes, sending emails from cron jobs is fairly common, exactly for the scheduling reason.</p>
<p>Unfortunately controlling cron jobs programatically is not (yet) possible. You may want to star <a href="https://code.google.com/p/googleappengine/issues/detail?id=3638" rel="nofollow">Issue 3638: Cron jobs to be schedule... | 0 | 2016-08-10T19:00:35Z | [
"python",
"email",
"google-app-engine",
"cron"
] |
Is there a way to schedule sending an e-mail through Google App Engine Mail API (Python)? | 38,880,555 | <p>I want to be able to schedule an e-mail or more of them to be sent on a specific date, preferably using GAE Mail API if possible (so far I haven't found the solution). </p>
<p>Would using Cron be an acceptable workaround and if so, would I even be able to create a Cron task with Python? The dates are various with n... | 0 | 2016-08-10T18:04:32Z | 38,884,139 | <p>You can easily accomplish what you need with Task API. When you create a task, you can set an ETA parameter (when to execute). ETA time can be up to 30 days into the future.</p>
<p>If 30 days is not enough, you can store a "send_email" entity in the Datastore, and set one of the properties to the date/time when thi... | 2 | 2016-08-10T21:49:41Z | [
"python",
"email",
"google-app-engine",
"cron"
] |
Repetitve seach and replace on constantly changing file. Python | 38,880,640 | <p>So I'm trying to have a script that will run every 3 seconds to read a text file, clean it up and write is as another text file. The original text file is always changing. It's from a music playout program, current song title. I went collecting bits of python code around the internet and personalizing them to my nee... | 1 | 2016-08-10T18:09:08Z | 38,920,138 | <p>When the original file is modified, the file reference <code>intext</code> is no longer a valid file. While the path is the same, the actual file has been modified. Thus, you should call <code>intext.close()</code> at the end of the <code>for</code> loop. To make sure it is actually recreating the file reference ... | 1 | 2016-08-12T14:13:16Z | [
"python",
"windows"
] |
Spark Flume streaming - missing packages? | 38,880,649 | <p>I try to execute the example of flume streaming but can't have my jars files working :
Here
<a href="https://github.com/spark-packages/dstream-flume/blob/master/examples/src/main/python/streaming/flume_wordcount.py" rel="nofollow">https://github.com/spark-packages/dstream-flume/blob/master/examples/src/main/python... | 0 | 2016-08-10T18:09:46Z | 38,883,060 | <p>I found my mistake : the jars file I downloaded were empty !</p>
<p>:-(((((
the mistake came from =
curl -O <a href="http://search.maven.org/remotecontent?filepath=org/apache/spark/spark-streaming-flume-sink_2.10/1.6.2/spark-streaming-flume-sink_2.10-1.6.2.jar" rel="nofollow">http://search.maven.org/remotecontent?... | 0 | 2016-08-10T20:34:21Z | [
"python",
"apache-spark"
] |
Analysing merge sort complexity | 38,880,719 | <p>The code I wrote is as follows:</p>
<pre><code>def merge(A, B): #merging two sorted lists
index_a = index_b = 0
result = []
while(index_a < len(A) and index_b < len(B)):
if(A[index_a] <= B[index_b]):
result += [A[index_a]]
index_a += 1
else:
result +=... | 0 | 2016-08-10T18:14:34Z | 38,880,850 | <p>The way you've structured your merge, while slightly more performant, makes it trickier to see the complexity. Try this: </p>
<pre><code>def merge(A, B): #merging two sorted lists
index_a = index_b = 0
result = []
while(index_a < len(A) or index_b < len(B)): # NOTE OR
if index_a < len(A) an... | 0 | 2016-08-10T18:21:49Z | [
"python",
"time-complexity",
"big-o",
"mergesort"
] |
telnet over SSH from server | 38,880,723 | <p>I am doing ssh to a server using parmiko in python. From there, I need to telnet to several devices and capture the output. I am able to ssh and then telnet to only one device but not ablke to telnet multiple devices from a loop. please suggest me how to do this.
I am using the following </p>
<pre><code>import para... | 3 | 2016-08-10T18:14:39Z | 38,880,916 | <p>You should likely be using a <code>for</code> loop instead:</p>
<pre><code>for i in f.readlines():
cmd = "telnet {0}".format(i)
print cmd
</code></pre>
<p>Ideally you'd want to execute the commands with:</p>
<pre><code>ssh.exec_command(cmd)
</code></pre>
<p>Then you could use it like the following exampl... | 1 | 2016-08-10T18:25:17Z | [
"python",
"ssh",
"telnet"
] |
Python OpenCV cv2.VideoWriter Error | 38,880,740 | <p>I'm trying to export the data coming from a thermal camera but I get an error message that says</p>
<pre><code>error: /build/opencv-ISmtkH/opencv-2.4.9.1+dfsg/modules/highgui/src/cap_ffmpeg.cpp:238: error: (-215) image->depth == 8 in function writeFrame
</code></pre>
<p>Can someone look at what I'm doing and te... | 1 | 2016-08-10T18:15:21Z | 38,881,513 | <p>You need to change <code>out.write(lepton_buf)</code> to <code>out.write(np.uint8(lepton_buf))</code></p>
<p>What you're trying to write isn't a number and that's what's confusing it.</p>
| 1 | 2016-08-10T18:59:23Z | [
"python",
"opencv",
"camera",
"thermal-printer"
] |
Python OpenCV cv2.VideoWriter Error | 38,880,740 | <p>I'm trying to export the data coming from a thermal camera but I get an error message that says</p>
<pre><code>error: /build/opencv-ISmtkH/opencv-2.4.9.1+dfsg/modules/highgui/src/cap_ffmpeg.cpp:238: error: (-215) image->depth == 8 in function writeFrame
</code></pre>
<p>Can someone look at what I'm doing and te... | 1 | 2016-08-10T18:15:21Z | 38,883,927 | <p>Several suggestions to try</p>
<p>Try a more common codec:</p>
<pre><code>fourcc=cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
</code></pre>
<p>make sure your video dimensions fit the image dimensions. Try
swapping width and height, the order of these can be confusing.</p>
<pre><code>height,width,channels=lepton_bu... | 0 | 2016-08-10T21:32:45Z | [
"python",
"opencv",
"camera",
"thermal-printer"
] |
csv files comparing, parsing, and writing (Linearly?) | 38,880,759 | <p>The below code looks at csv files, file1 and file2. According to a unique key from each file, Compares them with a csv cross-reference file and if there is a match it compares the unique identifiers from file1 and file2 together, if there is a match it will pick the values from file2 and do a write, otherwise it wil... | 0 | 2016-08-10T18:16:18Z | 38,882,070 | <p>1st the provided code is much too complicated, try to make it easier. Use better names (which file contains these cross reference(s)?)</p>
<p>I think smaller steps are the right way to solve this issue, somethink like:</p>
<pre><code>dict1 = get_dict_from_csv('file1.csv')
dict2 = get_dict_from_csv('file2.csv')
cro... | 0 | 2016-08-10T19:35:09Z | [
"python",
"python-3.x",
"csv",
"parsing"
] |
Search for pattern in string and add characters if found | 38,880,831 | <p>I am working on some address cleaning/geocoding software, and I recently ran into a specfic address format that is causing some problems for me.</p>
<p>My external geocoding module is having trouble finding addresses such as <code>30 w 60th new york</code> (<code>30 w 60th street new york</code> is the proper forma... | -1 | 2016-08-10T18:20:44Z | 38,881,054 | <p>While you could certainly use regex for this sort of problem, I can't help, but think that there's most likely a Python library out there that has already solved this problem for you. I've never used these, but just some quick searching finds me these:</p>
<p><a href="https://github.com/datamade/usaddress" rel="no... | 1 | 2016-08-10T18:33:12Z | [
"python"
] |
Search for pattern in string and add characters if found | 38,880,831 | <p>I am working on some address cleaning/geocoding software, and I recently ran into a specfic address format that is causing some problems for me.</p>
<p>My external geocoding module is having trouble finding addresses such as <code>30 w 60th new york</code> (<code>30 w 60th street new york</code> is the proper forma... | -1 | 2016-08-10T18:20:44Z | 38,881,060 | <p>You could possibly do this by turning each one of those strings into lists, and looking for certain groups of characters in those lists. For example:</p>
<pre><code>def check_th(address):
addressList = list(address)
for character in addressList:
if character == 't':
charIndex = addressL... | 0 | 2016-08-10T18:33:29Z | [
"python"
] |
Search for pattern in string and add characters if found | 38,880,831 | <p>I am working on some address cleaning/geocoding software, and I recently ran into a specfic address format that is causing some problems for me.</p>
<p>My external geocoding module is having trouble finding addresses such as <code>30 w 60th new york</code> (<code>30 w 60th street new york</code> is the proper forma... | -1 | 2016-08-10T18:20:44Z | 38,881,831 | <p>To check and add the word street, the following function should work as long as the street number comes before its name:</p>
<pre><code>def check_add_street(address):
addressList = list(address)
for character in addressList:
if character == 't':
charIndex_t = addressList.index(characte... | 0 | 2016-08-10T19:18:07Z | [
"python"
] |
Search for pattern in string and add characters if found | 38,880,831 | <p>I am working on some address cleaning/geocoding software, and I recently ran into a specfic address format that is causing some problems for me.</p>
<p>My external geocoding module is having trouble finding addresses such as <code>30 w 60th new york</code> (<code>30 w 60th street new york</code> is the proper forma... | -1 | 2016-08-10T18:20:44Z | 38,882,942 | <p>It seems that your looking for regexp. = P</p>
<p>Here some code I build specialy for you : </p>
<pre><code>import re
def check_th_add_street(address):
# compile regexp rule
has_th_st_nd_rd = re.compile(r"(?P<number>[\d]{1,3}(st|nd|rd|th)\s)(?P<following>.*)")
# first check if the addres... | 2 | 2016-08-10T20:27:44Z | [
"python"
] |
How to download PyHook module | 38,880,842 | <p>I have tried to install PyHook but I'm still getting the error: </p>
<blockquote>
<p>ImportError: No module named 'pyhook'</p>
</blockquote>
<p>Please give a me solution. How do I solve this error.</p>
<p>I am making a key-logger program.</p>
<pre><code>**code:**
import pythoncom, pyHook, sys, logging
LOG_FILE... | 0 | 2016-08-10T18:21:17Z | 38,881,110 | <p>First just check which python version you're running, in my case when i type python i'll see:</p>
<blockquote>
<p>Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32</p>
</blockquote>
<p>That means I'd need to install the 64bits version for python 2.7, the simplest wa... | 0 | 2016-08-10T18:37:07Z | [
"python",
"python-2.7"
] |
How to download PyHook module | 38,880,842 | <p>I have tried to install PyHook but I'm still getting the error: </p>
<blockquote>
<p>ImportError: No module named 'pyhook'</p>
</blockquote>
<p>Please give a me solution. How do I solve this error.</p>
<p>I am making a key-logger program.</p>
<pre><code>**code:**
import pythoncom, pyHook, sys, logging
LOG_FILE... | 0 | 2016-08-10T18:21:17Z | 38,881,207 | <p>First of. If you want PyHook your going to have to download it your self, since it is not part of the standard <a href="https://docs.python.org/2/library/" rel="nofollow">python library</a> that comes with python. There are my ways you could go about installing it. But the way I recommend is:</p>
<p><strong>1</stro... | 0 | 2016-08-10T18:42:01Z | [
"python",
"python-2.7"
] |
Python Networkx: preserving nodes ID when saving/serializing networks to hardisk | 38,880,872 | <p>I am using networkx1.10 in Python for a project that requires to dump the networks on the hardisk and later reload them in order to continue a the execution of some algorithm that manipulates such networks.</p>
<p>I've been trying doing that in a couple of different ways: using nx.write_gml() and nx_read_gml() at f... | 0 | 2016-08-10T18:22:37Z | 38,881,566 | <p>They seem to be the same graphs, up to isomorphism.</p>
<p>Your issue may be node order. Indeed, networkx uses dicts to store nodes and edges, which are unordered and randomized.</p>
<p>You have two solutions: either ignore that, or use ordered graphs:</p>
<pre><code>>>> class OrderedGraph(nx.Graph):
...... | 1 | 2016-08-10T19:02:05Z | [
"python",
"serialization",
"pickle",
"networkx",
"gml"
] |
SWIG 'cstring.i' Python return byte type instead of string type | 38,880,899 | <p>I have a C function like</p>
<pre><code>int foo(void ** buf, int * buf_size)
</code></pre>
<p>And I use <code>cstring.i</code> to wrap it for use in Python 3. The result of the wrapped Python function is of type string. </p>
<p>Is there a way to get the result as type binary?</p>
<p>Background: The data <code>bu... | 1 | 2016-08-10T18:24:25Z | 39,215,938 | <p>I solved my problem using <code>ctypes</code>, with the help of <a href="https://github.com/bit-01101/ctypesgen" rel="nofollow">https://github.com/bit-01101/ctypesgen</a></p>
| 0 | 2016-08-29T22:08:41Z | [
"python",
"swig"
] |
SWIG 'cstring.i' Python return byte type instead of string type | 38,880,899 | <p>I have a C function like</p>
<pre><code>int foo(void ** buf, int * buf_size)
</code></pre>
<p>And I use <code>cstring.i</code> to wrap it for use in Python 3. The result of the wrapped Python function is of type string. </p>
<p>Is there a way to get the result as type binary?</p>
<p>Background: The data <code>bu... | 1 | 2016-08-10T18:24:25Z | 39,518,594 | <p>If you use <code>%cstring_output_allocate_size</code> the wrapper function <code>_wrap_foo</code> calls <code>SWIG_FromCharPtrAndSize()</code> which has the following decoding logic:</p>
<pre><code>#if PY_VERSION_HEX >= 0x03000000
#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR)
return PyBytes_FromStringAndSize(c... | 0 | 2016-09-15T19:06:45Z | [
"python",
"swig"
] |
Keyed Random Shuffles in Python | 38,880,960 | <p>I have a list <code>a=[num1,num2,...,numn]</code>. I am shuffling it with <code>random.shuffle(a)</code>. However what I want as a functionality is the shuffle algorithm to take as input a key, and the owner of the key to deterministically produce the same shuffles?</p>
<p>I want an algorithm that takes as input th... | 0 | 2016-08-10T18:28:08Z | 38,881,327 | <p>In pseudo-random terminology, that key is called a <em>seed</em>, and you can set the random seed on a new <code>random.Random()</code> instance:</p>
<pre><code>def keyed_shuffle(x, seed=None):
random_obj = random.Random(seed)
random_obj.shuffle(x)
</code></pre>
<p>You could use <a href="https://docs.pytho... | 2 | 2016-08-10T18:50:16Z | [
"python",
"random",
"shuffle"
] |
Mac OSX $python3 test_imagenet.py --image images/dog_beagle.png ImportError: No module named 'cv2' | 38,880,999 | <p>I am using the tutorial found <a href="http://www.pyimagesearch.com/2016/08/10/imagenet-classification-with-python-and-keras/" rel="nofollow">here</a></p>
<p>The error I get on the command line and for the Pycharm IDE is that <code>cv2</code> can't be installed. Is this a problem because I am using a Macbook or can... | 0 | 2016-08-10T18:30:05Z | 38,881,348 | <p>If the error is saying "no module named cv2", you need to install OpenCV. You can do this with homebrew using <code>brew install opencv</code></p>
<p>For detailed instructions, take a look at: <a href="http://www.mobileway.net/2015/02/14/install-opencv-for-python-on-mac-os-x/" rel="nofollow">http://www.mobileway.ne... | 0 | 2016-08-10T18:51:27Z | [
"python",
"osx",
"computer-vision",
"keras"
] |
PIL isn't able to show images | 38,881,015 | <p>I've been trying to show a image with PIL but I don't know why the image viewer keeps giving me this:"Windows photo viewer can't open this picture because either the picture is deleted,or it's in a location that isn't available.
I've checked the pic is on my desktop and doesn't have any problem.
Here is my code:</p>... | 1 | 2016-08-10T18:31:05Z | 38,881,411 | <p>Try this little snippet:</p>
<pre><code>from PIL import Image
import os
home_path = os.path.expanduser('~')
filename = os.path.join(home_path,'Desktop','photo_2016-08-04_22-38-11.jpg')
if os.path.exists(filename):
print "Opening filename {0}".format(filename)
img = Image.open(filename)
img.show()
else... | 0 | 2016-08-10T18:54:37Z | [
"python",
"windows",
"python-imaging-library"
] |
How to create subplots with Pandas Scatter Matrix | 38,881,265 | <p>So I'm trying to create a subplot of pandas scatter matrices but have run into a bit of a wall. I've looked around at other similar questions, but none of the answers seemed to fix it. Right now I'm just trying to create a subplot of 2 of them. I'm going to move to a two by two subplot at some point, but am just try... | 0 | 2016-08-10T18:46:13Z | 38,883,657 | <p><code>pandas</code> doesn't currently do that, although it has a promising <code>ax</code> argument:</p>
<pre><code>iris = pd.DataFrame.from_csv('iris.csv')
chicks = pd.DataFrame.from_csv('ChickWeight.csv')
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2)
#iris.plot.scatter('PL', 'PW', ax = axs[0]) ... | 0 | 2016-08-10T21:13:21Z | [
"python",
"pandas",
"matplotlib"
] |
Python+Memcache changing array to string | 38,881,272 | <p>I am using Amazon Elasticache and pythons <code>pymemcache</code> module.</p>
<pre><code>client = Client(('xxxx', 11211))
test=[1,2,3,4]
client.set('test_key', test)
result = client.get('test_key')
pprint.pprint(result)
pprint.pprint(test)
</code></pre>
<p>This outputs the following:</p>
<pre><code>'[1, 2, 3, 4]... | 1 | 2016-08-10T18:46:22Z | 38,881,381 | <p>It seems the library wants you to serialise your data first.
<a href="https://pymemcache.readthedocs.io/en/latest/getting_started.html#serialization" rel="nofollow">https://pymemcache.readthedocs.io/en/latest/getting_started.html#serialization</a></p>
<p>Maybe you could use an alternative library?
<a href="https://... | 0 | 2016-08-10T18:53:05Z | [
"python",
"arrays",
"memcached"
] |
Python+Memcache changing array to string | 38,881,272 | <p>I am using Amazon Elasticache and pythons <code>pymemcache</code> module.</p>
<pre><code>client = Client(('xxxx', 11211))
test=[1,2,3,4]
client.set('test_key', test)
result = client.get('test_key')
pprint.pprint(result)
pprint.pprint(test)
</code></pre>
<p>This outputs the following:</p>
<pre><code>'[1, 2, 3, 4]... | 1 | 2016-08-10T18:46:22Z | 38,881,506 | <p>Memcache itself stores values as strings. You can <a href="http://pymemcache.readthedocs.io/en/latest/getting_started.html#serialization" rel="nofollow">customize your serialization</a> in <code>pymemcache</code> if needed. It looks like by <a href="http://pymemcache.readthedocs.io/en/latest/apidoc/pymemcache.client... | 1 | 2016-08-10T18:59:02Z | [
"python",
"arrays",
"memcached"
] |
Frequency of each word in pandas DataFrame | 38,881,305 | <p>I have a pandas DataFrame which look like following </p>
<pre><code> key message Final Category
0 1 I have not received my gifts which I ordered ok voucher
1 2 hth her wells idyll McGill kooky bbc.co noclass
2 3 test test test 1 test ... | 2 | 2016-08-10T18:48:36Z | 38,881,744 | <p>There's probably a more eloquent way to do this, but here it is with a bunch of nested for loops:</p>
<pre><code>final_cat_list = df['Final Category'].unique()
word_count = {}
for f in final_cat_list:
word_count[f] = {}
message_list = list(df.loc[df['Final Category'] == f, 'key message'])
for m in mess... | 0 | 2016-08-10T19:13:08Z | [
"python",
"pandas",
"dataframe"
] |
Frequency of each word in pandas DataFrame | 38,881,305 | <p>I have a pandas DataFrame which look like following </p>
<pre><code> key message Final Category
0 1 I have not received my gifts which I ordered ok voucher
1 2 hth her wells idyll McGill kooky bbc.co noclass
2 3 test test test 1 test ... | 2 | 2016-08-10T18:48:36Z | 38,881,873 | <p>This modifies the original df, so you might wanna copy it first</p>
<pre><code>from collections import Counter
df["message"] = df["message"].apply(lambda message: message + " ")
df.groupby(["Final Category"]).sum().applymap(lambda message: Counter(message.split()))
</code></pre>
<p>What this code does: first it ad... | 0 | 2016-08-10T19:21:41Z | [
"python",
"pandas",
"dataframe"
] |
Frequency of each word in pandas DataFrame | 38,881,305 | <p>I have a pandas DataFrame which look like following </p>
<pre><code> key message Final Category
0 1 I have not received my gifts which I ordered ok voucher
1 2 hth her wells idyll McGill kooky bbc.co noclass
2 3 test test test 1 test ... | 2 | 2016-08-10T18:48:36Z | 38,882,012 | <pre><code>import pandas as pd
import numpy as np
# copy/paste data (you can skip this since you already have a dataframe)
dict = {0 : {'key': 1 , 'message': "I have not received my gifts which I ordered ok", 'Final Category': 'voucher'},
1 : {'key': 2 , 'message': "hth her wells idyll McGill kooky bbc.co... | 0 | 2016-08-10T19:31:30Z | [
"python",
"pandas",
"dataframe"
] |
Twitter data to csv, getting error when trying to add to CSV file | 38,881,314 | <p>Trying to put the last 24hrs of data into a CSV file and getting using tweepy for python</p>
<pre><code>Traceback (most recent call last):
File "**", line 74, in <module>
get_all_tweets("BQ")
File "**", line 66, in get_all_tweets
writer.writerows(outtweets)
File "C:\Users\Barry\AppData\Local\Programs\Python\P... | -1 | 2016-08-10T18:49:23Z | 38,881,969 | <p>It seems that the character is something that cannot be encoded into utf-8. While it may be useful to view the tweet in question that triggered the error, you can prevent such an error in the future by changing <code>tweet.text.encode("utf-8")</code> to either <code>tweet.text.encode("utf-8", "ignore")</code>, <code... | 0 | 2016-08-10T19:28:16Z | [
"python",
"csv",
"twitter",
"tweepy"
] |
Twitter data to csv, getting error when trying to add to CSV file | 38,881,314 | <p>Trying to put the last 24hrs of data into a CSV file and getting using tweepy for python</p>
<pre><code>Traceback (most recent call last):
File "**", line 74, in <module>
get_all_tweets("BQ")
File "**", line 66, in get_all_tweets
writer.writerows(outtweets)
File "C:\Users\Barry\AppData\Local\Programs\Python\P... | -1 | 2016-08-10T18:49:23Z | 38,882,062 | <p>Your problem is with the characters in some tweets. You're not able to write them to the file you open.
If you replace this line</p>
<pre><code>with open('%s_tweets.csv' % screen_name, 'w') as f:
</code></pre>
<p>with this:</p>
<pre><code>with open('%s_tweets.csv' % screen_name, mode='w', encoding='utf-8') as f:
... | 0 | 2016-08-10T19:34:37Z | [
"python",
"csv",
"twitter",
"tweepy"
] |
Data in HDF file using Python missing | 38,881,326 | <p>I am trying to read in a hdf file but no groups show up. I have tried a couple different methods using tables and h5py but neither work in displaying the groups in the file. I checked and the file is 'Hierarchical Data Format (version 5) data' (See Update). The file information is <a href="https://ghrc.nsstc.nasa.go... | 1 | 2016-08-10T18:50:08Z | 38,881,492 | <p>Try using pandas:</p>
<pre><code>import pandas as pd
f = pd.read_hdf(C:/path/to/file)
</code></pre>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_hdf.html" rel="nofollow">See Pandas HDF documentation here.</a></p>
<p>This should read in any hdf file as a dataframe you can then mani... | 0 | 2016-08-10T18:58:25Z | [
"python",
"pandas",
"h5py",
"hdf"
] |
Data in HDF file using Python missing | 38,881,326 | <p>I am trying to read in a hdf file but no groups show up. I have tried a couple different methods using tables and h5py but neither work in displaying the groups in the file. I checked and the file is 'Hierarchical Data Format (version 5) data' (See Update). The file information is <a href="https://ghrc.nsstc.nasa.go... | 1 | 2016-08-10T18:50:08Z | 38,881,503 | <p>How big is the file? I think that doing <code>h5py.File(hdffile,'w')</code> overwrites it, so it's empty. Use <code>h5py.File(hdffile,'r')</code> to read.</p>
<p>I don't have enough karma to reply to @Luke H's answer, but reading it into pandas might not be a good idea. Pandas hdf5 uses pytables, which is an "opini... | 4 | 2016-08-10T18:58:57Z | [
"python",
"pandas",
"h5py",
"hdf"
] |
Data in HDF file using Python missing | 38,881,326 | <p>I am trying to read in a hdf file but no groups show up. I have tried a couple different methods using tables and h5py but neither work in displaying the groups in the file. I checked and the file is 'Hierarchical Data Format (version 5) data' (See Update). The file information is <a href="https://ghrc.nsstc.nasa.go... | 1 | 2016-08-10T18:50:08Z | 38,881,824 | <p><strong>UPDATE:</strong></p>
<p>i would recommend you first to <a href="https://www.hdfgroup.org/h4toh5/download.html" rel="nofollow">convert</a> your HDF version 4 files to HDF5 / h5 files as all modern libraries / modules are working with HDF version 5... </p>
<p><strong>OLD answer:</strong></p>
<p>try it this ... | 1 | 2016-08-10T19:17:52Z | [
"python",
"pandas",
"h5py",
"hdf"
] |
How can I select entries from list in random order in python | 38,881,468 | <p>Question is simple. I have a list of say 10 entries, I am running a loop over it. What i want here is getting each entry exactly once but in random order.</p>
<p>What is the best and most pythonic way to do it?</p>
| 2 | 2016-08-10T18:57:08Z | 38,881,508 | <pre><code>import random
s=set(range(10))
while len(s)>0:
s.remove(random.choice(yourlist(s)))
print(s)
</code></pre>
| -2 | 2016-08-10T18:59:13Z | [
"python",
"list"
] |
How can I select entries from list in random order in python | 38,881,468 | <p>Question is simple. I have a list of say 10 entries, I am running a loop over it. What i want here is getting each entry exactly once but in random order.</p>
<p>What is the best and most pythonic way to do it?</p>
| 2 | 2016-08-10T18:57:08Z | 38,881,536 | <p>You can use <a href="https://docs.python.org/2/library/random.html" rel="nofollow"><code>random.shuffle</code></a>:</p>
<pre><code>In [1]: import random
In [3]: a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [4]: random.shuffle(a)
In [5]: a
Out[5]: [3, 6, 9, 1, 8, 0, 4, 7, 5, 2]
</code></pre>
| 4 | 2016-08-10T19:00:53Z | [
"python",
"list"
] |
How can I select entries from list in random order in python | 38,881,468 | <p>Question is simple. I have a list of say 10 entries, I am running a loop over it. What i want here is getting each entry exactly once but in random order.</p>
<p>What is the best and most pythonic way to do it?</p>
| 2 | 2016-08-10T18:57:08Z | 38,881,544 | <p>Shuffle the list first by importing the <code>random</code> module and using the <code>shuffle</code> function:</p>
<pre><code>import random
x = ... # A list
random.shuffle(x)
</code></pre>
<p>Then loop over your list. Note that <code>shuffle</code> mutates the original list and does not return the shuffled versio... | 0 | 2016-08-10T19:01:07Z | [
"python",
"list"
] |
How can I select entries from list in random order in python | 38,881,468 | <p>Question is simple. I have a list of say 10 entries, I am running a loop over it. What i want here is getting each entry exactly once but in random order.</p>
<p>What is the best and most pythonic way to do it?</p>
| 2 | 2016-08-10T18:57:08Z | 38,881,564 | <p>you could use <a href="https://docs.python.org/3.5/library/random.html#random.shuffle" rel="nofollow"><code>random.shuffle()</code></a>:</p>
<pre><code>import random
original = range(10)
# Make a copy of the original list, as shuffling will be in-place
shuffled = list(original)
random.shuffle(shuffled)
</code></pr... | 0 | 2016-08-10T19:01:59Z | [
"python",
"list"
] |
How can I select entries from list in random order in python | 38,881,468 | <p>Question is simple. I have a list of say 10 entries, I am running a loop over it. What i want here is getting each entry exactly once but in random order.</p>
<p>What is the best and most pythonic way to do it?</p>
| 2 | 2016-08-10T18:57:08Z | 38,881,576 | <p>You could use shuffle:</p>
<pre><code>import random
random.shuffle(yourlist)
# loop as you would normally
for item in yourlist:
.....
</code></pre>
| 0 | 2016-08-10T19:02:32Z | [
"python",
"list"
] |
How can I select entries from list in random order in python | 38,881,468 | <p>Question is simple. I have a list of say 10 entries, I am running a loop over it. What i want here is getting each entry exactly once but in random order.</p>
<p>What is the best and most pythonic way to do it?</p>
| 2 | 2016-08-10T18:57:08Z | 38,881,603 | <p>You can use <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow"><code>random.sample</code></a>, it returns random elements preventing duplicates:</p>
<pre><code>>>> import random
>>> data = range(10)
>>> print(random.sample(data, len(data)))
[2, 4, 8, 7, 0... | 5 | 2016-08-10T19:04:23Z | [
"python",
"list"
] |
Django raw sql format tablename | 38,881,482 | <p>I am trying to interpolate the tablename into a raw sql but it's interpolating a badly formatted string so the SQL query fails. I can't find a proper way of interpolating the string into the SQL query properyly:</p>
<pre><code>from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT * fr... | 1 | 2016-08-10T18:57:57Z | 38,881,521 | <p>You can't pass table nor column names as parameter arguments. Instead do something like:</p>
<pre><code>qry = "SELECT * from %s;" % 'product'
cursor.execute(qry)
</code></pre>
<p>While being mindful of the possibility of <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofollow">SQL-injection</a> attack.... | 4 | 2016-08-10T18:59:49Z | [
"python",
"django",
"postgresql"
] |
pyspark group and split dataframe | 38,881,644 | <p>I am trying to filter and then split a dataset into two separate files.</p>
<p>Dataset: test.txt (Schema: uid, prod, score)</p>
<pre><code>1 XYZ 2.0
2 ABC 0.5
1 PQR 1.0
2 XYZ 2.1
3 PQR 0.5
1 ABC 0.5
</code></pre>
<p>First, I want to filter any uid having less than or equal to 1 product. I have already... | 0 | 2016-08-10T19:06:31Z | 38,883,244 | <p>I think the key issue here is that you don't have a primary key for your data.</p>
<pre><code>all_data = all_data.withColumn(
'id',
monotonically_increasing_id()
)
train = all_data.dropDuplicates(['prod'])
# could OOM if your dataset is too big
# consider BloomFilter if so
all_id = {row['id'] for row in a... | 0 | 2016-08-10T20:47:37Z | [
"python",
"pyspark",
"spark-dataframe"
] |
Multiple insertion of one value in sqlalchemy statement to pandas | 38,881,676 | <p>I have constructed a sql clause where I reference the same table as <code>a</code> and <code>b</code> to compare the two geometries as a postgis command. </p>
<p>I would like to pass a value into the sql statement using the <code>%s</code> operator and read the result into a pandas dataframe using <code>to_sql, par... | 0 | 2016-08-10T19:08:27Z | 38,882,015 | <ul>
<li><p>You dont need the subqueries, just join the table with itself:</p>
<p><code>SELECT a.*, b.* -- or whatwever
, st_distance(a.the_geom, b.the_geom, true) AS dist
FROM ztable a
JOIN ztable b ON a.nid < b.nid
WHERE a.id IN (%s)
AND b.id IN (%s)
;</code></p>... | 1 | 2016-08-10T19:31:46Z | [
"python",
"sql",
"postgresql",
"pandas",
"sqlalchemy"
] |
Multiple insertion of one value in sqlalchemy statement to pandas | 38,881,676 | <p>I have constructed a sql clause where I reference the same table as <code>a</code> and <code>b</code> to compare the two geometries as a postgis command. </p>
<p>I would like to pass a value into the sql statement using the <code>%s</code> operator and read the result into a pandas dataframe using <code>to_sql, par... | 0 | 2016-08-10T19:08:27Z | 38,882,461 | <p>first of all i would recommend you to use <a href="http://stackoverflow.com/a/38882015/5741205">updated SQL from @wildplasser</a> - it's much better and more efficient way to do that.</p>
<p>now you can do the following:</p>
<pre><code>sql_ = """\
WITH zt AS (
SELECT * FROM ztable
WHERE id IN ({})
... | 0 | 2016-08-10T19:58:52Z | [
"python",
"sql",
"postgresql",
"pandas",
"sqlalchemy"
] |
Group pandas dataframe by a nested dictionary key | 38,881,679 | <p>I have a pandas dataframe where one of the columns is dictionary type. This is an example dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a': [1,2,3],
'b': [4,5,6],
'version': [{'major': 7, 'minor':1},
{'major':8, 'minor': 5},... | 3 | 2016-08-10T19:08:41Z | 38,881,727 | <p><strong><em>Option 1</em></strong></p>
<pre><code>df.groupby(df.version.apply(lambda x: x['major'])).size()
version
7 2
8 1
dtype: int64
</code></pre>
<hr>
<pre><code>df.groupby(df.version.apply(lambda x: x['major']))[['a', 'b']].sum()
</code></pre>
<p><a href="http://i.stack.imgur.com/SNnuY.png" rel="nof... | 3 | 2016-08-10T19:11:53Z | [
"python",
"pandas",
"dictionary",
"dataframe"
] |
Group pandas dataframe by a nested dictionary key | 38,881,679 | <p>I have a pandas dataframe where one of the columns is dictionary type. This is an example dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a': [1,2,3],
'b': [4,5,6],
'version': [{'major': 7, 'minor':1},
{'major':8, 'minor': 5},... | 3 | 2016-08-10T19:08:41Z | 38,881,741 | <p>you can do it this way:</p>
<pre><code>In [15]: df.assign(major=df.version.apply(pd.Series).major).groupby('major').sum()
Out[15]:
a b
major
7 4 10
8 2 5
</code></pre>
| 2 | 2016-08-10T19:13:00Z | [
"python",
"pandas",
"dictionary",
"dataframe"
] |
re.sub() documentation misunderstanding | 38,881,732 | <p>I've just started learning regular expressions and the documentation for <code>re.sub()</code> states:</p>
<blockquote>
<p><strong>Changed in version 3.5</strong>: Unmatched groups are replaced with an empty
string.</p>
<p><strong>Deprecated since version 3.5, will be removed in version 3.6</strong>: Unkn... | -1 | 2016-08-10T19:12:19Z | 38,881,783 | <p>The two entries are not related, and <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow"><strong><code>re.sub</code></strong></a> will <em>not</em> be deprecated.</p>
<p>In Python version earlier than 3.5 <code>re.sub</code> failed if a backreference was used to a capturing group that did not... | 2 | 2016-08-10T19:15:40Z | [
"python",
"regex",
"python-3.x",
"python-3.5"
] |
re.sub() documentation misunderstanding | 38,881,732 | <p>I've just started learning regular expressions and the documentation for <code>re.sub()</code> states:</p>
<blockquote>
<p><strong>Changed in version 3.5</strong>: Unmatched groups are replaced with an empty
string.</p>
<p><strong>Deprecated since version 3.5, will be removed in version 3.6</strong>: Unkn... | -1 | 2016-08-10T19:12:19Z | 38,881,823 | <p>You misunderstand the documentation. The <code>re.sub()</code> function is <strong>not deprecated</strong>. The deprecation warning concerns <em>specific syntax</em>.</p>
<p>Earlier in the <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow"><code>re.sub()</code> documentation</a> you'll find t... | 3 | 2016-08-10T19:17:50Z | [
"python",
"regex",
"python-3.x",
"python-3.5"
] |
numpy.fft.fft can not have 4 arguments? | 38,881,797 | <p>I tried to do FFT with numpy using this:</p>
<pre><code> sp=np.fft.fft(np.exp(-t), 1000, -1, "ortho")
</code></pre>
<p>and it returns:</p>
<pre><code> TypeError: fft() takes at most 3 arguments (4 given)
</code></pre>
<p>But in the manual, numpy.fft.fft() is defined as: </p>
<pre><code> numpy.fft.fft(a... | 1 | 2016-08-10T19:16:39Z | 38,881,850 | <p>What version of numpy are you using?</p>
<p>I ask because </p>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fft.html#numpy.fft.fft" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fft.html#numpy.fft.fft</a> </p>
<p>refers to norm as "New in version 1.10.0.... | 0 | 2016-08-10T19:20:07Z | [
"python",
"numpy",
"fft"
] |
How to check in python that at least one of the default parameters of the function specified | 38,881,888 | <p>What is the best practice in python to check if at least one of the default parameters of the function is specified?</p>
<p>Let's suppose we have some function:</p>
<pre><code>def some_function(arg_a=None, arg_b=None, arg_c=False)
</code></pre>
<p>with some default parameters. In my case, I need to check if eithe... | 4 | 2016-08-10T19:22:48Z | 38,881,914 | <p>Depends on what you expect as values for <code>arg_a</code> and <code>arg_b</code>, but this is generally sufficient.</p>
<pre><code>if not arg_a and not arg_b:
raise ValueError(...)
</code></pre>
<p>Assumes that <code>arg_a</code> and <code>arg_b</code> are not both booleans and cannot have zeros, empty strin... | 3 | 2016-08-10T19:24:46Z | [
"python",
"function",
"parameter-passing"
] |
How to check in python that at least one of the default parameters of the function specified | 38,881,888 | <p>What is the best practice in python to check if at least one of the default parameters of the function is specified?</p>
<p>Let's suppose we have some function:</p>
<pre><code>def some_function(arg_a=None, arg_b=None, arg_c=False)
</code></pre>
<p>with some default parameters. In my case, I need to check if eithe... | 4 | 2016-08-10T19:22:48Z | 38,882,013 | <p>You could use <code>all</code> to check if they all equal <code>None</code> and raise the <code>ValueError</code>:</p>
<pre><code>if all(v is None for v in {arg_a, arg_b}):
raise ValueError('Expected either arg_a or arg_b args')
</code></pre>
<p>this gets rid of those <code>if-elif</code> clauses and groups al... | 4 | 2016-08-10T19:31:34Z | [
"python",
"function",
"parameter-passing"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.