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 |
|---|---|---|---|---|---|---|---|---|---|
Pretty Print output in a sideways tree format in console window | 12,255,793 | 4 | 2012-09-04T01:40:24Z | 17,260,252 | 8 | 2013-06-23T11:23:47Z | [
"python",
"console",
"pretty-print"
] | I have a dictionary such as this created using Python.
```
d = {'a': ['Adam', 'Book', 4], 'b': ['Bill', 'TV', 6, 'Jill', 'Sports', 1, 'Bill', 'Computer', 5], 'c': ['Bill', 'Sports', 3], 'd': ['Quin', 'Computer', 3, 'Adam', 'Computer', 3], 'e': ['Quin', 'TV', 2, 'Quin', 'Book', 5], 'f': ['Adam', 'Computer', 7]}
```
I ... | You can have a look at the code of the [ETE toolkit](http://ete.cgenomics.org). The function [\_asciiArt](https://github.com/jhcepas/ete/blob/master/ete_dev/coretype/tree.py#L1363) produces nice representations of trees even [with internal node labels](http://stackoverflow.com/a/11757919)
```
from ete2 import Tree
t =... |
Using @ndb.tasklet or @ndb.synctasklet in Google App Engine | 12,256,093 | 9 | 2012-09-04T02:34:12Z | 12,257,253 | 10 | 2012-09-04T05:24:20Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] | I have a `POST` method which calls a few tasklets. These tasklets do have yields in them, and I do have some `x.put_async()` in my code. So I don't want it to return before all the async stuff is done. So I decorated all my tasklets, which are just small functions with `@ndb.tasklet`. Also, on top of my `POST` method, ... | Regarding the handler and using @ndb.toplevel and @ndb.synctasklet:
The way I understood it was that you need to use both @ndb.synctasklet and @ndb.toplevel on the handler. All the sub-tasklets only need the @ndb.tasklet decorator. e.g.
```
class Foo(ndb.Model):
name = ndb.StringProperty()
@ndb.tasklet
de... |
adding a file path to sys.path in python | 12,257,747 | 20 | 2012-09-04T06:15:17Z | 12,257,807 | 20 | 2012-09-04T06:20:08Z | [
"python",
"sys"
] | i had a file `example_file.py` , i want to use this `example_file.py` from various files, so i decided to add `example_file.py` to `sys.path` and importing this file in another file for using the functionality of the file.
I had opened `ipython` and done the following
```
import sys
sys.path
sys.path.append('/path/to/... | There are a few ways. One of the simplest is to create a `my-paths.pth` file (as described [here](http://docs.python.org/library/site.html)). This is just a file with the extension `.pth` that you put into your system `site-packages` directory. On each line of the file you put one directory name, so you can put a line ... |
How to pass in command line arguments when using ideone? | 12,258,317 | 12 | 2012-09-04T07:02:08Z | 12,258,385 | 8 | 2012-09-04T07:07:46Z | [
"c++",
"python",
"command-line"
] | I'm using the ideone online interpreter (<http://ideone.com/>) to test some C++ and Python programs. How do I specify the command line arguments instead of using the STDIN input? | Looks like you can't, but a *quick hack* should do the trick:
```
static char * const ARGV[] = { "myprog", "hello", "world", NULL };
int main(int argc, char * argv[])
{
argc = 3;
argv = ARGV;
// ...
}
```
Or convert the standard input into args:
```
#include <vector>
#include <string>
#include <iterato... |
How can tox install the modules via the requirements file? | 12,258,456 | 27 | 2012-09-04T07:12:56Z | 12,258,504 | 33 | 2012-09-04T07:16:23Z | [
"python",
"tox"
] | Our python project has a requirements.txt file which lists some dependent module. We used to use
```
pip install -r requirements.txt
```
to install these dependencies. We are now using tox to build up the test environment. My question is that how can we install the modules via requirements.txt directly.
Followings a... | ```
deps = -r{toxinidir}/tools/pip-requires
-r{toxinidir}/tools/test-requires
``` |
How can tox install the modules via the requirements file? | 12,258,456 | 27 | 2012-09-04T07:12:56Z | 18,964,795 | 10 | 2013-09-23T16:56:03Z | [
"python",
"tox"
] | Our python project has a requirements.txt file which lists some dependent module. We used to use
```
pip install -r requirements.txt
```
to install these dependencies. We are now using tox to build up the test environment. My question is that how can we install the modules via requirements.txt directly.
Followings a... | What helped me is the following (the other solution didn't work for me):
```
deps=
pytest
-rrequirements.txt
```
This works at least if you add `requirements.txt` to `MANIFEST.in` and if you use a relatively new `tox (>= 1.6.1) version ([see here](http://tox.readthedocs.org/en/latest/example/basic.html#depend... |
How to remove duplicating character from beginning of a string | 12,260,377 | 2 | 2012-09-04T09:21:21Z | 12,260,400 | 12 | 2012-09-04T09:22:31Z | [
"python",
"regex"
] | I have a an array of human-entered numbers which contain random amount of zeros before actual number begins.
guess example will say more:
```
entry_1="0000005452508"
entry_2="02965054"
entry_3="5487864"
```
I need to get the string after these duplicating zeros end, i.e first entry should result in 5452508. Numbers o... | [`lstrip`](http://docs.python.org/library/stdtypes.html#str.lstrip) does what you want:
```
entry_1 = "0000005452508".lstrip("0")
entry_2 = "02965054".lstrip("0")
entry_3 = "5487864".lstrip("0")
``` |
Django Haystack autocompletion on two (multiple) fields | 12,262,590 | 6 | 2012-09-04T11:29:54Z | 16,025,675 | 7 | 2013-04-15T22:23:48Z | [
"python",
"django",
"django-haystack",
"whoosh"
] | I use haystack 1.2.6 with Whoosh 2.4 and Django 1.3.
Let's say that we have the below model describing an hypothetical post.
```
Post(models.Model):
title = models.CharField()
body = models.TextField()
```
We built our post index like this for autocompletion on body field:
```
PostIndex(SearchIndex):
tex... | I've managed to do it based on [this](https://groups.google.com/forum/#!msg/django-haystack/KU7aRHzNJaU/Qhqr_AUf3I4J). You just make an EdgeNgramField for each field you want to autocomplete on in your index, then apply the autocompletion to two different search querysets and concatenate them:
```
sqs = SearchQuerySet... |
Statistics on huge numpy (HDF5) arrays | 12,264,309 | 3 | 2012-09-04T13:16:06Z | 12,264,691 | 7 | 2012-09-04T13:36:28Z | [
"python",
"numpy",
"python-2.7",
"h5py"
] | I have fairly large 4D arrays [20x20x40x15000] that I save to disk as HDF5 files using [h5py](http://code.google.com/p/h5py/). Now the problem is that I want to calculate an average of the entire array i.e. using:
```
numpy.average(HDF5_file)
```
I get a `MemoryError`. It seems that numpy tries to load the HDF5 file ... | Folding 240 000 000 values will need a few lines of code to work effectively. Numpy works by loading all the data into the memory, so you won't be able to load naively the data as you discovered. You will have to divide the problem into chunks, and use a map/reduce approach:
* select a chunk size (according to memory ... |
what is the difference for python between lambda and regular function? | 12,264,834 | 20 | 2012-09-04T13:44:55Z | 12,264,881 | 15 | 2012-09-04T13:47:14Z | [
"python",
"lambda"
] | I'm curious about the difference between `lambda` function and a regular function (defined with `def`) - in the python level. (I know what is the difference for programmers and when to use each one.)
```
>>> def a():
return 1
>>> b = lambda: 1
>>> a
<function a at 0x0000000004036F98>
>>> b
<function <lambda> at 0... | They are the same type so they are treated the same way:
```
>>> type(a)
<type 'function'>
>>> type(b)
<type 'function'>
```
Python also knows that `b` was defined as a lambda function and it sets that as function name:
```
>>> a.func_name
'a'
>>> b.func_name
'<lambda>'
```
In other words, it influences the name th... |
How to plot 2d math vectors with matplotlib? | 12,265,234 | 9 | 2012-09-04T14:06:55Z | 12,267,492 | 18 | 2012-09-04T16:13:59Z | [
"python",
"math",
"matplotlib",
"visualization"
] | How can we plot 2D math vectors with `matplotlib`? Does anyone have an example or suggestion about that?
I have a couple of vectors stored as 2D `numpy` arrays, and I would like to plot them as directed edges.
The vectors to be plotted are constructed as below:
```
import numpy as np
# a list contains 3 vectors;
# e... | The suggestion in the comments by halex is correct, you want to use quiver ([doc](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.quiver)), but you need to tweak the properties a bit.
```
import numpy as np
import matplotlib.pyplot as plt
soa =np.array( [ [0,0,3,2], [0,0,1,1],[0,0,9,9]])
X,Y,U... |
"Ask forgiveness not permission" - explain | 12,265,451 | 21 | 2012-09-04T14:18:18Z | 12,265,860 | 25 | 2012-09-04T14:40:16Z | [
"python"
] | I'm not asking for personal "religious" opinions about this philosophy, rather something a bit more technical.
I understand this phrase is one of several litmus tests to see if your code is "pythonic". But to me, pythonic means clean, simple and intuitive, not loaded with exception handlers for bad coding.
So, practi... | The classical "ask forgiveness not permission" example is accessing values from a `dict` that may not exist. E.g.:
```
names = { 'joe': 'Joe Nathan', 'jo': 'Jo Mama', 'joy': 'Joy Full' }
name = 'hikaru'
try:
print names[name]
except KeyError:
print "Sorry, don't know this '{}' person".format(name)
```
Here t... |
"Ask forgiveness not permission" - explain | 12,265,451 | 21 | 2012-09-04T14:18:18Z | 12,270,384 | 23 | 2012-09-04T19:49:28Z | [
"python"
] | I'm not asking for personal "religious" opinions about this philosophy, rather something a bit more technical.
I understand this phrase is one of several litmus tests to see if your code is "pythonic". But to me, pythonic means clean, simple and intuitive, not loaded with exception handlers for bad coding.
So, practi... | âAsk forgiveness, not permissionâ opposes two programming styles. âAsk for permissionâ goes like this:
```
if can_do_operation():
perform_operation()
else:
handle_error_case()
```
âAsk forgivenessâ goes like this:
```
try:
perform_operation()
except Unable_to_perform:
handle_error_case()
... |
python - returning a default value | 12,265,695 | 7 | 2012-09-04T14:31:12Z | 12,265,735 | 11 | 2012-09-04T14:33:23Z | [
"python",
"return-value",
"default-value"
] | I'm looking to mimic the behavior of built-in functions (like `getattr`) that allow the user to specify a "default" return value. My initial attempt was to do this
```
def myfunc(foo, default=None):
# do stuff
if (default is not None):
return default
raise SomeException()
```
The problem is that i... | You need to use a sentinel to detect that a default value was not set:
```
sentinel = object()
def func(someparam, default=sentinel):
if default is not sentinel:
print("You passed in something else!")
```
This works because an instance of `object()` will always have it's own memory id and thus `is` will ... |
Where can I find python's built-in classes' methods and attributes? | 12,266,284 | 11 | 2012-09-04T15:03:26Z | 12,266,417 | 15 | 2012-09-04T15:10:58Z | [
"python",
"exception",
"documentation"
] | I'm trying to find out which methods and attributes come with the mother of all exception classes in python: the Exception class. However, I'm having a bit of trouble since the official documentation doesn't seem to provide it.
The best I could find was this: <http://docs.python.org/library/exceptions.html> but that o... | The built-in function `dir` will give a list of names comprising the methods and attributes of an object.
```
>>>print dir(Exception)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__getitem__', '__getslice__', '__hash__', '__init__', '__new__', '__reduc
e__', '__reduce_ex__', ... |
finding top k largest keys in a dictionary python | 12,266,617 | 3 | 2012-09-04T15:22:53Z | 12,266,692 | 11 | 2012-09-04T15:27:09Z | [
"python"
] | Lets say I have a dictionary:
```
{key1:value1........... keyn:valuen}
```
So lets say I want to write a function
```
def return_top_k(dictionary, k):
return list_of_keys_sorted
```
What is the most efficient way (in terms of big O) to get the keys which have the top k values (maintaining the order i.e the hig... | `O(n log k)`:
```
import heapq
k_keys_sorted = heapq.nlargest(k, dictionary)
```
You could use `key` keyword parameter to specify what should be used as a sorting key e.g.:
```
k_keys_sorted_by_values = heapq.nlargest(k, dictionary, key=dictionary.get)
``` |
Code style - 'hiding' functions inside other functions | 12,267,149 | 5 | 2012-09-04T15:53:06Z | 12,267,170 | 8 | 2012-09-04T15:54:25Z | [
"python",
"coding-style",
"scoping"
] | Recently I've been doing things like this:
```
import Tkinter
class C(object):
def __init__(self):
self.root = Tkinter.Tk()
def f():
print 'hello'
self.button = Tkinter.Button(master=self.root, command=f, text='say hello')
```
as opposed to something like this:
```
import Tkin... | The typical way to do something like this in the context of `Tkinter` is to use a `lambda` function.
```
self.button = Tkinter.Button(master=self.root,
command=lambda:sys.stdout.write("Hello!\n"),
text='say hello')
```
At it's core, this is really the same as... |
Machine Translation using babelize_shell() in NLTK | 12,267,544 | 2 | 2012-09-04T16:17:28Z | 12,301,950 | 7 | 2012-09-06T14:06:19Z | [
"python",
"nltk"
] | Hi I am learning Natural Language processing using NLTK. I am trying to implement babelize\_shell() example of the book. What I am doing is executing babelize\_shell(), after that I am entering my string, followed by german as stated in the book, followed by run.
The error I am getting is:
```
Traceback (most recent ... | I'm having the same problem right now.
I've found this:
<http://nltk.googlecode.com/svn/trunk/doc/api/nltk.misc.babelfish-module.html>
and it says:
BabelfishChangedError
Thrown when babelfish.yahoo.com changes some detail of their HTML layout, and babelizer no longer submits data in the correct form, or can no longer... |
Problems with issuing cp command with Popen in Python | 12,267,774 | 3 | 2012-09-04T16:34:09Z | 12,267,803 | 12 | 2012-09-04T16:36:20Z | [
"python",
"copy",
"subprocess",
"cp",
"globbing"
] | I'm trying to copy files from one location to another using subprocess library and Popen method. When runing following script I'm getting the error `cp: cannot stat /some/dev_path/*`. I was told that the `*` is not expanded to the file names and that's where the problem is. Also in some other posts people were suggesti... | Expanding the `*` (globbing) is a function of your shell, *bash* for example. Therefore you'd have to use the keyword argument `shell=True` in your `subprocess.Popen` call.
However, for this case I'd strongly suggest to use [shutil.copytree](http://docs.python.org/library/shutil.html) instead.
*(First of all, because... |
Non distinct prime factors of larger numbers | 12,268,526 | 4 | 2012-09-04T17:29:01Z | 12,269,105 | 8 | 2012-09-04T18:10:40Z | [
"python",
"math",
"numpy"
] | I wrote and use this function to produce prime factors of a number:
```
import numpy as np
from math import sqrt
def primesfrom3to(n):
""" Returns a array of primes, p < n """
assert n>=2
sieve = np.ones(n/2, dtype=np.bool)
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i/2]:
sieve[i... | The traditional way to do this is to divide out each prime factor in turn and then recurse on your factorisation method. This will in general be faster than sieving for all of the primes, because you only care about the (few) primes that actually divide your number.
Of course, there are many, many better prime factori... |
Sort argparse help alphabetically | 12,268,602 | 14 | 2012-09-04T17:34:29Z | 12,269,143 | 14 | 2012-09-04T18:13:19Z | [
"python",
"sorting",
"arguments",
"command-line-arguments",
"argparse"
] | I am using Python's (2.7) argparse facility and would like to automatically sort the help it produces alphabetically by option.
By default help entries are sorted in the order they are added\*, as in:
```
p = argparse.ArgumentParser(description='Load duration curves and other plots')
p.add_argument('--first', '-f', t... | You can do this by providing a custom [`HelpFormatter` class](http://docs.python.org/library/argparse.html#formatter-class); the internals of which are officially undocumented. This means you are on your own when it comes to compatibility from Python version to version, but I find the interface quite stable:
```
from ... |
Is it possible to run python SimpleHTTPServer on localhost only? | 12,268,835 | 39 | 2012-09-04T17:50:44Z | 12,268,922 | 34 | 2012-09-04T17:56:19Z | [
"python",
"http",
"shell",
"command-line",
"simplehttpserver"
] | I have a vpn connection and when I'm running python -m SimpleHTTPServer, it serves on 0.0.0.0:8000, which means it can be accessed via localhost **and** via my real ip.
I don't want robots to scan me and interested that the server will be accessed only via localhost.
Is it possible?
```
python -m SimpleHTTPServer 127... | If you read the source you will see that only the port can be overridden on the command line. If you want to change the host it is served on, you will need to implement the `test()` method of the `SimpleHTTPServer` and `BaseHTTPServer` yourself. But that should be really easy.
Here is how you can do it, pretty easily:... |
Is it possible to run python SimpleHTTPServer on localhost only? | 12,268,835 | 39 | 2012-09-04T17:50:44Z | 12,269,225 | 49 | 2012-09-04T18:18:49Z | [
"python",
"http",
"shell",
"command-line",
"simplehttpserver"
] | I have a vpn connection and when I'm running python -m SimpleHTTPServer, it serves on 0.0.0.0:8000, which means it can be accessed via localhost **and** via my real ip.
I don't want robots to scan me and interested that the server will be accessed only via localhost.
Is it possible?
```
python -m SimpleHTTPServer 127... | As *@sberry* explained, simply doing it by using the nice `python -m ...` method won't be possible, because the IP address is hardcoded in the implementation of the `BaseHttpServer.test` function.
A way of doing it from the command line without writing code to a file first would be
```
python -c 'import BaseHTTPServe... |
Using python pandas to parse CSV with date in format Year, Day, Hour, Min, Sec | 12,269,528 | 5 | 2012-09-04T18:43:55Z | 12,273,646 | 10 | 2012-09-05T02:14:39Z | [
"python",
"pandas",
"python-dateutil"
] | I have several CSV files with the format:
```
Year,Day,Hour,Min,Sec.,P1'S1
2003, 1, 0, 0,12.22, 0.541
2003, 1, 1, 0,20.69, 0.708
2003, 1, 2, 0, 4.95, 0.520
2003, 1, 3, 0,13.42, 0.539
...
```
(where *day*, is the *day of the year*) and I'm trying to read them using the **pandas** library (seems a fantastic lib... | In order to parse a multi-column date, you need to tell pandas which columns should be combined into a single date, so you need to say `parse_dates=['Year','Day','Hour','Min','Sec']`
You also need to define your own parser that takes a element from each column you specified in `parse_dates`:
```
In [1]: import pandas... |
Safe to deploy Flask framework's webserver in a production environment | 12,269,537 | 18 | 2012-09-04T18:44:10Z | 12,269,604 | 15 | 2012-09-04T18:49:29Z | [
"python",
"flask"
] | Is Python's flask server safe for deployment in a production environment?
Is there a better alternative? | Basically, no. The built-in development server is not safe for deployment in a production environment.
The built in *development* server is for just that. For use in production you should follow one of the steps detailed [here](http://flask.pocoo.org/docs/deploying/).
These include different servers that implement th... |
Safe to deploy Flask framework's webserver in a production environment | 12,269,537 | 18 | 2012-09-04T18:44:10Z | 12,269,934 | 22 | 2012-09-04T19:16:26Z | [
"python",
"flask"
] | Is Python's flask server safe for deployment in a production environment?
Is there a better alternative? | **No**. The bundled server is a *development* server. It's not designed with production environments in mind.
* It will not handle more than one request at a time by default.
* If you leave debug mode on and an error pops up, it opens up a shell that allows for arbitrary code to be executed on your server (think `os.s... |
How to format pubDate with Python | 12,270,531 | 4 | 2012-09-04T19:58:58Z | 12,271,253 | 8 | 2012-09-04T20:57:05Z | [
"python",
"parsing",
"date",
"rss"
] | I am newbie in Python and i m trying to do the following.
In PHP if we want to convert the date we use something like this:
```
$item_date = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate));
```
Now, i m trying to do the same using Python, but i cant understand the exact method for doing it.
Can anyone help me by... | According to [RSS specification](http://cyber.law.harvard.edu/rss/rss.html) `pubDate` must follow [RFC822](http://asg.web.cmu.edu/rfc/rfc822.html):
```
mytime.strftime("%a, %d %b %Y %H:%M:%S %z")
``` |
Convert UUID 32-character hex string into a "YouTube-style" short id and back | 12,270,852 | 17 | 2012-09-04T20:24:45Z | 12,270,917 | 32 | 2012-09-04T20:30:02Z | [
"python",
"guid",
"uuid"
] | I'm assigning all my MongoDB documents a GUID using uuid.uuid1(). I want a way I can derive an 11 character, unique, case-sensitive YouTube-like ID, such as
```
1_XmY09uRJ4
```
from uuid's resulting hex string which looks like
```
ae0a0c98-f1e5-11e1-9t2b-1231381dac60
```
I want to be able to match the shortened ID ... | Convert the underlying bytes to a base64 value, stripping the `=` padding and the newline.
You probably want to turn any `/` characters in the output to underscores:
```
>>> import uuid
>>> uuid.uuid1().bytes.encode('base64').rstrip('=\n').replace('/', '_')
'81CMD_bOEeGbPwAjMtYnhg'
```
The reverse:
```
>>> uuid.UUI... |
Python - read numbers from text file and put into list | 12,271,503 | 2 | 2012-09-04T21:19:15Z | 12,271,535 | 8 | 2012-09-04T21:21:52Z | [
"python"
] | So like the title says im starting to learn some python and im having trouble picking up on this technique. What I need to accomplish is to read in some numbers and store them in a list. The text file looks like the following:
```
0 0 3 50
50 100 4 20
```
Basically these are coordinates and directions to be used for... | ```
with open('data.txt') as f:
polyShape = []
for line in f:
line = line.split() # to deal with blank
if line: # lines (ie skip them)
line = [int(i) for i in line]
polyShape.append(line)
```
will give you
```
[[0, 0, 3, 50], [50, 100, 4, 20]]
```
This will... |
In Flask, set a cookie and then re-direct user | 12,272,418 | 14 | 2012-09-04T22:50:54Z | 12,272,522 | 25 | 2012-09-04T23:08:00Z | [
"python",
"flask"
] | It seems like in Flask, cookies are set by modifying the response object directly.
How can I return a response object, but also redirect a user to a different page upon successful login? I'd like to specifically redirect the user instead of rendering a different page, in case the user hits REFRESH.
Here's my current ... | You should change your code to something like:
```
if s.setSession():
response = make_response(redirect('/home'))
response.set_cookie('session_id', s.session_id)
return response
``` |
Why can't I "string".print()? | 12,272,856 | 7 | 2012-09-04T23:59:30Z | 12,272,872 | 9 | 2012-09-05T00:01:49Z | [
"python",
"ruby"
] | My understanding of the `print()` in both Python and Ruby (and other languages) is that it is a method on a string (or other types). Because it is so commonly used the syntax:
> print "hi"
works.
So why doesn't `"hi".print()` in Python or `"hi".print` in Ruby work? | When you do something like `"hi".print()`, you are implying that the string object `"hi"` has a method `print`. This is not the case. Instead, `print` is a function that takes a string (or other types) as input. |
Calculate execution time for every page in Python's Flask | 12,273,889 | 11 | 2012-09-05T02:51:17Z | 12,273,987 | 10 | 2012-09-05T03:08:03Z | [
"python",
"flask"
] | What's a good way to calculate the execution time for every page load using Python's Flask library?
I was thinking of putting a start timer in views/\_\_ init\_\_.py:
```
@app.before_request
def before_request():
g.start = time.time()
```
But where would I put the end part of the timer to calculate the difference,... | Put it in `teardown_request` function:
```
@app.teardown_request
def teardown_request(exception=None):
diff = time.time() - g.start
...
```
In `teardown_request` you are not allowed to change the response, If you want to use the calculated string in your response use `after_request`:
```
@app.after_request
d... |
Does Python use linked lists for lists? Why is inserting slow? | 12,274,060 | 9 | 2012-09-05T03:20:18Z | 12,274,070 | 17 | 2012-09-05T03:22:01Z | [
"python"
] | Just learning Python. Reading through the official tutorials. I ran across this:
> While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
I would have guessed that a mature language like Python wou... | Python uses a linear list layout in memory so that *indexing* is fast (O(1)). |
Does Python use linked lists for lists? Why is inserting slow? | 12,274,060 | 9 | 2012-09-05T03:20:18Z | 12,274,105 | 8 | 2012-09-05T03:26:52Z | [
"python"
] | Just learning Python. Reading through the official tutorials. I ran across this:
> While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
I would have guessed that a mature language like Python wou... | As Greg Hewgill has already pointed out, python lists use contiguous blocks of memory to make indexing fast. You can use a [`deque`](http://docs.python.org/library/collections.html#collections.deque) if you want the performance characteristics of a linked list. But your initial premise seems flawed to me. Indexed inser... |
How to smooth matplotlib contour plot? | 12,274,529 | 30 | 2012-09-05T04:32:35Z | 12,281,509 | 8 | 2012-09-05T12:31:49Z | [
"python",
"matplotlib"
] | I have numpy array with this shape: (33,10). When I plot contour I get ugly image like this:

while `contour()` doesn't seem to have any argument about smoothing or some sort of interpolation feature.
I somehow expected that tool which offers contour ... | There is no easy way to get a smooth contour. An alternative is to try `imshow`. You can look [here](http://stackoverflow.com/q/8055489/302369) for other possibilities.
```
import pylab as plt
import numpy as np
Z=np.loadtxt('data.txt')
plt.subplot(131)
plt.imshow(Z,interpolation='nearest')
plt.subplot(132)
plt.imsh... |
How to smooth matplotlib contour plot? | 12,274,529 | 30 | 2012-09-05T04:32:35Z | 12,311,139 | 33 | 2012-09-07T02:58:22Z | [
"python",
"matplotlib"
] | I have numpy array with this shape: (33,10). When I plot contour I get ugly image like this:

while `contour()` doesn't seem to have any argument about smoothing or some sort of interpolation feature.
I somehow expected that tool which offers contour ... | As others have already pointed out, you need to interpolate your data.
There are a number of different ways to do this, but for starters, consider `scipy.ndimage.zoom`.
As a quick exmaple:
```
import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt
data = np.loadtxt('data.txt')
# Resample your data... |
-9999 as missing value with numpy.genfromtxt() | 12,274,709 | 2 | 2012-09-05T04:58:32Z | 12,279,400 | 8 | 2012-09-05T10:27:49Z | [
"python",
"numpy",
"genfromtxt"
] | Lets say I have a dumb text file with the contents:
```
Year Recon Observed
1505 162.38 23
1506 46.14 -9999
1507 147.49 -9999
```
`-9999` is used to denote a missing value (don't ask).
So, I should be able to read this into a Numpy array with:
```
import numpy as np
x = np.... | Nope, you're not doing anything wrong. Using the `missing_values` argument indeed tells `np.genfromtxt` that the corresponding values should be flagged as "missing/invalid". The problem is that dealing with missing values is only supported if you use the `usemask=True` argument (I probably should have made that clearer... |
Django Pagination | 12,275,926 | 5 | 2012-09-05T06:48:54Z | 12,276,150 | 15 | 2012-09-05T07:03:53Z | [
"python",
"django",
"mongodb",
"django-pagination"
] | I need to make real pagination instead of paginating on all retreived data. The example in Django documentation site, is like;
```
def listing(request):
contact_list = Contacts.objects.all()
paginator = Paginator(contact_list, 25) # Show 25 contacts per page
page = request.GET.get('page')
try:
... | You make a false assumption. Django does not retrieve all objects when paginating: it slices the queryset appropriately, which uses LIMIT and COUNT on the SQL. |
Slices along arbitrary axis | 12,276,767 | 4 | 2012-09-05T07:44:52Z | 12,277,080 | 7 | 2012-09-05T08:07:50Z | [
"python",
"numpy",
"indexing"
] | I have a numpy array `A` such that
```
A.shape[axis] = n+1.
```
Now I want to construct two slices `B` and `C` of `A` by selecting the indices `0, .., n-1` and `1, ..., n` respectively along the axis `axis`. Thus
```
B.shape[axis] = C.shape[axis] = n
```
and `B` and `C` have the same size as `A` along the other axe... | ```
# exemple data
A = np.random.rand(2, 3, 4, 5)
axis = 2
n = A.ndim
# building n-dimensional slice
s = [slice(None), ] * n
s[axis] = slice(0, n - 1)
B = A[s]
s[axis] = slice(1, n)
C = A[s]
```
One-liners :
```
B = A[[slice(None) if i != axis else slice(0, n-1) for i in xrange(n)]]
C = A[[slice(None) if i != axis el... |
Permission denied error when trying to install pip in Mac OS X Lion | 12,277,716 | 4 | 2012-09-05T08:51:13Z | 12,277,916 | 19 | 2012-09-05T09:05:08Z | [
"python",
"osx",
"osx-lion",
"pip"
] | I'm trying to install pip on a Mac (OS X Lion). It doesn't seem to work. I use sudo and prompted for password.
```
$ sudo curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Uploa... | You are running the `curl` (download) command under `sudo`, but the python process itself is running without elevated privileges.
Run it like this instead:
```
$ curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py
$ sudo python get-pip.py
```
Alternatively, use the `sudo` command on the `python` part o... |
Send Data from a textbox into Flask? | 12,277,933 | 25 | 2012-09-05T09:05:38Z | 12,278,642 | 45 | 2012-09-05T09:47:09Z | [
"python",
"flask"
] | I was wondering if there was a way to take something from a text box in the HTML, feed it into flask, then parse that data with Python. I was thinking this might involve some JS but I could be wrong. Any ideas? | Unless you want to do something more complicated, feeding data from a HTML form into Flask is pretty easy.
This is a complete example of how doing it:
If your HTML is:
```
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Enter some text</h1>
<h2>(it will be converted to uppercase)</h2>
<form action="." method... |
How can I efficiently save a python pandas dataframe in hdf5 and open it as a dataframe in R? | 12,278,347 | 11 | 2012-09-05T09:29:34Z | 14,407,329 | 8 | 2013-01-18T20:45:51Z | [
"python",
"pandas",
"data.table",
"hdf5"
] | I think the title covers the issue, but to elucidate:
The [pandas](http://pandas.pydata.org) python package has a DataFrame data type for holding table data in python. It also has a convenient interface to the [hdf5](http://www.hdfgroup.org/HDF5/) file format, so pandas DataFrames (and other data) can be saved using a... | If you are still looking at this, take a look at this post on google groups. It shows how to exchange data between pandas/R via HDF5.
<https://groups.google.com/forum/?fromgroups#!topic/pydata/0LR72GN9p6w> |
Timedelta multiply with float in python | 12,278,362 | 11 | 2012-09-05T09:30:25Z | 12,278,493 | 16 | 2012-09-05T09:37:51Z | [
"python",
"datetime",
"multiplying",
"timedelta"
] | I have two dates and can calculate timedelta as usual.
But I want to calculate some percent with resulting timedelta:
```
full_time = (100/percentage) * timdelta
```
But it seems that it can only multiplying with interegs.
How can I use `float` instead of `int` as multiplier?
Example:
```
percentage = 43.27
p... | You can convert to total seconds and back again:
```
full_time = timedelta(seconds=multiplier * passed_time.total_seconds())
```
[`timedelta.total_seconds`](http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds) is available from Python 2.7; on earlier versions use
```
def timedelta_total_sec... |
Python list append | 12,279,599 | 3 | 2012-09-05T10:40:34Z | 12,279,749 | 7 | 2012-09-05T10:48:02Z | [
"python",
"list",
"append"
] | I want to store the intermediate values of a variable in Python. This variable is updated in a loop. When I try to do this with a `list.append` command, it updates every value in the list with the new value of the variable. How should I do it ?
```
while (step < maxstep):
for i in range(100):
x = a*b*c... | Assuming the original had a typo and `f1` is actualy `fi` (or vice verca):
`fi` is a pointer to an object, so you keep appending the same pointer, when you `fi += x` you actually changing the value of the object to which `fi` points. Hope this is clear.
To solve the issue you can `fi = fi + x` instead. |
How to move to one folder back in python | 12,280,143 | 8 | 2012-09-05T11:10:37Z | 12,280,192 | 12 | 2012-09-05T11:13:04Z | [
"python",
"operating-system"
] | Actually need to go some path and execute some command and below is the code
**code**:
```
import os
present_working_directory = '/home/Desktop/folder'
```
presently i am in `folder`
```
if some_condition == true :
change_path = "nodes/hellofolder"
os.chdir(change_path)
print os.getcwd()
if another_cond... | Just like you would in the shell.
```
os.chdir("../nodes")
``` |
Python: RuntimeError: super-class __init__() of %S was never called | 12,280,371 | 8 | 2012-09-05T11:24:38Z | 12,280,579 | 13 | 2012-09-05T11:37:25Z | [
"python",
"pyqt",
"runtime-error",
"superclass",
"deep-copy"
] | I tried to do some operation (`setParent`) on an object in Python (an instance of a class which inherits from a different class - to be specific, `QtGui.QLabel`), but during runtime the above error was raised. The object itself has had some fields with actual content (verified on debug), but from some reason I couldn't... | If you want to inherit `QObject` (or `QWidget`), you must always call the super-class `__init__`:
```
class MyObject(QObject):
def __init__(self, *args, **kwargs):
super(MyObject, self).__init__(arguments to parent class)
#other stuff here
```
You may also call the parent's class's `__init__` afte... |
PyQt Window Focus | 12,280,815 | 5 | 2012-09-05T11:51:58Z | 12,280,956 | 8 | 2012-09-05T12:00:03Z | [
"python",
"window",
"focus",
"pyqt",
"pyqt4"
] | I am trying to give focus to a window if the user clicks on another window.
Right now i have two windows: Window A is behind, and Window B is in front. When Window B appears, it disables Window A. Now what i want is that whenever the user clicks outside of Window B, it should give focus back to Window B.
Here is the ... | To get `window_b` to always stay on top you have to add the windowflag `QtCore.Qt.WindowStaysOnTopHint`. In your `__init__` add the call
```
self.setWindowFlags(PyQt4.QtCore.Qt.WindowStaysOnTopHint)
```
I have to add that this only is a hint to the windowing manager and not guaranteed to succeed. |
Python: Avoid short circuit evaluation | 12,281,469 | 15 | 2012-09-05T12:29:45Z | 12,281,524 | 21 | 2012-09-05T12:32:46Z | [
"python",
"logical-operators"
] | This is a problem that occured to me while working on a Django project. It's about form validation.
In Django, when you have a submitted form, you can call `is_valid()` on the corresponding form object to trigger the validation and return a Boolean value. So, usually you have code like that inside your view functions:... | How about something like:
```
if all([form1.is_valid(), form2.is_valid()]):
...
```
In a general case, a list-comprehension could be used so the results are calculated up front (as opposed to a generator expression which is commonly used in this context). e.g.:
```
if all([ form.is_valid() for form in (form1,form... |
Python: Avoid short circuit evaluation | 12,281,469 | 15 | 2012-09-05T12:29:45Z | 12,281,716 | 13 | 2012-09-05T12:43:30Z | [
"python",
"logical-operators"
] | This is a problem that occured to me while working on a Django project. It's about form validation.
In Django, when you have a submitted form, you can call `is_valid()` on the corresponding form object to trigger the validation and return a Boolean value. So, usually you have code like that inside your view functions:... | You can simply use the binary `&` operator, which will do a non-short-circuit logical *AND* on bools.
```
if form1.is_valid() & form2.is_valid():
...
``` |
Django foreign key relation in template | 12,281,965 | 3 | 2012-09-05T12:57:14Z | 12,282,211 | 14 | 2012-09-05T13:10:51Z | [
"python",
"django",
"django-models",
"django-templates",
"foreign-key-relationship"
] | i know you will say that this question is asked before many times but i havent solved it yet...
models.py
```
class Doc(UploadModel):
doc_no = models.CharField(max_length=100, verbose_name = "No", blank=True)
date_added = models.DateTimeField(verbose_name="Date", default=datetime.now,
editab... | If you review the [foreign key documentation](https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey), if you have a relationship like
```
Doc -> has many DocImages
```
you need to define your foreign key on the DocImages class like so:
```
class DocImage(models.Model):
property = models.ForeignKey(... |
Convert timestamps with offset to datetime obj using strptime | 12,281,975 | 19 | 2012-09-05T12:57:46Z | 12,282,040 | 25 | 2012-09-05T13:01:17Z | [
"python",
"datetime",
"timestamp",
"rfc3339"
] | I am trying to convert time-stamps of the format "2012-07-24T23:14:29-07:00"
to datetime objects in python using strptime method. The problem is with the time offset at the end(-07:00). Without the offset i can successfully do
```
time_str = "2012-07-24T23:14:29"
time_obj=datetime.datetime.strptime(time_str,'%Y-%m-%d... | The Python 2 `strptime()` function indeed does not the support `%z` format for timezones (because the underlying [`time.strptime()` function](http://docs.python.org/library/time.html#time.strptime) doesn't support it). You have two options:
* Ignore the timezone when parsing with `strptime`:
```
time_obj = dateti... |
How do I count unique values inside an array in Python? | 12,282,232 | 16 | 2012-09-05T13:11:47Z | 12,282,286 | 48 | 2012-09-05T13:14:32Z | [
"python",
"arrays",
"variables",
"loops",
"unique"
] | So I'm trying to make this program that will ask the user for input and store the values in an array / list. Then when a blank line is entered it will tell the user how many of those values are unique. I'm building this for real life reasons and not as a problem set.
```
enter: happy
enter: rofl
enter: happy
enter: mp... | You can use a [set](https://docs.python.org/2/library/sets.html) to remove duplicates, and then the [len](https://docs.python.org/2/library/functions.html#len) function to count the elements in the set:
```
len(set(new_words))
``` |
How do I count unique values inside an array in Python? | 12,282,232 | 16 | 2012-09-05T13:11:47Z | 12,282,304 | 10 | 2012-09-05T13:15:30Z | [
"python",
"arrays",
"variables",
"loops",
"unique"
] | So I'm trying to make this program that will ask the user for input and store the values in an array / list. Then when a blank line is entered it will tell the user how many of those values are unique. I'm building this for real life reasons and not as a problem set.
```
enter: happy
enter: rofl
enter: happy
enter: mp... | Use a [set](http://docs.python.org/library/stdtypes.html#set):
```
words = ['a', 'b', 'c', 'a']
unique_words = set(words) # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3
```
Armed with this, your solution could be as simple as:
```
words = []
ipta = raw_input("Word: ")
while ipta:... |
How do I count unique values inside an array in Python? | 12,282,232 | 16 | 2012-09-05T13:11:47Z | 12,288,109 | 40 | 2012-09-05T19:04:36Z | [
"python",
"arrays",
"variables",
"loops",
"unique"
] | So I'm trying to make this program that will ask the user for input and store the values in an array / list. Then when a blank line is entered it will tell the user how many of those values are unique. I'm building this for real life reasons and not as a problem set.
```
enter: happy
enter: rofl
enter: happy
enter: mp... | In addition, use [collections.Counter](http://docs.python.org/library/collections.html#collections.Counter) to refactor your code:
```
from collections import Counter
words = ['a', 'b', 'c', 'a']
Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency
``` |
Get primary key after inserting rows using sqlalchemy | 12,282,554 | 10 | 2012-09-05T13:26:48Z | 12,327,270 | 11 | 2012-09-08T01:17:44Z | [
"python",
"sqlalchemy"
] | I'm inseting many rows with sqlalchemy:
```
connection = engine.connect()
topic_res = connection.execute(message_topics.insert(),[
{
'mt_date': time.time(),
'mt_title': title,
'mt_hasattach':u'0',
'mt_starter_id':member.member_id,
'mt_start_time': time.time(),
'm... | the inserted\_primary\_key attribute is only functional for a single-row insert:
<http://docs.sqlalchemy.org/en/rel_0_7/core/connections.html?highlight=inserted_primary_key#sqlalchemy.engine.base.ResultProxy.inserted_primary_key>
> This only applies to single row insert() constructs which did not
> explicitly specify... |
How is Elastic Net used? | 12,283,184 | 16 | 2012-09-05T13:59:32Z | 12,294,769 | 15 | 2012-09-06T07:13:37Z | [
"python",
"statistics",
"machine-learning",
"regression",
"scikit-learn"
] | This is a beginner question on regularization with regression. Most information about Elastic Net and Lasso Regression online replicates the information from Wikipedia or the original 2005 paper by Zou and Hastie (Regularization and variable selection via the elastic net).
***Resource for simple theory?*** Is there a ... | The documentation is lacking. I created a new [issue](https://github.com/scikit-learn/scikit-learn/issues/1118) to improve it. As Andreas said the best resource is probably [ESL II](http://www-stat.stanford.edu/~tibs/ElemStatLearn/) freely available online as PDF.
To automatically tune the value of alpha it is indeed ... |
Are Python error numbers associated with IOError stable? | 12,283,377 | 4 | 2012-09-05T14:08:54Z | 12,283,450 | 7 | 2012-09-05T14:11:58Z | [
"python",
"api",
"exception",
"error-handling",
"errno"
] | I want to move a file, but in the case it is not found I should just ignore it. In all other cases the exception should be propagated. I have the following piece of Python code:
```
try:
shutil.move(old_path, new_path)
except IOError as e:
if e.errno != 2: raise e
```
errno == 2 is the one, that has 'No such ... | It is better to use values from the [errno](http://docs.python.org/library/errno.html#module-errno) module instead of hardcoding the value `2`:
```
try:
shutil.move(old_path, new_path)
except IOError as e:
if e.errno != errno.ENOENT: raise e
```
This makes your code less likely to break in case the integer er... |
Python __closure__ variables and cells | 12,284,254 | 4 | 2012-09-05T14:56:12Z | 12,284,300 | 8 | 2012-09-05T14:58:08Z | [
"python",
"python-3.x"
] | While exploring some solutions [to my previous question](http://stackoverflow.com/questions/12265756/c-python-running-python-code-within-a-context) about the inner workings of Python scope, I learned about the `__closure__` attribute. It seems that Python uses this attribute to access variables defined in an outer scop... | The python compiled code uses indices; the variables are tied to an index into the cells structure.
```
>>> def foo():
... x = 5
... def bar():
... return x
... return bar
...
>>> bar = foo()
>>> import dis
>>> dis.dis(bar)
4 0 LOAD_DEREF 0 (x)
3 RETURN_VAL... |
python tkinter: how to work with pixels? | 12,284,311 | 14 | 2012-09-05T14:58:55Z | 12,287,117 | 26 | 2012-09-05T17:54:41Z | [
"python",
"image",
"tkinter",
"pixel"
] | using google (and this site) i have seen some similar questions but my problem is still here:
"i want to draw an image (without reading a file) , being able to manipulate every single pixel's colour in that image."
i have seen another question where was suggested to do something like this:
```
from tkinter import *
... | It is indeed tricky --
I thought you had to use a Canvas widget, but that has no access to Pixels either.
Image items embedded in the Canvas do have, though. The Tkinter.PhotoImage class
does have a "put" method that accepts a color in html/css syntax and pixel coordinates:
```
from Tkinter import Tk, Canvas, PhotoIma... |
How to add an attribute that contains a hyphen to a WTForms field | 12,284,732 | 9 | 2012-09-05T15:22:11Z | 12,285,739 | 17 | 2012-09-05T16:20:33Z | [
"python",
"wtforms"
] | Calling a WTForms field object produces the rendered field, and any arguments are taken as attributes, for instance.
```
form.field(attribute='value')
```
would return something like
```
<input attribute='value'>
```
How can I add HTML5 custom data attributes such as data-provide which contain hyphens, making them ... | Create a dictionary with the corresponding key-value pairs and use \*\* to pass it to the field call:
```
attrs = {'data-provide': "foo"}
form.field(**attrs)
```
*Edit*: Looks like the comment by @NiklasB should be part of the answer:
For those using [flask](http://flask.pocoo.org/) with [flask-WTF](https://flask-wtf... |
Flask - How to create custom abort() code? | 12,285,903 | 14 | 2012-09-05T16:31:05Z | 12,286,035 | 17 | 2012-09-05T16:40:31Z | [
"python",
"flask",
"abort"
] | Flask has a good error handler by using `abort()` or when the error truly occurred.
From Flask documentation there is an example for error 404 handler:
```
@app.errorhandler(404)
def not_found(error):
return render_template('404.html'), 404
```
So, I tried to create custom error code like
```
if False:
abor... | The list of possible HTTP status codes is fixed by the Internet Assigned Numbers Authority, so you cannot add a custom one. Werkzeug recognizes this and tries to stop you sending a meaningless code to the browser. Look through the [list of status codes](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes) to find on... |
Flask - How to create custom abort() code? | 12,285,903 | 14 | 2012-09-05T16:31:05Z | 19,904,227 | 7 | 2013-11-11T10:37:48Z | [
"python",
"flask",
"abort"
] | Flask has a good error handler by using `abort()` or when the error truly occurred.
From Flask documentation there is an example for error 404 handler:
```
@app.errorhandler(404)
def not_found(error):
return render_template('404.html'), 404
```
So, I tried to create custom error code like
```
if False:
abor... | Depending on the reading of the question this might come in handy.
There is an easier way to add customer error page handling for a specific exception, you can do this:
```
class MyCustom404(Exception):
pass
@app.errorhandler(404)
def page_not_found(error):
return render_template("errors/404.html"), 404
@ap... |
python Making heatmap from DataFrame | 12,286,607 | 31 | 2012-09-05T17:18:21Z | 12,286,958 | 22 | 2012-09-05T17:42:37Z | [
"python",
"pandas",
"heatmap"
] | I have a dataframe generated from Python's Pandas package. How can I generate heatmap using DataFrame from pandas package.
```
import numpy as np
from pandas import *
Index= ['aaa','bbb','ccc','ddd','eee']
Cols = ['A', 'B', 'C','D']
df = DataFrame(abs(np.random.randn(5, 4)), index= Index, columns=Cols)
>>> df
... | You want `matplotlib.pcolor`:
```
import numpy as np
from pandas import DataFrame
import matplotlib.pyplot as plt
Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)
plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), d... |
python Making heatmap from DataFrame | 12,286,607 | 31 | 2012-09-05T17:18:21Z | 29,528,483 | 36 | 2015-04-09T02:00:13Z | [
"python",
"pandas",
"heatmap"
] | I have a dataframe generated from Python's Pandas package. How can I generate heatmap using DataFrame from pandas package.
```
import numpy as np
from pandas import *
Index= ['aaa','bbb','ccc','ddd','eee']
Cols = ['A', 'B', 'C','D']
df = DataFrame(abs(np.random.randn(5, 4)), index= Index, columns=Cols)
>>> df
... | For people looking at this today, I would recommend the Seaborn `heatmap()` function: <http://stanford.edu/~mwaskom/software/seaborn-dev/generated/seaborn.heatmap.html>
The example above would be done as follows:
```
import numpy as np
from pandas import DataFrame
import seaborn as sns
%matplotlib
Index= ['aaa', 'b... |
How to import custom jinja2 filters from another file (and using Flask)? | 12,288,454 | 14 | 2012-09-05T19:30:05Z | 12,289,648 | 23 | 2012-09-05T20:57:19Z | [
"python",
"flask",
"jinja2"
] | I have a jinja\_filters.py file with a few dozen custom filters I've written. Now I have multiple Flask apps that need to use these filters. (I'm not sure if my problem is Flask-specific or not.)
One hacky way to accomplish what I want is to do:
```
app = Flask(__name__)
import jinja_filters
@app.template_filter('f... | Where ever you're setting up your app object (app.py, perhaps), you only need to import your custom filters and then modify the Jinja environment attribute.
```
import jinja_filters
app = Flask(__name__)
app.jinja_env.filters['filter_name1'] = jinja_filters.filter_name1
app.jinja_env.filters['filter_name2'] = jinja_f... |
How to import custom jinja2 filters from another file (and using Flask)? | 12,288,454 | 14 | 2012-09-05T19:30:05Z | 24,435,908 | 21 | 2014-06-26T16:38:37Z | [
"python",
"flask",
"jinja2"
] | I have a jinja\_filters.py file with a few dozen custom filters I've written. Now I have multiple Flask apps that need to use these filters. (I'm not sure if my problem is Flask-specific or not.)
One hacky way to accomplish what I want is to do:
```
app = Flask(__name__)
import jinja_filters
@app.template_filter('f... | There is a recommended way of doing this using [Flask blueprints](http://flask.pocoo.org/docs/blueprints/). One of it's use cases is this functionality specifically:
> * Provide template filters, static files, templates, and other utilities through blueprints. A blueprint does not have to implement applications or vie... |
pypy memory usage grows forever? | 12,288,640 | 14 | 2012-09-05T19:43:51Z | 12,670,152 | 8 | 2012-10-01T08:54:55Z | [
"python",
"memory",
"memory-leaks",
"pypy"
] | I have a complicated python server app, that runs constantly all the time. Below is a very simplified version of it.
When I run the below app using python; "python Main.py". It uses 8mb of ram straight away, and stays at 8mb of ram, as it should.
When I run it using pypy "pypy Main.py". It begins by using 22mb of ram... | <http://doc.pypy.org/en/latest/gc_info.html#minimark-environment-variables> shows how to tweak the gc |
OpenCV 2.4 in python - Video processing | 12,290,023 | 8 | 2012-09-05T21:25:47Z | 12,333,066 | 17 | 2012-09-08T17:45:27Z | [
"python",
"opencv",
"video-processing"
] | The Project: Add a running date/time stamp on each and every frame of a video. (The result of digital video camera, and my father asked me how can he add the timestamp(to the milliseconds resolution) permanently to the video.
A friend pointed me to opencv (emgucv actually) , and because of my preferences I tried my lu... | Your task should be relatively easy to accomplish using OpenCV and Python. It seems that you are new to OpenCV, so I will try and keep my explanation thorough, but feel free to ask if you need any clarity.
I am not sure if you are getting your data from a live camera video feed, or are post-processing recorded footage... |
how to initialize time() object in python | 12,291,209 | 9 | 2012-09-05T23:42:24Z | 12,291,225 | 18 | 2012-09-05T23:44:48Z | [
"python",
"date",
"datetime",
"time",
"strptime"
] | I am trying to initialize a time object like this:
```
t = datetime.time(0,0,0)
```
but I am getting this error:
```
descriptor 'time' requires a 'datetime.datetime' object but received a 'int'
```
I have these things imported
```
import datetime
from datetime import datetime, date, time
import time
```
They seem... | You can create the object without any values:
```
>>> import datetime
>>> datetime.time()
datetime.time(0, 0)
```
You, however, imported the *class* datetime from the module, replacing the module itself:
```
>>> from datetime import datetime
>>> datetime.time
<method 'time' of 'datetime.datetime' objects>
```
and t... |
Python PIL ValueError: images do not match | 12,291,641 | 7 | 2012-09-06T00:56:02Z | 14,526,661 | 15 | 2013-01-25T16:59:13Z | [
"python",
"python-imaging-library"
] | I'm playing around with PIL and came across this problem and I can't see where in the docs I'm going wrong. Here is my simple code
```
from PIL import Image
from PIL.ImageChops import difference
imageA = Image.open("image1.png")
imageB = Image.open("image2.png")
if imageA.size == imageB.size:
diff = difference(i... | The documentation for this function doesn't tell much in fact. So let me try to clarify it a little. First, the sizes of the images are irrelevant to whether the function works or not, it internally checks for a size that both images fit.
Now, when can you actually compare the images by using the function `ImageChops.... |
Why is Python's Decimal function defaulting to 54 places? | 12,291,825 | 6 | 2012-09-06T01:30:48Z | 12,291,957 | 12 | 2012-09-06T01:53:24Z | [
"python",
"decimal"
] | After inputting
```
from decimal import *
getcontext().prec = 6
Decimal (1) / Decimal (7)
```
I get the value
```
Decimal('0.142857')
```
However if I enter `Decimal (1.0/7)` I get
```
Decimal('0.142857142857142849212692681248881854116916656494140625')
``` | The 1.0 / 7 computes a binary floating point number to 17 digits of precision. This happens *before* the *Decimal* constructor sees it:
```
>>> d = 1.0 / 7
>>> type(d)
<type 'float'>
>>> d.as_integer_ratio()
(2573485501354569, 18014398509481984)
```
The binary fraction, 2573485501354569 / 18014398509481984 is as clos... |
Django queryset and generator | 12,292,343 | 3 | 2012-09-06T02:53:18Z | 12,292,381 | 10 | 2012-09-06T02:59:14Z | [
"python",
"django",
"iteration",
"generator"
] | Just out of the blue I wonder if the following way of iterating through a result set using generator will cause any positive or negative impact against normal iteration?
eg.
```
def all_items_generator():
for item in Item.objects.all():
yield item
for item in all_items_generator():
do_stuff_with_item(item)
`... | The former will be slower, since it will create a list containing all the models and then yield them one at a time, whereas the latter will just use the list directly. If you want a generator then you should use [`QuerySet.iterator()`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#iterator) instead. |
how to create a list of lists | 12,293,208 | 2 | 2012-09-06T04:59:15Z | 12,293,243 | 8 | 2012-09-06T05:03:08Z | [
"python",
"list"
] | My Python code generates a list everytime it loops:
```
list = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
```
But I want to save each one - I need a list of lists right?
So I tried:
```
list[i] = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=... | You want to create an empty list, then append the created list to it. This will give you the list of lists. Example:
```
>>> l = []
>>> l.append([1,2,3])
>>> l.append([4,5,6])
>>> l
[[1, 2, 3], [4, 5, 6]]
``` |
How do I return a JSON array with Bottle? | 12,293,979 | 18 | 2012-09-06T06:13:40Z | 12,294,213 | 48 | 2012-09-06T06:33:10Z | [
"python",
"bottle"
] | I'm writing an API using [Bottle](http://bottlepy.org), which so far has been fantastic. However, I've run up against a small hurdle when trying to return a JSON array. Here's my test app code:
```
from bottle import route, run
@route('/single')
def returnsingle():
return { "id": 1, "name": "Test Item 1" }
@rout... | Bottle's JSON plugin expects only dicts to be returned - not arrays. There are vulnerabilities associated with returning JSON arrays - see for example [this post about JSON hijacking](http://haacked.com/archive/2009/06/25/json-hijacking.aspx/).
If you really need to do this, it can be done, e.g.
```
@route('/array')
... |
Use of lambda in the following expression | 12,294,234 | 5 | 2012-09-06T06:34:23Z | 12,294,271 | 13 | 2012-09-06T06:37:33Z | [
"python",
"lambda",
"openerp"
] | While going developing OpenERP, I found the following piece of code
`'app_date': lambda *a: time.strftime('%Y-%m-%d')`
I know what lambda is.My question is why use lambda?Why not just
`'app_date': time.strftime('%Y-%m-%d')` | `'app_date': time.strftime('%Y-%m-%d')` will evaluate the `time.strftime` immediately. By wrapping it in a lambda, its execution is deferred until later (the time when you call the lambda). Roughly speaking, the difference is between "the time when I defined this" and "the time when I am using this". Look:
```
>>> d =... |
Pyramid traversal is doing my head in | 12,295,699 | 4 | 2012-09-06T08:12:10Z | 12,296,172 | 7 | 2012-09-06T08:40:44Z | [
"python",
"pyramid",
"traversal"
] | I am trying to get my head around Pyramid traversal with this very simple example. What I haven't quite grasped yet is where to "inject" an `Article` object from the db.
As it is, `/Article` correctly finds and renders the `article_view` but that's fairly useless. How/when/where do I use the next part of the URL to qu... | You'd generally return a `Article` object from the *id* part of the URL traversal.
What happens with traversal is that for each element in the URL path, an object is looked up and made the new current object for the *next* path element lookup.
So for `Article`, the root object is asked for something matching that nam... |
Convert array to python scalar | 12,296,021 | 2 | 2012-09-06T08:31:14Z | 12,296,133 | 13 | 2012-09-06T08:38:42Z | [
"python"
] | I need big help, please check out this code:
```
import.math
dose =20.0
a = [[[2,3,4],[5,8,9],[12,56,32]]
[[25,36,45][21,65,987][21,58,89]]
[[78,21,98],[54,36,78],[23,12,36]]]
PAC = math.exp(-dose*a)
```
this what I would like to do. However the error I am getting is
```
TypeError: only length-1 arrays ca... | If you want to perform mathematical operations on arrays (whatever their dimensions...), you should really consider using [NumPy](http://numpy.scipy.org/) which is designed just for that. In your case, the corresponding NumPy command would be:
```
PAC = numpy.exp(-dose*np.array(a))
```
If NumPy is not an option, you'... |
Python Parse CSV Correctly | 12,296,585 | 10 | 2012-09-06T09:04:41Z | 12,296,863 | 12 | 2012-09-06T09:21:51Z | [
"python",
"parsing",
"csv"
] | I am very new to Python. I want to parse a csv file such that it will recognize quoted values - for example
> 1997,Ford,E350,"Super, luxurious truck"
should be split as
> ('1997', 'Ford', 'E350', 'Super, luxurious truck')
and NOT
> ('1997', 'Ford', 'E350', '"Super', ' luxurious truck"')
the above is what I get if... | You should use the `csv` module:
```
import csv
reader = csv.reader(['1997,Ford,E350,"Super, luxurious truck"'], skipinitialspace=True)
for r in reader:
print r
```
output:
```
['1997', 'Ford', 'E350', 'Super, luxurious truck']
``` |
Python Parse CSV Correctly | 12,296,585 | 10 | 2012-09-06T09:04:41Z | 12,356,046 | 8 | 2012-09-10T16:45:11Z | [
"python",
"parsing",
"csv"
] | I am very new to Python. I want to parse a csv file such that it will recognize quoted values - for example
> 1997,Ford,E350,"Super, luxurious truck"
should be split as
> ('1997', 'Ford', 'E350', 'Super, luxurious truck')
and NOT
> ('1997', 'Ford', 'E350', '"Super', ' luxurious truck"')
the above is what I get if... | The following method worked perfectly
```
d = {}
d['column1name'] = []
d['column2name'] = []
d['column3name'] = []
dictReader = csv.DictReader(open('filename.csv', 'rb'), fieldnames = ['column1name', 'column2name', 'column3name'], delimiter = ',', quotechar = '"')
for row in dictReader:
for key in row:
d... |
How to find most frequent values in numpy ndarray? | 12,297,016 | 9 | 2012-09-06T09:30:27Z | 12,300,214 | 8 | 2012-09-06T12:32:40Z | [
"python",
"numpy",
"multidimensional-array"
] | I have a numpy ndarray with shape of (30,480,640), the 1th and 2th axis representing locations(latitude and longitute), the 0th axis contains actual data points.I want to use the most frequent value along the 0th axis at each location, which is to construct a new array with shape of (1,480,640).ie:
```
>>> data
array(... | To find the most frequent value of a flat array, use `unique`, `bincount` and `argmax`:
```
arr = np.array([5, 4, -2, 1, -2, 0, 4, 4, -6, -1])
u, indices = np.unique(arr, return_inverse=True)
u[np.argmax(np.bincount(indices))]
```
To work with a multidimensional array, we don't need to worry about `unique`, but we do... |
Can I use SQLAlchemy with Cassandra CQL? | 12,297,847 | 5 | 2012-09-06T10:17:06Z | 12,297,899 | 11 | 2012-09-06T10:20:29Z | [
"python",
"sqlalchemy",
"cassandra"
] | I use Python with SQLAlchemy for some relational tables. For the storage of some larger data-structures I use Cassandra. I'd prefer to use just one technology (cassandra) instead of two (cassandra and PostgreSQL). Is it possible to store the relational data in cassandra as well? | No, Cassandra is a [NoSQL](https://en.wikipedia.org/wiki/NoSQL_%28concept%29) storage system, and doesn't support fundamental SQL semantics like joins, let alone SQL queries. SQLAlchemy works exclusively with SQL statements. CQL is only SQL-like, not actual SQL itself.
To quote from [the Cassandra CQL documentation](h... |
Unexpected behavior in PHP - Same code gives correct results in C# and Python | 12,297,872 | 16 | 2012-09-06T10:18:36Z | 12,297,969 | 13 | 2012-09-06T10:25:22Z | [
"c#",
"php",
"python",
"math"
] | Why does PHP return INF (infinity) for the following piece of code:
```
<?php
$n = 1234;
$m = 0;
while ($n > 0)
{
$m = ($m * 10) + ($n % 10);
$n = $n / 10;
}
var_dump($m);
?>
```
The expected result was **4321**, but PHP returned **INF**, float type:
```
float INF
```
I wrote the same code in Python and C... | In php `$n / 10` will return a float number, not integer.
So `$n > 0` will always be `true`.
Change `while($n > 0)`
to `while($n > 1)` or `while((int)$n > 0)`, then you will get the right result. |
how to use numpy vstack | 12,299,124 | 7 | 2012-09-06T11:31:45Z | 12,299,378 | 19 | 2012-09-06T11:45:36Z | [
"python",
"numpy"
] | I've spent ages on this (simple) Python code, and thanks to this forum I'm nearly there. I really hope someone can set me straight to get it 100% working!
Firstly, here is the relevant part of the code:
```
stokes_list = np.zeros(shape=(numrows,1024)) # 'numrows' defined earlier
for i in range(numrows):
epoch_nam... | `vstack`ing again and again is not good, because it copies the whole arrays.
Create a normal Python `list`, `.append` to it and then pass it whole to `np.vstack` to create a new array once.
```
stokes_list = []
for i in xrange(numrows):
...
stokes_line = ...
stokes_list.append(stokes_line)
big_stokes = n... |
how to use numpy vstack | 12,299,124 | 7 | 2012-09-06T11:31:45Z | 12,299,421 | 8 | 2012-09-06T11:47:59Z | [
"python",
"numpy"
] | I've spent ages on this (simple) Python code, and thanks to this forum I'm nearly there. I really hope someone can set me straight to get it 100% working!
Firstly, here is the relevant part of the code:
```
stokes_list = np.zeros(shape=(numrows,1024)) # 'numrows' defined earlier
for i in range(numrows):
epoch_nam... | You already now the final size of the `stokes_list` array since you know `numrows`. So it seems you don't need to grow an array (which is very inefficient). You can simply assign the correct row at each iteration.
Simply replace your last line by :
```
stokes_list[i] = stokes_line
```
By the way, about your non-worki... |
Plane fitting to 4 (or more) XYZ points | 12,299,540 | 2 | 2012-09-06T11:54:42Z | 12,301,583 | 7 | 2012-09-06T13:48:23Z | [
"python",
"geometry",
"least-squares",
"plane"
] | I have 4 points, which are very near to be at the one plane - it is the 1,4-Dihydropyridine cycle.
I need to calculate distance from C3 and N1 to the plane, which is made of C1-C2-C4-C5.
Calculating distance is OK, but fitting plane is quite difficult to me.
1,4-DHP cycle <http://i.stack.imgur.com/dhNDo.png>
1,4-DHP... | The fact that you are fitting to a plane is only slightly relevant here. What you are trying to do is minimize a *particular* function starting from a guess. For that use `scipy.optimize`. Note that there is no guarantee that this is the **globally optimal** solution, only **locally optimal**. A different initial condi... |
Format syntax in Python | 12,301,043 | 3 | 2012-09-06T13:19:14Z | 12,301,059 | 14 | 2012-09-06T13:20:04Z | [
"python",
"syntax",
"format"
] | Is there a way to write this line of code in a better way :
```
"""{a};{b};{c};{d}""".format(a = myDictionary[a], b = myDictionary[b], c = myDictionary[c], d = myDictionary[d])
```
something like this ?
```
"""{a};{b};{c};{d}""".format(myDictionary)
``` | Use [keyword expansion](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists) on the dictionary:
```
"{a};{b};{c};{d}".format(**myDictionary)
``` |
multidimensional confidence intervals | 12,301,071 | 16 | 2012-09-06T13:20:39Z | 12,321,306 | 28 | 2012-09-07T15:39:26Z | [
"python",
"matplotlib",
"scipy"
] | I have numerous tuples (par1,par2), i.e. points in a 2 dimensional parameter space obtained from repeating an experiment multiple times.
I'm looking for a possibility to calculate and visualize confidence ellipses (not sure if thats the correct term for this). Here an example plot that I found in the web to show what ... | It sounds like you just want the 2-sigma ellipse of the scatter of points?
If so, consider something like this (From some code for a paper here: <https://github.com/joferkington/oost_paper_code/blob/master/error_ellipse.py>):
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellip... |
The Requests streaming example does not work in my environment | 12,301,630 | 4 | 2012-09-06T13:50:57Z | 12,302,077 | 8 | 2012-09-06T14:11:32Z | [
"python",
"python-requests",
"twitter-streaming-api"
] | I've been trying to consume the Twitter Streaming API using Python Requests.
There's a [simple example](http://docs.python-requests.org/en/latest/user/advanced/#streaming-requests) in the documentation:
```
import requests
import json
r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
data={'... | You need to switch off prefetching, which I think is a parameter that changed defaults:
```
r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
data={'track': 'requests'}, auth=('username', 'password'),
prefetch=False)
for line in r.iter_lines():
if line: # filter out keep-alive new lin... |
How to use scikit-learn's SVM with histograms as features? | 12,301,640 | 4 | 2012-09-06T13:51:23Z | 12,315,034 | 8 | 2012-09-07T09:07:02Z | [
"python",
"machine-learning",
"svm",
"scikit-learn"
] | I wish to use scikit-learn's SVM with a chi-squared kernel, as shown [here](http://scikit-learn.org/0.11/modules/kernel_approximation.html#additive-chi-squared-kernel). In this scenario, the kernel is on histograms, which is what my data is represented as. However, I can't find an example of these used with histograms.... | There is an example of using an approximate feature map [here](http://scikit-learn.org/dev/auto_examples/plot_kernel_approximation.html#example-plot-kernel-approximation-py). It is for the RBF kernel but it works just the same.
The example above uses "pipeline" but you can also just apply the transform to your data be... |
urllib2 returns 404 for a website which displays fine in browsers | 12,302,304 | 7 | 2012-09-06T14:25:26Z | 12,302,584 | 7 | 2012-09-06T14:42:07Z | [
"python",
"html",
"url",
"urllib2"
] | I am not able to open one particular url using urllib2. Same approach works well with other websites such as "http://www.google.com" but not this site (which also displays fine in the browser).
my simple code:
```
from BeautifulSoup import BeautifulSoup
import urllib2
url="http://www.experts.scival.com/einstein/"
re... | I just tried this and received 404 code and page back.
At a guess it's doing User-Agent detection which either by accident or on purpose doesn't serve content to python urllib.
Clarification, with `urllib`, I received the `urlopen` returned a response object with a 404 code and HTML content. With `urllib2.urlopen` an... |
python plot simple histogram given binned data | 12,303,501 | 18 | 2012-09-06T15:31:24Z | 12,304,016 | 12 | 2012-09-06T16:01:16Z | [
"python",
"plot",
"matplotlib",
"histogram"
] | I have count data (a 100 of them), each correspond to a bin (0 to 99). I need to plot these data as histogram. However, histogram count those data and does not plot correctly because my data is already binned.
```
import random
import matplotlib.pyplot as plt
x = random.sample(range(1000), 100)
xbins = [0, len(x)]
#pl... | The problem is with your xbins. You currently have
```
xbins = [0, len(x)]
```
which will give you the list [0, 100]. This means you will only see 1 bin (not 2) bounded below by 0 and above by 100. I am not totally sure what you want from your histogram. If you want to have 2 unevenly spaced bins, you can use
```
xb... |
python plot simple histogram given binned data | 12,303,501 | 18 | 2012-09-06T15:31:24Z | 12,304,071 | 22 | 2012-09-06T16:05:14Z | [
"python",
"plot",
"matplotlib",
"histogram"
] | I have count data (a 100 of them), each correspond to a bin (0 to 99). I need to plot these data as histogram. However, histogram count those data and does not plot correctly because my data is already binned.
```
import random
import matplotlib.pyplot as plt
x = random.sample(range(1000), 100)
xbins = [0, len(x)]
#pl... | If I'm understanding what you want to achieve correctly then the following should give you what you want:
```
import matplotlib.pyplot as plt
plt.bar(range(0,100), x)
plt.show()
```
It doesn't use `hist()`, but it looks like you've already put your data into bins so there's no need. |
Set the default to false if another mutually exclusive argument is true | 12,303,547 | 7 | 2012-09-06T15:33:43Z | 12,303,962 | 16 | 2012-09-06T15:58:35Z | [
"python",
"arguments",
"command-line-arguments",
"argparse"
] | I realise this is a lot like [Setting default option in Python of two mutually exclusive options using the argparse module](http://stackoverflow.com/questions/9365486/setting-default-option-in-python-of-two-mutually-exclusive-options-using-the-arg) although from a different perspective (and the answers given there don'... | It occurs to me that perhaps `'store_const'` would be a more appropriate action (with all arguments pointing to the same destination).
```
import argparse
parser = argparse.ArgumentParser()
mutex_group = parser.add_mutually_exclusive_group()
mutex_group.add_argument("--show", action="store_const",
dest="mutex", c... |
Django Tutorial: Generic Views. Attribute Error | 12,304,050 | 15 | 2012-09-06T16:03:21Z | 12,902,706 | 40 | 2012-10-15T19:32:19Z | [
"python",
"django",
"django-generic-views"
] | I'm at the last part of [this](https://docs.djangoproject.com/en/1.4/intro/tutorial04/) tutorial.
```
from django.conf.urls import patterns, include, url
from django.views.generic import DetailView, ListView
from polls.models import Poll
urlpatterns = patterns('',
url(r'^$',
ListView.as_view(
... | I think the code you posted above, is not the one you have on your disk.
I had the same problem, but then I looked carefully at both, my code and the tutorial. The regex I had in my code was different from the tutorial.
This was my code:
```
url(r'^(?P<poll_id>\d+)/$',-$ ... |
How does one set the default property access on a class? | 12,304,284 | 3 | 2012-09-06T16:19:00Z | 12,304,314 | 10 | 2012-09-06T16:20:39Z | [
"python"
] | Python (2.7) newbie here. What I want to do is have a reference to an instance of a class return a given property as the 'default' without having to specify that property. I want to do this because the vast majority of the time I refer to an instance, it is to access this one property.
For example, let's say I have a ... | A [`__getitem__`](http://docs.python.org/reference/datamodel.html#object.__getitem__) override on `book` will give you this:
```
def __getitem__(self, item):
return self.page[item].text
``` |
Efficient way to normalize a Scipy Sparse Matrix | 12,305,021 | 15 | 2012-09-06T17:06:03Z | 12,396,922 | 20 | 2012-09-12T22:20:02Z | [
"python",
"numpy",
"scipy",
"sparse-matrix"
] | I'd like to write a function that normalizes the rows of a large sparse matrix (such that they sum to one).
```
from pylab import *
import scipy.sparse as sp
def normalize(W):
z = W.sum(0)
z[z < 1e-6] = 1e-6
return W / z[None,:]
w = (rand(10,10)<0.1)*rand(10,10)
w = sp.csr_matrix(w)
w = normalize(w)
```
... | This has been implemented in [scikit-learn sklearn.preprocessing.normalize](http://scikit-learn.org/dev/modules/generated/sklearn.preprocessing.normalize.html#sklearn.preprocessing.normalize).
```
from sklearn.preprocessing import normalize
w_normalized = normalize(w, norm='l1', axis=1)
```
`axis=1` should normalize ... |
Modifying a subset of rows in a pandas dataframe | 12,307,099 | 53 | 2012-09-06T19:32:25Z | 12,307,162 | 98 | 2012-09-06T19:37:18Z | [
"python",
"pandas"
] | Assume I have a pandas DataFrame with two columns, A and B. I'd like to modify this DataFrame (or create a copy) so that B is always NaN whenever A is 0. How would I achieve that?
I tried the following
```
df['A'==0]['B'] = np.nan
```
and
```
df['A'==0]['B'].values.fill(np.nan)
```
without success. | Try this:
```
df.ix[df.A==0, 'B'] = np.nan
```
the `df.A==0` expression creates a boolean series that indexes the rows, `'B'` selects the column. You can also use this to transform a subset of a column, e.g.:
```
df.ix[df.A==0, 'B'] = df.ix[df.A==0, 'B'] / 2
``` |
Modifying a subset of rows in a pandas dataframe | 12,307,099 | 53 | 2012-09-06T19:32:25Z | 12,607,018 | 38 | 2012-09-26T17:14:39Z | [
"python",
"pandas"
] | Assume I have a pandas DataFrame with two columns, A and B. I'd like to modify this DataFrame (or create a copy) so that B is always NaN whenever A is 0. How would I achieve that?
I tried the following
```
df['A'==0]['B'] = np.nan
```
and
```
df['A'==0]['B'].values.fill(np.nan)
```
without success. | [Here](http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-advanced) is from pandas docs on advanced indexing:
The section after 'Assignment / setting values is possible when using ix:' will explain exactly what you need! Turns out `df.ix` can be used for cool slicing/dicing of a dataframe. And. It can ... |
How do I write JSON data to a file in Python? | 12,309,269 | 287 | 2012-09-06T22:21:21Z | 12,309,296 | 587 | 2012-09-06T22:23:14Z | [
"python",
"json"
] | I have JSON data stored in the variable `data`.
I want to write this to a text file for testing so I don't have to grab the data from the server each time.
Currently, I am trying this:
```
obj = open('data.txt', 'wb')
obj.write(data)
obj.close
```
And am receiving the error:
```
TypeError: must be string or buffer... | You forgot the actual JSON part - `data` is a dictionary and not yet JSON-encoded. Write it like this:
```
import json
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
```
Note: Works on both 3.x and 2.x . |
How do I write JSON data to a file in Python? | 12,309,269 | 287 | 2012-09-06T22:21:21Z | 14,870,531 | 97 | 2013-02-14T08:22:36Z | [
"python",
"json"
] | I have JSON data stored in the variable `data`.
I want to write this to a text file for testing so I don't have to grab the data from the server each time.
Currently, I am trying this:
```
obj = open('data.txt', 'wb')
obj.write(data)
obj.close
```
And am receiving the error:
```
TypeError: must be string or buffer... | To get `utf8`-encoded file (for smaller size) in Python 2.x:
```
import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
f.write(unicode(json.dumps(data, ensure_ascii=False)))
```
For example for `data = {u'абвгд': 1}` I get 17 bytes for `utf8` vs 26 for `ascii` version.
The code is simpler in P... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.