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
Test if numpy array contains only zeros
18,395,725
24
2013-08-23T05:55:33Z
18,402,696
19
2013-08-23T12:19:45Z
[ "python", "numpy" ]
We initialize a numpy array with zeros as bellow: ``` np.zeros((N,N+1)) ``` But how do we check whether all elements in a given n\*n numpy array matrix is zero. The method just need to return a True if all the values are indeed zero.
I'd use np.all here, if you have an array a: ``` >>> np.all(a==0) ```
Test if numpy array contains only zeros
18,395,725
24
2013-08-23T05:55:33Z
23,567,941
38
2014-05-09T15:03:51Z
[ "python", "numpy" ]
We initialize a numpy array with zeros as bellow: ``` np.zeros((N,N+1)) ``` But how do we check whether all elements in a given n\*n numpy array matrix is zero. The method just need to return a True if all the values are indeed zero.
The other answers posted here will work, but the clearest and most efficient function to use is `numpy.any()`: ``` >>> all_zeros = not numpy.any() ``` * This is preferred over `numpy.all(a==0)` because it uses less RAM. (It does not require the temporary array created by the `a==0` term.) * Also, it is faster than `n...
Whats the difference between using {{STATIC_URL}} and {% static %}
18,400,315
18
2013-08-23T10:17:01Z
18,400,426
35
2013-08-23T10:22:30Z
[ "python", "django" ]
Throughout the django documentation and a lot of tutorials people seem to pick freely between using the `{% static %}` tag, and using `{{ STATIC_URL }}` with the correct context processor. Can someone explain what the difference between them is, and any advantages there might be to using on over the other.
# Abstract The `{% static %}` template tag is [aware of your `STATICFILES_STORAGE`](https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#static), using the `STATIC_URL` setting is not. # Rule of thumb Use the template tag. Manually concatenating is bad practice ("do I need a slash?"), and will eventually ...
How to close a mongodb python connection?
18,401,015
10
2013-08-23T10:50:53Z
18,401,169
21
2013-08-23T10:58:16Z
[ "python", "mongodb", "connection", "pymongo" ]
I'm doing a python script that writes some data to a mongodb. I need to close the connection and free some resources, when finishing. How is that done in Python?
Use [`close()`](http://api.mongodb.org/python/current/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient.close) method on your `MongoClient` instance: ``` client = pymongo.MongoClient() # some code here client.close() ``` `close()` is an alias for [`disconnect()`](http://api.mongodb.org/python/current/a...
Matplotlib colorbar background and label placement
18,403,226
5
2013-08-23T12:44:04Z
18,418,089
11
2013-08-24T11:30:02Z
[ "python", "matplotlib", "colorbar" ]
Up until recently I have been using Mathematica for my plots. Although it was a real pain and everything had to be done manually, the results where very close to what I wanted. One example is the following: ![Mathematica example plot](http://i.imgur.com/HORJBfv.jpg) I really like the grey rounded rectangle in the bac...
To your second question: you can use a negative `labelpad` value to move the label back towards the ticklabels, like this: ``` import numpy as np import matplotlib.pyplot as plt data = np.linspace(0, 10, num=256).reshape(16,16) cf = plt.contourf(data, levels=(0, 2.5, 5, 7.5, 10)) cb = plt.colorbar(cf) cb.set_tickl...
concatenating arrays in python like matlab without knowing the size of the output array
18,404,077
6
2013-08-23T13:28:06Z
18,404,198
7
2013-08-23T13:33:36Z
[ "python", "arrays", "matlab", "numpy", "concatenation" ]
I am trying to concatenate arrays in python similar to matlab ``` array1= zeros(3,500); array2=ones(3,700); array=[array1, array2]; ``` I did the following in python: ``` array1=np.zeros((3,500)) array2=np.ones((3,700)) array=numpy.concatenate((array1, array2), axis=2) ``` however this gives me different results wh...
`concatenate((a,b),1)` or `hstack((a,b))` or `column_stack((a,b))` or `c_[a,b]` From here: <http://wiki.scipy.org/NumPy_for_Matlab_Users>
Why is PyYAML spending so much time in just parsing a YAML File?
18,404,441
8
2013-08-23T13:44:32Z
18,437,951
12
2013-08-26T06:31:32Z
[ "python", "json", "yaml", "pyyaml" ]
I am parsing a YAML file with around 6500 lines with this format: ``` foo1: bar1: blah: { name: "john", age: 123 } metadata: { whatever1: "whatever", whatever2: "whatever" } stuff: thing1: bluh1: { name: "Doe1", age: 123 } bluh2: { name: "Doe2", age: 123 } thing2: ... thingN: foo...
According to [the docs](http://pyyaml.org/wiki/PyYAMLDocumentation) you must use `CLoader`/`CSafeLoader` (and `CDumper`): ``` import yaml try: from yaml import CLoader as Loader except ImportError: from yaml import Loader config_file = "test.yaml" stream = open(config_file, "r") sensors = yaml.load(stream, L...
Py Pandas .format(dataframe)
18,404,946
13
2013-08-23T14:10:45Z
18,405,221
19
2013-08-23T14:23:31Z
[ "python", "format", "pandas", "dataframe" ]
As Python newbie I recently discovered that with Py 2.7 I can do something like: ``` print '{:20,.2f}'.format(123456789) ``` which will give the resulting output: ``` 123,456,789.00 ``` I'm now looking to have a similar outcome for a pandas df so my code was like: ``` import pandas as pd import random data = [[ran...
``` import pandas as pd import numpy as np data = np.random.random((8,3))*10000 df = pd.DataFrame (data) pd.options.display.float_format = '{:20,.2f}'.format print(df) ``` yields (random output similar to) ``` 0 1 2 0 4,839.01 6,170.02...
How to reorder a python ordered dict based on array?
18,405,537
4
2013-08-23T14:37:18Z
18,405,632
7
2013-08-23T14:42:05Z
[ "python" ]
Say I have an Ordered Dict with the following items: ``` mydict = {'Rust': {'definition':'rusts definition'}, 'Iron': {'definition:'iron definition'}, 'Pyrite': {'definition':'pyrite definition'}} ``` If I have an array: ``` myorder = ['Pyrite', 'Rust', 'Iron'] ``` How can I reorder the Ordered Dict such that the i...
Try this: ``` mydict = {'Rust': {'definition':'rusts definition'}, 'Iron': {'definition':'iron definition'}, 'Pyrite': {'definition':'pyrite definition'}} myorder = ['Pyrite', 'Rust', 'Iron'] from collections import OrderedDict ordered = OrderedDict() for k in myorder: ordered[k] = mydict[k]...
Creating a timer in python
18,406,165
12
2013-08-23T15:07:40Z
18,406,263
16
2013-08-23T15:12:40Z
[ "python", "time" ]
``` import time def timer(): now = time.localtime(time.time()) return now[5] run = raw_input("Start? > ") while run == "start": minutes = 0 current_sec = timer() #print current_sec if current_sec == 59: mins = minutes + 1 print ">>>>>>>>>>>>>>>>>>>>>", mins ``` I want to create a kind o...
How about ``` from threading import Timer import time def timeout(): print("Game over") t = Timer(20 * 60, timeout) t.start() # do something else, such as time.sleep(1500) ``` Should you want pass arguments to the `timeout` function, you can give them in the timer constructor: ``` def timeout(foo, bar=None): ...
Creating a timer in python
18,406,165
12
2013-08-23T15:07:40Z
18,406,276
14
2013-08-23T15:13:33Z
[ "python", "time" ]
``` import time def timer(): now = time.localtime(time.time()) return now[5] run = raw_input("Start? > ") while run == "start": minutes = 0 current_sec = timer() #print current_sec if current_sec == 59: mins = minutes + 1 print ">>>>>>>>>>>>>>>>>>>>>", mins ``` I want to create a kind o...
You can really simplify this whole program by using [`time.sleep`](https://docs.python.org/2/library/time.html#time.sleep): ``` import time run = raw_input("Start? > ") mins = 0 # Only run if the user types in "start" if run == "start": # Loop until we reach 20 minutes running while mins != 20: print "...
Split a string into all possible ordered phrases
18,406,776
5
2013-08-23T15:40:11Z
18,406,982
8
2013-08-23T15:51:04Z
[ "python", "string", "list" ]
I am trying to explore the functionality of Python's built-in functions. I'm currently trying to work up something that takes a string such as: ``` 'the fast dog' ``` and break the string down into all possible ordered phrases, as lists. The example above would output as the following: ``` [['the', 'fast dog'], ['th...
Using [itertools.combinations](http://docs.python.org/2/library/itertools.html#itertools.combinations): ``` import itertools def break_down(text): words = text.split() ns = range(1, len(words)) # n = 1..(n-1) for n in ns: # split into 2, 3, 4, ..., n parts. for idxs in itertools.combinations(ns, n...
Long error in contour plot python
18,407,307
3
2013-08-23T16:08:53Z
18,407,490
8
2013-08-23T16:18:51Z
[ "python", "numpy", "matplotlib", "plot", "contour" ]
I am trying to create a contour plot with the x coordinates being label EF and y being labeled EB and z being a function labeled a. It returns a long error posted below. Any help would be appreciated. The error is ``` File "contour.py", line 19, in <module> c = plt.contour(EF,EB,a) File "/usr/lib/pymodules/python2.7...
The error states that ``` TypeError: Input z must be a 2D array. ``` if you look at the sizes of the input objects: ``` print EF.shape, EB.shape, a.shape (51,) (51,) (51,) ``` you'll see that these are **not** 2D arrays. Did you intend to use `X` and `Y` instead? When I make the change to ``` a = ((1+.5*(np.exp(1...
Custom sort order of list
18,408,247
4
2013-08-23T17:08:10Z
18,408,281
10
2013-08-23T17:10:38Z
[ "python", "list", "sorting" ]
I have lists such as: ``` mylist1 = ['alpha', 'green'] mylist2 = ['blue', 'alpha', 'red'] ``` I want to sort these two lists by this custom ordered list: `['red','blue','green','alpha']` so that `mylist1 = ['green', 'alpha']` and `mylist2 = ['red','blue','alpha']` How can i do this in Python?
**Demonstration**: ``` >>> mylist1 = ['alpha', 'green'] >>> mylist2 = ['blue', 'alpha', 'red'] >>> sort_order = ['red', 'blue', 'green', 'alpha'] >>> mylist1.sort(key=sort_order.index) >>> mylist1 ['green', 'alpha'] >>> mylist2.sort(key=sort_order.index) >>> mylist2 ['red', 'blue', 'alpha'] ``` **Explanation**: The ...
Is there a faster way to test if two lists have the exact same elements than Pythons built in == operator?
18,410,810
8
2013-08-23T19:53:00Z
18,410,915
10
2013-08-23T20:00:54Z
[ "python" ]
If I have two lists, each 800 elements long and filled with integers. Is there a faster way to compare that they have the exact same elements (and short circuit if they don't) than using the built in `==` operator? ``` a = [6,2,3,88,54,-486] b = [6,2,3,88,54,-486] a == b >>> True ``` Anything better than this? I'm ...
Let's not assume, but run some tests! The set-up: ``` >>> import time >>> def timeit(l1, l2, n): start = time.time() for i in xrange(n): l1 == l2 end = time.time() print "%d took %.2fs" % (n, end - start) ``` Two giant equal lists: ``` >>> hugeequal1 = [10]*30000 >>> ...
When to use Threadpool in Gevent
18,411,183
9
2013-08-23T20:19:28Z
19,153,826
9
2013-10-03T08:00:19Z
[ "python", "threadpool", "gevent" ]
I've noticed that Gevent has threadpool object. Can someone explain to me when to use threadpool and when to use regular pool? Whats the difference between gevent.threadpool and gevent.pool?
When you have a piece of python code that take's a long time to run (seconds) and will not cause swithing of greenlets. (no networking) All other greenlets / gevent jobs will 'starve' and have no computation time and it will look like you application 'hangs'. If you put this 'heavy' task in a Threadpool, ,the threaded...
Python sort list with None at the end
18,411,560
10
2013-08-23T20:45:54Z
18,411,598
9
2013-08-23T20:48:16Z
[ "python" ]
I have homogeneous list of objects with None, but it can contain any type of values. Example: ``` >>> l = [1, 3, 2, 5, 4, None, 7] >>> sorted(l) [None, 1, 2, 3, 4, 5, 7] >>> sorted(l, reverse=True) [7, 5, 4, 3, 2, 1, None] ``` Is there way without reinventing the wheel to get list sorted usual for python way, but Non...
Try this: ``` sorted(l, key=lambda x: float('inf') if x is None else x) ``` Since infinity is larger than all integers, `None` will always be placed last.
Python sort list with None at the end
18,411,560
10
2013-08-23T20:45:54Z
18,411,610
30
2013-08-23T20:48:52Z
[ "python" ]
I have homogeneous list of objects with None, but it can contain any type of values. Example: ``` >>> l = [1, 3, 2, 5, 4, None, 7] >>> sorted(l) [None, 1, 2, 3, 4, 5, 7] >>> sorted(l, reverse=True) [7, 5, 4, 3, 2, 1, None] ``` Is there way without reinventing the wheel to get list sorted usual for python way, but Non...
``` >>> l = [1, 3, 2, 5, 4, None, 7] >>> sorted(l, key=lambda x: (x is None, x)) [1, 2, 3, 4, 5, 7, None] ``` This constructs a tuple for each element in the list, if the value is `None` the tuple with be `(True, None)`, if the value is anything else it will be `(False, x)` (where `x` is the value). Since tuples are s...
django: TypeError: 'tuple' object is not callable
18,414,708
6
2013-08-24T03:45:03Z
18,414,711
21
2013-08-24T03:46:29Z
[ "python", "django", "tuples", "typeerror" ]
Getting a type error, 'tuple' object is not callable. Any idea what it could be? (dont worry about the indentation. It copies in weird.) I'm trying to create choices based on PackSize of storeliquor. Views.py: ``` def storeliquor(request, store_id, liquor_id): a = StoreLiquor.objects.get(StoreLiquorID=liquor_...
You're missing comma (`,`) inbetween: ``` >>> ((1,2) (2,3)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object is not callable ``` Put comma: ``` >>> ((1,2), (2,3)) ((1, 2), (2, 3)) ```
How can I sort tuples by reverse, yet breaking ties non-reverse? (Python)
18,414,995
3
2013-08-24T04:42:15Z
18,415,853
9
2013-08-24T06:50:24Z
[ "python", "sorting", "tuples", "reverse" ]
If I have a list of tuples: ``` results = [('10', 'Mary'), ('9', 'John'), ('10', 'George'), ('9', 'Frank'), ('9', 'Adam')] ``` How can I sort the list as you might see in a scoreboard - such that it will sort the score from biggest to smallest, but break ties alphabetically by name? So after the sort, the list shoul...
The simplest way to achieve what you want is to use the fact that python sort is stable. This allows to first sort alphabetically and then by score: ``` In [11]: results = [(10, 'Mary'), (9, 'John'), (10, 'George'), (9, 'Frank'), (9, 'Adam')] In [12]: results.sort(key=lambda x: x[1]) In [13]: results.sort(key=lambda...
Python class instance starts method in new thread
18,416,116
7
2013-08-24T07:22:57Z
18,416,308
14
2013-08-24T07:50:54Z
[ "python", "multithreading", "class" ]
I spent the last hour(s???) looking/googling for a way to have a class start one of its methods in a new thread as soon as it is instanciated. I could run something like this: ``` x = myClass() def updater(): while True: x.update() sleep(0.01) update_thread = Thread(target=updater) update_threa...
You can subclass directly from Thread in this specific case ``` from threading import Thread class MyClass(Thread): def __init__(self, other, arguments, here): super(MyClass, self).__init__() self.daemon = True self.cancelled = False # do other initialization here def run(self...
How do I run uwsgi with virtualenv
18,417,823
14
2013-08-24T10:59:35Z
18,418,014
22
2013-08-24T11:21:28Z
[ "python", "flask", "virtualenv", "uwsgi" ]
I'm currently developing my first real python flask project and am about to set up the build server to deploy the "Latest Build" which is built on every check-in. I have set up a startup script where I start the application using uwsgi and this part is working fine. I have recently also started using `virtualenv` and ...
Use `-H` to set virtualenv to python path. ``` uwsgi -H /path/to/your/virtualenv ``` <http://uwsgi-docs.readthedocs.org/en/latest/Options.html#virtualenv>
Reporting cumulative coverage across multiple Python versions
18,418,862
5
2013-08-24T12:59:02Z
18,420,710
7
2013-08-24T16:34:35Z
[ "python", "coverage.py", "tox", "python-coverage" ]
I have code that runs conditionally depending on the current version of Python, because I'm supporting 2.6, 2.7, and 3.3 from the same package. I currently generate a coverage report like this, using the default version of Python: ``` coverage run --source mypackage setup.py test coverage report -m coverage html ``` ...
<http://nedbatchelder.com/code/coverage/cmd.html#cmd-combining> is of use according to the developer.
improving code efficiency: standard deviation on sliding windows
18,419,871
17
2013-08-24T14:57:26Z
18,422,519
18
2013-08-24T19:50:07Z
[ "python", "optimization", "python-2.7", "numpy" ]
I am trying to improve function which calculate for each pixel of an image the standard deviation of the pixels located in the neighborhood of the pixel. My function uses two embedded loops to run accross the matrix, and it is the bottleneck of my programme. I guess there is likely a way to improve it by getting rid of...
Cool trick: you can compute the standard deviation given just the sum of squared values and the sum of values in the window. Therefore, you can compute the standard deviation very fast using a uniform filter on the data: ``` from scipy.ndimage.filters import uniform_filter def window_stdev(arr, radius): c1 = uni...
improving code efficiency: standard deviation on sliding windows
18,419,871
17
2013-08-24T14:57:26Z
18,423,835
10
2013-08-24T22:36:44Z
[ "python", "optimization", "python-2.7", "numpy" ]
I am trying to improve function which calculate for each pixel of an image the standard deviation of the pixels located in the neighborhood of the pixel. My function uses two embedded loops to run accross the matrix, and it is the bottleneck of my programme. I guess there is likely a way to improve it by getting rid of...
The most often used method to do this kind of things in image processing is using summed area tables, an idea introduced in [this paper](http://classes.soe.ucsc.edu/cmps160/Fall05/papers/p207-crow.pdf) in 1984. The idea is that, when you compute a quantity by adding over a window, and move the window e.g. one pixel to ...
How to compute weighted sum of all elements in a row in pandas?
18,419,962
8
2013-08-24T15:07:13Z
18,420,254
8
2013-08-24T15:39:43Z
[ "python", "pandas", "dataframe", "calculated-columns", "weighted-average" ]
I have a pandas data frame with multiple columns. I want to create a new column `weighted_sum` from the values in the row and another column vector dataframe `weight` `weighted_sum` should have the following value: `row[weighted_sum] = row[col0]*weight[0] + row[col1]*weight[1] + row[col2]*weight[2] + ...` I found th...
The problem is that you're multiplying a frame with a frame of a different size with a different row index. Here's the solution: ``` In [121]: df = DataFrame([[1,2.2,3.5],[6.1,0.4,1.2]], columns=list('abc')) In [122]: weight = DataFrame(Series([0.5, 0.3, 0.2], index=list('abc'), name=0)) In [123]: df Out[123]: ...
Issues changing a global variable value in python
18,420,071
3
2013-08-24T15:19:47Z
18,420,423
7
2013-08-24T15:58:45Z
[ "python" ]
Suppose I have this function ``` >>>a=3 >>>def num(a): a=5 return a >>>num(a) 5 >>>a 3 ``` *Value of a doesnt change.* Now consider this code : ``` >>> index = [1] >>> def change(a): a.append(2) return a >>> change(index) >>> index >>> [1,2] ``` In this code the value of index changes. ...
You need to understand how python names work. There is a good explanation [here](http://nedbatchelder.com/text/names.html), and you can [click here](http://pythontutor.com/visualize.html#code=a%3D3%0Adef+num%28a%29%3A%0A++++a%3D5%0A++++return+a%0Anum%28a%29%0A%0Aindex+%3D+%5B1%5D%0Adef+change%28a%29%3A%0A++a.append%282...
Class variables behave differently for list and int?
18,420,078
3
2013-08-24T15:20:35Z
18,420,138
10
2013-08-24T15:27:07Z
[ "python", "python-2.7" ]
The class shared variables are shared with all the instances of the classes as far as I know. But I am having trouble getting my head around this. ``` class c(): a=[1] b=1 def __init__(self): pass x=c() x.a.append(1) x.b+=1 #or x.b=2 print x.a #[1,1] print x.b #2 y=c() print y.a #[1,1] :As Expec...
``` x.a.append(1) ``` changes the class attribute `c.a`, a `list`, by calling its `append` method, which modifies the list in-place. ``` x.b += 1 ``` is actually a shorthand for ``` x.b = x.b + 1 ``` because integers in Python are immutable, so they don't have an `__iadd__` (in-place add) method. The result of thi...
How to set settings.LOGIN_URL to a view function name in Django 1.5+
18,420,300
4
2013-08-24T15:45:00Z
18,420,328
11
2013-08-24T15:47:50Z
[ "python", "django", "authentication" ]
As of Django 1.5, you can set [LOGIN\_URL](https://docs.djangoproject.com/en/1.5/ref/settings/#login-url) to a view function name, but I haven't been able to figure out how to specify it correctly. ``` LOGIN_URL = my_app.views.sign_in ``` ...does not work. I get the error, ``` ImproperlyConfigured: The SECRET_KEY se...
Django computes this url in django.contrib.auth.views:redirect\_to\_login function as: ``` resolved_url = resolve_url(login_url or settings.LOGIN_URL) ``` Therefore you should set it as string: ``` LOGIN_URL = 'my_app.views.sign_in' ``` Also in settings.py you can use reverse\_lazy function: ``` from django.core.u...
Multithreading for Python Django
18,420,699
13
2013-08-24T16:32:54Z
18,420,739
7
2013-08-24T16:36:47Z
[ "python", "django", "multithreading", "email", "decorator" ]
Some functions should run asynchronously on the web server. Sending emails is a classic example. What is the best (or most pythonic) way write a decorator function to run a function asynchronously? My setup is a common one: Python 2.4.7, Django 1.4, Gunicorn 0.17.2 For example, here's a start: ``` from threading im...
[Celery](http://www.celeryproject.org) is an asynchronous task queue/job queue. It's well documented and perfect for what you need. I suggest you start [here](http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html)
Multithreading for Python Django
18,420,699
13
2013-08-24T16:32:54Z
28,913,218
17
2015-03-07T09:11:28Z
[ "python", "django", "multithreading", "email", "decorator" ]
Some functions should run asynchronously on the web server. Sending emails is a classic example. What is the best (or most pythonic) way write a decorator function to run a function asynchronously? My setup is a common one: Python 2.4.7, Django 1.4, Gunicorn 0.17.2 For example, here's a start: ``` from threading im...
I posted the question above 18 months ago. Since then, I've continued using this implementation at scale and in production with no issues. decorator definition: ``` from threading import Thread def postpone(function): def decorator(*args, **kwargs): t = Thread(target = function, args=args, kwargs=kwargs) t....
live output from subprocess command
18,421,757
61
2013-08-24T18:27:18Z
18,422,264
53
2013-08-24T19:23:08Z
[ "python", "shell", "logging", "error-handling", "subprocess" ]
I'm using a python script as a driver for a hydrodynamics code. When it comes time to run the simulation, I use `subprocess.Popen` to run the code, collect the output from stdout and stderr into a `subprocess.PIPE` --- then I can print (and save to a log-file) the output information, and check for any errors. The probl...
You have two ways of doing this, either by creating an iterator from the `read` or `readline` functions and do: ``` import subprocess import sys with open('test.log', 'w') as f: process = subprocess.Popen(your_command, stdout=subprocess.PIPE) for c in iter(lambda: process.stdout.read(1), ''): sys.stdou...
live output from subprocess command
18,421,757
61
2013-08-24T18:27:18Z
18,423,003
38
2013-08-24T20:51:33Z
[ "python", "shell", "logging", "error-handling", "subprocess" ]
I'm using a python script as a driver for a hydrodynamics code. When it comes time to run the simulation, I use `subprocess.Popen` to run the code, collect the output from stdout and stderr into a `subprocess.PIPE` --- then I can print (and save to a log-file) the output information, and check for any errors. The probl...
## Executive Summary (or "tl;dr" version): it's easy when there's at most one `subprocess.PIPE`, otherwise it's hard. It may be time to explain a bit about how `subprocess.Popen` does its thing. (Caveat: this is for Python 2.x, although 3.x is similar; and I'm quite fuzzy on the Windows variant. I understand the POSI...
Match last occurence with regex
18,422,401
2
2013-08-24T19:38:35Z
18,422,469
9
2013-08-24T19:45:21Z
[ "python", "regex" ]
I would like to match last occurence of a pattern using regex. I have some text structured this way: ``` Pellentesque habitant morbi tristique senectus et netus et lesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas <br>se...
A non regex approach using the builtin `str` functions: ``` text = """ Pellentesque habitant morbi tristique senectus et netus et lesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas <br>semper<br>tizi ouzou<br>Tizi Ouzou<br...
Unable to install matplotlib on OSX 10.8.4 with VirtualEnv
18,422,746
3
2013-08-24T20:17:56Z
18,422,811
9
2013-08-24T20:27:35Z
[ "python", "matplotlib", "osx-mountain-lion", "virtualenv" ]
I tried every single link that is available on the web but still I am getting following error: ``` Edit setup.cfg to change the build options BUILDING MATPLOTLIB matplotlib: yes [1.4.x] python: yes [2.7.5 (default, Jul 28 2013, 07:27:04) [GCC 4.2.1 Compatible Apple...
If haven't yet install [brew](http://brew.sh) with: ``` ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go/install)" ``` and then do: ``` brew install freetype brew install libpng ``` The last line is probably not needed but just to be sure. Then try again with `pip`. EDIT: I also suggest you try the [c...
Cosine Similarity between 2 Number Lists
18,424,228
24
2013-08-24T23:37:20Z
18,424,300
8
2013-08-24T23:46:54Z
[ "python", "python-3.x", "cosine-similarity" ]
I need to calculate the **cosine similarity** between **two lists**, let's say for example list 1 which is `dataSetI` and list 2 which is `dataSetII`. I cannot use anything such as *numpy* or a statistics module. I must use common modules (math, etc) (and the least modules as possible, at that, to reduce time spent). ...
``` import math from itertools import izip def dot_product(v1, v2): return sum(map(lambda x: x[0] * x[1], izip(v1, v2))) def cosine_measure(v1, v2): prod = dot_product(v1, v2) len1 = math.sqrt(dot_product(v1, v1)) len2 = math.sqrt(dot_product(v2, v2)) return prod / (len1 * len2) ``` You can round...
Cosine Similarity between 2 Number Lists
18,424,228
24
2013-08-24T23:37:20Z
18,424,933
39
2013-08-25T01:56:36Z
[ "python", "python-3.x", "cosine-similarity" ]
I need to calculate the **cosine similarity** between **two lists**, let's say for example list 1 which is `dataSetI` and list 2 which is `dataSetII`. I cannot use anything such as *numpy* or a statistics module. I must use common modules (math, etc) (and the least modules as possible, at that, to reduce time spent). ...
You should try [SciPy](http://www.scipy.org/getting-started.html). It has a bunch of useful scientific routines for example, "routines for computing integrals numerically, solving differential equations, optimization, and sparse matrices." It uses the superfast optimized NumPy for its number crunching. See [here](http:...
Cosine Similarity between 2 Number Lists
18,424,228
24
2013-08-24T23:37:20Z
18,424,953
13
2013-08-25T02:03:00Z
[ "python", "python-3.x", "cosine-similarity" ]
I need to calculate the **cosine similarity** between **two lists**, let's say for example list 1 which is `dataSetI` and list 2 which is `dataSetII`. I cannot use anything such as *numpy* or a statistics module. I must use common modules (math, etc) (and the least modules as possible, at that, to reduce time spent). ...
I don't suppose performance matters much here, but I can't resist. The zip() function completely recopies both vectors (more of a matrix transpose, actually) just to get the data in "Pythonic" order. It would be interesting to time the nuts-and-bolts implementation: ``` import math def cosine_similarity(v1,v2): "c...
Cosine Similarity between 2 Number Lists
18,424,228
24
2013-08-24T23:37:20Z
27,046,041
14
2014-11-20T17:40:28Z
[ "python", "python-3.x", "cosine-similarity" ]
I need to calculate the **cosine similarity** between **two lists**, let's say for example list 1 which is `dataSetI` and list 2 which is `dataSetII`. I cannot use anything such as *numpy* or a statistics module. I must use common modules (math, etc) (and the least modules as possible, at that, to reduce time spent). ...
You can use `cosine_similarity` function form `sklearn.metrics.pairwise` [docs](http://scikit-learn.org/stable/modules/metrics.html) ``` In [23]: from sklearn.metrics.pairwise import cosine_similarity In [24]: cosine_similarity([1, 0, -1], [-1,-1, 0]) Out[24]: array([[-0.5]]) ```
django serving robots.txt efficiently
18,424,260
5
2013-08-24T23:41:22Z
18,424,412
19
2013-08-25T00:09:26Z
[ "python", "django", "robots.txt" ]
Here is my current method of serving robots.txt ``` url(r'^robots\.txt/$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), ``` I don't think that this is the best way. I think it would be better if it were just a pure static resource and served...
Yes, robots.txt should not be served by Django if the file is static. Try something like this in your Nginx config file: ``` location /robots.txt { alias /path/to/static/robots.txt; } ``` See here for more info: <http://wiki.nginx.org/HttpCoreModule#alias> Same thing applies to the favicon.ico file if You have...
Python: third Friday of a month
18,424,467
4
2013-08-25T00:22:56Z
18,424,560
11
2013-08-25T00:38:51Z
[ "python", "date", "datetime", "calendar", "datetimeoffset" ]
I am a rookie python programmer and I need to write a script to check if a given date (passed as a string in the form 'Month, day year') is the third Friday of the month. I am using Python 2.7. For example, these dates can help you better understand my problem. Have a yearly calendar at hand. * **input ---> output** ...
This should do it: ``` from datetime import datetime def is_third_friday(s): d = datetime.strptime(s, '%b %d, %Y') return d.weekday() == 4 and 14 < d.day < 22 ``` Test: ``` print is_third_friday('Jan 18, 2013') # True print is_third_friday('Feb 22, 2013') # False print is_third_friday('Jun 21, 2013') # ...
Python - vectorizing a sliding window
18,424,900
6
2013-08-25T01:50:43Z
18,430,026
7
2013-08-25T14:29:12Z
[ "python", "numpy", "scipy" ]
I'm trying to vectorize a sliding window operation. For the 1-d case a helpful example could go along the lines of: ``` x= vstack((np.array([range(10)]),np.array([range(10)]))) x[1,:]=np.where((x[0,:]<5)&(x[0,:]>0),x[1,x[0,:]+1],x[1,:]) ``` The n+1 value for each current value for indices <5. But I get this error: ...
If I understand the problem correctly you would like to take the mean of all numbers 1 step around the index, neglecting the index. I have patched your function to work, I believe you were going for something like this: ``` def original(matriz): vector2 = np.ndarray.flatten(matriz) nrows, ncols= matriz.shap...
Getting the name of a variable as a string
18,425,225
16
2013-08-25T02:58:26Z
18,425,275
21
2013-08-25T03:08:35Z
[ "python", "python-2.x" ]
This thread discusses how to get the name of a function as a string in Python: [How to get a function name as a string in Python?](http://stackoverflow.com/questions/251464/how-to-get-the-function-name-as-string-in-python) How can I do the same for a variable? (note that Python variables do not have the attribute `__n...
The only objects in Python that have canonical names are modules, functions, and classes, and of course there is no guarantee that this canonical name has any meaning in any namespace after the function or class has been defined or the module imported. These names can also be modified after the objects are created so t...
Getting the name of a variable as a string
18,425,225
16
2013-08-25T02:58:26Z
18,425,285
10
2013-08-25T03:10:34Z
[ "python", "python-2.x" ]
This thread discusses how to get the name of a function as a string in Python: [How to get a function name as a string in Python?](http://stackoverflow.com/questions/251464/how-to-get-the-function-name-as-string-in-python) How can I do the same for a variable? (note that Python variables do not have the attribute `__n...
I don't believe this is possible. Consider the following example: ``` >>> a = [] >>> b = a >>> id(a) 140031712435664 >>> id(b) 140031712435664 ``` The `a` and `b` point to the same object. It (the object) doesn't know what variables point to it.
Getting the name of a variable as a string
18,425,225
16
2013-08-25T02:58:26Z
18,425,523
14
2013-08-25T03:55:13Z
[ "python", "python-2.x" ]
This thread discusses how to get the name of a function as a string in Python: [How to get a function name as a string in Python?](http://stackoverflow.com/questions/251464/how-to-get-the-function-name-as-string-in-python) How can I do the same for a variable? (note that Python variables do not have the attribute `__n...
Even if variable values don't point back to the name, you have access to the list of every assigned variable and its value, so I'm astounded that only one person suggested looping through there to look for your var name. Someone mentioned on that answer that you might have to walk the stack and check everyone's locals...
How to set Python's default version to 3.3 on OS X?
18,425,379
43
2013-08-25T03:29:49Z
18,425,592
97
2013-08-25T04:06:41Z
[ "python", "osx", "install" ]
I'm running Mountain Lion and the basic default Python version is 2.7. I downloaded Python 3.3 and want to set it as default. Currently: ``` $ python version 2.7.5 $ python3.3 version 3.3 ``` How do I set it so that every time I run `$ python` it opens 3.3?
Changing the default python version system wide would break some applications that depend on python2. You can alias the commands in most shells, Mac OS X uses bash by default, if you also do put this into your `~/.bash_aliases`: ``` alias python='python3' ``` `python` command now refers to `python3`. If you want the...
Why is .pyc file created sometimes in same directory and sometimes in __pycache__ subdirectory?
18,426,739
3
2013-08-25T07:31:51Z
18,426,782
8
2013-08-25T07:39:46Z
[ "python", "python-2.7", "python-3.x" ]
I am using Windows 7 and have both Python 2.7.5 and 3.3.2 installed. My `path` environment variable is set as ``` C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\python27;C:\Python33\Scripts ``` When I import any Python module into another module a `.pyc` file is created. The p...
Python 3 has changed how the bytecode (`.pyc`) files are stored. Python 2 uses the convention of putting them in the same directory, but for Python 3 the developers decided to reduce clutter by putting them all in a separate directory. This also made support for Python implementations other than CPython easier, as each...
Exposing the LBP descriptors from OpenCV in Python
18,426,765
3
2013-08-25T07:35:49Z
18,431,418
7
2013-08-25T16:55:44Z
[ "c++", "python", "opencv" ]
I want to be able to calculate the LBP discriptor in python using OpenCV. According to [this](http://stackoverflow.com/questions/13733448/how-to-calculate-local-binary-pattern-histograms-with-opencv) I need to compile openCV again. I changed the `elbp()` functions in `opencv-2.4.6.1/modules/contrib/src/facerec.cpp`, s...
So, it worked. To make the function accessible: . 1. I made the following change to facerec.cpp, from: ``` static void elbp(InputArray src, OutputArray dst, int radius, int neighbors) { ... } static Mat elbp(InputArray src, int radius, int neighbors) { Mat dst; elbp(src, dst, rad...
Python - time difference in milliseconds not working for me
18,426,882
14
2013-08-25T07:59:33Z
18,426,915
28
2013-08-25T08:04:19Z
[ "python" ]
I've read a few posts about this and thought I had some code that worked. If the difference between the 2 values is less than a 1sec then the millisecs displayed is correct. If the difference is more than a sec, its still only showing me the difference of the millisecs. As below. Correct: ``` now_wind 2013-08-25 0...
Try using total\_seconds method: ``` print time_diff_wind.total_seconds() * 1000 ``` That method is equivalent to: `(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6` > Note: It's available since version 2.7
Python - time difference in milliseconds not working for me
18,426,882
14
2013-08-25T07:59:33Z
18,426,956
15
2013-08-25T08:08:44Z
[ "python" ]
I've read a few posts about this and thought I had some code that worked. If the difference between the 2 values is less than a 1sec then the millisecs displayed is correct. If the difference is more than a sec, its still only showing me the difference of the millisecs. As below. Correct: ``` now_wind 2013-08-25 0...
``` >>> a = datetime.datetime.now() >>> b = datetime.datetime.now() >>> a datetime.datetime(2013, 8, 25, 2, 5, 1, 879000) >>> b datetime.datetime(2013, 8, 25, 2, 5, 8, 984000) >>> a - b datetime.timedelta(-1, 86392, 895000) >>> b - a datetime.timedelta(0, 7, 105000) >>> (b - a).microseconds 105000 >>> (b - a).seconds 7...
How to load DLL using Iron python?
18,427,775
2
2013-08-25T09:52:12Z
18,428,597
7
2013-08-25T11:41:25Z
[ "python", ".net", "ironpython", "dllimport" ]
I wrote the simplest DLL using C# and copied it to the desktop. Now I wanted to load the DLL in order to see that I can use the API but I get some errors: the code I used: (edited after looking at some questions here) ``` import clr import sys sys.path.Add("C:\Desktop\DLLTest.dll") clr.AddReference("C:\Desktop\DLLTes...
User `clr.AddReferenceToFileAndPath` and double your backslashes. So: ``` import clr clr.AddReferenceToFileAndPath('C:\\Desktop\\DLLTest.dll') ```
How to debug python application under uWSGI?
18,427,948
19
2013-08-25T10:18:54Z
18,432,456
32
2013-08-25T18:48:36Z
[ "python", "uwsgi" ]
When I'm trying to use python pdb debugger under uWSGI, the execution doesn't stop on breakpoint, it just return trackback. here is the code: ``` def application(env, start_response): import pdb; pdb.set_trace() start_response('200 OK', [('Content-Type','text/html')]) return "Hello World" ``` this is how...
Being a server, uWSGI closes the stdin (effectively it remaps it to /dev/null). If you need stdin (as when you need a terminal debugger) add: ``` --honour-stdin ```
Kill python interpeter in linux from the terminal
18,428,750
23
2013-08-25T12:01:30Z
18,428,815
25
2013-08-25T12:10:17Z
[ "python", "linux", "terminal", "command" ]
I want to kill python interpeter - The intention is that all the python files that are running in this moment will stop (without any informantion about this files). obviously the processes should be closed. Any idea as delete files in python or destroy the interpeter is ok :D (I am working with virtual machine). I nee...
``` pkill -9 python ``` should kill any running python process.
Kill python interpeter in linux from the terminal
18,428,750
23
2013-08-25T12:01:30Z
18,428,847
12
2013-08-25T12:13:39Z
[ "python", "linux", "terminal", "command" ]
I want to kill python interpeter - The intention is that all the python files that are running in this moment will stop (without any informantion about this files). obviously the processes should be closed. Any idea as delete files in python or destroy the interpeter is ok :D (I am working with virtual machine). I nee...
You can try the [killall](http://linux.die.net/man/1/killall) command: `killall python`
Kill python interpeter in linux from the terminal
18,428,750
23
2013-08-25T12:01:30Z
18,428,853
22
2013-08-25T12:14:14Z
[ "python", "linux", "terminal", "command" ]
I want to kill python interpeter - The intention is that all the python files that are running in this moment will stop (without any informantion about this files). obviously the processes should be closed. Any idea as delete files in python or destroy the interpeter is ok :D (I am working with virtual machine). I nee...
There's a rather crude way of doing this, but be careful because first, this relies on python interpreter process identifying themselves as *python*, and second, it has the concomitant effect of also killing any other processes identified by that name. In short, you can kill all python interpreters by typing this into...
strip punctuation with regex - python
18,429,143
7
2013-08-25T12:48:10Z
18,429,172
27
2013-08-25T12:49:37Z
[ "python", "regex" ]
I need to use regex to strip punctuation at the *start* and *end* of a word. It seems like regex would be the best option for this. I don't want punctuation removed from words like 'you're', which is why I'm not using .replace(). Thanks in advance =)
You don't need regular expression to do this task. Use [`str.strip`](http://docs.python.org/2/library/stdtypes#str.strip) with [`string.punctuation`](http://docs.python.org/2/library/string#string.punctuation): ``` >>> import string >>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' >>> '!Hello.'.strip(string...
Convert pyQt UI to python
18,429,452
11
2013-08-25T13:24:29Z
18,430,351
13
2013-08-25T15:02:43Z
[ "python", "pyqt", "maya", "pymel" ]
Is there a way to convert a ui formed with qtDesigner to a python version to use without having an extra file? I'm using Maya for this UI, and converting this UI file to a readable python version to implement would be really great!
You can use `pyuic4` command on shell: `pyuic4 input.ui -o output.py`
Setting up virtual environment in PyCharm
18,430,726
9
2013-08-25T15:41:40Z
18,431,537
11
2013-08-25T17:07:35Z
[ "python", "django", "virtualenv", "pycharm" ]
Greetings to everyone! I've got a little issue in a project made by someone in PyCharm, with virtual environment(VE) precisely. I've set this VE up few months ago and didn't use it for some time. Now i need to go back to it, because it has a lot of necessary things installed. Therefore there is one more battery needed...
In settings, under the Project section (in the left pane) go to Interpreters. From there you can select a found environment or click the + to add your own from a path. Find the environment you created and add it to the list. Then, once you select the environment you can see the installed modules underneath. You can add...
How can static method access class variable in Python?
18,431,313
13
2013-08-25T16:47:44Z
18,431,364
16
2013-08-25T16:51:27Z
[ "python" ]
This is what my code looks like ``` class InviteManager(): ALREADY_INVITED_MESSAGE = "You are already on our invite list" INVITE_MESSAGE = "Thank you! we will be in touch soon" @staticmethod @missing_input_not_allowed def invite(email): try: db.session.add(Invite(email)) ...
You can access it as `InviteManager.INVITE_MESSAGE`, but a cleaner solution is to change the static method to a class method: ``` @classmethod @missing_input_not_allowed def invite(cls, email): return cls.INVITE_MESSAGE ``` (Or, if your code is really as simple as it looks, you can replace the whole class with a ...
Celery - How to send task from remote machine?
18,433,071
15
2013-08-25T19:54:43Z
19,257,867
21
2013-10-08T20:36:55Z
[ "python", "celery" ]
We have a server running celery workers and a Redis queue. The tasks are defined on that server. I need to be able to call these tasks from a remote machine. I know that it is done using `send_task` but I still haven't figured out HOW? How do I tell `send_task` where the queue is? Where do I pass connection params ...
This may be a way: Creating a Celery object and using send\_task from that object, the object can have the configuration to find the broker. ``` from celery import Celery celery = Celery() celery.config_from_object('celeryconfig') celery.send_task('tasks.add', (2,2)) ``` celeryconfig is a file containing the celery c...
Open file knowing only a part of its name
18,433,177
2
2013-08-25T20:06:50Z
18,433,264
11
2013-08-25T20:16:58Z
[ "python", "naming" ]
I'm currently reading a file and importing the data in it with the line: ``` # Read data from file. data = np.loadtxt(join(mypath, 'file.data'), unpack=True) ``` where the variable `mypath` is known. The issue is that the file `file.data` will change with time assuming names like: ``` file_3453453.data file_12324.da...
You can use the `glob` module. It allows pattern matching on filenames and does exactly what you're asking ``` import glob for fpath in glob.glob(mypath): print fpath ``` e.g I have a directory with files named google.xml, google.json and google.csv. I can use glob like this: ``` >>> import glob >>> glob.glob(...
learning python and also trying to implement scrapy ..getting this error
18,433,256
14
2013-08-25T20:16:15Z
18,433,386
31
2013-08-25T20:32:08Z
[ "python", "scrapy", "scrapyd" ]
I am going through the scrapy tutorial <http://doc.scrapy.org/en/latest/intro/tutorial.html> and I followed it till I ran this command ``` scrapy crawl dmoz ``` And it gave me output with an error ``` 2013-08-25 13:11:42-0700 [scrapy] INFO: Scrapy 0.18.0 started (bot: tutorial) 2013-08-25 13:11:42-0700 [scrapy] DEBU...
ok I found this somehow fixing the issue sudo pip install --upgrade zope.interface I am not sure what happened once issued this command but that solved my problem and now I see this ``` 2013-08-25 13:30:05-0700 [scrapy] INFO: Scrapy 0.18.0 started (bot: tutorial) 2013-08-25 13:30:05-0700 [scrapy] DEBUG: Optional fea...
Python Selenium with Phantomjs - Click Failed: ReferenceError: Cant't find variable
18,433,453
11
2013-08-25T20:38:06Z
18,433,763
31
2013-08-25T21:12:54Z
[ "python", "selenium-webdriver", "phantomjs" ]
Im writing a python script using selenium webdriver to get some data from a website, and Im trying to click the next button in [this](http://www.nordpoolspot.com/Market-data1/Elspot/Area-Prices/ALL1/Hourly/) webpage. Where the button is defined: ``` <a id="ctl00_FullRegion_npsGridView_lnkNext" class="nextCol" href="ja...
Try sending a different User-Agent header: ``` from selenium.webdriver.common.desired_capabilities import DesiredCapabilities user_agent = ( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36" ) dcap = dict(DesiredCapabilities.PHANTOM...
Non-lazy evaluation version of map in Python3?
18,433,488
4
2013-08-25T20:41:27Z
18,433,519
11
2013-08-25T20:44:49Z
[ "python" ]
I'm trying to use `map` in Python3. Here's some code I'm using: ``` import csv data = [ [1], [2], [3] ] with open("output.csv", "w") as f: writer = csv.writer(f) map(writer.writerow, data) ``` However, since `map` in Python3 returns an iterator, this code doesn't work in Python3 (but works fine ...
Using `map` for its side-effects (eg function call) when you're not interested in returned values is undesirable even in Python2.x. If the function returns `None`, but repeats a million times - you'd be building a list of a million `None`s just to discard it. The correct way is to either use a for-loop and call: ``` f...
Decrypt SHA1 with (password) in python
18,433,917
2
2013-08-25T21:29:28Z
18,433,948
7
2013-08-25T21:32:37Z
[ "python", "encryption", "sha" ]
I have a function for encrypting with SHA-1 in Python, using `hashlib`. I take a file and encrypt the contents with this hash. If I set a password for an encrypted text file can I use this password to decrypt and to restore the file with the original text?
`SHA-1` is not an *encryption* algorithm, it's a *hashing* algorithm. By definition, you can't "decrypt" anything that was hashed with the SHA-1 function, it doesn't have an inverse. If you have an arbitrary hashed password, there's very little you can do to retrieve the original password - If you're lucky, the passwo...
Pandas: Converting to numeric, creating NaNs when necessary
18,434,208
12
2013-08-25T22:04:50Z
18,434,403
26
2013-08-25T22:33:14Z
[ "python", "pandas" ]
Say I have a column in a dataframe that has some numbers and some non-numbers ``` >> df['foo'] 0 0.0 1 103.8 2 751.1 3 0.0 4 0.0 5 - 6 - 7 0.0 8 - 9 0.0 Name: foo, Length: 9, dtype: object ``` How can I convert this column to `np.float`, and have everythin...
Use the [`convert_objects`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html) Series method (and `convert_numeric`): ``` In [11]: s Out[11]: 0 103.8 1 751.1 2 0.0 3 0.0 4 - 5 - 6 0.0 7 - 8 0.0 dtype: object In [12]: s.convert_o...
Pandas: Converting to numeric, creating NaNs when necessary
18,434,208
12
2013-08-25T22:04:50Z
33,795,876
14
2015-11-19T05:25:35Z
[ "python", "pandas" ]
Say I have a column in a dataframe that has some numbers and some non-numbers ``` >> df['foo'] 0 0.0 1 103.8 2 751.1 3 0.0 4 0.0 5 - 6 - 7 0.0 8 - 9 0.0 Name: foo, Length: 9, dtype: object ``` How can I convert this column to `np.float`, and have everythin...
In pandas `0.17.0` [`convert_objects`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html) raise a warning: > FutureWarning: convert\_objects is deprecated. Use the data-type > specific converters pd.to\_datetime, pd.to\_timedelta and pd.to\_numeric. You could use [`pd.to_nume...
how to add annotate data in django-rest-framework queryset responses?
18,434,425
15
2013-08-25T22:35:17Z
18,435,414
16
2013-08-26T01:22:42Z
[ "python", "django", "django-rest-framework" ]
I am generating aggregates for each item in a QuerySet: ``` def get_queryset(self): from django.db.models import Count queryset = Book.objects.annotate(Count('authors')) return queryset ``` But I am not getting the count in the JSON response. thank you in advance.
The queryset returned from get\_queryset provides the list of things that will go through the serializer, which controls how the objects will be represented. Try adding an additional field in your Book serializer, like: ``` author_count = serializers.IntegerField( source='author_set.count', read_only=True ) `...
See if all items in a list = certain string
18,434,618
4
2013-08-25T23:05:47Z
18,434,625
14
2013-08-25T23:06:58Z
[ "python" ]
How would I find if I have a list of a given string, 'hello': ``` x = ['hello', 'hello', 'hello'] # evaluates to True x = ['hello', '1'] # evaluates to False ```
Use the [`all()` function](http://docs.python.org/2/library/functions.html#all) to test if a condition holds `True` for all elements: ``` all(el == 'hello' for el in x) ``` The `all()` function takes an iterable (something that produces results one by one) and will only return `True` itself if all those elements are ...
Adding field that isn't in model to serializer in Django REST framework
18,435,787
8
2013-08-26T02:27:41Z
18,479,676
8
2013-08-28T04:49:52Z
[ "python", "django", "api", "rest", "django-rest-framework" ]
I have a model Comment that when created may or may not create a new user. For this reason, my API requires a password field when creating a new comment. Here is my Comment model: ``` class Comment(models.Model): commenter = models.ManyToManyField(Commenter) email = models.EmailField(max_length=100) author...
If anyone is curious, the solution is to override the restore\_object method and add the extra instance variable to the comment object after it has been instantiated: ``` def restore_object(self, attrs, instance=None): if instance is not None: instance.email = attrs.get('email', instance.email) ...
whats the diff bw self.browse and self.pool.get in openerp development?
18,437,202
3
2013-08-26T05:27:42Z
18,517,183
15
2013-08-29T17:17:24Z
[ "python", "eclipse", "openerp", "openerp-8" ]
I have been working on developing a module in openerp-7.0. I have been using python and eclipse IDE for development. I wanted to know the difference bw self.browse and self.pool.get in openerp development . Plz reply me as soon as possible. Thanks. Best wishes Hopes for suggestion
To access a record by id you need you use ORM's browse method ``` def some_moethod(self, cr, uid, ids): self.browse(cr, uid, ids) // same class do_some_Stuff return something ``` You can use when you are writing a method in same class whose records you want browse but if you want browse records from anoth...
find vs in operation in string python
18,437,798
9
2013-08-26T06:20:10Z
18,437,853
16
2013-08-26T06:24:18Z
[ "python" ]
I need to find pattern into string and found that we can use in or find also. Could anyone suggest me which one will be better/fast on string. I need not to find index of pattern as find can also return the index of the pattern. ``` temp = "5.9" temp_1 = "1:5.9" >>> temp.find(":") -1 >>> if ":" not in temp: print ...
Use `in` , it is faster. ``` dh@d:~$ python -m timeit 'temp = "1:5.9";temp.find(":")' 10000000 loops, best of 3: 0.139 usec per loop dh@d:~$ python -m timeit 'temp = "1:5.9";":" in temp' 10000000 loops, best of 3: 0.0412 usec per loop ```
Create openoffice .odt document with Python
18,439,396
4
2013-08-26T08:02:06Z
18,439,583
9
2013-08-26T08:14:49Z
[ "python", "openoffice.org" ]
How can I create an open office .odt file from Python? I'm looking at this <http://wiki.openoffice.org/wiki/Python>, but am confused. I've already got Python 2.7 so where do I go from here? The above link talks about Open Office shipping with Python. Have I already got it?? And do I even need OpenOffice? Isn't there j...
I use [relatorio](https://pypi.python.org/pypi/relatorio) to be able to produce odt. You can have a look [at it here](http://code.google.com/p/python-relatorio/wiki/QuickExample)
Python regex: find and replace commas between quotation marks
18,439,708
2
2013-08-26T08:22:50Z
18,439,809
7
2013-08-26T08:29:47Z
[ "python", "regex" ]
I have a string, ``` line = '12/08/2013,3,"9,25",42:51,"3,08","12,9","13,9",159,170,"3,19",437,' ``` and I would like to find and replace the commas, between quotation marks, with ":". Looking for a results ``` line = '12/08/2013,3,9:25,42:51,3:08,12:9,13:9,159,170,3:19,437,' ``` So far I have been able to match th...
``` >>> import re >>> line = '12/08/2013,3,"9,25",42:51,"3,08","12,9","13,9",159,170,"3,19",437,' >>> re.sub(r'"(\d+),(\d+)"', r'\1:\2', line) '12/08/2013,3,9:25,42:51,3:08,12:9,13:9,159,170,3:19,437,' ``` `\1`, `\2` refer to matched groups. --- Non-regex solution: ``` >>> ''.join(x if i % 2 == 0 else x.replace(','...
downloading file using selenium
18,439,851
18
2013-08-26T08:32:13Z
18,440,478
31
2013-08-26T09:06:28Z
[ "python", "selenium", "selenium-webdriver" ]
I am working on python and selenium. I want to download file from clicking event using selenium. I wrote following code. ``` from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys browser = webdriver.Firefox() browser.get("http://ww...
Find the link using `find_element(s)_by_*`, then call `click` method. ``` from selenium import webdriver # To prevent download dialog profile = webdriver.FirefoxProfile() profile.set_preference('browser.download.folderList', 2) # custom location profile.set_preference('browser.download.manager.showWhenStarting', Fals...
How to specify upper and lower limits when using numpy.random.normal
18,441,779
7
2013-08-26T10:16:28Z
18,444,710
10
2013-08-26T12:57:27Z
[ "python", "numpy", "random", "scipy", "gaussian" ]
IOK so I want to be able to pick values from a normal distribution that only ever fall between 0 and 1. In some cases I want to be able to basically just return a completely random distribution, and in other cases I want to return values that fall in the shape of a gaussian. At the moment I am using the following func...
It sounds like you want a [truncated normal distribution](http://en.wikipedia.org/wiki/Truncated_normal_distribution). Using scipy, you could use `scipy.stats.truncnorm` to generate random variates from such a distribution: ``` import matplotlib.pyplot as plt import scipy.stats as stats lower, upper = 3.5, 6 mu, sigm...
Stucked in a django south migration - TransactionManagement error
18,442,057
4
2013-08-26T10:32:02Z
19,514,760
12
2013-10-22T10:05:22Z
[ "python", "django", "transactions", "django-south" ]
I am having a trouble when applying a django south migration: As always, I executed the migrate command after a successful schemamigration ``` python manage.py migrate webapp ``` The log console: ``` Running migrations for webapp: - Migrating forwards to 0020_auto__add_example. > webapp:0020_auto__add_example Tra...
I just ran into a similar issue. * MySQL 5.6.13 (on Amazon RDS) * Django==1.5.4 * MySQL-python==1.2.4 * South==0.8.2 I went through almost every possible fix here and through countless Google searches with zero luck. I looked at the database schema and a table I had not created named 'ROLLBACK\_TEST' was part of the...
BaseHTTPRequestHandler with custom instance
18,444,395
7
2013-08-26T12:42:34Z
26,724,272
9
2014-11-03T22:15:56Z
[ "python", "httpserver", "basehttpserver", "requesthandler", "basehttprequesthandler" ]
this is my http server: ``` from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer class test: def show(self): return "aaaa" class http_server: def __init__(self, t1): self.t1 = t1 server = HTTPServer(('', 8080), myHandler) server.serve_forever() class myHandler(BaseHTT...
Slightly better version, where t1 will not be the same for each instance. ``` from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer class test: def show(self): return "aaaa" class http_server: def __init__(self, t1): def handler(*args): myHandler(t1, *args) server =...
Python: Read and write TIFF 16 bit , three channel , colour images
18,446,804
8
2013-08-26T14:41:49Z
18,449,063
10
2013-08-26T16:51:51Z
[ "python", "image", "numpy", "png", "tiff" ]
Does anyone have a method for importing a 16 bit per channel, 3 channel TIFF image in Python? I have yet to find a method which will preserve the 16 bit depth per channel when dealing with the TIFF format. I am hoping that some helpful soul will have a solution. Here is a list of what I have tried so far without succ...
It has limited functionality, especially when it comes to writing back to disk non RGB images, but [Christoph Gohlke's `tifffile` module](http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html) reads in 3 channel 16-bit TIFFs with no problems, I just tested it: ``` >>> import tifffile as tiff >>> a = tiff.imread('Untitl...
Python: Read and write TIFF 16 bit , three channel , colour images
18,446,804
8
2013-08-26T14:41:49Z
18,461,475
8
2013-08-27T09:14:55Z
[ "python", "image", "numpy", "png", "tiff" ]
Does anyone have a method for importing a 16 bit per channel, 3 channel TIFF image in Python? I have yet to find a method which will preserve the 16 bit depth per channel when dealing with the TIFF format. I am hoping that some helpful soul will have a solution. Here is a list of what I have tried so far without succ...
The answer by [@Jaime](http://stackoverflow.com/users/110026/jaime) works. In the mean time I managed to also solve the problem using [`cv2.imread`](http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#imread) in OpenCV. By default `cv2.imread` will convert a 16 bit, three channel imag...
Python: Read and write TIFF 16 bit , three channel , colour images
18,446,804
8
2013-08-26T14:41:49Z
18,483,020
7
2013-08-28T08:33:22Z
[ "python", "image", "numpy", "png", "tiff" ]
Does anyone have a method for importing a 16 bit per channel, 3 channel TIFF image in Python? I have yet to find a method which will preserve the 16 bit depth per channel when dealing with the TIFF format. I am hoping that some helpful soul will have a solution. Here is a list of what I have tried so far without succ...
I found an additional alternative to the two methods above. The [scikit-image](http://scikit-image.org/) package can also read 16 bit, three channel TIFF files using both `tifffile.py` and FreeImage and specifying them as the plugin to be used. While reading using `tifffile.py` is probably done more simply in the man...
Programmatically setting access control limits in mosquitto
18,447,532
3
2013-08-26T15:21:10Z
24,770,392
7
2014-07-16T00:38:11Z
[ "python", "mq", "mqtt", "mosquitto" ]
I am working on an application that will use mqtt. I will be using the python library. I have been leaning towards using mosquitto but can find no way of programmatically setting access control limits for it. The application I'm writing needs to be able to differentiate between users, and only allow them to subscribe t...
Even if this might not concern you anymore, others could find it useful. I am following here mosquitto's [man page](http://mosquitto.org/man/mosquitto-conf-5.html). There are two configuration files, a general one, say `mosquitto.conf`, and an ACL (Access Control List) one, say `acl.conf`. `mosquitto.conf` enables th...
Django - how to filter using QuerySet to get subset of objects?
18,448,468
5
2013-08-26T16:15:52Z
18,450,708
8
2013-08-26T18:35:51Z
[ "python", "django" ]
According to [documentation](https://docs.djangoproject.com/en/dev/ref/models/querysets/#filter): > filter(\*\*kwargs) Returns a new QuerySet containing objects that match > the given lookup parameters. > > The lookup parameters (\*\*kwargs) should be in the format described in > Field lookups below. Multiple paramete...
This is kind of ugly, but works (without any type safety): ``` toy_owners = Toy.objects.values("owner_id") # optionally with .distinct() Kid.objects.filter(id__in=toy_owners) ``` If performance is not an issue, I think @limelights is right. PS! I tested your query on Django 1.6b2 and got the same unnecessary comple...
Python: filter list of list with another list
18,448,469
3
2013-08-26T16:15:59Z
18,448,494
8
2013-08-26T16:17:55Z
[ "python", "list", "filter" ]
i'm trying to filter a list, i want to extract from a list A (is a list of lists), the elements what matches they key index 0, with another list B what has a serie of values like this ``` list_a = list( list(1, ...), list(5, ...), list(8, ...), list(14, ...) ) list_b = list(5, 8) return filter(lambda list_a...
Use a list comprehension: ``` result = [x for x in list_a if x[0] in list_b] ``` For improved performance convert `list_b` to a set first. As @kevin noted in comments something like `list(5,8)`(unless it's not a pseudo-code) is invalid and you'll get an error. `list()` accepts only one item and that item should be ...
Import txt file and having each line as a list
18,448,847
4
2013-08-26T16:38:37Z
18,448,884
11
2013-08-26T16:41:20Z
[ "python", "list", "python-3.x", "file-io" ]
I'm a new Python user. I have a txt file that will be something like: ``` 3,1,3,2,3 3,2,2,3,2 2,1,3,3,2,2 1,2,2,3,3,1 3,2,1,2,2,3 ``` but may be less or more lines. I want to import each line as a list. I know you can do it as such: ``` filename = 'MyFile.txt' fin=open(filename,'r') L1list = fin.readline() L2lis...
Do not create separate lists; create a list of lists: ``` results = [] with open('inputfile.txt') as inputfile: for line in inputfile: results.append(line.strip().split(',')) ``` or better still, use the [`csv` module](http://docs.python.org/3/library/csv.html): ``` import csv results = [] with open('in...
2.7 CSV module wants unicode, but doesn't want unicode
18,449,233
6
2013-08-26T17:02:34Z
18,449,496
8
2013-08-26T17:19:36Z
[ "python", "csv", "python-2.7", "unicode", "error-handling" ]
``` csvfile_ = open(finishedFileName+num+".csv","w",newline='') writ = csv.writer(csvfile_, dialect='excel') firstline = unicode(str(firstline)) try: writ.writerow(firstline) except TypeError: print firstline print type(firstline) raise ``` I get a `TypeError: must be unicode, not str` with this code. ...
Unfortunately, `3to2` used the `io.open()` call instead of the built-in Python 2 `open()` function. This opened the file in text mode, which like on Python 3 expects Unicode input. However, the *`csv` module* does not support Unicode data; it certainly does not produce Unicode. You'll either have to open the file in ...
Matplotlib, creating stacked histogram from three unequal length arrays
18,449,602
16
2013-08-26T17:26:13Z
18,449,729
29
2013-08-26T17:35:44Z
[ "python", "matplotlib" ]
I'd like to create a stacked histogram. If I have a single 2-D array, made of three equal length data sets, this is simple. Code and image below: ``` import numpy as np from matplotlib import pyplot as plt # create 3 data sets with 1,000 samples mu, sigma = 200, 25 x = mu + sigma*np.random.randn(1000,3) #Stack the d...
Well, this is simple. I just need to put the three arrays in a list. ``` ##Continued from above ###Now as three separate arrays x1 = mu + sigma*np.random.randn(990,1) x2 = mu + sigma*np.random.randn(980,1) x3 = mu + sigma*np.random.randn(1000,1) #Stack the data plt.figure() plt.hist([x1,x2,x3], bins, stacked=True, no...
In Python, how to test whether a line is the last one?
18,449,646
5
2013-08-26T17:30:41Z
18,449,683
13
2013-08-26T17:32:35Z
[ "python" ]
Suppose I want to process each line of a file, but the last line needs special treatment: ``` with open('my_file.txt') as f: for line in f: if <line is the last line>: handle_last_line(line) else: handle_line(line) ``` The question is, how does one implement ? There seems t...
Process the **previous** line: ``` with open('my_file.txt') as f: line = None previous = next(f, None) for line in f: handle_line(previous) previous = line if previous is not None: handle_last_line(previous) ``` When the loop terminates, you know that the last line was just re...
What is the right way to compress and decompress UTF-8 data using zlib?
18,449,678
5
2013-08-26T17:32:26Z
27,077,366
7
2014-11-22T12:26:56Z
[ "python", "json", "utf-8", "compression" ]
I have a very long JSON message that contains characters that go beyond the ASCII table. I convert it into a string as follows: ``` messStr = json.dumps(message,encoding='utf-8', ensure_ascii=False, sort_keys=True) ``` I need to store this string using a service that restricts its size to X bytes. I want to split the...
A little addition to Martijn's response. I read [in an Enthought blog](http://blog.enthought.com/general/compressing-text-using-pythons-unicode-support/#.VHBO7otJyqw) a nifty one liner statement that will spare you the need to import zlib in your own code. Safely compressing a string (including your json dump) would l...
Python Indexing with List of Indices to Exclude
18,450,835
5
2013-08-26T18:42:48Z
18,450,875
8
2013-08-26T18:45:27Z
[ "python", "list", "indexing" ]
This is similar to some other questions ([Explicitly select items from a Python list or tuple](http://stackoverflow.com/questions/6632188/explicitly-select-items-from-a-python-list-or-tuple), [Grabbing specific indices of a list in Python](http://stackoverflow.com/questions/17904791/grabbing-specific-indices-of-a-list-...
``` >>> to_exclude = {1, 2} >>> vector = ['a', 'b', 'c', 'd'] >>> vector2 = [element for i, element in enumerate(vector) if i not in to_exclude] ``` The tricks here are: * Use a list comprehension to transform one list into another. (You can also use the `filter` function, especially if the predicate you're filtering...
error: invalid command 'bdist_egg'
18,451,823
10
2013-08-26T19:44:20Z
18,452,363
10
2013-08-26T20:20:20Z
[ "python", "python-2.7", "setup.py", "egg" ]
I am running: Ubuntu 13.04 Python 2.7.4 I am trying this [very simple tutorial](http://www.mxm.dk/2008/02/python-eggs-simple-introduction.html) on making a python egg, but am having difficulties when I actually try to run the command to make the egg. ``` <me>@<compname>:~/Desktop/SANDBOX/somedir$ python setup.p...
`bdist_egg` is a command supplied by `setuptools`. Make sure you import from that project in `setup.py`, *not* from `distutils`: ``` from setuptools import setup ``` The tutorial does tell you to do this, but it appears you missed that part.
fast python numpy where functionality?
18,452,591
8
2013-08-26T20:37:14Z
18,453,609
7
2013-08-26T21:49:31Z
[ "python", "performance", "for-loop", "numpy", "where" ]
I am using numpy's where function many times inside several `for` loops, but it becomes way too slow. Are there any ways to perform this functionality faster? I read you should try to do in-line for loops, as well as make local variables for functions before the `for` loops, but nothing seems to improve speed by much (...
Can use `np.unique` with `return_index`: ``` def using_sort(): #UNIQ_IDS,uind=np.unique(obj_data, return_inverse=True) uind= np.digitize(obj_data.ravel(), UNIQ_IDS) - 1 vals=uind.argsort() count=np.bincount(uind) start=0 end=0 out=np.empty(count.shape[0]) for ind,x in np.ndenumerate(c...
Removing all HTML tags along with their content from text
18,453,176
6
2013-08-26T21:17:43Z
18,453,346
11
2013-08-26T21:30:46Z
[ "python", "html", "html-parsing", "beautifulsoup" ]
I am wondering how I can delete all HTML tags along with their contents using `BeautifulSoup`. Input: ``` ... text <strong>ha</strong> ... text ``` Output: ``` ... text ... text ```
Use [`replace_with()`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#replace-with) (or `replaceWith()`): ``` from bs4 import BeautifulSoup, Tag text = "text <strong>ha</strong> ... text" soup = BeautifulSoup(text) for tag in soup.find_all('strong'): tag.replaceWith('') print soup.get_text() ``` print...
func(*args, **kwargs, x) throwing invalid syntax
18,453,290
4
2013-08-26T21:26:34Z
18,453,296
10
2013-08-26T21:27:08Z
[ "python" ]
Studied myself into a corner again... ``` def superfunction(*args, **kwargs, k): ^ SyntaxError: invalid syntax ``` Whats the rule Im breaking here? It seems that youre not supposed to mix 'regular' variables with \* variables, but I cant find anyone to confirm or deny this. I read som...
Try this: ``` def superfunction(k, *args, **kwargs): ``` The `**kwargs` variable keyword parameter must be the last part in the function declaration. Second-to-last, the `*args` variable position parameter. (In Python 3.x only, you can also have keyword-only parameters between `*args` and `**kwargs`.) And in the firs...
Comparing pandas.Series for equality when they contain nan?
18,453,442
7
2013-08-26T21:37:02Z
18,453,481
7
2013-08-26T21:40:33Z
[ "python", "numpy", "pandas" ]
My application needs to compare Series instances that sometimes contain nans. The key issue is that: ``` >>> (Series([1, nan]) == Series([1, nan])).all() False ``` Since `nan != nan`. What's the proper way to compare such Series?
How about this. First check the NaNs are in the same place (using [isnull](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html)): ``` In [11]: s1.isnull() Out[11]: 0 False 1 True dtype: bool In [12]: s1.isnull() == s2.isnull() Out[12]: 0 True 1 True dtype: bool ``` Then che...
What is the most pythonic way to call a method with optional parameters?
18,453,511
3
2013-08-26T21:42:03Z
18,453,615
7
2013-08-26T21:49:51Z
[ "python", "python-2.7", "optional-parameters" ]
Let's say I have a method with a few optional parameters. `def foo(a, b=1, c=2, d=3)` How do I go about calling it so that if my variables are None or empty strings the defaults are used? Conditionals like the following seems like a horrible solution: ``` if b and not c and d: foo(myA, b = myB, d = myD) elif b ...
I would change `foo` so it replaces empty values with default ones. ``` def foo(a, b=None, c=None, d=None): if not b: b = 1 if not c: c = 2 if not d: d = 3 ``` Note that this will treat all "false-y" values as defaults, meaning not only `None` and `''` but also `0`, `False`, `[]`, etc. Personally I would ...
Python dictionary: Get list of values for list of keys
18,453,566
56
2013-08-26T21:45:38Z
18,453,567
67
2013-08-26T21:45:38Z
[ "python", "list", "dictionary", "key" ]
Is there a built-in/quick way to use a list of keys to a dictionary to get a list of corresponding items? For instance I have: ``` >>> mydict = {'one': 1, 'two': 2, 'three': 3} >>> mykeys = ['three', 'one'] ``` How can I use `mykeys` to get the corresponding values in the dictionary as a list? ``` >>> mydict.WHAT_G...
A list comprehension seems to be a good way to do this: ``` >>> [mydict[x] for x in mykeys] [3, 1] ```
Python dictionary: Get list of values for list of keys
18,453,566
56
2013-08-26T21:45:38Z
18,453,871
30
2013-08-26T22:10:27Z
[ "python", "list", "dictionary", "key" ]
Is there a built-in/quick way to use a list of keys to a dictionary to get a list of corresponding items? For instance I have: ``` >>> mydict = {'one': 1, 'two': 2, 'three': 3} >>> mykeys = ['three', 'one'] ``` How can I use `mykeys` to get the corresponding values in the dictionary as a list? ``` >>> mydict.WHAT_G...
A couple of other ways than list-comp: * Build list and throw exception if key not found: `map(mydict.__getitem__, mykeys)` * Build list with `None` if key not found: `map(mydict.get, mykeys)` Alternatively, using `operator.itemgetter` can return a tuple: ``` from operator import itemgetter myvalues = itemgetter(*my...
Python dictionary: Get list of values for list of keys
18,453,566
56
2013-08-26T21:45:38Z
34,452,268
10
2015-12-24T11:42:13Z
[ "python", "list", "dictionary", "key" ]
Is there a built-in/quick way to use a list of keys to a dictionary to get a list of corresponding items? For instance I have: ``` >>> mydict = {'one': 1, 'two': 2, 'three': 3} >>> mykeys = ['three', 'one'] ``` How can I use `mykeys` to get the corresponding values in the dictionary as a list? ``` >>> mydict.WHAT_G...
A little speed comparison: ``` Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec 7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32 In[1]: l = [0,1,2,3,2,3,1,2,0] In[2]: m = {0:10, 1:11, 2:12, 3:13} In[3]: %timeit [m[_] for _ in l] # list comprehension 1000000 loops, best of 3: 762 ns per loop In[4]: %timeit...
Opacity misleading when plotting two histograms at the same time with matplotlib
18,453,570
4
2013-08-26T21:45:52Z
18,466,428
7
2013-08-27T13:11:01Z
[ "python", "matplotlib", "opacity", "histogram" ]
Let's say I have two histograms and I set the opacity using the parameter of hist: 'alpha=0.5' I have plotted two histograms yet I get three colors! I understand this makes sense from an opacity point of view. But! It makes is very confusing to show someone a graph of two things with three colors. Can I just somehow ...
The usual way this issue is handled is to have the plots with some small separation. This is done by default when `plt.hist` is given multiple sets of data: ``` import pylab as plt x = 200 + 25*plt.randn(1000) y = 150 + 25*plt.randn(1000) n, bins, patches = plt.hist([x, y]) ``` ![Example 1](http://i.stack.imgur.com/...