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
How to use PyCharm to debug Scrapy projects
21,788,939
45
2014-02-14T20:27:14Z
23,462,150
27
2014-05-04T22:09:56Z
[ "python", "debugging", "python-2.7", "scrapy", "pycharm" ]
I am working on Scrapy 0.20 with Python 2.7. I found PyCharm has a good Python debugger. I want to test my Scrapy spiders using it. Anyone knows how to do that please? ### What I have tried Actually I tried to run the spider as a scrip. As a result, I built that scrip. Then, I tried to add my Scrapy project to PyChar...
You just need to do this. Create a Python file on crawler folder on your project. I used main.py. * Project + Crawler - Crawler * Spiders * ... - **main.py** - scrapy.cfg Inside your main.py put this code below. ``` from scrapy import cmdline cmdline.execute("scrapy crawl spider".split...
Split list into different variables
21,791,482
2
2014-02-14T23:48:27Z
21,791,491
9
2014-02-14T23:49:02Z
[ "python", "list" ]
I have a list like this: `[('love', 'yes', 'no'), ('valentine', 'no', 'yes'), ('day', 'yes','yes')]` How do I split this list into three variables with each variable holding only `('love', 'yes', 'no')`, `('valentine', 'no', 'yes')`, `('day', 'yes','yes')` respectively?
Assign to three names: ``` var1, var2, var3 = listobj ``` Demo: ``` >>> listobj = [('love', 'yes', 'no'), ('valentine', 'no', 'yes'), ('day', 'yes','yes')] >>> var1, var2, var3 = listobj >>> var1 ('love', 'yes', 'no') >>> var2 ('valentine', 'no', 'yes') >>> var3 ('day', 'yes', 'yes') ```
Python: Passing a list through a recursive function call causes the list to become 'NoneType', why?
21,792,571
6
2014-02-15T02:17:12Z
21,792,579
8
2014-02-15T02:18:45Z
[ "python", "recursion", "nonetype" ]
I have the following recursive function: ``` def recurse(y,n): if len(y) == n: return y else: return recurse(y.append(1),n) ``` When I run it: ``` x=recurse([],10) ``` I get the following error: ``` TypeError: object of type 'NoneType' has no len() ``` It seems that the function gets past ...
The problem is here: ``` y.append(1) ``` The `append()` method returns `None`, so you can't pass its result for building the output list (you'd have to first `append` to the list and then pass it, as shown in other answers). Try this instead: ``` def recurse(y, n): if len(y) == n: return y else: ...
Python: How to get multiple variables from a URL in Flask?
21,796,672
4
2014-02-15T11:08:54Z
21,796,711
11
2014-02-15T11:12:35Z
[ "python", "url", "get", "request", "flask" ]
I'm trying to get multiple arguments from a url in Flask. After reading [this SO answer](http://stackoverflow.com/a/15182724/1650012) I thought I could do it like this: ``` @app.route('/api/v1/getQ/', methods=['GET']) def getQ(request): print request.args.get('a') print request.args.get('b') return "lalala...
You misread the error message; the exception is about how `getQ` is called with *python* arguments, not how many URL parameters you added to invoke the view. Flask views don't take `request` as a function argument, but use it as a global context instead. Remove `request` from the function signature: ``` from flask im...
Django [Errno 13] Permission denied: '/var/www/media/animals/user_uploads'
21,797,372
9
2014-02-15T12:11:30Z
21,797,786
21
2014-02-15T12:50:49Z
[ "python", "linux", "django", "apache", "ubuntu" ]
I am developing a django API which will be running on top of Apache2 via WSGI on a server running Ubuntu. Users will be able to upload pictures they take to the server using a POST request. The API processes this request and then attempts to write the image to `/var/www/media/animals/user_uploads/<animal_type>/<pictur...
I have solved this myself in the end. When running on the development machines, I am in fact running using my current user's privileges. However, when running on the deployment server, I am in fact running through `wsgi`, which means it's running using `www-data`'s privileges. `www-data` is neither the owner nor in t...
Sending xml by SUDS
21,797,389
8
2014-02-15T12:13:00Z
21,800,232
12
2014-02-15T16:22:11Z
[ "python", "web-services", "suds" ]
I would like to send my hand build xml by SUDS using WSDL. I found, that I can do it like that: ``` xml = Raw(""" <SOAP-ENV:Envelope xmlns:ns0="urn:ca:std:cdc:tech:xsd:cdc.001.01" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas....
According to the suds documentation, you can send a raw SOAP message using the [`__inject`](https://fedorahosted.org/suds/wiki/Documentation#MESSAGEINJECTIONDiagnosticsTesting) argument to the method you're calling: ``` client.service.GetAccountBalance(__inject={'msg': xml}) ```
common letters in two strings
21,798,222
3
2014-02-15T13:31:08Z
21,798,232
7
2014-02-15T13:32:25Z
[ "python", "string" ]
I've been trying to solve this program which takes two strings as input and outputs number of common letters. For Example, if the input was "common" and "connor" then the output should be 4 ( 1 c , 1 n and 2 o's ).I used set() function but it outputs 3 ( it treats both o's as a single common letter ). Any help would be...
Use [`collections.Counter`](http://docs.python.org/3/library/collections.html#collections.Counter): ``` >>> from collections import Counter >>> Counter('common') Counter({'m': 2, 'o': 2, 'c': 1, 'n': 1}) >>> Counter('connor') Counter({'o': 2, 'n': 2, 'c': 1, 'r': 1}) >>> common = Counter('common') & Counter('connor'...
Python Pandas: Get index of rows which column matches certain value
21,800,169
31
2014-02-15T16:18:11Z
21,800,319
55
2014-02-15T16:28:46Z
[ "python", "indexing", "pandas" ]
Given a DataFrame with a column "BoolCol", we want to find the indexes of the DataFrame in which the values for "BoolCol" == True I currently have the iterating way to do it, which works perfectly: ``` for i in range(100,3000): if df.iloc[i]['BoolCol']== True: print i,df.iloc[i]['BoolCol'] ``` But this ...
`df.iloc[i]` returns the `ith` row of `df`. `i` does not refer to the index value, `i` is a 0-based index. In contrast, the attribute `index` is returning index values: ``` df[df['BoolCol'] == True].index.tolist() ``` or equivalently, ``` df[df['BoolCol']].index.tolist() ``` You can see the difference quite clearl...
py.test: ImportError: No module named mysql
21,800,582
7
2014-02-15T16:47:58Z
21,800,862
14
2014-02-15T17:11:34Z
[ "python", "mysql", "virtualenv", "py.test" ]
I have problems running py.test over packages that imports mysql. The package mysql was installed with pip in a virtualenv. ``` # test_mysql.py import mysql def foo(): pass ``` I can run without any problem `python test_mysql.py`, but when I execute `py.test test_mysql.py` I get: ``` > import mysql E ImportE...
It seems like you're using system-wide version of `py.test` which use non-virtualenv-version of python. (In which, `mysql` package is not installed). Install `py.test` inside the virtualenv, then your problem will be solved. --- **SIDE NOTE** To make sure you're using the newly-installed `py.test`, clear the comman...
Comparing two large lists in python
21,801,616
13
2014-02-15T18:13:55Z
21,801,647
12
2014-02-15T18:17:11Z
[ "python", "performance", "list", "numpy" ]
I have one list which contains about 400 words. And another list of lists, in which each list contains about 150,000 words. This list has 20 such lists. Now I want to see how many of these 400 words appear in all of these 150,000 words list. I also want to know a word from this 400 words, appear how many times in 150k...
This sounds like a good opportunity for using a [`set`](http://docs.python.org/2/library/stdtypes.html#set): ``` set_of_150kwords = set(list_of_150kwords) one_set = set(one_list) len(one_set & set_of_150kwords) # set intersection is & => number of elements common to both sets ``` As per set theory, the intersection ...
Unable to set file content type in S3
21,801,706
5
2014-02-15T18:22:25Z
21,802,871
11
2014-02-15T20:00:42Z
[ "python", "amazon-s3", "boto" ]
How do you set content type on a file in a webhosting-enabled S3 account via the Python boto module? I'm doing: ``` from boto.s3.connection import S3Connection from boto.s3.key import Key from boto.cloudfront import CloudFrontConnection conn = S3Connection(access_key_id, secret_access_key) bucket = conn.create_bucke...
The `set_metadata` method is really for setting user metadata on S3 objects. Many of the standard HTTP metadata fields have first class attributes to represent them, e.g. `content_type`. Also, you want to set the metadata before you actually send the object to S3. Something like this should work: ``` import boto conn...
Error: Setting an array element with a sequence. Python / Numpy
21,803,256
8
2014-02-15T20:31:05Z
21,803,517
7
2014-02-15T20:53:46Z
[ "python", "arrays", "numpy" ]
I'm receiving this error when trying to assign an array to another array specific position. I was doing this before creating simple lists and doing such assignment. But Numpy is faster than simple lists and I was trying to use it now. The problem is cause I have a 2D array that stores some data and, in my code, I have...
You could add another dimension of size 3 to your array. ``` import numpy as np cols = 2 rows = 3 matrix_b = np.zeros((rows, cols, 3)) matrix_b[0, 0] = np.array([0, 0, 1]) matrix_b[0, 0] = [0, 0, 1] #This also works ``` Another option is to set the dtype to `list` and then you can set each element to a list. But t...
Error: Setting an array element with a sequence. Python / Numpy
21,803,256
8
2014-02-15T20:31:05Z
21,808,641
13
2014-02-16T07:48:24Z
[ "python", "arrays", "numpy" ]
I'm receiving this error when trying to assign an array to another array specific position. I was doing this before creating simple lists and doing such assignment. But Numpy is faster than simple lists and I was trying to use it now. The problem is cause I have a 2D array that stores some data and, in my code, I have...
The trouble is that matrix\_b is defaulting to a float dtype. On my machine, checking ``` matrix_b.dtype ``` returns `dtype('float64')`. To create a numpy array that can hold anything, you can manually set dtype to object, which will allow you to place a matrix inside of it: ``` matrix_b = np.zeros((rows, cols), dty...
Docopt: options after repeating elements are interpeted as repeating elements
21,804,165
6
2014-02-15T21:56:05Z
21,804,457
8
2014-02-15T22:22:50Z
[ "python", "docopt" ]
I am using *[docopt](http://docopt.org/)* in my simple Python program: ``` #!/usr/bin/env python """ Farmers market Usage: farmersmarket.py buy -i <item> -q <quantity> [<quantity>] [-p <price>] [-dvh] farmersmarket.py -d | --debug farmersmarket.py -v | --version farmersmarket.py -h | --help Options: -i --i...
actually, you forgot to add the `<price>` argument to the `Options:` description part ; the following code: ``` #!/usr/bin/env python """ Farmers market Usage: farmersmarket.py buy -i <item> -q <quantity> [<quantity>] [-p <price>] [-dvh] farmersmarket.py -d | --debug farmersmarket.py -v | --version farmersmar...
QTreeWidget to Mirror python Dictionary
21,805,047
3
2014-02-15T23:22:10Z
21,806,048
7
2014-02-16T01:21:09Z
[ "python", "qt", "pyqt", "qtreewidget" ]
Is there a way to make a `QTreeWidget` mirror the changes made to an internal data structure such as dictionary? It seems like they would have created this functionality within the api, because there are many programs which may interact with `QTreeWidget`s from multiple GUI areas, but the main purpose required of the `...
This is a straightforward implementation: ``` def fill_item(item, value): item.setExpanded(True) if type(value) is dict: for key, val in sorted(value.iteritems()): child = QTreeWidgetItem() child.setText(0, unicode(key)) item.addChild(child) fill_item(child, val) elif type(value) is l...
Python Regex - checking for a capital letter with a lowercase after
21,805,490
5
2014-02-16T00:07:42Z
21,805,505
9
2014-02-16T00:09:31Z
[ "python", "regex", "string" ]
I am trying to check for a capital letter that has a lowercase letter coming directly after it. The trick is that there is going to be a bunch of garbage capital letters and number coming directly before it. For example: ``` AASKH317298DIUANFProgramming is fun ``` as you can see, there is a bunch of stuff we don't ne...
Use a negative look-ahead: ``` re.sub(r'^[A-Z0-9]*(?![a-z])', '', string) ``` This matches any uppercase character or digit that is *not* followed by a lowercase character. Demo: ``` >>> import re >>> string = 'AASKH317298DIUANFProgramming is fun' >>> re.sub(r'^[A-Z0-9]*(?![a-z])', '', string) 'Programming is fun' ...
Python - list in a list string reversing with sort
21,805,872
2
2014-02-16T00:55:26Z
21,805,885
7
2014-02-16T00:57:41Z
[ "python", "string", "sorting" ]
I am trying to sort lists in a list by an int, then by a string. ``` lst = [['Bob', 22], ['Jim', 33], ['Stan', 22]] lst.sort(key = lambda x: (x[1], -x[0]), reverse = True) ``` As you can see, I am trying to sort them by their age and then by their names if they have the same age, in descending order. This, however, r...
Sort straight-ahead (not reversed) and negate the *age* instead: ``` lst.sort(key=lambda x: (-x[1], x[0])) ``` This sorts on age in descending order (since -33 will sort before -22), then on name in alphabetical order. Demo: ``` >>> lst = [['Stan', 22], ['Jim', 33], ['Bob', 22]] >>> sorted(lst, key=lambda x: (-x[1]...
Pandas seems to ignore first column name when reading tab-delimited data, gives KeyError
21,806,496
7
2014-02-16T02:25:03Z
21,811,763
13
2014-02-16T13:29:56Z
[ "python", "pandas", "ipython", "tab-delimited", "keyerror" ]
I am using pandas 0.12.0 in ipython3 on Ubuntu 13.10, in order to wrangle large tab-delimited datasets in txt files. Using read\_table to create a DataFrame from the txt appears to work, and the first row is read as a header, but attempting to access the first column using its name as an index throws a KeyError. I don'...
This seems to be (related to) a known issue, see [GH #4793](https://github.com/pydata/pandas/issues/4793). Using `'utf-8-sig'` as the encoding seems to work. Without it, we have: ``` >>> df = pd.read_table("datafile.txt") >>> df.columns Index([u'RECORDING_SESSION_LABEL', u'LEFT_GAZE_X', u'LEFT_GAZE_Y', u'RIGHT_GAZE_X'...
Combine two weighted graphs in NetworkX
21,806,751
3
2014-02-16T03:02:55Z
21,811,980
7
2014-02-16T13:45:43Z
[ "python", "networkx" ]
I'm using python multiprocessing to create multiple different NetworkX graphs and then using the below function to combine the graphs. However, while this function works fine for small graphs, for larger graphs it uses a huge amount of memory and hangs on both my system and a memory-heavy AWS system (using only about a...
There are two places where memory will expand in your code: 1) making a copy of graph1 (perhaps you need to keep a copy though) 2) using graph2.edges() makes a list of all edges in memory, graph2.edges\_iter() iterates over the edges without creating a new list You can probably make it faster by handling the edge da...
Failed to load OpenCL runtime in OpenCV for Python
21,807,660
3
2014-02-16T05:21:40Z
22,878,498
10
2014-04-05T08:29:54Z
[ "python", "opencv", "ubuntu", "opencl" ]
I am trying to run the first example [here](http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html), but I am getting this error. I am using Ubuntu 13.10. ``` Failed to load OpenCL runtime OpenCV Error: Unknown error code -220 (OpenCL function is not availabl...
As for the OpenCL failure, try installing required packages: `sudo apt-get install ocl-icd-opencl-dev` Worked for me. My guess is that OCL is a part of the `opencv_core` module, and if it failed to initialise, then many other components might behave strange.
cv2.imshow command doesn't work properly in opencv-python
21,810,452
24
2014-02-16T11:24:54Z
21,810,481
47
2014-02-16T11:27:52Z
[ "python", "opencv", "image-processing" ]
I'm using opencv 2.4.2, python 2.7 The following simple code created a window of the correct name, but its content is just blank and doesn't show the image: ``` import cv2 img=cv2.imread('C:/Python27/03323_HD.jpg') cv2.imshow('ImageWindow',img) ``` does anyone knows about this issue?
imshow() only works with waitKey() ``` import cv2 img=cv2.imread('C:/Python27/03323_HD.jpg') cv2.imshow('ImageWindow',img) cv2.waitKey() ``` (the whole message-loop nessecary for updating the window is hidden in there)
cv2.imshow command doesn't work properly in opencv-python
21,810,452
24
2014-02-16T11:24:54Z
29,584,090
18
2015-04-11T23:07:46Z
[ "python", "opencv", "image-processing" ]
I'm using opencv 2.4.2, python 2.7 The following simple code created a window of the correct name, but its content is just blank and doesn't show the image: ``` import cv2 img=cv2.imread('C:/Python27/03323_HD.jpg') cv2.imshow('ImageWindow',img) ``` does anyone knows about this issue?
I found the answer that worked for me here: <http://txt.arboreus.com/2012/07/11/highgui-opencv-window-from-ipython.html> > If you run an interactive ipython session, and want to use highgui > windows, do cv2.startWindowThread() first. > > In detail: HighGUI is a simplified interface to display images and > video from ...
How to shove this loop into numpy?
21,811,381
3
2014-02-16T12:54:17Z
21,818,591
9
2014-02-17T00:05:55Z
[ "python", "performance", "loops", "for-loop", "numpy" ]
I have a slow loop that I want to make (much) faster by pushing it into numpy. I have spent days playing with this code without getting anywhere. Is it even possible, or is there a numpy trick I am missing? Is there some refactoring I can do to help? As you can see, I want to sum the mixins as shifted by the xs. ``` ...
Get Numba 0.11 (not 0.12 yet) from numba.pydata.org. Now we can jit compile this code with LLVM: ``` # plain NumPy version import numpy as np def foobar(mixinsize, count, xs, mixins, acc): for i in xrange(count): k = xs[i] acc[k:k + mixinsize] += mixins[i,:] # LLVM compiled version from numba im...
Split datetime64 column into a date and time column in pandas dataframe
21,811,641
4
2014-02-16T13:20:30Z
21,811,766
16
2014-02-16T13:30:02Z
[ "python", "pandas" ]
If I have a dataframe with the first column being a datetime64 column. How do I split this column into 2 new columns, a date column and a time column. Here is my data and code so far: ``` DateTime,Actual,Consensus,Previous 20140110 13:30:00,74000,196000,241000 20131206 13:30:00,241000,180000,200000 20131108 13:30:00,2...
**How to parse the CSV directly into the desired DataFrame:** Pass a dict of functions to `pandas.read_csv`'s `converters` keyword argument: ``` import pandas as pd import datetime as DT nfp = pd.read_csv("NFP.csv", sep=r'[\s,]', # 1 header=None, skiprows=1, ...
Python: calling method in the map function
21,814,230
2
2014-02-16T16:46:31Z
21,814,240
8
2014-02-16T16:47:16Z
[ "python", "methods", "list-comprehension", "map-function" ]
`map()` and list comprehension are roughly equivalent: ``` map(function, list1) [function(i) for i in list1] ``` What if the function we want to use is a method? ``` [i.function() for i in list1] map(.function, list1) # error! map(run_method(function), list1) # error! ``` How could I perform this kind of manipulati...
You'd use [`operator.methodcaller()`](http://docs.python.org/2/library/operator.html#operator.methodcaller): ``` from operator import methodcaller map(methodcaller('function'), list1) ``` `methodcaller()` accepts additional arguments that are then passed into the called method; `methodcaller('foo', 'bar', spam='eggs...
How do I validate wtforms fields against one another?
21,815,067
9
2014-02-16T17:52:36Z
21,815,180
12
2014-02-16T18:00:49Z
[ "python", "validation", "flask", "wtforms", "flask-wtforms" ]
I have three identical `SelectField` inputs in a form, each with the same set of options. I can't use one multiple select. I want to make sure that the user selects three different choices for these three fields. In custom validation, it appears that you can only reference one field at a time, not compare the value o...
You can override `validate` in your `Form`... ``` class MyForm(Form): select1 = SelectField('Select 1', ...) select2 = SelectField('Select 2', ...) select3 = SelectField('Select 3', ...) def validate(self): if not Form.validate(self): return False result = True seen ...
numpy: how to fill multiple fields in a structured array at once
21,818,140
3
2014-02-16T23:17:10Z
21,818,731
8
2014-02-17T00:24:00Z
[ "python", "numpy", "structured-array" ]
Very simple question: I have a structured array with multiple columns and I'd like to fill only some of them (but more than one) with another preexisting array. This is what I'm trying: ``` strc = np.zeros(4, dtype=[('x', int), ('y', int), ('z', int)]) x = np.array([2, 3]) strc[['x', 'y']][0] = x ``` This gives me t...
If all the field have the same dtype, you can create a view: ``` import numpy as np strc = np.zeros(4, dtype=[('x', int), ('y', int), ('z', int)]) strc_view = strc.view(int).reshape(len(strc), -1) x = np.array([2, 3]) strc_view[0, [0, 1]] = x ``` If you want a common solution that can create columns views of any stru...
How to fix the issue "PyPI-test not found in .pypic" when submit package to PyPI?
21,823,705
10
2014-02-17T08:04:06Z
22,430,122
10
2014-03-15T21:41:13Z
[ "python", "pip", "python-2.6", "easy-install", "pypi" ]
I followed the guide [How to submit a package to PyPI](http://peterdowns.com/posts/first-time-with-pypi.html) to submit one package. It throwed the error below: ``` Traceback (most recent call last): File "setup.py", line 27, in 'Programming Language :: Python', File "/usr/lib64/python2.6/dist...
Make sure your .pypirc file is in your /home directory.
In Python, how do I iterate over one iterator and then another?
21,825,984
48
2014-02-17T10:04:54Z
21,826,012
88
2014-02-17T10:05:55Z
[ "python", "file", "iteration" ]
I'd like to iterate two different iterators, something like this: ``` file1 = open('file1', 'r') file2 = open('file2', 'r') for item in one_then_another(file1, file2): print item ``` Which I'd expect to print all the lines of file1, then all the lines of file2. I'd like something generic, as the iterators might ...
Use [`itertools.chain`](http://docs.python.org/2/library/itertools.html#itertools.chain): ``` from itertools import chain for line in chain(file1, file2): pass ``` [`fileinput`](http://docs.python.org/2/library/fileinput.html#fileinput.input) module also provides a similar feature: ``` import fileinput for line i...
In Python, how do I iterate over one iterator and then another?
21,825,984
48
2014-02-17T10:04:54Z
21,826,406
17
2014-02-17T10:24:26Z
[ "python", "file", "iteration" ]
I'd like to iterate two different iterators, something like this: ``` file1 = open('file1', 'r') file2 = open('file2', 'r') for item in one_then_another(file1, file2): print item ``` Which I'd expect to print all the lines of file1, then all the lines of file2. I'd like something generic, as the iterators might ...
You can also do it with simple **[generator expression](http://www.python.org/dev/peps/pep-0289/)**: ``` for line in (l for f in (file1, file2) for l in f): # do something with line ``` with this method you can specify some **condition** in expression itself: ``` for line in (l for f in (file1, file2) for l in f...
In Python, how do I iterate over one iterator and then another?
21,825,984
48
2014-02-17T10:04:54Z
21,837,185
7
2014-02-17T19:01:44Z
[ "python", "file", "iteration" ]
I'd like to iterate two different iterators, something like this: ``` file1 = open('file1', 'r') file2 = open('file2', 'r') for item in one_then_another(file1, file2): print item ``` Which I'd expect to print all the lines of file1, then all the lines of file2. I'd like something generic, as the iterators might ...
I think the most Pythonic approach to this particular file problem is to use the `fileinput` module (since you either need complex context managers or error handling with `open`), I'm going to start with Ashwini's example, but add a few things. The first is that it's better to open with the `U` flag for Universal Newli...
Cython setup.py for several .pyx
21,826,137
5
2014-02-17T10:11:12Z
21,826,294
11
2014-02-17T10:19:40Z
[ "python", "compilation", "installation", "cython", "setup.py" ]
I would like to cythonize faster. Code for one .pyx is ``` from distutils.core import setup from Cython.Build import cythonize setup( ext_modules = cythonize("MyFile.pyx") ) ``` What if i want to cythonize * several files with ext .pyx, that i will call by their name * all .pyx files in a folder What would be ...
From: <https://github.com/cython/cython/wiki/enhancements-distutils_preprocessing> ``` # several files with ext .pyx, that i will call by their name from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules=[ Extension("primes", ["primes.py...
using python WeakSet to enable a callback functionality
21,826,700
9
2014-02-17T10:35:55Z
21,941,670
10
2014-02-21T17:52:44Z
[ "python", "callback", "destructor", "weak-references" ]
I'm investigating if I can implement an easy callback functionality in python. I thought I might be able to use weakref.WeakSet for this, but there is clearly something I'm missing or have misunderstood. As you can see in the code I first tried with a list of call back methods in 'ClassA' objects, but realized that thi...
You cannot create weak references to method objects. Method objects are *short lived*; they are created on the fly as you access the name on the instance. See the [descriptor howto](http://docs.python.org/2/howto/descriptor.html) how that works. When you access a method name, a *new* method object is created for you, ...
Setting up a virtualenv: No module named 'pip'
21,826,859
10
2014-02-17T10:42:29Z
21,829,823
17
2014-02-17T13:01:53Z
[ "python", "virtualenv", "pip", "importerror" ]
I have a fresh install of Python 3.3.4 on a Windows Server 2008 R2 machine. I've successfully installed the latest versions of Setuptools, Pip and Virtualenv globally: ``` python ez_setup.py easy_install pip pip install virtualenv ``` Now when I try to set up a virtualenv using `virtualenv ENV` I get the following st...
Useful workaround from the Python bug ticket for anybody else with this issue: * Run `virtualenv venv --no-setuptools` * Activate that virtualenv (venv\Scripts\activate) * Download and run [get-pip.py](https://raw.github.com/pypa/pip/master/contrib/get-pip.py) to manually install pip & setuptools into this virtualenv ...
Timeout a python function in windows
21,827,874
6
2014-02-17T11:29:32Z
21,861,599
7
2014-02-18T17:51:42Z
[ "python", "python-2.7", "timeout" ]
I am trying to implement timeout for a particular function. I have checked many of the questions in SE and couldn't find any solution which fits my problem, because 1. I am running python in Windows 2. Timeout is applied on a python function which I don't have control on, i.e, it is defined in an already designed modu...
i think a good way to approach this is to create a decorator and use the Thread.join(timeout) method. bear in mind that there's no good way to kill the thread, so it will continue to run in the background, more or less, as long as your program is running. first, create a decorator like this: ``` from threading import...
How to format with a UNICODE string to JINJA's variable in a template?
21,828,102
5
2014-02-17T11:39:52Z
21,828,209
9
2014-02-17T11:44:38Z
[ "python", "django", "jinja2" ]
How to set format a string with unicode value in Jinja2 template? ``` {% set left='<span class="link" onclick="toggleLoginRegister(this)">{0}</span>'.format( registerHint ) %} ``` Raises UnicodeEncodeError if **registerHint** is a unicode string. Otherwise doesn't.
Use the [`|format()` filter](http://jinja.pocoo.org/docs/templates/#format) instead and Jinja will decode your string literal to `unicode` for you: ``` {% set left='<span class="link" onclick="toggleLoginRegister(this)">%s</span>'|format( registerHint ) %} ```
Concise flexible struct definition
21,832,165
7
2014-02-17T14:52:39Z
21,832,268
7
2014-02-17T14:56:40Z
[ "python" ]
I need to define a bunch of flexible structs (objects with a simple collection of named fields, where you can add new fields later, but I don't need methods or inheritance or anything like that) in Python 2.7. (The context is that I'm reading stuff from binary files with struct.unpack\_from, then adding further data to...
A pattern that I found sometimes useful is ``` class Obj(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) ``` and you can use it like ``` p = Obj(x=10, y=20) ```
Why does pylint object to single character variable names?
21,833,872
20
2014-02-17T16:08:02Z
21,833,974
20
2014-02-17T16:12:20Z
[ "python", "pylint", "naming-conventions" ]
I'm still getting used to python conventions and using `pylint` to make my code more pythonic, but I'm puzzled by the fact that pylint doesn't like single character variable names. I have a few loops like this: ``` for x in x_values: my_list.append(x) ``` and when I run `pylint`, I'm getting `Invalid name "x" for ...
PyLint checks not only PEP8 recomendations. It has also its own recommendations, one of which is that a variable name should be descriptive and not too short. You can use this to avoid such short names: ``` my_list.extend(x_values) ``` Or use `_` as a placeholder for temporary variables (which the regex will pass)
Why does pylint object to single character variable names?
21,833,872
20
2014-02-17T16:08:02Z
21,834,413
7
2014-02-17T16:33:39Z
[ "python", "pylint", "naming-conventions" ]
I'm still getting used to python conventions and using `pylint` to make my code more pythonic, but I'm puzzled by the fact that pylint doesn't like single character variable names. I have a few loops like this: ``` for x in x_values: my_list.append(x) ``` and when I run `pylint`, I'm getting `Invalid name "x" for ...
The deeper reason is that you may remember what you intended `a`, `b`, `c`, `x`, `y`, and `z` to mean when you wrote your code, but when others read it, or even when you come back to your code, the code becomes much more readable when you give it a semantic name. We're not writing stuff once on a chalkboard and then er...
interpolate 3D volume with numpy and or scipy
21,836,067
6
2014-02-17T17:56:03Z
28,858,633
7
2015-03-04T15:43:00Z
[ "python", "numpy", "3d", "scipy", "interpolation" ]
I am extremely frustrated because after several hours I can't seem to be able to do a seemingly easy 3D interpolation in python. In Matlab all I had to do was ``` Vi = interp3(x,y,z,V,xi,yi,zi) ``` What is the exact equivalent of this using scipy's ndimage.map\_coordinate or other numpy methods? Thanks
In scipy 0.14 or later, there is a new function [`scipy.interpolate.RegularGridInterpolator`](http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.RegularGridInterpolator.html#scipy.interpolate.RegularGridInterpolator) which closely resembles `interp3`. The MATLAB command `Vi = interp3(x,y,z,V,...
How to append new data onto a new line
21,839,803
13
2014-02-17T21:40:32Z
21,839,863
17
2014-02-17T21:43:49Z
[ "python", "file-io", "append" ]
My code looks like this: ``` def storescores(): hs = open("hst.txt","a") hs.write(name) hs.close() ``` so if I run it and enter "Ryan" then run it again and enter "Bob" the file hst.txt looks like ``` RyanBob ``` instead of ``` Ryan Bob ``` How do I fix this?
If you want a newline, you have to write one explicitly. The usual way is like this: ``` hs.write(name + "\n") ``` This uses a backslash escape, `\n`, which Python converts to a newline character in string literals. It just concatenates your string, `name`, and that newline character into a bigger string, which gets ...
How to efficiently apply an operator to the cartesian product of two arrays?
21,840,670
5
2014-02-17T22:35:43Z
21,840,695
10
2014-02-17T22:37:41Z
[ "python", "arrays", "performance", "numpy" ]
I have `a = array([1, 2, 3, 4, 5])` and `b = array([10, 20, 30, 40, 50])`. I want: ``` array([[ -9, -19, -29, -39, -49], [ -8, -18, -28, -38, -48], [ -7, -17, -27, -37, -47], [ -6, -16, -26, -36, -46], [ -5, -15, -25, -35, -45]]) ``` What's the most efficient way to do this? I have ``` np...
Some NumPy functions, like `np.subtract`, `np.add`, `np.multiply`, `np.divide`, `np.logical_and`, `np.bitwise_and`, etc. have an "outer" method which can be used to create the equivalent of "multiplication tables": ``` In [76]: np.subtract.outer(a, b) Out[76]: array([[ -9, -19, -29, -39, -49], [ -8, -18, -28, ...
empty function object in python
21,841,960
2
2014-02-18T00:20:11Z
21,842,093
9
2014-02-18T00:33:57Z
[ "python", "function", "design-patterns" ]
I've heard that python functions are objects, similar to lists or dictionaries, etc. However, what would be a similar way of performing this type of action with a function? ``` # Assigning empty list to 'a' a = list() # Assigning empty function to 'a' a = lambda: pass # ??? ``` How would you do this? Further, is it ...
First, the reason this doesn't work: ``` a = lamdba: pass ``` … is that [`lambda`](http://docs.python.org/3/reference/expressions.html#lambda) only allows an expression, and defines a function that returns the value of the expression. Since [`pass`](http://docs.python.org/3/reference/simple_stmts.html#the-pass-stat...
Python: Find a substring in a string and returning the index of the substring
21,842,885
15
2014-02-18T01:52:51Z
21,844,040
51
2014-02-18T03:57:14Z
[ "python", "string", "indexing", "substring" ]
For example i have a function def find\_str(s, char) and a string "Happy Birthday", i essentially want to input "py" and return 3 but i keep getting 2 to return instead. ``` def find_str(s, char): index = 0 if char in s: char = char[0] for ch in s: if ch in s: ...
There's a builtin method on string objects to do this in python you know? ``` s = "Happy Birthday" s2 = "py" print s.find(s2) ``` Python is a "batteries included language" there's code written to do most of what you want already (whatever you want).. unless this is homework :)
Weighted percentile using numpy
21,844,024
9
2014-02-18T03:55:32Z
29,677,616
12
2015-04-16T14:22:35Z
[ "python", "numpy", "weighted", "percentile" ]
Is there a way to use the numpy.percentile function to compute weighted percentile? Or is anyone aware of an alternative python function to compute weighted percentile? thanks!
## Completely vectorized numpy solution Here is the code I'm using. It's not an optimal one (which I'm unable write in `numpy`), but still much faster and more reliable than accepted solution ``` def weighted_quantile(values, quantiles, sample_weight=None, values_sorted=False, old_style=False): """ Very close to ...
Forming Bigrams of words in list of sentences with Python
21,844,546
5
2014-02-18T04:41:47Z
21,844,800
9
2014-02-18T05:04:29Z
[ "python", "list", "list-comprehension", "nltk", "collocation" ]
I have a list of sentences: ``` text = ['cant railway station','citadel hotel',' police stn']. ``` I need to form bigram pairs and store them in a variable. The problem is that when I do that, I get a pair of sentences instead of words. Here is what I did: ``` text2 = [[word for word in line.split()] for line in tex...
Using [list comprehensions](http://docs.python.org/3.3/tutorial/datastructures.html#list-comprehensions) and [zip](http://docs.python.org/3/library/functions.html#zip): ``` >>> text = ["this is a sentence", "so is this one"] >>> bigrams = [b for l in text for b in zip(l.split(" ")[:-1], l.split(" ")[1:])] >>> print(bi...
Access denied using Py2exe
21,848,033
9
2014-02-18T08:30:48Z
21,884,736
30
2014-02-19T15:18:22Z
[ "python", "windows-services", "py2exe" ]
I'm using Py2exe to create an executable as a windows service. When I run the script I get this error: > File "C:\TeamCity\buildAgent\work\582d895bd5b431ac\winpython\WinPython-32bit-2.7.3.3\python-2.7.3\lib\site-packages\py2exe\build\_exe.py", line 860, in build\_executable > **add\_resource(ensure\_unicode(exe\_path...
After two days investigating we found a solution with the help of the IT staff. The issue arise when py2exe try to modify the executable adding metadata and\or icon. The root cause? Simple... ANTIVIRUS. It considers that operation a threat and cause the Access Denied error. Thank you all!
Trying to install Couchbase, with gcc command fails, Python
21,852,929
7
2014-02-18T11:52:47Z
21,855,520
17
2014-02-18T13:35:41Z
[ "python", "gcc", "couchbase" ]
I try to install couchbase for python, but I get the following error: ``` building 'couchbase._libcouchbase' extension creating build/temp.linux-i686-2.7 creating build/temp.linux-i686-2.7/src creating build/temp.linux-i686-2.7/src/viewrow creating build/temp.linux-i686-2.7/src/contrib creating build/temp.linux-i686-2...
You should install libcouchbase first <http://www.couchbase.com/communities/c/getting-started> ``` wget -O- http://packages.couchbase.com/ubuntu/couchbase.key | sudo apt-key add - sudo wget -O/etc/apt/sources.list.d/couchbase.list \ http://packages.couchbase.com/ubuntu/couchbase-ubuntu1204.list sudo apt-get updat...
How to check float string?
21,855,118
2
2014-02-18T13:20:21Z
21,855,267
9
2014-02-18T13:26:25Z
[ "python", "string", "list" ]
I have a list which consists irregular words and `float` numbers, I'd like to delete all these `float` numbers from the list, but first I need to find a way to detect them. I know `str.isdigit()` can discriminate numbers, but it can't work for `float` numbers. How to do it? My code is like this: ``` my_list = ['fun',...
Use exception handling and a list comprehension. [Don't modify the list while iterating over it.](http://stackoverflow.com/questions/17299581/loop-forgets-to-remove-some-items) ``` >>> def is_float(x): ... try: ... float(x) ... return True ... except ValueError: ... return False >>> li...
How to add Indian Standard Time (IST) in Django?
21,855,357
8
2014-02-18T13:29:50Z
21,855,719
26
2014-02-18T13:44:44Z
[ "python", "django" ]
We want to get the current time in India in our Django project. In settings.py, UTC is there by default. How do we change it to IST?
Change the field `TIME_ZONE` in the `settings.py`. For the Indian standard time you will need: ``` TIME_ZONE = 'Asia/Kolkata' ``` For more information about the TIME\_ZONE in Django you can see: <https://docs.djangoproject.com/en/dev/ref/settings/#time-zone>
Can I convert an egg to wheel?
21,856,048
7
2014-02-18T13:58:41Z
21,856,049
11
2014-02-18T13:58:41Z
[ "python", "pip", "packaging", "egg", "python-wheel" ]
I have an already built/downloaded Python egg and I would like to convert it to the wheel format documented in [PEP 427](http://www.python.org/dev/peps/pep-0427/). How can I do this?
The answer is yes. We need only [wheel](https://pypi.python.org/pypi/wheel) package and we don't even need to install it, as according to [docs](http://wheel.readthedocs.org/en/latest/), we can use it directly (due to the fact `.whl` files have the same format as `.zip` files and Python can run code in `.zip` files d...
add a tuple to a tuple in Python
21,857,089
2
2014-02-18T14:41:29Z
21,857,134
8
2014-02-18T14:43:04Z
[ "python", "tuples" ]
I have a tuple: ``` a = (1,2,3) ``` and I need to add a tuple at the end ``` b = (4,5) ``` The result should be: ``` (1,2,3,(4,5)) ``` Even if I wrap b in extra parents: a + (b), I get (1,2,3,4,5) which is not what I wanted.
When you do `a + b` you are simply concatenating both the tuples. Here, you want the entire tuple to be a part of another tuple. So, we wrap that inside another tuple. ``` a, b = (1, 2, 3), (4,5) print a + (b,) # (1, 2, 3, (4, 5)) ```
How to make sure that my AJAX requests are originating from the same server in Python
21,857,523
24
2014-02-18T15:00:26Z
21,917,363
7
2014-02-20T19:15:28Z
[ "python", "django", "tastypie" ]
I have already asked a question about IP Authentication here: [TastyPie Authentication from the same server](http://stackoverflow.com/questions/21708113/tastypie-authentication-from-the-same-server) However, I need something more! An IP address could be very easily spoofed. ![enter image description here](http://i.st...
Depending on your infrastructure @dragonx's answer might interest you most. my 2c You want to make sure that only if a client visits your website can use the api? Hmm does the bot, robot, crawler fall in the same category with the client then? Or am I wrong? This can be easily exploited in case you really want to sec...
Why termcolor doesn't work in python?
21,858,567
4
2014-02-18T15:43:55Z
21,859,983
8
2014-02-18T16:40:28Z
[ "python", "colors" ]
I just installed termcolor in Python 2.7 and when I try to print something colored instead of coloring my text I get the code I guess of color printed. Any help? ``` from termcolor import colored print colored('Text text text', 'red') ``` Here is the result: ![enter image description here](http://i.stack.imgur.com/C...
To make the ANSI colors used in termcolor work with the windows terminal, you'll need to also import/init [`colorama`](https://pypi.python.org/pypi/colorama); ``` >>> from termcolor import * >>> cprint('hello', 'red') ←[31mhello←[0m >>> import colorama >>> colorama.init() >>> cprint('hello', 'red') hello ...
Error when trying to overload an operator "/"
21,859,440
9
2014-02-18T16:19:21Z
21,859,568
12
2014-02-18T16:23:46Z
[ "python", "python-3.x", "operator-overloading", "vector-graphics" ]
I recently start teaching myself game programming. Someone recommend me to start with Python and I got the book "Beginning game development with Python and Pygame: From novice to professional". I got to a part where they teach about Vectors and creating a Vector2 class. Everything was going well until I tried to overlo...
In python 3.x, you need to overload the `__floordiv__` and `__truediv__` operators, not the `__div__` operator. The former corresponds to the '//' operation (returns an integer) and the latter to '/' (returns a float).
Python - Remove list(s) from list of lists (Similar functionality to .pop() )
21,860,605
2
2014-02-18T17:07:51Z
21,860,630
11
2014-02-18T17:09:02Z
[ "python", "list", "python-3.x", "pop" ]
``` a=[[1,2,3],[4,5,6],[7,8,9]] ``` .pop() has the capacity to not only remove an element of a list but also return that element. I am looking for a similar function that can remove and return a whole list that could exist in the middle of another list. E.g is there a function that will remove `[4,5,6]` from the abo...
The nested lists are just values in the outer list. Just use `.pop()` on that outer list: ``` inner_list = a.pop(1) ``` Demo: ``` >>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> a.pop(1) [4, 5, 6] >>> a [[1, 2, 3], [7, 8, 9]] ``` You could just use a slice to remove the first row from consideration if a header row is...
import a.b also imports a?
21,866,036
10
2014-02-18T21:41:35Z
21,866,202
7
2014-02-18T21:50:36Z
[ "python", "python-import" ]
When I import a subpackage in a package, can I rely on the fact that the parent package is also imported ? e.g. this works ``` python -c "import os.path; print os.getcwd()" ``` Shouldn't I explicitly `import os` for `os.getcwd` to be available ?
There's an important thing to know about packages, that is that there is a difference between being loaded and being available. With `import a` you load module `a` (which can be a package) and make it available under the name `a`. With `from a import b` you load module `a` (which definitely is a package), then load m...
Cython not much faster than Python for Basic Sum Calculation
21,866,182
6
2014-02-18T21:49:23Z
21,866,666
8
2014-02-18T22:16:51Z
[ "python", "cython", "python-2.x", "anaconda" ]
I'm trying to follow an example given on the [Continuum Analytics blog](http://continuum.io/blog/numba_performance) benchmarking Python, Cython, Numba for a sum calculated using a for loop. Unfortunately, I'm seeing that Cython is slower than Python! Here's my Python function definition: ``` def python_sum(y): N ...
I am not sure why you get that result. As a commenter said, your code, as-is, shouldn't even work, since you'd be passing `float`s into a function expecting `int`s. Maybe you left a `cython_sum.py` file lying around in the same directory? I did the following. I created a **python\_sum.py** that contained your exact de...
What could cause an open file dialog window in Tkinter/Python to be really slow to close after the user selects a file?
21,866,537
6
2014-02-18T22:08:55Z
25,734,916
7
2014-09-09T00:11:53Z
[ "python", "osx", "python-3.x", "tkinter" ]
I can do the following in my program to get a simple open file dialog and print the selected file path. Unfortunately it doesn't go away right away when the user selects the file, and stays around for over 5 minutes. **How do I make the window disappear immediately once a selection has been made before executing more p...
I was having some trouble with Tkinter dialog boxes. Like you, the dialog just sat there after I had selected a file. I didn't try leaving it for very long, it may have disappeared after 5 minutes as you said your's did. After lots of random experimentation I found that calling `root.update()` **before** the `askopenfi...
Project Euler - How is this haskell code so fast?
21,868,427
16
2014-02-19T00:19:42Z
21,868,909
42
2014-02-19T01:07:31Z
[ "python", "haskell", "python-3.x" ]
I'm working on problem 401 in project euler, I coded up my solution in python but it's going to take a few days to run, obviously I'll need to speed it up or use a different approach. I came across a solution in Haskell that looks almost identical to my python solution but completes almost instantaneously. Can someone...
``` Prelude> sigma2big 1000 401382971 (0.48 secs, 28491864 bytes) Prelude> sigma2big 10^3 103161709 (0.02 secs, 1035252 bytes) Prelude> (sigma2big 10)^3 103161709 ``` function precedence (shh...)
Pip doesn't install latest available version from pypi (argparse in this case)
21,868,684
14
2014-02-19T00:44:42Z
21,872,198
9
2014-02-19T05:52:06Z
[ "python", "osx", "pip", "argparse", "pypi" ]
## The problem I worked on some python projects lately and had lots of problems with `pip` not installing the latest versions of some requirements. I am on `osx` and and I used [brew](http://brew.sh/) to install `Python 2.7.6`. In the project I'm working on, we simply `pip install -r requirements.txt`. In the current ...
I think this line is the key: > Some externally hosted files were ignored (use --allow-external to allow). When I install argparse here I get > You are installing an externally hosted file. Future versions of pip will default to disallowing externally hosted files. > > Downloading argparse-1.2.1.tar.gz (69kB): 69kB ...
Pip doesn't install latest available version from pypi (argparse in this case)
21,868,684
14
2014-02-19T00:44:42Z
23,426,583
7
2014-05-02T11:03:35Z
[ "python", "osx", "pip", "argparse", "pypi" ]
## The problem I worked on some python projects lately and had lots of problems with `pip` not installing the latest versions of some requirements. I am on `osx` and and I used [brew](http://brew.sh/) to install `Python 2.7.6`. In the project I'm working on, we simply `pip install -r requirements.txt`. In the current ...
Here's the command I used to install argparse using pip 1.5.4: ``` pip install --allow-all-external argparse==1.2.1 ```
Plural String Formatting
21,872,366
9
2014-02-19T06:03:12Z
21,872,861
12
2014-02-19T06:34:16Z
[ "python", "string", "string-formatting" ]
Given a dictionary of `int`s, I'm trying to format a string with each number, and a pluralization of the item. Sample input `dict`: ``` data = {'tree': 1, 'bush': 2, 'flower': 3, 'cactus': 0} ``` Sample output `str`: ``` 'My garden has 1 tree, 2 bushes, 3 flowers, and 0 cacti' ``` It needs to work with an arbitrar...
Check out the [inflect package](https://pypi.python.org/pypi/inflect). It will pluralize things, as well as do a whole host of other linguistic trickery. There are too many situations to special-case these yourself! From the docs at the link above: ``` # UNCONDITIONALLY FORM THE PLURAL print("The plural of ", word, "...
Floating point math in different programming languages
21,872,854
15
2014-02-19T06:34:04Z
21,874,981
37
2014-02-19T08:35:04Z
[ "python", "haskell", "floating-point", "julia-lang" ]
I know that floating point math can be ugly at best but I am wondering if somebody can explain the following quirk. In most of the programing languages I tested the addition of 0.4 to 0.2 gave a slight error, where as 0.4 + 0.1 + 0.1 gave non. What is the reason for the inequality of both calculation and what measures...
All these languages are using the system-provided floating-point format, which represents values in *binary* rather than in *decimal*. Values like `0.2` and `0.4` can't be represented exactly in that format, so instead the closest representable value is stored, resulting in a small error. For example, the numeric liter...
Python/IPython ImportError: no module named site
21,874,407
10
2014-02-19T08:01:43Z
21,874,450
13
2014-02-19T08:04:40Z
[ "python", "linux", "ubuntu-12.04", "ipython", "importerror" ]
I had `python 2.7.3` and `ipython 1.2` up and running correctly on my `Linux` system (`ubuntu 12.04`) but was trying to install an updated version of matplotlab needed for coursework. After running this code line in the terminal ``` user$ sudo easy_install -U distribute user$ export PYTHONHOME=/usr/lib/python2.7/ ```...
[`PYTHONHOME`](http://docs.python.org/2/using/cmdline.html#envvar-PYTHONHOME) > Change the location of the standard Python libraries. By default, the > libraries are searched in prefix/lib/pythonversion and > exec\_prefix/lib/pythonversion, where prefix and exec\_prefix are > installation-dependent directories, both d...
Saving a figure after invoking pyplot.show() results in an empty file
21,875,356
12
2014-02-19T08:53:47Z
21,884,187
19
2014-02-19T14:58:18Z
[ "python", "matplotlib" ]
The following example code generates a simple plot, then saves it to 'fig1.pdf', then displays it, then saves it again to 'fig2.pdf'. The first image looks as expected, but the second one is blank (contains a white square). What's actually going on here? The line `plt.show()` apparently messes something up, but I can...
If you want to save the figure after displaying it, you'll need to hold on to the figure instance. The reason that `plt.savefig` doesn't work after calling `show` is that the current figure has been reset. `pyplot` keeps track of which figures, axes, etc are "current" (i.e. have not yet been displayed with `show`) beh...
Do something every n iterations without using counter variable
21,879,424
3
2014-02-19T11:42:00Z
21,879,513
11
2014-02-19T11:45:20Z
[ "python" ]
I've an iterable list of over 100 elements. I want to do something after every 10th iterable element. I don't want to use a counter variable. I'm looking for some solution which does not includes a counter variable. Currently I do like this: ``` count = 0 for i in range(0,len(mylist)): if count == 10: cou...
``` for count, element in enumerate(mylist, 1): # Start counting from 1 if count % 10 == 0: # do something ``` Use [enumerate](http://docs.python.org/2/library/functions.html#enumerate). Its built for this
Why does Python handle '1 is 1**2' differently from '1000 is 10**3'?
21,880,308
25
2014-02-19T12:20:16Z
21,880,358
41
2014-02-19T12:22:03Z
[ "python", "reference", "semantics", "python-internals" ]
Inspired by [this](http://stackoverflow.com/questions/11485879/is-it-possible-for-the-python-compiler-to-optimize-away-some-integer-arithmetic) question about caching small integers and strings I discovered the following behavior which I don't understand. ``` >>> 1000 is 10**3 False ``` I thought I understood this be...
There are two separate things going on here: Python stores `int` literals (and other literals) as constants with compiled bytecode *and* small integer objects are cached as singletons. When you run `1000 is 1000` only one such constant is stored and reused. You are really looking at the same object: ``` >>> import di...
Daemonizing celery
21,880,360
5
2014-02-19T12:22:06Z
25,752,601
7
2014-09-09T19:56:13Z
[ "python", "linux", "celery", "celeryd" ]
Following instructions found [here](http://docs.celeryproject.org/en/latest/tutorials/daemonizing.html), I copied [the script from github](https://github.com/celery/celery/blob/3.1/extra/generic-init.d/celeryd) into */etc/init.d/celeryd*, then made it executable; ``` $ ll /etc/init.d/celeryd -rwxr-xr-x 1 root root 948...
I replicated your steps and it resulted in the same issue. The problem was the celery user not having a shell. ``` sudo useradd -N -M --system -s /bin/false celery ``` Changing `-s /bin/false` to `-s /bin/bash` fixed the issue. The reason being is that the celeryd init script uses the celery user's shell to execute c...
Why does ~True result in -2?
21,881,362
126
2014-02-19T13:04:51Z
21,881,422
44
2014-02-19T13:07:21Z
[ "python", "data-conversion", "tilde" ]
In Python console: ``` ~True ``` Gives me: ``` -2 ``` Why? Can someone explain this particular case to me in binary?
The Python `bool` type is a subclass of `int` (for historical reasons; booleans were only added in Python 2.3). Since `int(True)` is `1`, `~True` is `~1` is `-2`. See [PEP 285](http://www.python.org/dev/peps/pep-0285/) for why `bool` is a subclass of `int`. If you wanted the boolean inverse, use `not`: ``` >>> not ...
Why does ~True result in -2?
21,881,362
126
2014-02-19T13:04:51Z
21,881,463
228
2014-02-19T13:09:39Z
[ "python", "data-conversion", "tilde" ]
In Python console: ``` ~True ``` Gives me: ``` -2 ``` Why? Can someone explain this particular case to me in binary?
What is `int(True)`? It is `1`. `1` is: ``` 00000001 ``` and `~1` is: ``` 11111110 ``` Which is `-2` in [Two's complement](http://en.wikipedia.org/wiki/Two%27s_complement)1 1 Flip all the bits, add 1 to the resulting number and interpret the result as a *binary representation* of the magnitude and add a negative ...
ImportError: No module named pxssh
21,883,912
2
2014-02-19T14:47:47Z
21,884,115
7
2014-02-19T14:55:26Z
[ "python", "python-2.7", "ssh" ]
I am trying to use `pxssh` module to make SSH connection to the client - however I am getting ``` ImportError: No module named pxssh ``` I found this file in Python installation so I would guess that's correct ``` /usr/lib/python2.7/site-packages/pexpect/pxssh.py ``` I am of course running my app with Python 2.7 an...
Well, try `from pexpect import pxssh`.
Figure and axes methods in matplotlib
21,885,176
2
2014-02-19T15:34:48Z
21,885,235
8
2014-02-19T15:37:16Z
[ "python", "matplotlib" ]
Say I have the following setup: ``` import matplotlib.pyplot as plt import numpy as np x = np.arange(5) y = np.exp(x) fig1 = plt.figure() ax1 = fig1.add_subplot(111) ax1.plot(x, y) ``` I would like to add a title to the plot (or to the subplot). I tried: ``` > fig1.title('foo') AttributeError: 'Figure' object has ...
use `ax1.set_title('foo')` instead `ax1.title` returns a `matplotlib.text.Text`object: ``` In [289]: ax1.set_title('foo') Out[289]: <matplotlib.text.Text at 0x939cdb0> In [290]: print ax1.title Text(0.5,1,'foo') ``` You can also add a centered title to the figure when there are multiple `AxesSubplot`: ``` In [152]...
Python Empirical distribution function (ecdf) implementation
21,887,625
4
2014-02-19T17:16:07Z
21,888,413
8
2014-02-19T17:51:14Z
[ "python", "numpy", "pandas", "ecdf" ]
I am aware of [statsmodels.tools.tools.ECDF](http://statsmodels.sourceforge.net/stable/generated/statsmodels.tools.tools.ECDF.html) but since the calculation of an empricial cumulative distribution function (ECDF) is pretty straight-forward and I want to minimise dependencies in my project, I want to code it manually. ...
Since you are already using `pandas` I think it will be silly not to use some of its features: ``` In [15]: import numpy as np from numpy import * sq=ser.value_counts() sq.sort_index().cumsum()*1./len(sq) Out[15]: 2.083520e-12 0.058824 1.283440e-09 0.117647 8.517870e-09 0.176471 4.282550e-08 0.235294 1.121...
numpy concatenate two arrays vertically
21,887,754
23
2014-02-19T17:22:08Z
21,888,214
25
2014-02-19T17:42:18Z
[ "python", "arrays", "numpy", "concatenation" ]
I tried the following: ``` >>> a = np.array([1,2,3]) >>> b = np.array([4,5,6]) >>> np.concatenate((a,b), axis=0) array([1, 2, 3, 4, 5, 6]) >>> np.concatenate((a,b), axis=1) array([1, 2, 3, 4, 5, 6]) ``` However, I'd expect at least that one result looks like this ``` array([[1, 2, 3], [4, 5, 6]]) ``` Why is ...
Because both `a` and `b` have only one axis, as their shape is `(3)`, and the axis parameter specifically refers to the axis of the elements to concatenate. this example should clarify what `concatenate` is doing with axis. Take two vectors with two axis, with shape `(2,3)`: ``` a = np.array([[1,5,9],[2,6,10]]) b = n...
Always execute Code and the end of a python script
21,887,826
7
2014-02-19T17:26:10Z
21,887,917
11
2014-02-19T17:29:03Z
[ "python", "jenkins" ]
Is there a way in Python to have a block of code always execute at the end of a program (barring a `kill -9`? We have a Jenkins project that launches a python script as part of the build process. If a developer decides to abort the job, then there are a lot of artifacts left lying around that can (and are) influencing...
Use the `atexit` exit handlers. Here's an example from the [python docs](http://docs.python.org/2/library/atexit.html): ``` try: _count = int(open("counter").read()) except IOError: _count = 0 def incrcounter(n): global _count _count = _count + n def savecounter(): open("counter", "w").write("%d"...
Inverse of numpy.dot
21,891,043
8
2014-02-19T19:57:58Z
21,891,453
8
2014-02-19T20:15:58Z
[ "python", "numpy", "inverse" ]
I can easily calculate something like: ``` R = numpy.column_stack([A,np.ones(len(A))]) M = numpy.dot(R,[k,m0]) ``` where A is a simple array and k,m0 are known values. I want something different. Having fixed R, M and k, I need to obtain m0. Is there a way to calculate this by an inverse of the function numpy.dot()...
``` M = numpy.dot(R,[k,m0]) ``` is performing matrix multiplication. `M = R * x`. So to compute the inverse, you could use [`np.linalg.lstsq(R, M)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html): ``` import numpy as np A = np.random.random(5) R = np.column_stack([A,np.ones(len(A))]) k...
Ipython is working in command prompt but not in browser
21,892,529
8
2014-02-19T21:13:19Z
25,187,899
13
2014-08-07T16:44:20Z
[ "python", "ipython", "ipython-notebook" ]
I am using a windows 8 64 bit laptop. I already have python 2.7 on my pc. So I installed Ipython using the easy\_install. I can now see an ipython application file in C:\Python27\Scripts. When I run that file it opens up my cmd and I can write code. However when I say `Ipython notebook` in the cmd under the same folder...
## Short answer: make sure pyzmq is installed in the same virtualenvironment (or lack of) as ipython. For me, ipython notebook was installed as regular, but its dependencies got put in my virtualenvironment. A quick install in the proper place fixed this error for me. ## Long answer: I'm putting this solution here b...
Django Bad Request(400) Error in Deployment with Apache/NginX
21,893,636
4
2014-02-19T22:10:56Z
21,896,006
16
2014-02-20T01:03:16Z
[ "python", "django", "apache", "python-2.7", "nginx" ]
I'm trying to lunch my app on VPS in `Debug=False` mode. `Debug=True` works fine but when I change it to false I got this error. I'm using Apache for rendering python pages and Nginx to serve my static files. I tried using this [answer]: [Debugging Apache/Django/WSGI Bad Request (400) Error](http://stackoverflow.com/qu...
To discover your problem, first in `settings.py` set `ALLOWED_HOSTS` temporarily to: ``` ALLOWED_HOSTS = '*' ``` And then in somewhere in your `view`, try to print out and see output of this command: ``` print(request.META['HTTP_HOST']) # or print(request.get_host()) ``` Then according to output, set that (just dom...
Finding indices given condition in numpy matrix
21,894,847
5
2014-02-19T23:26:48Z
21,894,930
7
2014-02-19T23:32:04Z
[ "python", "numpy" ]
So I have a numpy matrix, such as: ``` [[1,2,3], [0,59,2], [54,4,2]] ``` Now I want to find the indices, where all values are greater than 50 (not the maximum). This should give me `[1,1],[2,0]`. Other than iterating through, checking each value and keeping track of indices for values which obey condition and then r...
You want to use either numpy.where or numpy.argwhere: ``` import numpy as np A = np.array([[99, 2, 3], [0, 59, 2], [54, 4, 2]]) np.where(A > 50) # (array([0, 1, 2]), array([0, 1, 0])) np.argwhere(A > 50) # array([[0, 0], # [1, 1], # [2, 0]]) ```
Python programming functional vs. imperative code
21,895,525
5
2014-02-20T00:19:01Z
21,895,631
10
2014-02-20T00:27:46Z
[ "python", "functional-programming", "imperative-programming" ]
So I'm currently in a class learning about the 3 major programming paradigms. I know that python uses both the functional and imperative paradigms. I was looking for a short sample code in python of each of these paradigms to better understand this before my exam tomorrow. Thank you!
Given `L = [1, 2, 3, 4, 5]` we can compute the sum in two ways. Imperative: ``` sum = 0 for x in L: sum += x ``` Functional (local function): ``` def add(x, y): return x + y sum = reduce(add, L) ``` Functional (lambda expression): ``` sum = reduce(lambda x, y: x + y, L) ``` (Of course, the built in `sum`...
Python programming functional vs. imperative code
21,895,525
5
2014-02-20T00:19:01Z
21,895,854
7
2014-02-20T00:46:10Z
[ "python", "functional-programming", "imperative-programming" ]
So I'm currently in a class learning about the 3 major programming paradigms. I know that python uses both the functional and imperative paradigms. I was looking for a short sample code in python of each of these paradigms to better understand this before my exam tomorrow. Thank you!
One way to think of the difference between imperative and functional paradigms is that with imperative you have to explicitly code the order of your operations (I'm using very loose language here to make it simple for you). In contrast, with functional programming you are not defining the sequence but rather you are de...
How to get Python Class to Return Some Data and not its Object Address
21,896,051
4
2014-02-20T01:08:20Z
21,896,063
7
2014-02-20T01:10:08Z
[ "python", "oop", "methods", "pandas", "representation" ]
## Context: Using the following: ``` class test: def __init__(self): self._x = 2 def __str__(self): return str(self._x) def __call__(self): return self._x ``` Then creating an instance with `t = test()` I see how to use `__str__` for print: ``` >>> print t 2 ``` I can see how...
[Define `__repr__`](http://stackoverflow.com/q/1436703/190597). ``` def __repr__(self): return str(self._x) ``` The Python interpreter prints the `repr` of the object by default.
How to get Python Class to Return Some Data and not its Object Address
21,896,051
4
2014-02-20T01:08:20Z
21,896,101
8
2014-02-20T01:14:25Z
[ "python", "oop", "methods", "pandas", "representation" ]
## Context: Using the following: ``` class test: def __init__(self): self._x = 2 def __str__(self): return str(self._x) def __call__(self): return self._x ``` Then creating an instance with `t = test()` I see how to use `__str__` for print: ``` >>> print t 2 ``` I can see how...
`__repr__` is intended to be the literal **representation** of the object. Note that if you define `__repr__`, you don't have to define `__str__`, if you want them both to return the same thing. `__repr__` is `__str__`'s fallback. ``` class test: def __init__(self): self._x = 2 def __repr__(self): ...
Rate Limit an Infinite While Loop in Python
21,897,438
4
2014-02-20T03:23:58Z
21,897,458
8
2014-02-20T03:26:32Z
[ "python", "python-2.7" ]
If I have a infinite `while` loop, how can I have the loop run the next iteration every 10 minutes from the start of the loop iteration? If the first iteration starts at 1:00am and finishes at 1:09am, the next iteration should run at 1:10am instead of waiting for another 10 minutes (like in the code snippet below). If...
Remember the start time, calculate sleep time using that. ``` while True: start = time.time() some_long_process() end = time.time() remain = start + 10*60 - end if remain > 0: time.sleep(remain) ```
How to set window size using phantomjs and selenium webdriver in python
21,899,953
10
2014-02-20T06:29:01Z
21,900,590
14
2014-02-20T07:04:35Z
[ "python", "selenium", "phantomjs" ]
I'm trying to get a full sized browser screenshot with phantomjs driven by python webdriver . right now my screenshot is measured at 927 x 870, I'd like to reset it. I have tried: ``` driver.manage().Window().setSize(new Dimension(1400,1000)) ``` based on <https://groups.google.com/forum/#!msg/phantomjs/f29lxBQNLqY/_...
Because that's Java. Python's documentation is [here](http://selenium.googlecode.com/git/docs/api/py/api.html). There's a method called `set_window_size`, which is defined [here](http://selenium.googlecode.com/git/docs/api/py/webdriver_remote/selenium.webdriver.remote.webdriver.html#selenium.webdriver.remote.webdriver...
python pandas not reading first column from csv file
21,902,080
12
2014-02-20T08:26:31Z
21,902,162
19
2014-02-20T08:30:39Z
[ "python", "csv", "pandas" ]
I have a simple 2 column csv file called st1.csv: ``` GRID St1 1457 614 1458 657 1459 679 1460 732 1461 754 1462 811 1463 748 ``` However, when I try to read the csv file, the first column is not loaded: ``` a = pandas.DataFrame.from_csv('st1.csv') a.columns ``` **outputs:** ...
Judging by your data it looks like the delimiter you're using is a . Try the following: ``` a = pandas.DataFrame.from_csv('st1.csv', sep=' ') ``` The other issue is that it's assuming your first column is an index, which we can also disable: ``` a = pandas.DataFrame.from_csv('st1.csv', index_col=False) ```
How do I compare two strings in python?
21,903,842
29
2014-02-20T09:42:04Z
21,903,857
16
2014-02-20T09:42:47Z
[ "python", "string", "python-2.7" ]
I have two strings like ``` string1="abc def ghi" ``` and ``` string2="def ghi abc" ``` How to get that this two string are same without breaking the words?
If you want to know if both the strings are equal, you can simply do ``` print string1 == string2 ``` But if you want to know if they both have the same set of characters and they are occur for the same number of times, you can use [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections....
How do I compare two strings in python?
21,903,842
29
2014-02-20T09:42:04Z
21,905,220
31
2014-02-20T10:39:25Z
[ "python", "string", "python-2.7" ]
I have two strings like ``` string1="abc def ghi" ``` and ``` string2="def ghi abc" ``` How to get that this two string are same without breaking the words?
Seems question is not about strings equality, but of **sets** equality. You can compare them this way *only* by splitting strings and converting them to sets: ``` s1 = 'abc def ghi' s2 = 'def ghi abc' set1 = set(s1.split(' ')) set2 = set(s2.split(' ')) print set1 == set2 ``` Result will be ``` True ```
icontains in Django QuerySet doesn't give the case insensitive result?
21,905,543
4
2014-02-20T10:53:56Z
21,905,883
11
2014-02-20T11:07:48Z
[ "python", "mysql", "django", "django-models" ]
I am using Django1.6, I am trying to use QuerySet filter, but it is behaving strangely. Here is my code: ``` test_listing = Test.objects.filter(site__id=_site_id, show_on_site=True) ``` Then I am trying to get the listing based on the searched text: ``` test_listing = test_listing.filter(name__icontains = searched_...
this is perhaps due to the [mysql-db](https://dev.mysql.com/doc/refman/5.0/en/charset-column.html) which you are using, may be your db table (name) column have the sql case-sensitive coollate ``` ALTER TABLE t1 MODIFY col1 VARCHAR(5) CHARACTER SET latin1 COLLATE latin1_swedish_ci; ```
Why set_xticks doesn't set the lables of ticks?
21,910,986
12
2014-02-20T14:39:22Z
21,911,813
23
2014-02-20T15:12:07Z
[ "python", "matplotlib" ]
``` import pylab as plt x = range(1, 7) y = (220, 300, 300, 290, 320, 315) def test(axes): axes.bar(x,y) axes.set_xticks(x, [i+100 for i in x]) a = plt.subplot(1,2,1) test(a) b = plt.subplot(1,2,2) test(b) ``` ![enter image description here](http://i.stack.imgur.com/Vagh2.png) I am expecting the xlabs as `...
[`.set_xticks()`](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_xticks) on the axes will set the locations and [`set_xticklabels()`](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_xticklabels) will set the displayed text. ``` def test(axes): axes.bar(x,y) axes.set_xticks(x)...
Settting Different error bar colors in bar plot in matplotlib
21,912,197
17
2014-02-20T15:26:56Z
21,915,157
31
2014-02-20T17:24:45Z
[ "python", "matplotlib" ]
Following [Settting Different Bar color in matplotlib Python](http://stackoverflow.com/questions/18973404/settting-different-bar-color-in-matplotlib-python/18973430#18973430) I would like to change the error bar colors. I have figured out a way after a number of attempts: ``` a = plt.gca() b = a.bar(range(4), [2]*4, ...
If you just want to set them to a single color, use the `error_kw` kwarg (expected to be a dict of keyword arguments that's passed on to `ax.errorbar`). Also, just so you know, you can pass a sequence of facecolors directly to `bar`, though this won't change the errorbar color. As a quick example: ``` import matplot...
numpy negative indexing a[:-0]
21,913,935
14
2014-02-20T16:33:33Z
21,914,093
24
2014-02-20T16:40:55Z
[ "python", "numpy" ]
I want to use array slicing to trim my array i.e. ``` a_trimmed = a[trim_left:-trim_right] ``` this is great, except if `trim_right` is 0, I get `a[trim_left:0]`, which is an empty array. I suppose I can could it to ``` a[trim_left:a.shape[0]-trim_right] ``` but it's uglier. What's the cleanest way to express this...
`None` is a valid slice endpoint: ``` a[trim_left:-trim_right or None] ```
python setuptools install_requires is ignored when overriding cmdclass
21,915,469
11
2014-02-20T17:39:38Z
22,179,371
8
2014-03-04T17:54:15Z
[ "python", "setuptools", "distutils", "install-requires" ]
I have a `setup.py` that looks like this: ``` from setuptools import setup from subprocess import call from setuptools.command.install import install class MyInstall(install): def run(self): call(["pip install -r requirements.txt --no-clean"], shell=True) install.run(self) setup( author='Atti...
The same problem just happened to me. It somehow seems like something triggers setuptools to do an 'old-style install' with `distutils`, which indeed does not support `install_requires`. You call install.run(self) which calls run(self) in setuptools/setuptools/command/install.py, line 51-74 <https://bitbucket.org/pyp...
ajax post data in flask view
21,917,016
3
2014-02-20T18:56:23Z
21,917,103
8
2014-02-20T19:01:35Z
[ "python", "ajax", "python-2.7", "flask" ]
Here is my view function ``` @app.route('/share', methods=['GET', 'POST']) def share(): form = ShareForm(request.form) if request.method == 'POST': title = form.title.data body = form.body.data share_id = form.share_id.data print 'form data %s %s %s' % (title, body, share_id) ...
You are setting the content type to `application/json` but are sending `application/x-www-form-urlencoded` data instead. Set the correct content type: ``` $.ajax({ url: '/share', type: 'post', contentType: "application/x-www-form-urlencoded", data: $('#share-form').serialize(), ``` or better still, leave it ...
Rotating axes label text in 3D matplotlib
21,918,380
11
2014-02-20T20:07:10Z
21,921,168
13
2014-02-20T22:33:48Z
[ "python", "matplotlib", "mplot3d" ]
How do I rotate the z-label so the text reads (bottom => top) rather than (top => bottom)? ``` import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_zlabel('label text flipped', rotation=90) ax.azim = 225 plt.show() ``` ![enter i...
As a workaround, you could set the direction of the z-label manually by: ``` ax.zaxis.set_rotate_label(False) # disable automatic rotation ax.set_zlabel('label text', rotation=90) ``` Please note that the direction of your z-label also depends on your viewpoint, e.g: ``` import matplotlib.pyplot as plt from mpl_too...
Total number of paths in directed acyclic graph containing a specific link
21,918,436
3
2014-02-20T20:09:32Z
21,919,879
8
2014-02-20T21:21:36Z
[ "python", "path", "directed-acyclic-graphs", "totals" ]
I've been trying to code up an algorithm that takes a directed set of nodes (I have expressed as a sparse directed adjacency matrix, for now) say, A, B, C, and D, that, when called, gives me all possible paths that contain a given path (such as AB or AD). A node cannot connect to itself, and all nodes are directed to f...
Start by solving the simpler problem: given two points A and B in a DAG can you count all the paths that start with A and end with B? (A "path" is defined as a list of edges where the end node of one is equal to the start node of the next.) Sounds hard. Can we simplify it? Well clearly the most trivial case is where ...
Multivariate kernel density estimation in Python
21,918,529
5
2014-02-20T20:14:18Z
21,918,893
10
2014-02-20T20:32:11Z
[ "python", "numpy", "scipy", "gaussian", "kernel-density" ]
I am trying to use scipy gaussian\_kde function to estimate the density of multivariate data. In my code below I sample a 3D multivariate normal and fit the kernel density but I'm not sure how to evaluate my fit. ``` import numpy as np from scipy import stats mu=np.array([1,10,20]) sigma=np.matrix([[4,10,0],[10,25,0]...
There are several ways you might visualize the results in 3D. The easiest is to evaluate the gaussian KDE at the points that you used to generate it, and then color the points by the density estimate. For example: ``` import numpy as np from scipy import stats import matplotlib.pyplot as plt from mpl_toolkits.mplot3...
Matplotlib log scale tick label number formatting
21,920,233
19
2014-02-20T21:42:24Z
21,920,673
30
2014-02-20T22:05:06Z
[ "python", "numpy", "matplotlib", "graphing" ]
With `matplotlib` when a log scale is specified for an axis, the default method of labeling that axis is with numbers that are 10 to a power eg. 10^6. Is there an easy way to change all of these labels to be their full numerical representation? eg. 1, 10, 100, etc. Note that I do not know what the range of powers will...
Sure, just change the formatter. For example, if we have this plot: ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.axis([1, 10000, 1, 100000]) ax.loglog() plt.show() ``` ![enter image description here](http://i.stack.imgur.com/DhZH8.png) You could set the tick labels manually, but then the tick l...
Matplotlib log scale tick label number formatting
21,920,233
19
2014-02-20T21:42:24Z
33,213,196
12
2015-10-19T11:26:09Z
[ "python", "numpy", "matplotlib", "graphing" ]
With `matplotlib` when a log scale is specified for an axis, the default method of labeling that axis is with numbers that are 10 to a power eg. 10^6. Is there an easy way to change all of these labels to be their full numerical representation? eg. 1, 10, 100, etc. Note that I do not know what the range of powers will...
I've found that using `ScalarFormatter` is great if all your tick values are greater than or equal to 1. However, if you have a tick at a number `<1`, the `ScalarFormatter` prints the tick label as `0`. [![enter image description here](http://i.stack.imgur.com/wcvAF.png)](http://i.stack.imgur.com/wcvAF.png) I've used...