title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Why can a dictionary be unpacked as a tuple? | 23,268,615 | 61 | 2014-04-24T12:15:44Z | 23,268,720 | 7 | 2014-04-24T12:20:34Z | [
"python",
"python-2.7",
"dictionary",
"iterable-unpacking"
] | Today, I saw one statement which didn't throw an exception. Can anyone explain the theory behind it?
```
>>> x, y = {'a': 2, 'b': 5}
>>> x
'a'
>>> y
'b'
``` | No rocket science behind it. `dict` is an iterable, which return the keys in each iteration. `tuple()` can receive any iterable as argument (as long as they are finite), so:
```
>>>tuple({'a': 2, 'b': 5})
('a','b')
```
Seeing this, is easy to infer that unpacking will work as shown. Moreover, any *finite* iterable ca... |
Why can a dictionary be unpacked as a tuple? | 23,268,615 | 61 | 2014-04-24T12:15:44Z | 23,268,733 | 8 | 2014-04-24T12:20:51Z | [
"python",
"python-2.7",
"dictionary",
"iterable-unpacking"
] | Today, I saw one statement which didn't throw an exception. Can anyone explain the theory behind it?
```
>>> x, y = {'a': 2, 'b': 5}
>>> x
'a'
>>> y
'b'
``` | when you iterate over a dictionary, you get its keys
```
data = {'a': 2, 'b': 5}
for key in data:
print key
```
Unpacking is nothing else than iterating over the object and put the elements in the given variables:
```
keys = tuple(data) # gives ('a', 'b')
x, y = ('a', 'b')
``` |
What makes lists unhashable? | 23,268,899 | 6 | 2014-04-24T12:28:32Z | 23,268,979 | 14 | 2014-04-24T12:31:46Z | [
"python",
"list",
"dictionary",
"hash",
"python-internals"
] | So lists are unhashable:
```
>>> { [1,2]:3 }
TypeError: unhashable type: 'list'
```
The following [page](http://stackoverflow.com/questions/16803393/python-error-unhashable-type-list) gives an explanation:
> A list is a mutable type, and cannot be used as a key in a dictionary
> (it could change in-place making the ... | Dictionaries and sets use hashing algorithms to uniquely determine an item. And those algorithms make use of the items used as keys to come up the unique hash value. Since lists are mutable, the contents of a list can change. After allowing a list to be in a dictionary as a key, if the contents of the list changes, the... |
Scapy In A Script | 23,269,226 | 3 | 2014-04-24T12:42:34Z | 23,275,930 | 7 | 2014-04-24T17:35:08Z | [
"python",
"scapy"
] | I have used scapy as a session in python, but I want to use it in a script. Why so? I want to be able to use `sys.argv` to specify an IP address to use as well as use other modules. How can this be accomplished? | You just need to import it, as any other Python module.
```
from scapy.layers.inet import IP, ICMP
from scapy.sendrecv import sr
import sys
sr(IP(dst=sys.argv[1])/ICMP())
```
Or if you want to import everything at once:
```
import scapy.all as scapy
import sys
scapy.sr(scapy.IP(dst=sys.argv[1])/scapy.ICMP())
[...]
`... |
Python pip installation error | 23,276,866 | 5 | 2014-04-24T18:23:54Z | 23,277,314 | 9 | 2014-04-24T18:48:15Z | [
"python",
"osx",
"installation",
"pip",
"homebrew"
] | I installed Python on Mac OS X using Homebrew with
```
$ brew install python
```
And then I try to do use pip to do update but get errors:
```
$ which python
/usr/local/bin/python
$ python --version
Python 2.7.5
$ pip --version
pip 1.5.4 from /usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/... | Upgrade setuptools separately before you try to install distribute:
```
pip install --upgrade setuptools
pip install --upgrade distribute
``` |
Custom sorting with Pandas | 23,279,238 | 5 | 2014-04-24T20:34:50Z | 23,279,342 | 12 | 2014-04-24T20:40:28Z | [
"python",
"sorting",
"pandas"
] | I have the following dataframe that I would like to sort first by Criticality and then by Name:
```
Name Criticality
baz High
foo Critical
baz Low
foo Medium
bar High
bar Low
bar Medium
...
```
I've been trying to do this using the answer provided in [thi... | One approach would be to use a custom dict to create a 'rank' column, we then use to sort with and then drop the column after sorting:
```
In [17]:
custom_dict = {'Critical':0, 'High':1, 'Medium':2, 'Low':3}
df['rank'] = df['Criticality'].map(custom_dict)
df
Out[17]:
Name Criticality rank
0 baz High ... |
multiple SparkContexts error in tutorial | 23,280,629 | 7 | 2014-04-24T21:57:39Z | 23,281,377 | 15 | 2014-04-24T23:01:37Z | [
"python",
"apache",
"apache-spark"
] | I am attempting to run the very basic Spark+Python pyspark tutorial -- see <http://spark.apache.org/docs/0.9.0/quick-start.html>
When I attempt to initialize a new SparkContext,
```
from pyspark import SparkContext
sc = SparkContext("local[4]", "test")
```
I get the following error:
```
ValueError: Cannot run multi... | Turns out that running ./bin/pyspark interactively AUTOMATICALLY LOADS A SPARKCONTEXT. Here is what I see when I start pyspark:
```
Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/__ / .__/\_,_/_/ /_/\_\ version 0.9.1
/_/
Using Python version 2.6.6 (r266:842... |
Principal components analysis using pandas dataframe | 23,282,130 | 13 | 2014-04-25T00:22:48Z | 23,282,290 | 27 | 2014-04-25T00:42:14Z | [
"python",
"pandas",
"pca",
"scientific-computing",
"principal-components"
] | How can I calculate Principal Components Analysis from data in a pandas dataframe? | Most [sklearn](http://scikit-learn.org/stable/) objects work with panadas dataframes just fine, would something like this work for you?
```
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
df = pd.DataFrame(data=np.random.normal(0, 1, (20, 10)))
pca = PCA(n_components=5)
pca.fit(df)
```
... |
when will main thread exit in python | 23,285,743 | 4 | 2014-04-25T06:31:50Z | 23,285,807 | 8 | 2014-04-25T06:36:14Z | [
"python",
"multithreading"
] | I am reading `The Python Standard Library by Example` and get confused when I arrived page 509.
> Up to this point, the example programs have implicitly waited to exit until all threads have completed their work. Programs sometimes spawn a thread as a daemon that runs without blocking the main program from exiting.
b... | The main thread will exit whenever it is finished executing all the code in your script that is not started in a separate thread.
Since the `t.start()` will start the thread and then return to the main thread, the main thread will simply continue to execute until it reaches the bottom of your script and then exit.
Si... |
Convert List to a list of tuples python | 23,286,254 | 13 | 2014-04-25T07:00:48Z | 23,286,299 | 37 | 2014-04-25T07:03:03Z | [
"python",
"list",
"tuples"
] | I am newbie to python and need to convert a list to dictionary. I know that we can convert list of tuples to dictionary.
This is the input list:
```
L = [1,term1, 3, term2, x, term3,... z, termN]
```
and I want to convert this list to a list of tuples (OR to a dictionary) like this:
```
[(1, term1), (3, term2), (x,... | ```
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
# Create an iterator
>>> it = iter(L)
# zip the iterator with itself
>>> zip(it, it)
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
```
You want to group three items at a time?
```
>>> zip(it, it, it)
```
You want to group N items at a time?
```... |
Sorting a python dictionary of lists by date | 23,288,354 | 3 | 2014-04-25T08:47:45Z | 23,288,459 | 7 | 2014-04-25T08:52:43Z | [
"python",
"list",
"sorting",
"date",
"dictionary"
] | I'm writing a Django project as a student intern.
I have the following dictionary of list of data in my python file :
```
list_sequences = {'01': [["Calcul Red Shift", "2014-09-24", "Running"]],
'02': [["Calcul Dérive", "2014-09-22", "Stopped"]],
'03': [["Calcul simple", "2014-04-1... | `dict.items()` returns (key, value) pairs, so the value is at index 1(`e[1]`) not 0(`e[0]`). You need to change `e[0][1]` to `e[1][0][1]`.
**Demo:**
```
>>> OrderedDict(sorted(list_sequences.items(), key=lambda e:datetime.strptime(e[1][0][1], '%Y-%m-%d')))
OrderedDict([('09', [['Cuisson de choucroute', '2013-11-13', ... |
Shuffle two list at once with same order | 23,289,547 | 6 | 2014-04-25T09:43:28Z | 23,289,591 | 15 | 2014-04-25T09:45:20Z | [
"python",
"list",
"order",
"shuffle"
] | I'm using nltk corpus movie\_reviews where are a lot of documents. My task is get predictive performance of these reviews with pre-processing of the data and without pre-processing. But there is problem, in lists `documents` and `documents2` I have the same documents and I need shuffle them in order to keep same order ... | You can do it as:
```
import random
a = ['a', 'b', 'c']
b = [1, 2, 3]
c = list(zip(a, b))
random.shuffle(c)
a, b = zip(*c)
print a
print b
[OUTPUT]
['a', 'c', 'b']
[1, 3, 2]
```
Of course, this was an example with simpler lists, but the adaptation will be the same for your case.
Hope it helps. Good Luck. |
Why are some numpy calls not implemented as methods? | 23,289,642 | 5 | 2014-04-25T09:47:19Z | 23,290,842 | 9 | 2014-04-25T10:44:21Z | [
"python",
"numpy"
] | I always considered Python as a highly object-oriented programming language. Recently, I've been using `numpy` a lot and I'm beginning to wonder why a number of things are implemented there as functions only, and not as methods of the `numpy.array` (or `ndarray`) object.
If we have a given array `a` for example, you c... | When numpy was introduced as a successor to Numeric, a lot of things that were just functions and not methods were added as methods to the `ndarray` type. At this particular time, having the ability to subclass the array type was a new feature. It was thought that making some of these common functions methods would all... |
How to find zero crossings with hysteresis? | 23,289,976 | 7 | 2014-04-25T10:03:56Z | 23,291,658 | 9 | 2014-04-25T11:23:08Z | [
"python",
"numpy",
"debouncing"
] | In numpy, I would like to detect the points at which the signal crosses from (having been previously) below a certain threshold, to being above a certain other threshold. This is for things like debouncing, or accurate zero crossings in the presence of noise, etc.
Like this:
```
import numpy
# set up little test pro... | This can be done like so:
```
def hyst(x, th_lo, th_hi, initial = False):
hi = x >= th_hi
lo_or_hi = (x <= th_lo) | hi
ind = np.nonzero(lo_or_hi)[0]
if not ind.size: # prevent index error if ind is empty
return np.zeros_like(x, dtype=bool) | initial
cnt = np.cumsum(lo_or_hi) # from 0 to len... |
Converting to (not from) ipython Notebook format | 23,292,242 | 20 | 2014-04-25T11:48:07Z | 23,292,713 | 20 | 2014-04-25T12:08:56Z | [
"python",
"ipython",
"ipython-notebook",
"jupyter-notebook"
] | IPython Notebook comes with [`nbconvert`](http://ipython.org/ipython-doc/2/notebook/nbconvert.html), which can *export* notebooks to other formats. But how do I convert text in the opposite direction? I ask because I already have materials, and a good workflow, in a different format, but I would like to take advantage ... | The IPython API has functions for reading and writing notebook files. You should use this API and not create JSON directly. For example, the following code snippet converts a script `test.py` into a notebook `test.ipynb`.
```
import IPython.nbformat.current as nbf
nb = nbf.read(open('test.py', 'r'), 'py')
nbf.write(nb... |
Converting to (not from) ipython Notebook format | 23,292,242 | 20 | 2014-04-25T11:48:07Z | 35,720,002 | 9 | 2016-03-01T10:08:52Z | [
"python",
"ipython",
"ipython-notebook",
"jupyter-notebook"
] | IPython Notebook comes with [`nbconvert`](http://ipython.org/ipython-doc/2/notebook/nbconvert.html), which can *export* notebooks to other formats. But how do I convert text in the opposite direction? I ask because I already have materials, and a good workflow, in a different format, but I would like to take advantage ... | Since the code in the accepted answer does not work anymore, I have added this self-answer that shows how to import into a notebook with the current (`v4`) API.
## Input format
Versions 2 and 3 of the IPython Notebook API can import a python script with special structuring comments, and break it up into cells as desi... |
Transposing arrays in an array | 23,292,940 | 5 | 2014-04-25T12:17:57Z | 23,293,390 | 8 | 2014-04-25T12:37:50Z | [
"python",
"numpy"
] | I have a 2D array of shape `(M*N,N)` which in fact consists of `M`, `N*N` arrays. I would like to transpose all of these elements(`N*N` matrices) in a vectorized fashion. As an example,
```
import numpy as np
A=np.arange(1,28).reshape((9,3))
print "A before transposing:\n", A
for i in range(3):
A[i*3:(i+1)*3,:]=A[... | Here's a nasty way to do it in one line!
```
A.reshape((-1, 3, 3)).swapaxes(-1, 1).reshape(A.shape)
```
Step by step. Reshape to `(3, 3, 3)`
```
>>> A.reshape((-1, 3, 3))
array([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]],
[[1... |
How to use scikit-learn PCA for features reduction and know which features are discarded | 23,294,616 | 6 | 2014-04-25T13:30:11Z | 23,296,084 | 9 | 2014-04-25T14:34:43Z | [
"python",
"machine-learning",
"scikit-learn",
"pca",
"feature-selection"
] | I am trying to run a PCA on a matrix of dimensions m x n where m is the number of features and n the number of samples.
Suppose I want to preserve the `nf` features with the maximum variance. With `scikit-learn` I am able to do it in this way:
```
from sklearn.decomposition import PCA
nf = 100
pca = PCA(n_components... | The features that your `PCA` object has determined during fitting are in `pca.components_`. The vector space orthogonal to the one spanned by `pca.components_` is discarded.
Please note that PCA does not "discard" or "retain" any of your pre-defined features (encoded by the columns you specify). It mixes all of them (... |
Asking the user for input until they give a valid response | 23,294,658 | 190 | 2014-04-25T13:31:47Z | 23,294,659 | 252 | 2014-04-25T13:31:47Z | [
"python",
"validation",
"loops",
"python-3.x",
"user-input"
] | I am writing a program that must accept input from the user.
```
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United Sta... | The simplest way to accomplish this would be to put the `input` method in a while loop. Use [`continue`](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) when you get bad input, and `break` out of the loop when you're satisfied.
## When Your Input Might Raise... |
Asking the user for input until they give a valid response | 23,294,658 | 190 | 2014-04-25T13:31:47Z | 31,105,868 | 9 | 2015-06-28T23:29:47Z | [
"python",
"validation",
"loops",
"python-3.x",
"user-input"
] | I am writing a program that must accept input from the user.
```
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United Sta... | Though the accepted answer is amazing. I would also like to share a quick hack for this problem. (This takes care of the negative age problem as well.)
```
f=lambda age: (age.isdigit() and ((int(age)>=18 and "Can vote" ) or "Cannot vote")) or \
f(raw_input("invalid input. Try again\nPlease enter your age: "))
print f... |
Asking the user for input until they give a valid response | 23,294,658 | 190 | 2014-04-25T13:31:47Z | 34,789,951 | 11 | 2016-01-14T12:43:55Z | [
"python",
"validation",
"loops",
"python-3.x",
"user-input"
] | I am writing a program that must accept input from the user.
```
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United Sta... | Why would you do a `while True` and then break out of this loop while you can also just put your requirements in the while statement since all you want is to stop once you have the age?
```
age = None
while age is None:
input_value = raw_input("Please enter your age: ")
try:
# try and convert the strin... |
How to speed up numpy code | 23,295,642 | 4 | 2014-04-25T14:14:22Z | 23,297,607 | 7 | 2014-04-25T15:46:17Z | [
"python",
"performance",
"numpy",
"cython"
] | I have the following code. In principle it takes 2^6 \* 1000 = 64000 iterations which is quite a small number. However it takes 9s on my computer and I would like to run it for n = 15 at least.
```
from __future__ import division
import numpy as np
import itertools
n=6
iters = 1000
firstzero = 0
bothzero = 0
for S in... | An almost fully vectorized version of your code is much faster (16.9%), suppose yours is named `f()`:
```
def g():
n=6
iters = 1000
S=np.repeat(list(itertools.product([-1,1], repeat = n+1)),iters, axis=0).reshape((-1,n+1))
F=np.random.choice(np.array([-1,0,0,1], dtype=np.int8), size = (... |
What rules does Pandas use to generate a view vs a copy? | 23,296,282 | 19 | 2014-04-25T14:44:07Z | 23,296,545 | 22 | 2014-04-25T14:57:14Z | [
"python",
"pandas",
"indexing",
"dataframe",
"slice"
] | I'm confused about the rules Pandas uses when deciding that a selection from a dataframe is a copy of the original dataframe, or a view on the original.
If I have, for example,
```
df = pd.DataFrame(np.random.randn(8,8), columns=list('ABCDEFGH'), index=[1, 2, 3, 4, 5, 6, 7, 8])
```
I understand that a `query` return... | Here's the rules, subsequent override:
* All operations generate a copy
* If `inplace=True` is provided, it will modify in-place; only some operations support this
* An indexer that sets, e.g. `.loc/.ix/.iloc/.iat/.at` will set inplace.
* An indexer that gets on a single-dtyped object is almost always a view (dependin... |
Why does this code raise csv.Error? | 23,296,356 | 4 | 2014-04-25T14:48:12Z | 23,296,450 | 8 | 2014-04-25T14:53:23Z | [
"python",
"csv"
] | I'm trying to write out CSV using Python's built-in [csv](https://docs.python.org/2/library/csv.html) module.
```
import csv
import sys
writer = csv.writer(sys.stdout, delimiter="|", quoting=csv.QUOTE_NONE)
writer.writerow(['"foo', "bar"])
```
The output I expect is:
```
"foo|bar
```
However, I get this:
```
Error... | Setting `quoting=csv.QUOTE_NONE` is not enough; you also need to set `quotechar` to an empty string:
```
>>> import sys
>>> import csv
>>> writer = csv.writer(sys.stdout, delimiter="|", quoting=csv.QUOTE_NONE, quotechar='')
>>> writer.writerow(['"foo', "bar"])
"foo|bar
```
Otherwise, `csv.writer()` will try to escape... |
Permit argparse global flags after subcommand | 23,296,695 | 6 | 2014-04-25T15:04:05Z | 23,296,874 | 8 | 2014-04-25T15:12:51Z | [
"python",
"argparse"
] | I am using argparse to build a command with subcommands:
mycommand [GLOBAL FLAGS] subcommand [FLAGS]
I would like the global flags to work whether they are before or after the subcommand. Is there a clean way to do this that doesn't involve repeating code?
For example:
```
parser = argparse.ArgumentParser()
sub... | This is a perfect use case for [`parents`](https://docs.python.org/2/library/argparse.html#parents) argparse feature:
> Sometimes, several parsers share a common set of arguments. Rather
> than repeating the definitions of these arguments, a single parser
> with all the shared arguments and passed to parents= argument... |
Tuple() on GenExp vs. ListComp | 23,297,702 | 5 | 2014-04-25T15:50:21Z | 23,297,842 | 7 | 2014-04-25T15:56:52Z | [
"python",
"performance",
"list",
"tuples"
] | I have a list of some (small number) of items, eg:
```
my_list = [1,2,3,4,5,6,7,8,9,10]
```
and I have a tuple of indexes, eg:
```
indexes = (1,5,9)
```
I want the *tuple* of the values from the list, eg:
```
tuple(my_list[x] for x in indexes)
```
but this is proving to be quite slow (when run many many times).
... | [operator.itemgetter](https://docs.python.org/2.5/lib/module-operator.html#l2h-1193) (do you really have to use 2.5? It's dead and buried.)
Aside from being simpler, it also ought to be slightly faster due to being implemented in C. You can construct an `itemgetter` item once when you know which indices you want, then... |
pyodbc and python 3.4 on Windows | 23,299,034 | 18 | 2014-04-25T17:01:11Z | 23,299,671 | 21 | 2014-04-25T17:42:41Z | [
"python",
"pyodbc"
] | pyodbc is a very nice thing, but the Windows installers only work with their very specific python version. With the release of Python 3.4, the only available installers just stop once they don't see 3.3 in the registry (though 3.4 is certainly there).
Copying the .pyd and .egg-info files from a 3.3 installation into t... | The different versions of Python are (for the most part) not binary-compatible, and thus any compiled extensions (such as pyodbc) will only work for a specific version.
Note that pure-Python packages (the ones that are completely written in Python, and have no non-Python dependencies) do not need to be compiled, and t... |
pyodbc and python 3.4 on Windows | 23,299,034 | 18 | 2014-04-25T17:01:11Z | 23,300,440 | 9 | 2014-04-25T18:27:47Z | [
"python",
"pyodbc"
] | pyodbc is a very nice thing, but the Windows installers only work with their very specific python version. With the release of Python 3.4, the only available installers just stop once they don't see 3.3 in the registry (though 3.4 is certainly there).
Copying the .pyd and .egg-info files from a 3.3 installation into t... | Did you try to download from [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyodbc)? It has an unofficial build for 3.4. I did a quick test myself, looks like it's working fine for me. |
Beautifulsoup 4: Remove comment tag and its content | 23,299,557 | 5 | 2014-04-25T17:34:33Z | 23,299,678 | 9 | 2014-04-25T17:43:07Z | [
"python",
"html",
"web-scraping",
"html-parsing",
"beautifulsoup"
] | So the page that I'm scrapping contains these html codes. How do I remove the comment tag `<!-- -->` along with its content with **bs4**?
```
<div class="foo">
cat dog sheep goat
<!--
<p>NewPP limit report
Preprocessor node count: 478/300000
Postâexpand include size: 4852/2097152 bytes
Template argument size: 870/2... | You can use [`extract()`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#extract) (solution is based on [this answer](http://stackoverflow.com/a/3507360/771848)):
> PageElement.extract() removes a tag or string from the tree. It
> returns the tag or string that was extracted.
```
from bs4 import BeautifulSoup,... |
Invalid transaction persisting across requests | 23,301,968 | 24 | 2014-04-25T20:00:44Z | 23,478,870 | 19 | 2014-05-05T18:06:15Z | [
"python",
"flask",
"sqlalchemy",
"uwsgi",
"flask-sqlalchemy"
] | # Summary
One of our threads in production hit an error and is now producing `InvalidRequestError: This session is in 'prepared' state; no further SQL can be emitted within this transaction.` errors, on every request with a query that it serves, for the rest of its life! It's been doing this for *days*, now! How is th... | **Edit 2016-06-05:**
A PR that solves this problem has been merged on May 26, 2016.
[Flask PR 1822](https://github.com/pallets/flask/pull/1822)
**Edit 2015-04-13:**
Mystery solved!
**TL;DR: Be *absolutely sure* your teardown functions succeed, by using the teardown-wrapping recipe in the 2014-12-11 edit!**
Starte... |
Usefulness of def __init__(self)? | 23,302,018 | 22 | 2014-04-25T20:04:04Z | 23,302,073 | 23 | 2014-04-25T20:07:09Z | [
"python"
] | I am fairly new to python, and noticed these posts:
[Python \_\_init\_\_ and self what do they do?](http://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do) and
[Python Classes without using def \_\_init\_\_(self)](http://stackoverflow.com/questions/17331126/python-classes-without-using-def-init-... | Yeah, check this out:
```
class A(object):
def __init__(self):
self.lst = []
class B(object):
lst = []
```
and now try:
```
>>> x = B()
>>> y = B()
>>> x.lst.append(1)
>>> y.lst.append(2)
>>> x.lst
[1, 2]
>>> x.lst is y.lst
True
```
and this:
```
>>> x = A()
>>> y = A()
>>> x.lst.append(1)
>>> y.l... |
How do I run graphx with Python / pyspark? | 23,302,270 | 18 | 2014-04-25T20:18:44Z | 28,638,270 | 14 | 2015-02-20T21:11:59Z | [
"python",
"hadoop",
"graph-theory",
"apache-spark"
] | I am attempting to run Spark graphx with Python using pyspark. My installation appears correct, as I am able to run the pyspark tutorials and the (Java) GraphX tutorials just fine. Presumably since GraphX is part of Spark, pyspark should be able to interface it, correct?
Here are the tutorials for pyspark:
<http://spa... | It looks like the python bindings to GraphX are delayed at least to Spark 1.4 1.5 â. It is waiting behind the Java API.
You can track the status at [SPARK-3789 GRAPHX Python bindings for GraphX - ASF JIRA](https://issues.apache.org/jira/browse/SPARK-3789) |
How do I scrape pages with dynamically generated URLs using Python? | 23,302,676 | 7 | 2014-04-25T20:44:47Z | 23,303,600 | 16 | 2014-04-25T21:47:11Z | [
"python",
"web-scraping",
"beautifulsoup",
"urllib2"
] | I am trying to scrape <http://www.dailyfinance.com/quote/NYSE/international-business-machines/IBM/financial-ratios>, but the traditional url string building technique doesn't work because the "full-company-name-is-inserted-in-the-path" string. And the exact "full-company-name" isn't known in advance. Only the company s... | I like this question. And because of that, I'll give a very thorough answer. For this, I'll use my favorite Requests library along with BeautifulSoup4. Porting over to Mechanize if you really want to use that is up to you. Requests will save you tons of headaches though.
---
First off, you're probably looking for a P... |
PyQT -- How can you make a QTreeview uneditable but also selectable? | 23,305,320 | 3 | 2014-04-26T00:59:14Z | 23,305,417 | 7 | 2014-04-26T01:13:19Z | [
"python",
"pyqt",
"qtreeview",
"qstandarditemmodel",
"qstandarditem"
] | I just switched from wxPython to PyQT and I am having some trouble with the QTreeview. I have a QTreeview that will display data categorized into sections that are expandable, but the data in this TreeView should not be editable, but I need to be able to have the user select the data (doubleclicking is going to execute... | You can set individual items to be uneditable by doing this when you create the `QSandardItem`
```
item = QStandardItem('my_item_text')
item.setEditable(False)
```
You can disable editing for the entire treeview by calling
```
my_treeview.setEditTriggers(QAbstractItemView.NoEditTriggers)
```
By default the treeview... |
Which is the appropriate way to test for a dictionary type? | 23,305,359 | 3 | 2014-04-26T01:04:41Z | 23,305,409 | 9 | 2014-04-26T01:12:50Z | [
"python",
"dictionary",
"isinstance"
] | Why are there so many different ways to test for a dictionary?
And what would be the most modern way to test if an object is a dictionary?
```
adict = {'a': 1}
In [10]: isinstance(adict, types.DictType)
Out[10]: True
In [11]: isinstance(adict, types.DictionaryType)
Out[11]: True
In [12]: isinstance(adict, dict)
Out... | `types.DictType` and `types.DictionaryType` are deprecated (well, removed in Python 3) aliases of `dict`.
`collections.Mapping` and `collections.MutableMapping` are *Abstract* Base Classes (ABCs) so they work with mappings that don't subclass from `dict`. Normally that makes them a better choice, although very occasio... |
What's the difference between getattr(self, '__a') and self.__a in python? | 23,305,914 | 9 | 2014-04-26T02:27:17Z | 23,305,938 | 8 | 2014-04-26T02:31:16Z | [
"python",
"python-2.7"
] | I thought they were the same before I ran this code:
```
class B(object):
def show(self):
self.__a = "test"
print "B"
def this_b(self):
print "this_b"
print self.__a
print getattr(self, '__a') #exception
class C(B):
def show(self):
print "C"
# B.sh... | It is because of the [Private name mangling](https://docs.python.org/2/reference/expressions.html#atom-identifiers).
> **Private name mangling:** When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a ... |
Python Accessing Nested JSON Data | 23,306,653 | 6 | 2014-04-26T04:30:06Z | 23,306,721 | 11 | 2014-04-26T04:41:03Z | [
"python",
"json",
"rest"
] | I'm trying to get the zip code for a particular city using zippopotam.us. I have the following code which works, except when I try to access the `post code` key which returns `TypeError: expected string or buffer`
```
r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()
data = json.loads(j)
print ... | Places is a list and not a dictionary. This line below should therefore not work:
```
print data['places']['latitude']
```
You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:
```
print data['places'][0]['post code']
``` |
Pandas: Replacing column values in dataframe | 23,307,301 | 21 | 2014-04-26T06:04:24Z | 23,307,361 | 36 | 2014-04-26T06:12:02Z | [
"python",
"pandas"
] | I'm trying to replace the values in one column of a dataframe. The column ('female') only contains the values 'female' and 'male'.
I have tried the following:
```
w['female']['female']='1'
w['female']['male']='0'
```
But receive the exact same copy of the previous results.
I would ideally like to get some output wh... | If I understand right, you want something like this:
```
w['female'] = w['female'].map({'female': 1, 'male': 0})
```
(Here I convert the values to numbers instead of strings containing numbers. You can convert them to `"1"` and `"0"`, if you really want, but I'm not sure why you'd want that.)
The reason your code do... |
Pandas: Replacing column values in dataframe | 23,307,301 | 21 | 2014-04-26T06:04:24Z | 28,541,443 | 27 | 2015-02-16T12:27:17Z | [
"python",
"pandas"
] | I'm trying to replace the values in one column of a dataframe. The column ('female') only contains the values 'female' and 'male'.
I have tried the following:
```
w['female']['female']='1'
w['female']['male']='0'
```
But receive the exact same copy of the previous results.
I would ideally like to get some output wh... | You can edit a subset of a dataframe by using loc:
```
df.loc[<row selection>, <column selection>]
```
In this case:
```
w.loc[w.female != 'female', 'female'] = 0
w.loc[w.female == 'female', 'female'] = 1
``` |
How is the R2 value in Scikit learn calculated? | 23,309,073 | 4 | 2014-04-26T09:35:58Z | 23,310,565 | 8 | 2014-04-26T12:02:21Z | [
"python",
"machine-learning",
"statistics",
"scikit-learn"
] | The R^2 value returned by scikit learn (`metrics.r2_score()`) can be negative. The [docs](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.r2_score.html) say:
> "Unlike most other scores, R² score may be negative (it need not
> actually be the square of a quantity R)."
However the [wikipedia article]... | The `R^2` in scikit learn is essentially the same as what is described in [the wikipedia article on the coefficient of determination](http://en.wikipedia.org/wiki/Coefficient_of_determination) (grep for "the most general definition"). It is `1 - residual sum of square / total sum of squares`.
The big difference betwee... |
Trying to figure out how the 'with..as' construct works in python | 23,313,535 | 16 | 2014-04-26T16:18:37Z | 23,313,570 | 17 | 2014-04-26T16:22:21Z | [
"python"
] | I am trying to learn python and I landed on the
> with..as
construct, that used like this:
```
with open("somefile.txt", 'rt') as file:
print(file.read())
# at the end of execution file.close() is called automatically.
```
So as a learning strategy I tried to do the following:
```
class Derived():
de... | The name `derived` is bound to the object returned by the `__enter__` method, which is `None`. Try:
```
def __enter__(self):
print('__enter__')
return self
```
[Docs:](https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers)
> `object.__enter__(self)`
>
> Enter the runtime context ... |
What exactly is a tensor in theano? | 23,314,351 | 7 | 2014-04-26T17:30:52Z | 23,314,906 | 7 | 2014-04-26T18:26:33Z | [
"python",
"scipy",
"theano"
] | What exactly is a **Tensor** in [Theano](http://www.deeplearning.net/software/theano/index.html#), and what is the precise connection with [Tensors](http://en.wikipedia.org/wiki/Tensor#Definition) as they are typically understood in Physics or Math?
I went through the [Theano at Glance](http://www.deeplearning.net/sof... | There is a good breakdown of different physics/math ways to think of tensor in Jim Belk's [answer](http://math.stackexchange.com/a/192441) to a question on math.stackexchange. After looking over the [documentation](http://deeplearning.net/software/theano/library/tensor/index.html) on tensor and the various operations T... |
Converting a list of dicts to a Pandas dataframe | 23,314,939 | 5 | 2014-04-26T18:29:31Z | 23,314,961 | 8 | 2014-04-26T18:32:36Z | [
"python",
"dictionary",
"pandas",
"dataframe"
] | I have a list of Python `dict`s each with the same keys,
```
dict_keys= ['k1','k2','k3','k4','k5','k6'] # More like 30 keys in practice
data = []
for i in range(20): # More like 3000 in practice
data.append({k: np.random.randint(100) for k in dict_keys})
```
and would like to use it to create a corresponding Pand... | Simply pass `data` to `DataFrame`'s `__init__`, or to [`DataFrame.from_records`](http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.from_records.html) (either would work).
You might also want to set an index, e.g. `DataFrame.from_records(data, index = 'k1')`.
If you need to also perform so... |
Python : Comma at the end of print statement | 23,315,421 | 2 | 2014-04-26T19:14:03Z | 23,315,439 | 7 | 2014-04-26T19:15:16Z | [
"python"
] | I've just started learning python from the source `learnjavathehardway`.
There was a "fun" code that goes as follows
```
while True:
for i in ["/","-","|","\\","|"]:
print "%s\r" % i,
```
Now what it does is that at the same place in my console, it prints the different character one by one. (Try it yours... | That's because of the `\r`, which is the [`carriage return <CR>`](http://en.wikipedia.org/wiki/Carriage_return) character in ascii. It basically resets the cursor to the start of the line.
The comma at the end of that line is because in python 2.7, the [`print`](https://docs.python.org/2/reference/simple_stmts.html#pr... |
Pandas Dataframe: split column into multiple columns, right-align inconsistent cell entries | 23,317,342 | 12 | 2014-04-26T22:49:49Z | 23,317,595 | 20 | 2014-04-26T23:23:50Z | [
"python",
"split",
"pandas"
] | I have a pandas dataframe with a column named 'City, State, Country'. I want to separate this column into three new columns, 'City, 'State' and 'Country'.
```
0 HUN
1 ESP
2 GBR
3 ESP
4 FRA
5 ID, USA
6 GA, USA
7 H... | I'd do something like the following:
```
foo = lambda x: pd.Series([i for i in reversed(x.split(','))])
rev = df['City, State, Country'].apply(foo)
print rev
0 1 2
0 HUN NaN NaN
1 ESP NaN NaN
2 GBR NaN NaN
3 ESP NaN NaN
4 FRA NaN NaN
5 USA ID NaN
6 US... |
Embedding a Pygame window into a Tkinter or WxPython frame | 23,319,059 | 8 | 2014-04-27T03:30:13Z | 23,464,185 | 7 | 2014-05-05T03:09:09Z | [
"python",
"tkinter",
"wxpython",
"pygame",
"embed"
] | A friend and I are making a game in pygame. We would like to have a pygame window embedded into a tkinter or WxPython frame, so that we can include text input, buttons, and dropdown menus that are supported by WX or Tkinter. I have scoured the internet for an answer, but all I have found are people asking the same ques... | According to [this](http://stackoverflow.com/questions/13545911/drawing-a-circle-on-a-pygame-window-using-tkinter-using-python-2-7) SO question and the accepted answer, the simplest way to do this would be to use an SDL drawing frame.
This code is the work of SO user [Alex Sallons](http://stackoverflow.com/users/17470... |
How to render markdown content with jinja2, in a django project? | 23,320,668 | 3 | 2014-04-27T07:37:24Z | 23,321,514 | 9 | 2014-04-27T09:14:08Z | [
"python",
"markdown",
"jinja2"
] | I am working on a django project with a model like:
```
class Article(models.Model):
...
# which is submitted by users through a markdown editor.
content = models.TextField(_('content'), blank=True)
...
```
As a result, I render the content in the templates with [Jinja2](http://jinja.pocoo.org/docs/),... | Not sure about Django, but I use Markdown with Jinja2 in flask. I initialize Markdown when the app runs like this.
### app
```
from flask.ext.markdown import Markdown
md = Markdown(app, extensions=['fenced_code'])
```
Then I add the filter to the template.
### template
```
<H2>{{ post.title }}</H2>
{{post.body|mar... |
How to improve speed with Stanford NLP Tagger and NLTK | 23,322,674 | 8 | 2014-04-27T11:15:19Z | 23,323,042 | 10 | 2014-04-27T11:50:30Z | [
"python",
"nltk",
"stanford-nlp"
] | Is there any way to use the Standford Tagger in a more performant fashion?
Each call to NLTK's wrapper starts a new java instance per analyzed string which is very very slow especially when a larger foreign language model is used...
<http://www.nltk.org/api/nltk.tag.html#module-nltk.tag.stanford> | Found the solution. It is possible to run the POS Tagger in servlet mode and then connect to it via HTTP. Perfect.
<http://nlp.stanford.edu/software/pos-tagger-faq.shtml#d>
example
**start server in background**
```
nohup java -mx1000m -cp /var/stanford-postagger-full-2014-01-04/stanford-postagger.jar edu.stanford.... |
convert c enum bitfield to python | 23,324,957 | 5 | 2014-04-27T15:02:38Z | 23,325,125 | 8 | 2014-04-27T15:20:02Z | [
"python",
"enums"
] | Looking at kismet's source code in packet\_ieee80211.h is the section
```
enum crypt_type {
crypt_none = 0,
crypt_unknown = 1,
crypt_wep = (1 << 1),
crypt_layer3 = (1 << 2),
// Derived from WPA headers
crypt_wep40 = (1 << 3),
crypt_wep104 = (1 << 4),
crypt_tkip = (1 << 5),
crypt_wpa = (1 << 6),
crypt_psk = (1 << 7... | So, what you have to understand here is that this enum is defining a series of [bitmasks](http://en.wikipedia.org/wiki/Mask_%28computing%29). In this case, each one of these enum values, in binary, contains one and only one `1`. For example,
```
crypt_wep = (1 << 1) = 0b10
crypt_wpa = (1 << 6) = 0b1000000
```
And so ... |
Flask request.args vs request.form | 23,326,368 | 8 | 2014-04-27T17:09:11Z | 23,357,819 | 21 | 2014-04-29T07:07:41Z | [
"python",
"rest",
"curl",
"flask",
"postman"
] | My understanding is that `request.args` in Flask contains the URL encoded parameters from a `GET` request while `request.form` contains `POST` data. What I'm having a hard time grasping is why when sending a `POST` request, trying to access the data with `request.form` returns a `400` error but when I try to access it ... | You are POST-ing JSON, neither `request.args` nor `request.form` will work.
`request.form` works only if you POST data *with the right content types*; *form data* is either POSTed with the [`application/x-www-form-urlencoded` or `multipart/form-data`](http://stackoverflow.com/questions/4007969/application-x-www-form-u... |
Flask raises TemplateNotFound error even though template file exists | 23,327,293 | 6 | 2014-04-27T18:30:28Z | 23,327,352 | 15 | 2014-04-27T18:36:01Z | [
"python",
"flask"
] | I am trying to render the file `home.html`. The file exists in my project, but I keep getting `jinja2.exceptions.TemplateNotFound: home.html` when I try to render it. Why can't Flask find my template?
```
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_tem... | You must create your template files in the correct location; in the `templates` subdirectory next to your python module.
The error indicates that there is no `home.html` file in the `templates/` directory. Make sure you created that directory in the same directory as your python module, and that you did in fact put a ... |
Update a dataframe in pandas while iterating row by row | 23,330,654 | 19 | 2014-04-28T00:19:49Z | 29,262,040 | 18 | 2015-03-25T17:07:22Z | [
"python",
"pandas",
"updates",
"dataframe"
] | I have a pandas data frame that looks like this (its a pretty big one)
```
date exer exp ifor mat
1092 2014-03-17 American M 528.205 2014-04-19
1093 2014-03-17 American M 528.205 2014-04-19
1094 2014-03-17 American M 528.205 2014-04-19
1095 2014-03-17 American M ... | You can assign values in the loop using df.set\_value:
```
for i, row in df.iterrows():
ifor_val = something
if <condition>:
ifor_val = something_else
df.set_value(i,'ifor',ifor_val)
```
if you don't need the row values you could simply iterate over the indices of df, but I kept the original for-loop in cas... |
Is the use of del bad? | 23,331,419 | 40 | 2014-04-28T02:03:16Z | 23,331,463 | 8 | 2014-04-28T02:10:56Z | [
"python",
"slice",
"mutable",
"side-effects"
] | I commonly use `del` in my code to delete objects:
```
>>> array = [4, 6, 7, 'hello', 8]
>>> del(array[array.index('hello')])
>>> array
[4, 6, 7, 8]
>>>
```
But I have heard [many people](http://stackoverflow.com/questions/23140529/how-do-i-remove-almost-duplicate-integers-from-list/23140922#comment35382858_23140922)... | Nope, I don't think using `del` is bad at all. In fact, there are situations where it's essentially the only reasonable option, like removing elements from a dictionary:
```
k = {'foo': 1, 'bar': 2}
del k['foo']
```
Maybe the problem is that beginners do not fully understand how variables work in Python, so the use (... |
Is the use of del bad? | 23,331,419 | 40 | 2014-04-28T02:03:16Z | 23,331,470 | 11 | 2014-04-28T02:11:56Z | [
"python",
"slice",
"mutable",
"side-effects"
] | I commonly use `del` in my code to delete objects:
```
>>> array = [4, 6, 7, 'hello', 8]
>>> del(array[array.index('hello')])
>>> array
[4, 6, 7, 8]
>>>
```
But I have heard [many people](http://stackoverflow.com/questions/23140529/how-do-i-remove-almost-duplicate-integers-from-list/23140922#comment35382858_23140922)... | Python simply contains many different ways to remove items from a list. All are useful in different situations.
```
# removes the first index of a list
del arr[0]
# Removes the first element containing integer 8 from a list
arr.remove(8)
# removes index 3 and returns the previous value at index 3
arr.pop(3)
# remov... |
Is the use of del bad? | 23,331,419 | 40 | 2014-04-28T02:03:16Z | 23,331,576 | 40 | 2014-04-28T02:26:00Z | [
"python",
"slice",
"mutable",
"side-effects"
] | I commonly use `del` in my code to delete objects:
```
>>> array = [4, 6, 7, 'hello', 8]
>>> del(array[array.index('hello')])
>>> array
[4, 6, 7, 8]
>>>
```
But I have heard [many people](http://stackoverflow.com/questions/23140529/how-do-i-remove-almost-duplicate-integers-from-list/23140922#comment35382858_23140922)... | The other answers are looking at it from a technical point of view (i.e. what's the best way to modify a list), but I would say the (much) more important reason people are suggesting e.g. slicing is that it doesn't modify the original list.
The reason for this in turn is that usually, the list came from somewhere. If ... |
How to convert Strings to into a phone number | 23,332,562 | 3 | 2014-04-28T04:34:52Z | 23,332,621 | 11 | 2014-04-28T04:41:05Z | [
"python",
"string",
"for-loop"
] | I've been stuck on this questions for so long this is the question:
Write a function that takes a string as an argument and returns the phone number
corresponding to that string as the result.
The phone number should also be a string.
The conversion rules are the standard word to phone number rules:
> 'a', 'b' or 'c'... | I'd do it like this:
```
def string_to_num(in_str):
try:
translationdict = str.maketrans("abcdefghijklmnopqrstuvwxyz","22233344455566677778889999")
except AttributeError:
import string
translationdict = string.maketrans("abcdefghijklmnopqrstuvwxyz","22233344455566677778889999")
out... |
How to properly assert that exception raises in pytest? | 23,337,471 | 25 | 2014-04-28T09:33:45Z | 23,514,853 | 17 | 2014-05-07T10:10:10Z | [
"python",
"unit-testing",
"testing",
"py.test"
] | ## Code:
```
# coding=utf-8
import pytest
def whatever():
return 9/0
def test_whatever():
try:
whatever()
except ZeroDivisionError as exc:
pytest.fail(exc, pytrace=True)
```
## Output:
```
================================ test session starts =================================
platform l... | Do you mean something like this:
```
def test_raises():
with pytest.raises(Exception) as excinfo:
raise Exception('some info')
assert excinfo.value.message == 'some info'
``` |
How to properly assert that exception raises in pytest? | 23,337,471 | 25 | 2014-04-28T09:33:45Z | 29,855,337 | 26 | 2015-04-24T18:52:57Z | [
"python",
"unit-testing",
"testing",
"py.test"
] | ## Code:
```
# coding=utf-8
import pytest
def whatever():
return 9/0
def test_whatever():
try:
whatever()
except ZeroDivisionError as exc:
pytest.fail(exc, pytrace=True)
```
## Output:
```
================================ test session starts =================================
platform l... | `pytest.raises(Exception)` is what you need.
**Code**
```
import pytest
def test_passes():
with pytest.raises(Exception) as e_info:
x = 1 / 0
def test_passes_without_info():
with pytest.raises(Exception):
x = 1 / 0
def test_fails():
with pytest.raises(Exception) as e_info:
x = 1... |
Read image grayscale opencv 3.0.0-dev | 23,339,315 | 6 | 2014-04-28T10:58:29Z | 23,345,253 | 9 | 2014-04-28T15:35:47Z | [
"python",
"opencv",
"grayscale"
] | I am trying to read images directly as black and white.
I recently updated my OpenCv version to 3.0.0-dev, and the code that I used before does not work anymore.
```
img = cv2.imread(f, cv2.CV_LOAD_IMAGE_GRAYSCALE)
```
works fine for 2.4 but does not work for the new version, as there is no field `CV_LOAD_IMAGE_G... | The flag has been renamed to `cv2.IMREAD_GRAYSCALE`. Generally speaking, flags now have names prefixed in a manner that relates to the function to which they refer. (e.g. `imread` flags start with `IMREAD_`, `cvtColor` flags start with `COLOR_`, etc.) |
How to convert a decimal number into fraction? | 23,344,185 | 10 | 2014-04-28T14:47:40Z | 23,344,270 | 29 | 2014-04-28T14:51:56Z | [
"python",
"decimal",
"fractions"
] | I was wondering how to convert a decimal into a fraction in its lowest form in Python.
For example:
```
0.25 -> 1/4
0.5 -> 1/2
1.25 -> 5/4
3 -> 3/1
``` | You have two options:
1. Use [`float.as_integer_ratio()`](https://docs.python.org/2/library/stdtypes.html#float.as_integer_ratio):
```
>>> (0.25).as_integer_ratio()
(1, 4)
```
2. Use the [`fractions.Fraction()` type](https://docs.python.org/2/library/fractions.html#fractions.Fraction):
```
>>> from... |
Python: Why is threaded function slower than non thread | 23,344,936 | 5 | 2014-04-28T15:22:35Z | 23,345,019 | 10 | 2014-04-28T15:26:32Z | [
"python",
"multithreading"
] | Hello I'm trying to calculate the first 10000 prime numbers.
I'm doing this first non threaded and then splitting the calculation in 1 to 5000 and 5001 to 10000. I expected that the use of threads makes it significant faster but the output is like this:
```
--------Results--------
Non threaded Duration: 0.012244... | from: <https://wiki.python.org/moin/GlobalInterpreterLock>
> In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native threads from executing Python bytecodes at once. This lock is necessary mainly because CPython's memory management is not thread-safe. (However, since the GIL exists, o... |
Python: validate and format JSON files | 23,344,948 | 4 | 2014-04-28T15:23:13Z | 23,345,704 | 7 | 2014-04-28T15:55:47Z | [
"python",
"json"
] | I have around 2000 JSON files which I'm trying to run through a Python program. A problem occurs when a JSON file is not in the correct format. (Error: `ValueError: No JSON object could be decoded`) In turn, I can't read it into my program.
I am currently doing something like the below:
```
for files in folder:
w... | The built-in JSON module can be used as a validator:
```
import json
def parse(text):
try:
return json.loads(text)
except ValueError as e:
print('invalid json: %s' % e)
return None # or: raise
```
You can make it work with files by using:
```
with open(filename) as f:
return json... |
Is it possible to control matplotlib marker orientation? | 23,345,565 | 4 | 2014-04-28T15:49:37Z | 23,345,696 | 8 | 2014-04-28T15:55:25Z | [
"python",
"matplotlib",
"matplotlib-basemap"
] | I would like to know if I have a triangular marker, is it possible to control its orientation? I have a series of facets, with their corresponding vertices, and I would like to plot a basemap of them. I know it is straight forward script when using Mayavi and tvtk.PolyData. But since I'm dealing with maps and not 3D ob... | You can create [custom polygons](http://matplotlib.org/api/markers_api.html) using the keyword argument `marker` and passing it a tuple of 3 numbers `(number of sides, style, rotation)`.
To create a triangle you would use `(3, 0, rotation)`, an example is shown below.
```
import matplotlib.pyplot as plt
x = [1,2,3]
... |
X-Forwarded-Proto and Flask | 23,347,387 | 7 | 2014-04-28T17:23:33Z | 23,504,684 | 13 | 2014-05-06T21:18:02Z | [
"python",
"nginx",
"flask",
"uwsgi",
"werkzeug"
] | I have precisely the same problem described in [this SO question and answer](http://stackoverflow.com/questions/19840051/mutating-request-base-url-in-flask). The answer to that question is a nice work around but I don't understand the fundamental problem. Terminating SSL at the load balancer and using HTTP between the ... | You are missing the [`ProxyFix()` middleware component](http://werkzeug.pocoo.org/docs/contrib/fixers/#werkzeug.contrib.fixers.ProxyFix). See the Flask [Proxy Setups documentation](http://flask.pocoo.org/docs/deploying/wsgi-standalone/#proxy-setups).
There is no need to subclass anything; simply add this middleware co... |
Argparse with required subparser | 23,349,349 | 19 | 2014-04-28T19:12:58Z | 23,354,355 | 26 | 2014-04-29T02:17:24Z | [
"python",
"argparse",
"python-3.4"
] | I'm using Python 3.4, I'm trying to use `argparse` with subparsers, and I want to have a similar behavior to the one in Python 2.x where if I don't supply a positional argument (to indicate the subparser/subprogram) I'll get a helpful error message. I.e., with `python2` I'll get the following error message:
```
$ pyth... | You need to give `subparsers` a `dest`.
```
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='cmd')
subparsers.required = True
```
Now:
```
1909:~/mypy$ argdev/python3 stack23349349.py
usage: stack23349349.py [-h] {foo} ...
stack23349349.py: error: the following arguments are required: cmd
... |
Openpyxl 1.8.5: Reading the result of a formula typed in a cell using openpyxl | 23,350,581 | 5 | 2014-04-28T20:28:31Z | 23,362,361 | 7 | 2014-04-29T10:42:44Z | [
"python",
"openpyxl"
] | I am printing some formula in one of the Excel sheets:
```
wsOld.cell(row = 1, column = 1).value = "=B3=B4"
```
But I cannot use its result in implementing some other logic, as:
```
if((wsOld.cell(row=1, column=1).value)='true'):
# copy the 1st row to another sheet
```
Even when I am trying to print the result ... | openpyxl support either the formula or the value of the formula. You can select which using the `data_only` flag when opening a workbook. However, openpyxl does not and will not calculate the result of a formula. There are libraries out there like pycel which purport to do this. |
Django - Filter queryset by CharField value length | 23,351,183 | 8 | 2014-04-28T21:06:27Z | 23,351,303 | 11 | 2014-04-28T21:14:35Z | [
"python",
"django",
"django-south",
"data-migration"
] | Given that I have a legacy model with a `CharField` or `CharField`-based model field like:
```
class MyModel(models.Model):
name = models.CharField(max_length=1024, ...)
...
```
I need to make migrations to make it have a `max_length` of max. 255. First I'm writing a `datamigration` to make any values with lo... | I think you have to options:
Using 'extra' on the queryset:
```
MyModel.objects.extra(where=["CHAR_LENGTH(text) > 254"])
```
Or abusing Regex lookups, I'm assuming this will be slower:
```
MyModel.objects.filter(text__regex = r'^.{254}.*')
``` |
How to declare an ndarray in cython with a general floating point type | 23,351,813 | 5 | 2014-04-28T21:53:40Z | 23,362,091 | 9 | 2014-04-29T10:30:23Z | [
"python",
"numpy",
"cython"
] | What is the best way to declare a numpy array in cython if It should be able to handle both float and double?
I guess it won't be possible with a memory view since there the datatype is crucial, but for an ndarray is there any way to give it a general float type which would still benifit from the swiftness of cython?
... | Well this is actually really easy with fused types support:
> *This goes inside your code.*
```
from cython cimport floating
def cythonfloating_memoryview(floating[:, :] array):
cdef int i, j
for i in range(array.shape[0]):
for j in range(array.shape[1]):
array[i, j] += 10
```
Of course... |
django-admin.py makemessages not working | 23,353,113 | 11 | 2014-04-28T23:49:08Z | 23,370,327 | 29 | 2014-04-29T16:32:54Z | [
"python",
"django",
"homebrew",
"gettext"
] | I am trying to translate a string.
```
{% load i18n %}
{% trans "Well, Hello there, how are you?" %}
```
to...
```
Hola amigo, ¿que tal?
```
My settings.py file has this:
```
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'translations'),
)
```
And I am getting this:
```
(env)glitch:translations nathann$ django-ad... | After making sure I had this in settings:
```
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
print(LOCALE_PATHS)
```
I double checked I had the `locale` directory in the right place with its name spelled correctly.
I ended up linking gettext (after asking about that on [superuser](http://superuser.com/ques... |
django-admin.py makemessages not working | 23,353,113 | 11 | 2014-04-28T23:49:08Z | 25,074,840 | 16 | 2014-08-01T07:14:47Z | [
"python",
"django",
"homebrew",
"gettext"
] | I am trying to translate a string.
```
{% load i18n %}
{% trans "Well, Hello there, how are you?" %}
```
to...
```
Hola amigo, ¿que tal?
```
My settings.py file has this:
```
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'translations'),
)
```
And I am getting this:
```
(env)glitch:translations nathann$ django-ad... | Please try this in Ubuntu OS
sudo apt-get install gettext
And use brew install gettext in OSX
Also make sure set the local path in settings.py file. |
Trouble installing Pyspark | 23,353,477 | 4 | 2014-04-29T00:30:32Z | 24,891,867 | 8 | 2014-07-22T15:42:36Z | [
"python",
"apache-spark"
] | I want to run Spark on a local machine using pyspark. From [here](http://spark.apache.org/docs/0.9.1/python-programming-guide.html) I use the commands:
```
sbt/sbt assembly
$ ./bin/pyspark
```
The install completes, but pyspark is unable to run, resulting in the following error (in full):
```
138:spark-0.9.1 comp_na... | The right solution is to set SPARK\_LOCAL\_IP environment variable to localhost or whatever your host name is. |
"Got 1 columns instead of ..." error in numpy | 23,353,585 | 6 | 2014-04-29T00:42:39Z | 23,364,383 | 7 | 2014-04-29T12:15:13Z | [
"python",
"numpy",
"genfromtxt"
] | I'm working on the following code for performing Random Forest Classification on train and test sets;
```
from sklearn.ensemble import RandomForestClassifier
from numpy import genfromtxt, savetxt
def main():
dataset = genfromtxt(open('filepath','r'), delimiter=' ', dtype='f8')
target = [x[0] for x in datas... | `genfromtxt` will give this error if the number of columns is unequal.
I can think of 3 ways around it:
**1. Use the [`usecols`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html) parameter**
```
np.genfromtxt('yourfile.txt',delimiter=',',usecols=np.arange(0,1434))
```
However - this may mea... |
Python Pandas write to sql with NaN values | 23,353,732 | 7 | 2014-04-29T00:58:59Z | 23,358,894 | 16 | 2014-04-29T08:00:44Z | [
"python",
"mysql",
"sql",
"pandas"
] | I'm trying to read a few hundred tables from ascii and then write them to mySQL. It seems easy to do with Pandas but I hit an error that doesn't make sense to me:
I have a data frame of 8 columns. Here is the column list/index:
```
metricDF.columns
Index([u'FID', u'TYPE', u'CO', u'CITY', u'LINENO', u'SUBLINE', u'VAL... | **Update**: starting with pandas 0.15, `to_sql` supports writing `NaN` values (they will be written as `NULL` in the database), so the workaround described below should not be needed anymore (see <https://github.com/pydata/pandas/pull/8208>).
Pandas 0.15 will be released in coming October, and the feature is merged i... |
How can I "unpivot" specific columns from a pandas DataFrame? | 23,354,124 | 11 | 2014-04-29T01:48:25Z | 23,354,240 | 8 | 2014-04-29T02:05:49Z | [
"python",
"pandas",
"pivot-table"
] | I have a pandas DataFrame, eg:
```
x = DataFrame.from_dict({'farm' : ['A','B','A','B'],
'fruit':['apple','apple','pear','pear'],
'2014':[10,12,6,8],
'2015':[11,13,7,9]})
```
ie:
```
2014 2015 farm fruit
0 10 11 A apple
1 ... | This can be done with `pd.melt()`:
```
# value_name is 'value' by default, but setting it here to make it clear
pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')
```
Result:
```
farm fruit year value
0 A apple 2014 10
1 B apple 2014 12
2 A pear 2014 6
3 B... |
Python Flask downloading a file returns 0 bytes | 23,354,314 | 5 | 2014-04-29T02:13:14Z | 25,460,035 | 10 | 2014-08-23T08:32:09Z | [
"python",
"flask",
"download",
"content-disposition"
] | Here is the code my flask server is running:
```
from flask import Flask, make_response
import os
app = Flask(__name__)
@app.route("/")
def index():
return str(os.listdir("."))
@app.route("/<file_name>")
def getFile(file_name):
response = make_response()
response.headers["Content-Disposition... | As danny wrote, you don't provide any content in your response, that's why you get 0 bytes. There is however an easy function [send\_file](http://flask.pocoo.org/docs/0.10/api/#flask.send_file) in Flask to return file content:
```
from flask import send_file
@app.route("/<file_name>")
def getFile(file_name):
retu... |
Can I specify a numpy dtype when generating random values? | 23,355,433 | 7 | 2014-04-29T04:23:53Z | 23,355,493 | 8 | 2014-04-29T04:28:45Z | [
"python",
"numpy",
"random",
"floating-point-precision"
] | I'm creating a `numpy` array of random values and adding them to an existing array containing 32-bit floats. I'd like to generate the random values using the same dtype as the target array, so that I don't have to convert the dtypes manually. Currently I do this:
```
import numpy as np
x = np.zeros((10, 10), dtype='f... | > Q: is it possible to specify a dtype for random numbers when I create them.
>
> A: No it isn't. randn accepts the shape only as randn(d0, d1, ..., dn)
Simply try this:
```
x = np.random.randn(10, 10).astype('f')
```
Or define a new function like
```
np.random.randn2 = lambda *args, **kwarg: np.random.randn(*args)... |
How to convert webpage into PDF by using Python | 23,359,083 | 21 | 2014-04-29T08:10:40Z | 23,382,176 | 11 | 2014-04-30T07:31:14Z | [
"python",
"pdf",
"webpage",
"qprinter"
] | I was finding solution to print webpage into local file PDF, using Python. one of the good solution is to use Qt, found here, <https://bharatikunal.wordpress.com/2010/01/>.
It didn't work at the beginning as I had problem with the installation of PyQt4 because it gave error messages such as 'ImportError: No module nam... | thanks to below posts, and I am able to add on the webpage link address to be printed and present time on the PDF generated, no matter how many pages it has.
[Add text to Existing PDF using Python](http://stackoverflow.com/questions/1180115/add-text-to-existing-pdf-using-python)
<https://github.com/disflux/django-mtr... |
How to convert webpage into PDF by using Python | 23,359,083 | 21 | 2014-04-29T08:10:40Z | 23,761,093 | 41 | 2014-05-20T13:24:28Z | [
"python",
"pdf",
"webpage",
"qprinter"
] | I was finding solution to print webpage into local file PDF, using Python. one of the good solution is to use Qt, found here, <https://bharatikunal.wordpress.com/2010/01/>.
It didn't work at the beginning as I had problem with the installation of PyQt4 because it gave error messages such as 'ImportError: No module nam... | You also can use [pdfkit](https://pypi.python.org/pypi/pdfkit/0.4.1):
```
import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
``` |
django - comparing old and new field value before saving | 23,361,057 | 23 | 2014-04-29T09:43:19Z | 23,363,123 | 18 | 2014-04-29T11:16:15Z | [
"python",
"django",
"django-signals"
] | I have a django model, and I need to compare old and new values of field BEFORE saving.
I've tried the save() inheritence, and pre\_save signal. It was triggered correctly, but I can't find the list of actualy changed fields and can't compare old and new values. There is a way? I need it for optimization of presave ac... | There is very simple django way for doing it.
"Memorise" the values in model init like this:
```
def __init__(self, *args, **kwargs):
super(MyClass, self).__init__(*args, **kwargs)
self.initial_parametername = self.parametername
---
self.initial_parameternameX = self.parameternameX
```
Real life exam... |
django - comparing old and new field value before saving | 23,361,057 | 23 | 2014-04-29T09:43:19Z | 23,363,551 | 16 | 2014-04-29T11:35:23Z | [
"python",
"django",
"django-signals"
] | I have a django model, and I need to compare old and new values of field BEFORE saving.
I've tried the save() inheritence, and pre\_save signal. It was triggered correctly, but I can't find the list of actualy changed fields and can't compare old and new values. There is a way? I need it for optimization of presave ac... | It is better to do this at **ModelForm level**.
There you get all the Data that you need for comparision in save method:
1. **self.data** : Actual Data passed to the Form.
2. **self.cleaned\_data** : Data cleaned after validations, Contains Data eligible to be saved in the Model
3. **self.changed\_data** : List of Fi... |
django - comparing old and new field value before saving | 23,361,057 | 23 | 2014-04-29T09:43:19Z | 23,383,445 | 12 | 2014-04-30T08:39:27Z | [
"python",
"django",
"django-signals"
] | I have a django model, and I need to compare old and new values of field BEFORE saving.
I've tried the save() inheritence, and pre\_save signal. It was triggered correctly, but I can't find the list of actualy changed fields and can't compare old and new values. There is a way? I need it for optimization of presave ac... | Also you can use [FieldTracker](https://django-model-utils.readthedocs.org/en/latest/utilities.html#field-tracker) from [django-model-utils](https://github.com/carljm/django-model-utils) for this:
1. Just add tracker field to your model:
```
tracker = FieldTracker()
```
2. Now in pre\_save and post\_save you... |
Triple quotation in python | 23,361,171 | 6 | 2014-04-29T09:48:19Z | 23,361,210 | 10 | 2014-04-29T09:49:53Z | [
"python",
"syntax"
] | So I understand that if I do the following
```
print """ Anything I
type in here
works. Multiple LINES woohoo!"""
```
But what if following is my python script
```
""" This is my python Script. Just this much """
```
What does the above thing do? Is it taken as comment? Why is it not a syntax ... | The triple quotes `'''` or `"""` are just different ways of representing strings. The advantage of triple quotes is that it can span multiple lines and sometimes serve as [**docstrings**](http://legacy.python.org/dev/peps/pep-0257/).
The reason:
`"hadfasdfas"`
doesn't raise any error is because python simply creates... |
Import of 'urllib3.util' failing in Python 2.7? | 23,361,432 | 4 | 2014-04-29T09:59:55Z | 23,361,911 | 11 | 2014-04-29T10:21:20Z | [
"python",
"python-2.7"
] | I'm working on a Python script written by someone else. I'm trying to get it to run without any problems on my local development machine.
I've installed the modules required by the script (requests, urllib3 and oath2), however I'm getting the following error which I'm struggling to resolve;
```
Traceback (most recent... | **Broken install**
If for some reason your install of urllib3 is failing to include the `util` submodule, you could simply download the archive from the pypi page and copy the util folder from there to your urllib3 instal location.
**Outdated urllib3**
The error you've posted is saying that within `urllib3` the rela... |
Using regular expression in Twitter API | 23,363,940 | 3 | 2014-04-29T11:53:58Z | 23,411,001 | 7 | 2014-05-01T15:35:34Z | [
"python",
"regex",
"twitter",
"tweepy"
] | I am using Tweepy Library in Python to search for tweets. I am wondering, if I can use regular expression to search Tweets.
I am using the following code :
```
query = 'ARNOLD or SYLVESTER'
for tweet in tweepy.Cursor(api.search,
query,
count=100,
... | Twitter unfortunately doesn't support searching of tweets using regular expressions which means that you do have to post process. There's not actually any official documentation from Twitter to that effect, but [everyone](http://www.johndcook.com/blog/2009/03/12/grep-twitter-regex/) who uses the Twitter search API [pos... |
How to know if the CPython executable is the debug version, in python? | 23,364,556 | 4 | 2014-04-29T12:22:55Z | 23,364,776 | 8 | 2014-04-29T12:32:30Z | [
"python",
"cpython"
] | We need to find out if our code is running under a CPython executable built with debugging enabled, programmatically. `sys` module did not seem to have any information, at least on `python3.4-dbg` of Ubuntu 14.04. `sys.flags.debug` is set to 0. The reason for this is that our code unmodified actually crashes the debug ... | The following code might be what you're after
Using `python3.4`:
```
>>> import sysconfig
>>> sysconfig.get_config_var('Py_DEBUG')
0
```
On the other hand using `python3.4-dbg`:
```
>>> import sysconfig
>>> sysconfig.get_config_var('Py_DEBUG')
1
```
However, there are also compile time options controlling "debug" ... |
AWS aws.push ImportError: No module named boto in Ubuntu | 23,365,374 | 13 | 2014-04-29T12:59:22Z | 23,431,912 | 31 | 2014-05-02T15:39:10Z | [
"python",
"ubuntu",
"amazon-web-services",
"elastic-beanstalk"
] | I'm trying to follow this tutorial:
<http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Ruby_rails.html>
in order to deploy a Ruby on Rails app in AWS with Ubuntu.
Everything went ok (I can run my app in local), until the final step. When I run aws.push I get next error.
```
roberto@ubuntu:~/dev/... | What happened is that the eb command line interface available in that specific AWS tutorial (<http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Ruby_rails.html>) does not provide the latest version of boto.
When you did
```
pip install boto
```
you installed the latest version from <https://github.... |
AWS aws.push ImportError: No module named boto in Ubuntu | 23,365,374 | 13 | 2014-04-29T12:59:22Z | 26,229,007 | 17 | 2014-10-07T05:17:25Z | [
"python",
"ubuntu",
"amazon-web-services",
"elastic-beanstalk"
] | I'm trying to follow this tutorial:
<http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Ruby_rails.html>
in order to deploy a Ruby on Rails app in AWS with Ubuntu.
Everything went ok (I can run my app in local), until the final step. When I run aws.push I get next error.
```
roberto@ubuntu:~/dev/... | If on OSX w/o pip installed:
```
sudo easy_install pip
sudo pip install boto
``` |
Pandas Series to Excel | 23,365,466 | 3 | 2014-04-29T13:03:04Z | 23,366,074 | 9 | 2014-04-29T13:28:03Z | [
"python",
"pandas"
] | The pandas.Series object [does have many `to_*` functions](http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.Series.html), yet it lacks a `to_excel` function. Is there an easier/better way to accomplish the export in line 3 of this snippet? It feels clunky to first convert the Series to a DataFrame s... | You can either:
### 1. construct a `DataFrame` from the start,
in which case you've already answered your own question.
### 2. Use `Series.to_frame()`
```
s.to_frame(name='column_name').to_excel('xlfile.xlsx', sheet_name='s')
``` |
How to filter list based on another list containing wildcards? | 23,368,477 | 7 | 2014-04-29T15:06:04Z | 23,368,549 | 10 | 2014-04-29T15:09:00Z | [
"python",
"list",
"glob"
] | How can I filter a list based on another list which contains partial values and wildcards? The following example is what I have so far:
```
l1 = ['test1', 'test2', 'test3', 'test4', 'test5']
l2 = set(['*t1*', '*t4*'])
filtered = [x for x in l1 if x not in l2]
print filtered
```
This example results in:
```
['test1'... | Use the [`fnmatch`](https://docs.python.org/2/library/fnmatch.html) module and a list comprehension with [`any()`](https://docs.python.org/2/library/functions.html#any):
```
>>> from fnmatch import fnmatch
>>> l1 = ['test1', 'test2', 'test3', 'test4', 'test5']
>>> l2 = set(['*t1*', '*t4*'])
>>> [x for x in l1 if not a... |
Pymongo find and modify | 23,368,575 | 2 | 2014-04-29T15:10:27Z | 23,369,162 | 7 | 2014-04-29T15:37:20Z | [
"python",
"mongodb",
"pymongo"
] | I have a find query in a mongodb collection and would like this query to also update a field... something like this...
```
db = pymongo.MongoClient(DB_HOST)[COLLECTION][Product]
new_posts = db.find({'type':{'$ne':'overview'}, 'indice':0, 'thread_id':{'$nin':front_db_ids}, 'updated':{'$exists':False}},{'_id': 0}) + {{'... | refer the [documentation](http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update),
for example
```
db.update({"_id": acs_num}, {"$set": mydata}, upsert = True)
```
or `find_and_modify` according to [docs](http://api.mongodb.org/python/current/api/pymongo/collection.html... |
Why can't I detect that the tuple is empty? | 23,370,921 | 2 | 2014-04-29T17:04:14Z | 23,371,027 | 8 | 2014-04-29T17:08:52Z | [
"python",
"arrays",
"numpy",
"tuples"
] | I am using the where function in numpy to look for a one letter string in an array of strings.
For example:
I will look for `'U'` in `['B' 'U' 'A' 'M' 'R' 'O']` and get the index of `'U'`.
```
letter = 'U'
row = ['B', 'U', 'A', 'M', 'R', 'O']
letter_found = np.where(row == letter)
```
However when I am looking for a ... | The nomeclature:
```
if some_iterable:
#only if non-empty
```
only works when something is empty. In your case, the tuple isn't actually empty. The thing the tuple contains is empty. So you might want to do the following:
```
if any(map(len, my_tuple)):
#passes if any of the contained items are not empty
```... |
How to return html of a page using robobrowser | 23,372,311 | 3 | 2014-04-29T18:18:41Z | 23,375,257 | 9 | 2014-04-29T21:04:40Z | [
"python",
"django",
"beautifulsoup",
"robobrowser"
] | I'm experimenting with <http://robobrowser.readthedocs.org/en/latest/readme.html>, a new python library based on the beautiful soup library. I'm trying to test it out by opening an html page and returning it within a django app, but I can't figure out to do this most simple task. My django app contains :
```
def index... | You can try using the `parsed` property.
**Code:**
```
from robobrowser import RoboBrowser
url = "http://www.google.com"
br = RoboBrowser(history=True)
br.open(url)
print br.parsed
```
**Result:**
```
<!DOCTYPE html>
<html itemscope="" itemtype="http://schema.org/WebPage" lang="en-PH"><head><meta content="/images/... |
Python 3.4.0 with MySQL database | 23,376,103 | 26 | 2014-04-29T22:01:32Z | 23,376,193 | 32 | 2014-04-29T22:08:54Z | [
"python",
"mysql",
"python-3.x",
"mysql-python",
"python-3.4"
] | I have installed **Python version** **3.4.0** and I would like to do a project with MySQL database. I downloaded and tried installing **MySQLdb**, but it wasn't successful for this version of Python. Any suggestions how could I fix this problem and install it properly? | MySQLdb does not support Python 3 but it is not the only MySQL driver for Python.
[mysqlclient](https://pypi.python.org/pypi/mysqlclient) is essentially just a fork of MySQLdb with Python 3 support merged in (and a few other improvements).
[PyMySQL](http://www.pymysql.org/) is a pure python MySQL driver, which means ... |
Python 3.4.0 with MySQL database | 23,376,103 | 26 | 2014-04-29T22:01:32Z | 24,900,065 | 17 | 2014-07-23T00:38:47Z | [
"python",
"mysql",
"python-3.x",
"mysql-python",
"python-3.4"
] | I have installed **Python version** **3.4.0** and I would like to do a project with MySQL database. I downloaded and tried installing **MySQLdb**, but it wasn't successful for this version of Python. Any suggestions how could I fix this problem and install it properly? | Use [mysql-connector-python](http://dev.mysql.com/downloads/connector/python/). I prefer to install it with pip from [PyPI](https://pypi.python.org/pypi/mysql-connector-python):
```
pip install --allow-external mysql-connector-python mysql-connector-python
```
Have a look at its [documentation](http://dev.mysql.com/d... |
Pandas percentage of total with groupby | 23,377,108 | 13 | 2014-04-29T23:30:40Z | 23,377,155 | 12 | 2014-04-29T23:35:30Z | [
"python",
"pandas"
] | This is obviously simple, but as a numpy newbe I'm getting stuck.
I have a CSV file that contains 3 columns, the State, the Office ID, and the Sales for that office.
I want to calculate the percentage of sales per office in a given state (total of all percentages in each state is 100%).
```
df = pd.DataFrame({'state... | You need to make a second groupby object that groups by the states, and then use the `div` method:
```
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'office_id': list(range(1, 7)) * 2,
'sales': [np.random.randint(100000,... |
Pandas percentage of total with groupby | 23,377,108 | 13 | 2014-04-29T23:30:40Z | 23,377,232 | 22 | 2014-04-29T23:45:31Z | [
"python",
"pandas"
] | This is obviously simple, but as a numpy newbe I'm getting stuck.
I have a CSV file that contains 3 columns, the State, the Office ID, and the Sales for that office.
I want to calculate the percentage of sales per office in a given state (total of all percentages in each state is 100%).
```
df = pd.DataFrame({'state... | [Paul H's answer](http://stackoverflow.com/a/23377155/3393459) is right that you will have to make a second groupby object, but you can calculate the percentage in a simpler way -- just groupby the stateoffice and divide the sales column by its sum. Starting with the state\_office df in Paul H's answer:
```
state_pcts... |
python BeautifulSoup parsing table | 23,377,533 | 11 | 2014-04-30T00:17:58Z | 23,377,804 | 33 | 2014-04-30T00:47:40Z | [
"python",
"beautifulsoup"
] | Folks, I learning python `requests` and BeautifulSoup. For the exercise, I've chosen to write a quick NYC parking ticket parser. I am able to get a html response which is quite ugly. I need to grab the `lineItemsTable` and parse all the tickets.
You can reproduce the page by going here: `https://paydirect.link2gov.com... | Here you go:
```
data = []
table = soup.find('table', attrs={'class':'lineItemsTable'})
table_body = table.find('tbody')
rows = table_body.find_all('tr')
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele]) # Get rid of empty values... |
Python Scipy FFT wav files | 23,377,665 | 14 | 2014-04-30T00:31:20Z | 23,378,284 | 26 | 2014-04-30T01:45:55Z | [
"python",
"scipy",
"fft"
] | I have a handful of wav files. I'd like to use SciPy FFT to plot the frequency spectrum of these wav files. How would I go about doing this? | `Python` provides several api to do this fairly quickly. I download the sheep-bleats wav file from [this link](http://download.wavetlan.com/SVV/Media/HTTP/http-wav.htm). You can save it on the desktop and `cd` there within terminal. These lines in the `python` prompt should be enough: (omit `>>>`)
```
import matplotli... |
Merge python dictionaries with common key | 23,379,215 | 2 | 2014-04-30T03:33:16Z | 23,379,498 | 7 | 2014-04-30T04:05:50Z | [
"python",
"python-2.7",
"dictionary"
] | Assume I have the following dictionaries:
```
{name: "john", place: "nyc", owns: "gold", quantity: 30}
{name: "john", place: "nyc", owns: "silver", quantity: 20}
{name: "jane", place: "nyc", owns: "platinum", quantity: 5}
{name: "john", place: "chicago", owns: "brass", quantity: 60}
{name: "john", place: "chicago", ow... | First, getting the output that you asked for:
```
data = [{'name': "john", 'place': "nyc", 'owns': "gold", 'quantity': 30},
{'name': "john", 'place': "nyc", 'owns': "silver", 'quantity': 20},
{'name': "jane", 'place': "nyc", 'owns': "platinum", 'quantity': 5},
{'name': "john", 'place': "chicago", 'owns': "brass", 'qua... |
Using BeautifulSoup Extract Text without Tags | 23,380,171 | 8 | 2014-04-30T05:15:58Z | 23,380,199 | 7 | 2014-04-30T05:18:21Z | [
"python",
"web-scraping",
"beautifulsoup"
] | My Webpage is something like this -
```
<p>
<strong class="offender">YOB:</strong> 1987<br />
<strong class="offender">RACE:</strong> WHITE<br />
<strong class="offender">GENDER:</strong> FEMALE<br />
<strong class="offender">HEIGHT:</strong> 5'05''<br />
<strong class="offender">WEIGHT:</strong> 1... | I think you can get it using `subc1.text`.
```
>>> html = """
<p>
<strong class="offender">YOB:</strong> 1987<br />
<strong class="offender">RACE:</strong> WHITE<br />
<strong class="offender">GENDER:</strong> FEMALE<br />
<strong class="offender">HEIGHT:</strong> 5'05''<br />
<strong class="offend... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.