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 |
|---|---|---|---|---|---|---|---|---|---|
python - invalid syntax when I use * | 21,386,362 | 2 | 2014-01-27T16:38:04Z | 21,386,431 | 7 | 2014-01-27T16:41:13Z | [
"python",
"python-2.7"
] | I created a simple function to unpack N elements from an iterable.
```
def drop_first_last(grades):
grades = first, *middle, last
return avg(middle)
```
When I run this function occurred following error:
```
grades = first, *middle, last
SyntaxError: invalid syntax
```
I don't know why this error occurred,... | Just do:
```
middle = grades[1:-1]
return avg(middle)
``` |
List of Python functions, in their order of definition in the module | 21,386,366 | 4 | 2014-01-27T16:38:18Z | 21,386,484 | 9 | 2014-01-27T16:42:55Z | [
"python",
"doctest"
] | For a test-driven pedagogical module, I need to check doctests in a precise order.
Is there a way to grab all callables in the current module, in their order of definition?
What I tried:
* Loop on globals and check if the object is a callable. The problem is that globals is a dict and thus not ordered.
* Using the do... | Each function object has a code object which stores the first line number, so you can use:
```
import inspect
ordered = sorted(inspect.getmembers(moduleobj, inspect.isfunction),
key=lambda kv: kv[1].__code__.co_firstlineno)
```
to get a sorted list of `(name, function)` pairs. For Python 2.5 and ol... |
How do you check if a string contains ONLY numbers - python | 21,388,541 | 30 | 2014-01-27T18:19:34Z | 21,388,552 | 16 | 2014-01-27T18:20:20Z | [
"python",
"string",
"numbers"
] | How do you check if a string contains only numbers?
I've given it a go here, need it in the simplest way. Thanks.
```
import string
def main():
isbn = input("Enter you're 10 digit ISBN number: ")
if len(isbn) == 10 and string.digits == True:
print ("Works")
else:
print("Error, 10 digit num... | Use [`str.isdigit`](http://docs.python.org/2.7/library/stdtypes.html#str.isdigit):
```
>>> "12345".isdigit()
True
>>> "12345a".isdigit()
False
>>>
``` |
How do you check if a string contains ONLY numbers - python | 21,388,541 | 30 | 2014-01-27T18:19:34Z | 21,388,567 | 66 | 2014-01-27T18:21:00Z | [
"python",
"string",
"numbers"
] | How do you check if a string contains only numbers?
I've given it a go here, need it in the simplest way. Thanks.
```
import string
def main():
isbn = input("Enter you're 10 digit ISBN number: ")
if len(isbn) == 10 and string.digits == True:
print ("Works")
else:
print("Error, 10 digit num... | You'll want to use the `isdigit` method on your `str` object:
```
if len(isbn) == 10 and isbn.isdigit():
```
From the [`isdigit` documentation:](http://docs.python.org/2/library/stdtypes.html#str.isdigit)
> ```
> str.isdigit()
> ```
>
> Return true if all characters in the string are digits
> and there is at least o... |
Classification tree in sklearn giving inconsistent answers | 21,391,429 | 3 | 2014-01-27T20:53:06Z | 21,394,528 | 7 | 2014-01-28T00:19:53Z | [
"python",
"classification",
"scikit-learn",
"decision-tree"
] | I am using a classification tree from `sklearn` and when I have the the model train twice using the same data, and predict with the same test data, I am getting different results. I tried reproducing on a smaller iris data set and it worked as predicted. Here is some code
```
from sklearn import tree
from sklearn.data... | The `DecisionTreeClassifier` works by repeatedly splitting the training data, based on the value of some feature. The Scikit-learn implementation lets you choose between a few splitting algorithms by providing a value to the `splitter` keyword argument.
* "best" randomly chooses a feature and finds the 'best' possible... |
How to make print statement one line in python? | 21,391,708 | 4 | 2014-01-27T21:09:09Z | 21,391,746 | 13 | 2014-01-27T21:10:59Z | [
"python"
] | How do i make this code print as one line?:
```
print("If a hippo ways 2000 pounds, gives birth to a 100 pound calf and
then eats a 50 pound meal how much does she weigh?")
```
I have it this way to make it more readable, i know i could use triple quotes to get it to print exactly the way it is and that i ... | Adjacent string literals are concatenated implicitly:
```
print("If a hippo ways 2000 pounds, gives birth to a 100 pound calf and "
"then eats a 50 pound meal how much does she weigh?")
``` |
Wrap slice around edges of a 2D array in numpy | 21,396,121 | 4 | 2014-01-28T03:11:05Z | 21,421,172 | 7 | 2014-01-29T02:57:26Z | [
"python",
"numpy"
] | Suppose I am working with numpy in Python and I have a two-dimensional array of arbitrary size. For convenience, let's say I have a 5 x 5 array. The specific numbers are not particularly important to my question; they're just an example.
```
a = numpy.arrange(25).reshape(5,5)
```
This yields:
```
[[0, 1, 2, 3, 4 ],
... | This will work with numpy >= 1.7.
```
a = np.arange(25).reshape(5,5)
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
```
The pad routine has a 'wrap' method...
```
b = np.pad(a, 1, mode='wrap')
array([[24, 20, 21, 22,... |
stack bar plot in matplotlib and add label to each section (and suggestions) | 21,397,549 | 6 | 2014-01-28T05:26:35Z | 21,405,292 | 10 | 2014-01-28T12:08:42Z | [
"python",
"matplotlib"
] | I am trying to replicate the following image in matplotlib and it seems barh is my only option. Though it appears that you can't stack barh graphs so I don't know what to do

If you know of a better python library to draw this kind of thing, please le... | Edit 2: for more heterogeneous data. (I've left the above method since I find it more usual to work with the same number of records per series)
Answering the two parts of the question:
a) `barh` returns a container of handles to all the patches that it drew. You can use the coordinates of the patches to aid the text ... |
Python array simple issue | 21,403,146 | 2 | 2014-01-28T10:33:59Z | 21,403,211 | 7 | 2014-01-28T10:36:08Z | [
"python",
"arrays",
"list"
] | I've the following two arrays:
```
array1 = [0, 1, 1, 0]
array2 = ['foo', 'bar', 'hello', 'bye']
```
I want to save into an array the values of `array2` that has the index `1`in `array1`.
On the example above, the desired result should be `result_array = ['bar', 'hello']`.
I've tried something like this, but it's n... | The problem with your code is that you're using `=` in `if` condition, replace it with `==`. And secondly to get the index as well as item you need to use `enumerate`, currently you're appending `array[i]`, so your code will end up appending `'bar'` two times.
```
>>> result_array = []
>>> for i, x in enumerate(array1... |
Flask view raises TypeError: 'bool' object is not callable | 21,406,057 | 4 | 2014-01-28T12:53:02Z | 21,406,866 | 15 | 2014-01-28T13:26:50Z | [
"python",
"flask",
"flask-login"
] | I am trying to debug a view in my Flask app that is return a 500 status with the error `TypeError: 'bool' object is not callable` in the traceback. The view calls `login_user` from Flask-Login then returns `True` to indicate that the login was successful.
I have debugged until `app_iter = app(environ, start_response)`... | In Flask, a view must return one of the following:
* a string
* a `Response` object (or subclass)
* a tuple of `(string, status, headers)` or `(string, status)`
* a valid WSGI application
Flask tests for the first 3 options, and if they don't fit, assumes it is the fourth. You returned True somewhere, and it is being... |
python subprocess changing directory | 21,406,887 | 19 | 2014-01-28T13:28:30Z | 21,406,995 | 30 | 2014-01-28T13:33:00Z | [
"python",
"subprocess"
] | I want to execute a script inside a subdirectory/superdirectory (I need to be inside this sub/super-directory first). I can't get `subprocess` to enter my subdirectory:
```
tducin@localhost:~/Projekty/tests/ve$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:26)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credi... | What your code tries to do is call a program named `cd ..`. What you want is call a command named `cd`.
But `cd` is a shell internal. So you can only call it as
```
subprocess.call('cd ..', shell=True) # pointless code! See text below.
```
**But it is pointless to do so.** As no process can change another process's ... |
python subprocess changing directory | 21,406,887 | 19 | 2014-01-28T13:28:30Z | 21,407,005 | 14 | 2014-01-28T13:33:21Z | [
"python",
"subprocess"
] | I want to execute a script inside a subdirectory/superdirectory (I need to be inside this sub/super-directory first). I can't get `subprocess` to enter my subdirectory:
```
tducin@localhost:~/Projekty/tests/ve$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:26)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credi... | You want to use an absolute path to the executable, and use the `cwd` kwarg of `Popen` to set the working directory. See the [docs](http://docs.python.org/2/library/subprocess.html#popen-constructor).
> If cwd is not None, the childâs current directory will be changed to
> cwd before it is executed. Note that this d... |
python subprocess changing directory | 21,406,887 | 19 | 2014-01-28T13:28:30Z | 34,539,434 | 8 | 2015-12-31T00:38:04Z | [
"python",
"subprocess"
] | I want to execute a script inside a subdirectory/superdirectory (I need to be inside this sub/super-directory first). I can't get `subprocess` to enter my subdirectory:
```
tducin@localhost:~/Projekty/tests/ve$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:26)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credi... | To run `your_command` as a subprocess in a different directory, pass `cwd` parameter, as [suggested in @wim's answer](http://stackoverflow.com/a/21407005/4279):
```
import subprocess
subprocess.check_call(['your_command', 'arg 1', 'arg 2'], cwd=working_dir)
```
A child process can't change its parent's working direc... |
Python requests - Exception Type: ConnectionError - try: except does not work | 21,407,147 | 8 | 2014-01-28T13:40:08Z | 21,407,552 | 14 | 2014-01-28T13:58:12Z | [
"python",
"url",
"connection",
"python-requests",
"try-except"
] | I am using a webservice to retrieve some data but sometimes the url is not working and my site is not loading. Do you know how I can handle the following exception so there is no problem with the site in case the webservice is not working?
```
Django Version: 1.3.1
Exception Type: ConnectionError
Exception Value:
HT... | You should not exit your worker instance `sys.exit(1)`
Furthermore you 're catching the wrong Error.
What you could do for for example is:
```
from requests.exceptions import ConnectionError
try:
r = requests.get("http://example.com", timeout=0.001)
except ConnectionError as e: # This is the correct syntax
p... |
Get (column, row) index from NumPy array that meets a boolean condition | 21,407,815 | 7 | 2014-01-28T14:09:21Z | 21,407,851 | 10 | 2014-01-28T14:11:01Z | [
"python",
"arrays",
"numpy"
] | I am working with a 2D NumPy array. I would like to get the (column, row) index, or (x, y) coordinate, if you prefer thinking that way, from my 2D array that meets a boolean condition.
The best way I can explain what I am trying to do is via a trivial example:
```
>>> a = np.arange(9).reshape(3, 3)
>>> b = a > 4
>>> ... | Use [`numpy.where`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) with [`numpy.column_stack`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html):
```
>>> np.column_stack(np.where(b))
array([[1, 2],
[2, 0],
[2, 1],
[2, 2]])
``` |
TemplateDoesNotExist - Django Error | 21,408,344 | 42 | 2014-01-28T14:29:49Z | 21,482,412 | 112 | 2014-01-31T14:27:40Z | [
"python",
"django",
"django-rest-framework"
] | I'm using Django Rest Framework. and I keep getting an error
```
Exception Type: TemplateDoesNotExist
Exception Value: rest_framework/api.html
```
I dont know how I'm going wrong. This is the first time I'm trying out hands on REST Framework.
This is code.
**views.py**
```
import socket, json
from modules.data.mode... | Make sure you have `rest_framework` listed in your `settings.py` `INSTALLED_APPS`. |
what is trailing whitespace and how can I handle this? | 21,410,075 | 9 | 2014-01-28T15:39:56Z | 21,410,096 | 12 | 2014-01-28T15:40:49Z | [
"python",
"pep8"
] | some piece of my codes:
```
if self.tagname and self.tagname2 in list1:
try:
question = soup.find("div", "post-text")
title = soup.find("a", "question-hyperlink")
self.list2.append(str(title)+str(question)+url)
... | Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.
In your posted question, there is one extra space after `try:`, and there are 12 extra spaces after `pass`:
```
>>> post_text = '''\
... if self.tagname and self.tagname2 in list1:
... ... |
How do I crop to largest interior bounding box in OpenCV? | 21,410,449 | 9 | 2014-01-28T15:54:41Z | 21,479,072 | 12 | 2014-01-31T11:33:04Z | [
"python",
"opencv"
] | I have some images on a black background where the images don't have square edges (see bottom right of image below). I would like to crop them down the largest rectangular image (red border). I know I will potentially lose from of the original image. Is it possible to do this in OpenCV with Python. I know there are are... | ok, I've played with an idea and tested it (it's c++ but you'll probably be able to convert that to python):
1. assumption: background is black and the interior has no black boundary parts
2. you can find the external contour with `findContours`
3. use min/max x/y point positions from that contour until the rectangle ... |
Flask jsonify a list of objects | 21,411,497 | 19 | 2014-01-28T16:38:37Z | 21,411,576 | 33 | 2014-01-28T16:42:09Z | [
"python",
"json",
"serialization",
"flask"
] | I have a list of objects that I need to jsonify. I've looked at the flask jsonify docs, but I'm just not getting it.
My class has several inst-vars, each of which is a string: `gene_id`, `gene_symbol`, `p_value`. What do I need to do to make this serializable as JSON?
My naive code:
```
jsonify(eqtls = my_list_of_eq... | Give your `EqltByGene` an extra method that returns a dictionary:
```
class EqltByGene(object):
#
def serialize(self):
return {
'gene_id': self.gene_id,
'gene_symbol': self.gene_symbol,
'p_value': self.p_value,
}
```
then use a list comprehension to turn y... |
is there a way to config python json library to ignore fields that has null values when calling json.loads? | 21,411,992 | 3 | 2014-01-28T17:00:51Z | 21,412,056 | 9 | 2014-01-28T17:04:08Z | [
"python",
"json"
] | python version 2.7
```
>>> json.loads('{"key":null,"key2":"yyy"}')
{u'key2': u'yyy', u'key': None}
```
the above is the default behaviour what I want is the result becomes {u'key2': u'yyy'}
any suggestions? thanks a lot! | You can filter the result after loading:
```
res = json.loads(json_value)
res = {k: v for k, v in res.iteritems() if v is not None}
```
Or you can do this in the `object_hook` callable:
```
def remove_nulls(d):
return {k: v for k, v in d.iteritems() if v is not None}
res = json.loads(json_value, object_hook=rem... |
django rest framework - always INSERTs, never UPDATES | 21,412,324 | 7 | 2014-01-28T17:16:26Z | 21,412,365 | 9 | 2014-01-28T17:18:23Z | [
"python",
"django",
"rest",
"frameworks",
"django-rest-framework"
] | I want to be able to UPDATE a user record by POST. However, the id is always NULL. Even if I pass the id it seems to be ignored
View Code:
JSON POSTED:
```
{
"id": 1,
"name": "Craig Champion",
"profession": "Developer",
"email": "[email protected]"
}
```
```
@api_view(['POST'])
def get_pur... | You need to use `partial=True` to update a row with partial data:
```
serializer = UserSerializer(user, data=request.DATA, partial=True)
```
From [docs](http://www.django-rest-framework.org/api-guide/serializers#deserializing-objects):
> By default, serializers must be passed values for all required fields
> or they... |
Python 'requests' adding parameters in the wrong order | 21,413,321 | 2 | 2014-01-28T18:04:25Z | 21,413,359 | 13 | 2014-01-28T18:06:04Z | [
"python",
"python-2.7",
"python-requests"
] | ```
import requests
endpoint = 'http://data.alexa.com/data?'
qparams = {'cli': 10,
'url': 'www.google.com'}
response = requests.get(endpoint, params=qparams)
print response.url
```
This shows me that it looked at <http://data.alexa.com/data?url=www.google.com&cli=10>
Which is the wrong URL, it should be ... | Dictionaries have *no* fixed order. Pass in your parameters as a sequence of `(key, value)` pairs instead if you require ordered parameters:
```
qparams = (
('cli', 10),
('url', 'www.google.com'),
)
```
You should also leave off the `?` from the URL, `requests` will handle that for you.
Demo:
```
>>> import... |
How to run python macros in LibreOffice? | 21,413,664 | 19 | 2014-01-28T18:20:29Z | 22,074,770 | 14 | 2014-02-27T16:40:38Z | [
"python",
"ubuntu",
"macros",
"libreoffice",
"ubuntu-13.10"
] | When I go to **Tools -> Macros -> Organize Macros -> Python** I get this dialog:

It is **not possible** to create new Python macros.
Apparently LibreOffice has **no Python editor** so I have to write the macros elsewhere and then just execute them.
... | Try to manually make a subdirectory `python` (all lowercase) inside `/home/martin/.config/libreoffice/4/user/Scripts` and put your script there.
This is based on <https://wiki.openoffice.org/wiki/Python_as_a_macro_language> |
Multiple instances of a class | 21,414,621 | 3 | 2014-01-28T19:09:19Z | 21,414,650 | 8 | 2014-01-28T19:11:06Z | [
"python",
"multiple-instances",
"instances"
] | I have a class called `Points` and I need to create 100 points.
I need to do something like:
```
class Point(object)
...
for i in range(1,100):
pi = Point()
```
the points should be named `p1`, `p2`, ... `p100`
The lines above do not work, obviously.
The question is: I know that I could use `exec` inside a loo... | You can create several objects using list comprehension:
```
# 100 points in list
points = [Point() for _ in range(100)]
``` |
Convert timedelta to floating-point | 21,414,639 | 19 | 2014-01-28T19:10:22Z | 21,414,672 | 25 | 2014-01-28T19:11:51Z | [
"python",
"datetime",
"python-2.7",
"floating-point",
"timedelta"
] | I got a timedelta object from the subtraction of two datetimes. I need this value as floating point for further calculations.
All that I've found enables the calculation with floating-points, but the result
is still a timedelta object.
```
time_d = datetime_1 - datetime_2
time_d_float = float(time_d)
```
does not wor... | You could use the [`total_seconds`](http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds) method:
```
time_d_float = time_d.total_seconds()
``` |
Convert timedelta to floating-point | 21,414,639 | 19 | 2014-01-28T19:10:22Z | 21,418,736 | 8 | 2014-01-28T22:57:45Z | [
"python",
"datetime",
"python-2.7",
"floating-point",
"timedelta"
] | I got a timedelta object from the subtraction of two datetimes. I need this value as floating point for further calculations.
All that I've found enables the calculation with floating-points, but the result
is still a timedelta object.
```
time_d = datetime_1 - datetime_2
time_d_float = float(time_d)
```
does not wor... | In recent versions of Python, you can divide two `timedelta`s to give a float. This is useful if you need the value to be in units other than seconds.
```
time_d_min = time_d / datetime.timedelta(minutes=1)
time_d_ms = time_d / datetime.timedelta(milliseconds=1)
``` |
Cartesian projection issue in a FITS image through PyFITS / AstroPy | 21,415,059 | 5 | 2014-01-28T19:33:43Z | 21,416,968 | 7 | 2014-01-28T21:12:58Z | [
"python",
"matplotlib-basemap",
"fits",
"pyfits",
"astropy"
] | I've looked and looked for a solution to this problem and am turning up nothing.
I'm generating rectangular FITS images through matplotlib and subsequently applying WCS coordinates to them using AstroPy (or PyFITS). My images are in galactic latitude and longitude, so the header keywords appropriate for my maps should... | In the modern definition of the `-CAR` projection (from Calabretta et al.), `GLON-CAR`/`GLAT-CAR` projection only produces a rectilinear grid if `CRVAL2` is set to zero. If `CRVAL2` is not zero, then the grid is curved (this should have nothing to do with Astropy). You can try and fix this by adjusting `CRVAL2` and `CR... |
Logic operator for boolean indexing in Pandas | 21,415,661 | 20 | 2014-01-28T20:04:04Z | 21,415,990 | 41 | 2014-01-28T20:22:56Z | [
"python",
"pandas",
"boolean-logic"
] | I'm working with boolean index in Pandas.
The question is why the statement:
```
a[(a['some_column']==some_number) & (a['some_other_column']==some_other_number)]
```
works fine whereas
```
a[(a['some_column']==some_number) and (a['some_other_column']==some_other_number)]
```
exists with error?
Example:
```
a=pd.D... | When you say
```
(a['x']==1) and (a['y']==10)
```
You are implicitly asking Python to convert `(a['x']==1)` and `(a['y']==10)` to boolean values.
NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise
```
ValueError: The truth value of an ... |
python - inheriting parent class | 21,416,733 | 2 | 2014-01-28T21:01:34Z | 21,416,834 | 8 | 2014-01-28T21:06:48Z | [
"python",
"python-3.x"
] | ```
class A:
class B(A):
pass
```
This does not work. Why? How do I make something that behaves the same way?
By same I mean:
* The same `__class__.__name__`
* The same `__class__.__qualname__`
* `A.B.__base__ is A` | No, not without workarounds. The first class doesn't even exist at the time its body (including the `class B(A)` part) is executed. You can define the two separtely though:
```
class A:
pass
class B(A):
pass
A.B = B
B.__name__ = ...
B.__qualname__ = ...
```
But honestly this doesn't look like the best desig... |
how do I do the equivelant of casting to int, in python | 21,418,707 | 4 | 2014-01-28T22:55:54Z | 21,418,744 | 7 | 2014-01-28T22:58:24Z | [
"python",
"c"
] | I have a function that returns a value to me as a string. This is not the ascii representation of the value, this is the actual value, but the function returns it as a string type, while I need to treat it as an int. I'm not allowed to change the function I just have to extract my data out of it.
in C I would just cas... | Check out the [`struct`](http://docs.python.org/2/library/struct.html) module:
```
>>> struct.unpack('i', 'AAAA')[0] # 'i' means "long" integer
# 'AAAA' was the string you wanted cast to int
1094795585
>>> hex(_)
0x41414141
``` |
Why there is no early termination in bitwise operations? | 21,418,855 | 6 | 2014-01-28T23:06:09Z | 21,418,895 | 8 | 2014-01-28T23:09:11Z | [
"python",
"bit-manipulation"
] | ```
def func():
print 'no early termination'
return 0
if __name__ == "__main__":
if 1 or func():
print 'finished'
```
The output:
```
finished
```
since the "1 or func()" terminates early without calling the func() because "1 or something" is always true.
However, when switching to bitwise opera... | `|` can't short-circuit because its value depends on its right-hand operand even if its left-hand operand is true. For example, in
```
x = 1 | 2
```
the value of `x` can't be determined without knowing that there's a `2` on the right.
If we only cared about whether the `if` branch was taken, Python might be able to ... |
Need help in adding binary numbers in python | 21,420,447 | 2 | 2014-01-29T01:36:17Z | 21,420,557 | 13 | 2014-01-29T01:48:39Z | [
"python",
"binary",
"addition"
] | If I have 2 numbers in binary form as a string, and I want to add them I will do it digit by digit, from the right most end. So 001 + 010 = 011
But suppose I have to do 001+001, how should I create a code to figure out how to take carry over responses? | `bin` and `int` are very useful here:
```
a = '001'
b = '011'
c = bin(int(a,2) + int(b,2))
# 0b100
```
`int` allows you to specify what base the first argument is in when converting from a string (in this case two), and `bin` converts a number back to a binary string. |
How to use pyreverse on Windows | 21,420,715 | 5 | 2014-01-29T02:05:27Z | 22,222,786 | 7 | 2014-03-06T11:14:13Z | [
"python",
"class",
"uml",
"diagram"
] | I would like to create diagram class using pyreverse. I download it, and when I use this command:
```
pyreverse.bat -c PyreverseCommand -a1 -s1 -f ALL -o png test.py
```
I get an error "The name 'dot' is not recognized....". What is "dot", how can I create diagram class?
Thanks for answers. | dot is part of Graphviz (<http://www.graphviz.org/About.php>). You need to install Graphviz and then modify your PATH so Windows (what I assume you are using) can find it. "the command pyreverse generates the diagrams in all formats that graphviz/dot knows." (<http://www.logilab.org/blogentry/6883>.)
Once installed do... |
Exponential curve fitting in SciPy | 21,420,792 | 15 | 2014-01-29T02:14:06Z | 21,421,137 | 22 | 2014-01-29T02:53:39Z | [
"python",
"numpy",
"scipy",
"curve-fitting"
] | I have two NumPy arrays x and y. When I try to fit my data using exponential function and curve\_fit (SciPy) with this simple code
```
#!/usr/bin/env python
from pylab import *
from scipy.optimize import curve_fit
x = np.array([399.75, 989.25, 1578.75, 2168.25, 2757.75, 3347.25, 3936.75, 4526.25, 5115.75, 5705.25])
y... | First comment: since `a*exp(b - c*x) = (a*exp(b))*exp(-c*x) = A*exp(-c*x)`, `a` or `b` is redundant. I'll drop `b` and use:
```
def func(x, a, c, d):
return a*np.exp(-c*x)+d
```
That isn't the main issue. The problem is simply that `curve_fit` fails to converge to a solution to this problem when you use the defau... |
What is the pythonic way to calculate argmax? | 21,420,800 | 2 | 2014-01-29T02:14:39Z | 21,420,851 | 8 | 2014-01-29T02:20:35Z | [
"python",
"list",
"function",
"max",
"argmax"
] | If i have a list and a function to calculate score, I could calculate argmax as such:
```
maxscore = 0; argmax = None
x = [3.49, 0.122, 293, 0.98] # Imagine a LARGE list.
for i in x:
# Maybe there're some other func() to calculate score
# For now just sum the digits in i.
score = sum([int(j) for j in str(i... | ```
def score(i):
return sum([int(j) for j in str(i) if j.isdigit()])
max(x, key=score)
``` |
How to fix the false positives rate of a linear SVM? | 21,420,868 | 5 | 2014-01-29T02:23:17Z | 21,428,278 | 8 | 2014-01-29T10:29:52Z | [
"python",
"svm",
"scikit-learn"
] | I am an SVM newbie and this is my use case: I have a lot of unbalanced data to be binary classified using a linear SVM. I need to fix the false positives rate at certain values and measure the corresponding false negatives for each value. I am using something like the following code making use of scikit-learn svm imple... | The `class_weights` parameter allows you to push this false positive rate up or down. Let me use an everyday example to illustrate how this work. Suppose you own a night club, and you operate under two constraints:
1. You want as many people as possible to enter the club (paying customers)
2. You do not want any under... |
How to use Cleaner, lxml.html without returning div tag? | 21,420,922 | 4 | 2014-01-29T02:28:27Z | 21,420,985 | 12 | 2014-01-29T02:36:14Z | [
"python",
"lxml.html"
] | I have this code:
```
evil = "<script>malignus script</script><b>bold text</b><i>italic text</i>"
cleaner = Cleaner(remove_unknown_tags=False, allow_tags=['p', 'br', 'b'],
page_structure=True)
print cleaner.clean_html(evil)
```
I expected to get this:
```
<b>bold text</b>italic text
```
But instea... | lxml expects your html to have a tree structure, ie a single root node. If it does not have one, it adds it. |
How can I start an interactive python/ipython session from the middle of my python program? | 21,421,207 | 4 | 2014-01-29T02:59:56Z | 21,421,336 | 7 | 2014-01-29T03:14:23Z | [
"python",
"ipython"
] | I have a python program which first does some tasks, and then in certain conditions goes into an interactive mode, where the user has access to an interactive python console with the current program's scope. Right now I do this using the code module by calling code.InteractiveConsole(globals()).interact('') (see <http:... | Just use [`IPython.embed()`](http://ipython.org/ipython-doc/rel-1.1.0/interactive/reference.html) where you're currently using `code.InteractiveConsole(globals()).interact('')`.
Make sure you're importing IPython before you do that, though:
```
import IPython
# lots of code
# even more code
IPython.embed()
``` |
Read file with timeout in Python | 21,429,369 | 7 | 2014-01-29T11:13:31Z | 21,429,655 | 10 | 2014-01-29T11:25:22Z | [
"python",
"linux",
"python-2.7"
] | Within Linux, there is a file, `/sys/kernel/debug/tracing/trace_pipe`, which as the name says, is a pipe. So, let's say I want to read the first 50 bytes from it using Python - and I run the following code:
```
$sudo python -c 'f=open("/sys/kernel/debug/tracing/trace_pipe","r"); print f; print f.read(50); f.close()<br... | Use
```
os.read(f.fileno(), 50)
```
instead. That does not wait until the specified amount of bytes has been read but returns when it has read anything (at most the specified amount of bytes).
This does not solve your issue in case you've got *nothing* to read from that pipe. In that case you should use `select` fro... |
Read file with timeout in Python | 21,429,369 | 7 | 2014-01-29T11:13:31Z | 21,429,900 | 8 | 2014-01-29T11:35:37Z | [
"python",
"linux",
"python-2.7"
] | Within Linux, there is a file, `/sys/kernel/debug/tracing/trace_pipe`, which as the name says, is a pipe. So, let's say I want to read the first 50 bytes from it using Python - and I run the following code:
```
$sudo python -c 'f=open("/sys/kernel/debug/tracing/trace_pipe","r"); print f; print f.read(50); f.close()<br... | ```
f = os.open("/sys/kernel/debug/tracing/trace_pipe", os.O_RDONLY|os.O_NONBLOCK)
```
Should prevent blocking (works in Unix only)..
No need for select here.. |
ReferenceError: "something" is not defined in QML | 21,430,421 | 7 | 2014-01-29T11:56:09Z | 21,511,448 | 12 | 2014-02-02T14:01:27Z | [
"python",
"qt",
"qml",
"python-3.3",
"pyqt5"
] | I have Main.qml file like this:
```
import QtQuick 2.0
Rectangle {
color: ggg.Colors.notificationMouseOverColor
width: 1024
height: 768
}
```
in python file, i have this(i use form PyQt5):
```
App = QGuiApplication(sys.argv)
View = QQuickView()
View.setSource(QUrl('views/sc_side/Main.qml'))
Context ... | You need to set the context property *before* you call `View.setSource`, otherwise at the moment the qml file is read the property `ggg` is indeed not defined.
Try this:
```
App = QGuiApplication(sys.argv)
View = QQuickView()
Context = View.rootContext()
GlobalConfig = Config('sc').getGlobalConfig()
print (GlobalCon... |
ReferenceError: "something" is not defined in QML | 21,430,421 | 7 | 2014-01-29T11:56:09Z | 21,557,036 | 7 | 2014-02-04T15:50:53Z | [
"python",
"qt",
"qml",
"python-3.3",
"pyqt5"
] | I have Main.qml file like this:
```
import QtQuick 2.0
Rectangle {
color: ggg.Colors.notificationMouseOverColor
width: 1024
height: 768
}
```
in python file, i have this(i use form PyQt5):
```
App = QGuiApplication(sys.argv)
View = QQuickView()
View.setSource(QUrl('views/sc_side/Main.qml'))
Context ... | You have to define the context property before loading QML file,
it's better because it avoids warnings and context reloading.
If you are REALLY forced to do it after, just add a security in your QML code :
```
color: (typeof (ggg) !== "undefined" ? ggg.Colors.notificationMouseOverColor : "transparent");
```
Then wh... |
py.test skips test class if constructor is defined | 21,430,900 | 13 | 2014-01-29T12:17:16Z | 21,431,187 | 7 | 2014-01-29T12:30:20Z | [
"python",
"py.test"
] | I have following unittest code running via py.test.
Mere presence of the constructor make the entire class skip when running
py.test -v -s
collected 0 items / 1 skipped
Can anyone please explain to me this behaviour of py.test?
I am interested in understanding py.test behaviour, I know the constructor is not needed.... | The documentation for py.test [says](http://pytest.org/latest/goodpractices.html#conventions-for-python-test-discovery) that py.test implements the following standard test discovery:
* collection starts from the initial command line arguments which may be directories, filenames or test ids.
recurse into directories,... |
py.test skips test class if constructor is defined | 21,430,900 | 13 | 2014-01-29T12:17:16Z | 21,440,548 | 12 | 2014-01-29T19:20:28Z | [
"python",
"py.test"
] | I have following unittest code running via py.test.
Mere presence of the constructor make the entire class skip when running
py.test -v -s
collected 0 items / 1 skipped
Can anyone please explain to me this behaviour of py.test?
I am interested in understanding py.test behaviour, I know the constructor is not needed.... | As already mentioned in the answer by Matti Lyra py.test purposely skips classes which have a constructor. The reason for this is that classes are only used for structural reasons in py.test and do not have any inherent behaviour, while when actually writing code it is the opposite and much rarer to not have an `.__ini... |
What is the new approach to get user profile in Django 1.6? | 21,431,477 | 4 | 2014-01-29T12:42:12Z | 21,431,659 | 8 | 2014-01-29T12:49:35Z | [
"python",
"django"
] | I'm quite new to Django. I'm trying to get user profile with the help of `request.user.get_profile()` but there is a warning that the use of `AUTH_PROFILE_MODULE` has been deprecated.
I have a line in my settings.py: `AUTH_PROFILE_MODULE = "log_viewer.Configs"` where `Configs` is a model with fields to keep user profi... | At first,I create a 'profile' for User:
```
User.profile = property(lambda u: Configs.objects.get_or_create(user=u)[0])
```
and use this to get the profile:
```
request.user.profile
```
more detail here: <https://code.djangoproject.com/ticket/15937> |
Django REST - AssertionError: `fields` must be a list or tuple | 21,431,782 | 3 | 2014-01-29T12:55:43Z | 21,431,823 | 10 | 2014-01-29T12:57:39Z | [
"python",
"django-rest-framework"
] | When querying Django via REST using the Django REST framework I get the error,
```
File "/folder/pythonenv/project/lib/python2.7/site-packages/rest_framework/serializers.py", line 241, in get_fields
assert isinstance(self.opts.fields, (list, tuple)), '`fields` must be a list or tuple'
AssertionError: `fields` mu... | You need to use a tuple or list for `fields`, to represent a tuple with single item you need to use a trailing comma:
```
fields = ('test', )
```
Without a comma `fields = ('test')` is actually equivalent to `fields = 'test'`.
From [docs](http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences):
... |
Python append to csv file without whiteline | 21,432,610 | 4 | 2014-01-29T13:32:20Z | 21,432,697 | 8 | 2014-01-29T13:35:55Z | [
"python",
"python-2.7",
"csv"
] | I'm writing a game in python. And after each round of the game (yes, the game has multiple rounds) I want to write the data to a CSV file.
this is my code:
```
with open('data.csv', 'a') as fp:
for player in self.players:
a = csv.writer(fp, delimiter=',');
data = [[player.n... | **Python 3:**
```
with open('data.csv', 'a', newline='') as fp:
for player in self.players:
a = csv.writer(fp, delimiter=',');
data = [[player.name, player.penalty(), player.score()]];
a.writerows(data);
```
With python 3 there is change in the CSV module you can read [here](http://docs.py... |
Merge multiple dictionaries conditionally | 21,433,084 | 7 | 2014-01-29T13:52:06Z | 21,433,202 | 7 | 2014-01-29T13:57:32Z | [
"python",
"dictionary"
] | I have N dictionaries that contain the same keys, with values that are integers. I want to merge these into a single dictionary based on the maximum value. Currently I have something like this:
```
max_dict = {}
for dict in original_dict_list:
for key, val in dict.iteritems():
if key not in max_dict or max... | Use [`collection.Counter()` objects](http://docs.python.org/2/library/collections.html#collections.Counter) instead, they support 'merging' counts natively:
```
from collections import Counter
max_dict = Counter()
for d in original_dict_list:
max_dict |= Counter(d)
```
or even:
```
from collections import Count... |
Cubic spline memory error | 21,435,648 | 9 | 2014-01-29T15:37:47Z | 21,440,722 | 10 | 2014-01-29T19:28:49Z | [
"python",
"numpy",
"scipy",
"interpolation"
] | On a computer with 4GB of memory this simple interpolation leads to a memory error:
(based on: <http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html>)
```
import numpy as np
from scipy.interpolate import interp1d
x = np.linspace(0, 10, 80000)
y = np.cos(-x**2/8.0)
f2 = interp1d(x, y, kind='cubic')
```... | If you look at the traceback when the error occurs, you'll see something like:
```
---------------------------------------------------------------------------
MemoryError Traceback (most recent call last)
<ipython-input-4-1e538e8d766e> in <module>()
----> 1 f2 = interp1d(x, y, kind='cubic... |
TypeError: can't use a string pattern on a bytes-like object | 21,436,163 | 23 | 2014-01-29T15:59:10Z | 21,436,251 | 32 | 2014-01-29T16:02:28Z | [
"python",
"json",
"string",
"python-3.x",
"bytestring"
] | ```
import json
import requests
url = 'http://developer.usa.gov/1usagov.json'
r = requests.get(url, stream=True)
for line in r.iter_lines():
if line:
print (json.loads(line))
```
Gives this error:
```
TypeError: can't use a string pattern on a bytes-like object
```
While viewing through the browser i d... | If you use Python 3.x, you should pass `str` object to [`json.loads`](http://docs.python.org/3/library/json.html#json.loads).
Replace following line:
```
print(json.loads(line))
```
with:
```
print(json.loads(line.decode()))
``` |
defining python argparse arguments | 21,437,258 | 3 | 2014-01-29T16:44:37Z | 21,437,360 | 9 | 2014-01-29T16:48:51Z | [
"python",
"command-line",
"argparse"
] | Im trying to write a python program that I will run at the command line. I'd like the program to take a single input variable. Specifically, I would use a date in the form of 2014-01-28 (yyyy-mm-dd):
e.g.
python my\_script.py 2014-01-28
It seems argparse might be able to help me but I have found very little document... | There's lots of documentation [in the standard library](http://docs.python.org/dev/library/argparse.html), but generally, something like:
```
import argparse
import datetime
parser = argparse.ArgumentParser()
parser.add_argument('date', type=lambda s: datetime.datetime.strptime(s, '%Y-%m-%d'))
args = parser.parse_arg... |
Launch HTML code in browser (that is generated by BeautifulSoup) straight from Python | 21,437,386 | 7 | 2014-01-29T16:49:49Z | 21,437,460 | 8 | 2014-01-29T16:53:09Z | [
"python",
"html",
"python-3.x",
"beautifulsoup"
] | I have used BeautifulSoup for Python 3.3 to successfully pull desired info from a web page. I have also used BeautifulSoup to generate new HTML code to display this info. Currently, my Python program prints out the HTML code, which I then have to copy, paste, and save as an HTML file, then from there, I can test it in ... | Using [`webbrowser.open`](http://docs.python.org/3/library/webbrowser.html#webbrowser.open):
```
import os
import webbrowser
html = '<html> ... generated html string ...</html>'
path = os.path.abspath('temp.html')
url = 'file://' + path
with open(path, 'w') as f:
f.write(html)
webbrowser.open(url)
``` |
Best way to split a list into randomly sized chunks? | 21,439,011 | 2 | 2014-01-29T18:01:41Z | 21,439,176 | 9 | 2014-01-29T18:10:50Z | [
"python",
"list",
"math"
] | I have a list of numbers such as [5000, 5000, 5000, 5000, 5000, 5000]
I need to create a function that turns that list into a list of randomly sized smaller lists, such as
[[5000, 5000], [5000, 5000, 5000], [5000]]
What's the best way to do this in python? | ```
from itertools import islice
from random import randint
def random_chunk(li, min_chunk=1, max_chunk=3):
it = iter(li)
while True:
nxt = list(islice(it,randint(min_chunk,max_chunk)))
if nxt:
yield nxt
else:
break
```
demo:
```
li = [5000, 5000, 5000, 5000, 5... |
Install mysql-python (Windows) | 21,440,230 | 18 | 2014-01-29T19:03:17Z | 25,445,938 | 8 | 2014-08-22T11:28:48Z | [
"python",
"mysql",
"django",
"mysql-python"
] | I've spent hours trying to make Django work on my computer. The problem is that I can't install the mysql-python package. I'm running Windows 7 64bit. This is what I've tried:
1. I have downloaded easy\_install
2. I have downloaded Cygwin64 to be able to run Linux commands (Win cmd was driving me crazy)
3. I have type... | There are windows installers for MySQLdb avaialable for both 32 and 64 bit, supporting Python from 2.6 to 3.4. Check [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python). |
Install mysql-python (Windows) | 21,440,230 | 18 | 2014-01-29T19:03:17Z | 31,287,400 | 22 | 2015-07-08T08:31:49Z | [
"python",
"mysql",
"django",
"mysql-python"
] | I've spent hours trying to make Django work on my computer. The problem is that I can't install the mysql-python package. I'm running Windows 7 64bit. This is what I've tried:
1. I have downloaded easy\_install
2. I have downloaded Cygwin64 to be able to run Linux commands (Win cmd was driving me crazy)
3. I have type... | try running the follow command:
pip install mysqlclient |
Django got an unexpected keyword argument | 21,440,846 | 2 | 2014-01-29T19:35:18Z | 21,440,938 | 7 | 2014-01-29T19:40:10Z | [
"python",
"django"
] | I'm trying to create an archive so I pass to the view the arguments year and month.
However, I get an error with the code below and I can't figure out what it means and how to solve it:
```
Exception Type: TypeError
Exception Value: archive() got an unexpected keyword argument 'year_id'
Exception Location: /usr/lo... | There is something wrong with your parameters names :
```
def archive(request, year, month):
```
Replace `year` and `month` by `year_id` and `month_id` and it should work.
EDIT:
For your second error, and accordingly to [this question](http://stackoverflow.com/questions/6194117/simple-django-program-causing-me-tro... |
Pandas Groupby Range of Values | 21,441,259 | 17 | 2014-01-29T19:55:27Z | 21,441,621 | 26 | 2014-01-29T20:12:29Z | [
"python",
"group-by",
"pandas"
] | Is there an easy method in pandas to groupby a range of value increments? For instance given the example below can I bin and group column B with a 0.155 increment so that for example, the first couple of groups in column B are divided into ranges between 0 - 0.155, 0.155 - 0.31 ...
```
import numpy as np
import pandas... | You might be interested in [`pd.cut`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html):
```
>>> df.groupby(pd.cut(df["B"], np.arange(0, 1.0+0.155, 0.155))).sum()
A B
B
(0, 0.155] 2.775458 0.246394
(0.155, 0.31] 1.123989 0.471618... |
Fabric - Is there any way to capture run stdout? | 21,443,690 | 13 | 2014-01-29T22:06:43Z | 21,444,507 | 17 | 2014-01-29T22:58:40Z | [
"python",
"fabric"
] | I'm trying to do the following:
```
output = run("ls -l backups")
for line in output.split("/n"):
do_stuff(line)
```
Any way of having the `stdout` of `ls` sent to `output`?
---
To be more specific I'm using a CLI app called `s3cmd` which does something similar to `ls`, but with remote Amazon S3 buckets.
So a ... | Exactly what you are asking for should be happening. From the [docs](http://docs.fabfile.org/en/latest/api/core/operations.html#fabric.operations.run):
> run will return the result of the remote programâs stdout as a single (likely multiline) string.
`run()`, and related commands like `local()` and `sudo()`, return... |
Fabric - Is there any way to capture run stdout? | 21,443,690 | 13 | 2014-01-29T22:06:43Z | 22,373,249 | 12 | 2014-03-13T08:43:52Z | [
"python",
"fabric"
] | I'm trying to do the following:
```
output = run("ls -l backups")
for line in output.split("/n"):
do_stuff(line)
```
Any way of having the `stdout` of `ls` sent to `output`?
---
To be more specific I'm using a CLI app called `s3cmd` which does something similar to `ls`, but with remote Amazon S3 buckets.
So a ... | Try as below using String IO
```
from fabric.api import *
from StringIO import StringIO
fh = StringIO();
run("ls -l backups", stdout=fh)
for line in fh.readlines():
do_stuff(line)
``` |
scikit-learn cross validation, negative values with mean squared error | 21,443,865 | 13 | 2014-01-29T22:18:07Z | 27,323,356 | 12 | 2014-12-05T19:36:00Z | [
"python",
"regression",
"scikit-learn",
"cross-validation"
] | When I use the following code with Data matrix `X` of size (952,144) and output vector `y` of size (952), `mean_squared_error` metric returns negative values, which is unexpected. Do you have any idea?
```
from sklearn.svm import SVR
from sklearn import cross_validation as CV
reg = SVR(C=1., epsilon=0.1, kernel='rbf'... | Trying to close this out, so am providing the answer that David and larsmans have eloquently described in the comments section:
Yes, this is supposed to happen. The actual MSE is simply the positive version of the number you're getting.
The unified scoring API always maximizes the score, so scores which need to be mi... |
Pandas: Multilevel column names | 21,443,963 | 9 | 2014-01-29T22:24:06Z | 26,332,512 | 7 | 2014-10-13T03:26:18Z | [
"python",
"pandas"
] | `pandas` has support for multi-level column names:
```
>>> x = pd.DataFrame({'instance':['first','first','first'],'foo':['a','b','c'],'bar':rand(3)})
>>> x = x.set_index(['instance','foo']).transpose()
>>> x.columns
MultiIndex
[(u'first', u'a'), (u'first', u'b'), (u'first', u'c')]
>>> x
instance first ... | Try this:
```
df=pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})
columns=[('c','a'),('c','b')]
df.columns=pd.MultiIndex.from_tuples(columns)
``` |
Transpose nested list in python | 21,444,338 | 10 | 2014-01-29T22:47:46Z | 21,444,360 | 20 | 2014-01-29T22:48:57Z | [
"python",
"list"
] | I like to move each item in this list to another nested list could someone help me?
```
a = [['AAA', '1', '1', '10', '92'], ['BBB', '262', '56', '238', '142'], ['CCC', '86', '84', '149', '30'], ['DDD', '48', '362', '205', '237'], ['EEE', '8', '33', '96', '336'], ['FFF', '39', '82', '89', '140'], ['GGG', '170', '296', ... | Use `zip` with `*` and `map`:
```
>>> map(list, zip(*a))
[['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG', 'HHH', 'III'],
['1', '262', '86', '48', '8', '39', '170', '16', '4'],
['1', '56', '84', '362', '33', '82', '296', '40', '3'],
['10', '238', '149', '205', '96', '89', '223', '65', '5'],
['92', '142', '30', '2... |
wxpython 3.0 breaks older apps? (locale error) | 21,444,951 | 4 | 2014-01-29T23:29:47Z | 24,763,770 | 10 | 2014-07-15T16:46:25Z | [
"python",
"python-2.7",
"wxpython"
] | I had an app that was working properly with old verions of wxpython
Now with wxpython 3.0, when trying to run the app, I get the following error
```
File "C:\Python27\lib\site-packages\wx-3.0-msw\wx\_controls.py", line 6523, in __init__
_controls_.DatePickerCtrl_swiginit(self,_controls_.new_DatePickerCtrl(*args... | I know it's been a while since this question was asked, but I just had the same issue and thought I'd add my solution in case someone else finds this thread. Basically what's happening is that the locale of your script is somehow conflicting with the locale of the machine, although I'm not sure how or why. Maybe someon... |
Drawing rectangle with border only in matplotlib | 21,445,005 | 9 | 2014-01-29T23:35:15Z | 21,445,449 | 8 | 2014-01-30T00:12:50Z | [
"python",
"matplotlib"
] | So I found the following code [here](http://stackoverflow.com/questions/13013781/how-to-draw-a-rectangle-over-a-specific-region-in-a-matplotlib-graph):
```
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
someX, someY = 0.5, 0.5
plt.figure()
currentAxis = plt.gca()
currentAxis.add_patch(Re... | You just need to set the `facecolor` to the string 'none' (not the python `None`)
```
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
someX, someY = 0.5, 0.5
fig,ax = plt.subplots()
currentAxis = plt.gca()
currentAxis.add_patch(Rectangle((someX - 0.1, someY - 0.1), 0.2, 0.2,
... |
Average of all values in a list - is there a more 'Pythonic' way to do this? | 21,446,189 | 2 | 2014-01-30T01:26:21Z | 21,446,195 | 9 | 2014-01-30T01:27:09Z | [
"python",
"python-3.x"
] | So I'm following a beginner's guide to Python and I got this exercise:
> Create a list containing 100 random integers between 0 and 1000 (use
> iteration, append, and the random module). Write a function called
> `average` that will take the list as a parameter and return the average.
I solved it easily in a few minu... | Using Python's builtin `sum` and `len` functions:
```
print sum(myList)/len(myList)
``` |
Linux - Weird Python Output | 21,446,220 | 5 | 2014-01-30T01:30:42Z | 21,446,333 | 7 | 2014-01-30T01:43:46Z | [
"python",
"linux"
] | When ever i mistype or do a error into the console the following message come up:
```
Traceback (most recent call last):
File "/usr/lib/python3.3/site.py", line 629, in <module>
main()
File "/usr/lib/python3.3/site.py", line 614, in main
known_paths = addusersitepackages(known_paths)
File "/usr/lib/pyt... | Assuming you are using ubuntu, here is the relevant bug report <https://bugs.launchpad.net/ubuntu/+source/python3.3/+bug/1192890>
You need to patch your /etc/bash.bashrc. See comment #6 for details |
Persist variable changes between tests in unittest? | 21,447,740 | 9 | 2014-01-30T04:19:26Z | 24,934,145 | 10 | 2014-07-24T12:49:11Z | [
"python",
"unit-testing",
"persistence",
"testcase",
"python-unittest"
] | How do I persist changes made within the same object inheriting from `TestCase` in unitttest?
```
from unittest import TestCase, main as unittest_main
class TestSimpleFoo(TestCase):
foo = 'bar'
def setUp(self):
pass
def test_a(self):
self.assertEqual(self.foo, 'bar')
self.foo = ... | As some comments have echoed, structuring your tests in this manner is probably a design flaw in the tests themselves and you should consider restructuring them. However, if you want to do this and rely on the fact that the test runner you are using executes them in an alphabetical (seemingly) order then I suggest the ... |
Getting indices of True values in a boolean list | 21,448,225 | 14 | 2014-01-30T05:04:45Z | 21,448,251 | 22 | 2014-01-30T05:07:31Z | [
"python",
"list"
] | I have a piece of my code where I'm supposed to create a switchboard. I want to return a list of all the switches that are on. Here "on" will equal `True` and "off" equal `False`. So now I just want to return a list of all the `True` values and their position. This is all I have but it only return the position of the f... | Use `enumerate`, `list.index` returns the index of first match found.
```
>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> [i for i, x in enumerate(t) if x]
[4, 5, 7]
```
For huge lists, it'd be better to use `itertools.compress`:
```
>>> from ... |
Python List in a For Loop | 21,450,874 | 5 | 2014-01-30T08:07:22Z | 21,450,922 | 7 | 2014-01-30T08:10:20Z | [
"python",
"string",
"list",
"loops"
] | I am new to Python and had a question about updating a list using a for loop. Here is my code:
```
urls = ['http://www.city-data.com/city/javascript:l("Abbott");' , 'http://www.city-data.com/city/javascript:l("Abernathy");' ,
'http://www.city-data.com/city/Abilene-Texas.html' ,'http://www.city-data.com/city/javascrip... | You can update the list items using their index:
```
for i, url in enumerate(urls):
if "javascript" in url:
urls[i] = url.replace('javascript:l("','').replace('");','-Texas.html')
```
Another alternative is to use a list comprehension:
```
def my_replace(s):
return s.replace('javascript:l("','').repl... |
Finding minimal distance between unsorted and sorted lists | 21,452,645 | 8 | 2014-01-30T09:38:10Z | 21,455,037 | 10 | 2014-01-30T11:21:26Z | [
"javascript",
"python",
"algorithm",
"language-agnostic"
] | Let A be a list and S a sorted list of the same elements. Assume all elements are different. How do I find a minimal set of "moves" (`move X before Y (or end)`) that turns A into S?
Examples:
```
A = [8,1,2,3]
S = [1,2,3,8]
A => S requires one move:
move 8 before end
A = [9,1,2,3,0]
S = [0,1,2,3,9]
A => S requ... | This problem is equivalent to [longest increasing subsequence](http://en.wikipedia.org/wiki/Longest_increasing_subsequence) problem.
You will have to define a comparison operator `less`. `less(a, b)` will return `true` if and only if `a` is before `b` in the target sequence. Now using this comparison operator, compute... |
Plotting confidence intervals for Maximum Likelihood Estimate | 21,453,404 | 13 | 2014-01-30T10:09:47Z | 21,500,840 | 8 | 2014-02-01T16:56:31Z | [
"python",
"numpy",
"statistics",
"scipy",
"statsmodels"
] | I am trying to write code to produce confidence intervals for the number of different books in a library (as well as produce an informative plot).
My cousin is at elementary school and every week is given a book by his teacher. He then reads it and returns it in time to get another one the next week. After a while we ... | Looks like you're ok on the first part, so I'll tackle your second and third points.
There are plenty of ways to fit smooth curves, with [scipy.interpolate](http://docs.scipy.org/doc/scipy/reference/interpolate.html) and splines, or with [scipy.optimize.curve\_fit](http://docs.scipy.org/doc/scipy/reference/generated/s... |
List available tests with py.test | 21,455,134 | 5 | 2014-01-30T11:25:52Z | 21,462,398 | 13 | 2014-01-30T16:45:07Z | [
"python",
"unit-testing",
"py.test"
] | I can't find a way to list the tests which I can call with `py.test -k PATTERN`
How can I see the list of the available tests? | You can also use `--collect-only`, this will show a tree-like structure of the collected nodes. Usually one can simply `-k` on the names of the Function nodes. |
install filter on logging level in python using dictConfig | 21,455,515 | 2 | 2014-01-30T11:41:26Z | 21,464,327 | 9 | 2014-01-30T18:12:03Z | [
"python",
"python-2.7",
"logging"
] | I cannot install a filter on a logging handler using `dictConfig()` syntax. `LoggingErrorFilter.filter()` is simply ignored, nothing happens.
I want to filter out error messages so that they do not appear twice in the log output. So I wrote `LoggingErrorFilter` class and overrode `filter()`.
My configuration:
```
cl... | Actually, `Tupteq`'s answer is not correct in general. The following script:
```
import logging
import logging.config
import sys
class MyFilter(logging.Filter):
def __init__(self, param=None):
self.param = param
def filter(self, record):
if self.param is None:
allow = True
... |
plot() doesn't work on IPython notebook | 21,457,571 | 6 | 2014-01-30T13:14:39Z | 21,457,629 | 14 | 2014-01-30T13:17:50Z | [
"python",
"matplotlib",
"ipython",
"ipython-notebook"
] | I'm new to python scientific computing, and I tried to make a simple graph on IPython notebook.
```
import pandas
plot(arange(10))
```
Then error had shown as below.
```
---------------------------------------------------------------------------
NameError Traceback (most recent call l... | It is not advisable to use `pylab` mode. See the following [post](http://nbviewer.ipython.org/github/Carreau/posts/blob/master/10-No-PyLab-Thanks.ipynb?create=1) from [Matthias Bussonnier](https://twitter.com/Mbussonn)
A summary from that post:
Why not to use `pylab` flag:
1. It is irreversible- Cannot unimport
2. U... |
TransactionManagementError "You can't execute queries until the end of the 'atomic' block" while using signals, but only during Unit Testing | 21,458,387 | 74 | 2014-01-30T13:52:26Z | 23,326,971 | 85 | 2014-04-27T18:01:05Z | [
"python",
"django",
"unit-testing",
"django-signals"
] | I am getting TransactionManagementError when trying to save a Django User model instance and in its post\_save signal, I'm saving some models that have the user as the foreign key.
The context and error is pretty similar to this question
[django TransactionManagementError when using signals](http://stackoverflow.com/q... | I ran into this same problem myself. This is caused by a quirk in how transactions are handled in the newer versions of Django coupled with a unittest that intentionally triggers an exception.
I had a unittest that checked to make sure a unique column constraint was enforced by purposefully triggering an IntegrityErro... |
TransactionManagementError "You can't execute queries until the end of the 'atomic' block" while using signals, but only during Unit Testing | 21,458,387 | 74 | 2014-01-30T13:52:26Z | 34,801,920 | 7 | 2016-01-14T23:45:00Z | [
"python",
"django",
"unit-testing",
"django-signals"
] | I am getting TransactionManagementError when trying to save a Django User model instance and in its post\_save signal, I'm saving some models that have the user as the foreign key.
The context and error is pretty similar to this question
[django TransactionManagementError when using signals](http://stackoverflow.com/q... | Since @mkoistinen never made [his comment](http://stackoverflow.com/questions/21458387/transactionmanagementerror-you-cant-execute-queries-until-the-end-of-the-atom#comment44444356_23326971), an answer, I'll post his suggestion so people won't have to dig through comments.
> consider just declaring your test class as ... |
NumPy - Faster way to implement threshold value ceiling | 21,459,758 | 4 | 2014-01-30T14:53:43Z | 21,459,810 | 10 | 2014-01-30T14:55:43Z | [
"python",
"image-processing",
"numpy"
] | I'm writing a script to modify the luminance of a RGB image using NumPy and CV2 via converting from RGB to YCrCb and back again. However, the loop I'm using takes a while to execute, and am wondering if there is a faster way.
```
import cv2 as cv, numpy as np
threshold = 64
image = cv.imread("motorist.jpg", -1)
image... | The idea is to create a [*mask*](http://docs.scipy.org/doc/numpy/reference/routines.ma.html) that lets you use the numpy's vectorization. Since the shape is `(n,m,3)`, loop over the first two dimensions and grab the first index of the last dimension with `[:,:,0]`
```
idx = image[:,:,0] > threshold
image[idx,0] = thre... |
Select specific columns from table in SQLAlchemy | 21,460,013 | 2 | 2014-01-30T15:04:12Z | 21,460,189 | 7 | 2014-01-30T15:11:45Z | [
"python",
"sql",
"select",
"sqlalchemy"
] | I'm trying to select specific columns from a table like this:
```
users = Table('users', metadata, autoload=True)
s = users.select([users.c.email])
results = s.execute()
print results
```
and I'm getting this error:
```
> Traceback (most recent call last): File "my_mailer.py", line 35, in
> <module>
> s = user... | Use general purpose [`select`](http://docs.sqlalchemy.org/en/rel_0_9/core/selectable.html#sqlalchemy.sql.expression.select) instead of [`Table.select`](http://docs.sqlalchemy.org/en/rel_0_9/core/metadata.html#sqlalchemy.schema.Table.select):
```
stmt = select([users.c.email])
result = conn.execute(stmt)
``` |
change matplotlib's default font | 21,461,155 | 16 | 2014-01-30T15:52:54Z | 21,777,207 | 9 | 2014-02-14T10:45:39Z | [
"python",
"fonts",
"matplotlib",
"defaults"
] | I'm trying to change matplotlib's default font to Helvetica Neue. On my Mac with EPD/Canopy everything worked fine some time ago.
Trying to do the same on ubuntu now and it's not working.
This is what I did:
1. Installed Helvetica Neue
```
$ fc-match 'Helvetica Neue':Light
HelveticaNeue-Light.otf: "Helveti... | This won't change you font permanently, but it's worth a try
```
matplotlib.rc('font', family='sans-serif')
matplotlib.rc('font', serif='Helvetica Neue')
matplotlib.rc('text', usetex='false')
matplotlib.rcParams.update({'font.size': 22})
``` |
Pandas: Chained assignments | 21,463,589 | 13 | 2014-01-30T17:37:52Z | 21,463,854 | 16 | 2014-01-30T17:49:49Z | [
"python",
"pandas",
"copy"
] | I have been reading this [link](http://pandas-docs.github.io/pandas-docs-travis/indexing.html#indexing-view-versus-copy) on "Returning a view versus a copy". I do not really get how the **chained assignment** concept in Pandas works and how the usage of `.ix()`, `.iloc()`, or `.loc()` affects it.
I get the `SettingWit... | The point of the `SettingWithCopy` is to warn the user that you *may* be doing something that will not update the original data frame as one might expect.
Here, `data` is a dataframe, possibly of a single dtype (or not). You are then taking a reference to this `data['amount']` which is a Series, and updating it. This ... |
Resolving AmbiguousTimeError from Django's make_aware | 21,465,528 | 6 | 2014-01-30T19:17:01Z | 21,465,529 | 7 | 2014-01-30T19:17:01Z | [
"python",
"django",
"timezone",
"dst"
] | I have a code as follows:
```
from django.utils.timezone import get_current_timezone, make_aware
make_aware(some_datetime, get_current_timezone())
```
The `make_aware` call occasionally raises
```
AmbiguousTimeError: 2013-11-03 01:23:17
```
I know from the Django docs that this is a daylight savings problem, and t... | ## Prophylactics
You should avoid naive datetimes in the first place using the following:
```
from django.utils import timezone
now = timezone.now()
```
If like me, you have naive times already that you must convert, read on!
## Django 1.9+:
You can resolve the AmbiguousTimeError by using the following ([thanks to... |
Python equivalent to 'hold on' in Matlab | 21,465,988 | 22 | 2014-01-30T19:40:44Z | 21,466,136 | 22 | 2014-01-30T19:49:11Z | [
"python",
"matlab",
"graph",
"matplotlib"
] | Is there an explicit equivalent command in Python's matplotlib for Matlab's `hold on`? I'm trying to plot all my graphs on the same axes. Some graphs are generated inside a `for` loop, and these are plotted separately from `su` and `sl`:
```
import numpy as np
import matplotlib.pyplot as plt
for i in np.arange(1,5):
... | Just call `plt.show()` at the end:
```
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0,50,60,80])
for i in np.arange(1,5):
z = 68 + 4 * np.random.randn(50)
zm = np.cumsum(z) / range(1,len(z)+1)
plt.plot(zm)
n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)
plt.plot... |
Python equivalent to 'hold on' in Matlab | 21,465,988 | 22 | 2014-01-30T19:40:44Z | 24,319,077 | 13 | 2014-06-20T02:32:01Z | [
"python",
"matlab",
"graph",
"matplotlib"
] | Is there an explicit equivalent command in Python's matplotlib for Matlab's `hold on`? I'm trying to plot all my graphs on the same axes. Some graphs are generated inside a `for` loop, and these are plotted separately from `su` and `sl`:
```
import numpy as np
import matplotlib.pyplot as plt
for i in np.arange(1,5):
... | You can use the following:
```
plt.hold(True)
``` |
Numba code slower than pure python | 21,468,170 | 12 | 2014-01-30T21:51:28Z | 21,489,540 | 13 | 2014-01-31T20:33:18Z | [
"python",
"performance",
"numpy",
"cython",
"numba"
] | I've been working on speeding up a resampling calculation for a particle filter. As python has many ways to speed it up, I though I'd try them all. Unfortunately, the numba version is incredibly slow. As Numba should result in a speed up, I assume this is an error on my part.
I tried 4 different versions:
1. Numba
2.... | The problem is that numba can't intuit the type of `lookup`. If you put a `print nb.typeof(lookup)` in your method, you'll see that numba is treating it as an object, which is slow. Normally I would just define the type of `lookup` in a locals dict, but I was getting a strange error. Instead I just created a little wra... |
How to do linear regression, taking errorbars into account? | 21,469,620 | 5 | 2014-01-30T23:26:01Z | 21,470,140 | 8 | 2014-01-31T00:04:54Z | [
"python",
"numpy",
"linear-regression",
"least-squares",
"extrapolation"
] | I am doing a computer simulation for some physical system of finite size, and after this I am doing extrapolation to the infinity (Thermodynamic limit). Some theory says that data should scale linearly with system size, so I am doing linear regression.
The data I have is noisy, but for each data point I can estimate e... | Not entirely sure if this is what you mean, butâ¦using pandas, [statsmodels](http://statsmodels.sourceforge.net/stable/), and patsy, we can compare an ordinary least-squares fit and a weighted least-squares fit which uses the inverse of the noise you provided as a weight matrix (statsmodels will complain about sample ... |
cannot perform reduce with flexible type plt.hist | 21,472,243 | 10 | 2014-01-31T04:07:53Z | 21,472,904 | 16 | 2014-01-31T05:15:45Z | [
"python",
"text",
"matplotlib",
"word-frequency"
] | I have a dataset with 1000s of elements and their respective frquencies. i need to plot a histogram of the top 10 occurring elements.
i did:
```
top_words = Counter(my_data).most_common()
top_words_10 = top_words[:10]
plt.hist(top_words_10,label='True')
```
and got this error :
```
TypeError ... | You get this error because you need to convert your data to a numeric type. Your array contains strings.
```
import matplotlib.pyplot as plt
import numpy as np
data = [(' whitefield', 65299), (' bellandur', 57061), (' kundalahalli', 51769), (' marathahalli', 50639),
(' electronic city', 44041), (' sarjapur road junct... |
Send code to interactive python sublime text | 21,472,642 | 3 | 2014-01-31T04:54:48Z | 21,642,696 | 7 | 2014-02-08T06:16:03Z | [
"python",
"sublimetext2"
] | How does one sent highlighted code from *sublime text 2* editor to the interactive console started by going to *`view > show console`* in sublime text 2? | If you are on Sublime Text 2 for a Mac, then press 'command' + 'B' to build. If you are on Windows, then press 'Ctrl' + 'B'.
* Make sure to save your file with a .py extension (so your system will
know to build in Python)
* Also check to make sure that your 'Tools' > 'Build System' > 'Automatic'
I hope I interprete... |
Matplotlib Python Barplot: Position of xtick labels have irregular spaces between eachother | 21,477,465 | 4 | 2014-01-31T10:15:18Z | 21,479,052 | 14 | 2014-01-31T11:31:46Z | [
"python",
"matplotlib",
"label",
"bar-chart"
] | I'm trying to do a bar plot for many countries and i want the names displayed a bit rotated underneath the bars.
The problem is that the spaces between the labels are irregular.

Here's the relevant code:
```
plt.bar(... | I think the problem is that the xtick label is aligned to the centre of the text, but when it is rotated you care about the end of it. As a side note, you can use the position of the bars to select the xtick positions which better handles gaps/uneven spacing.
Here's an example that uses a web resource for list of coun... |
Read Outlook Events via Python | 21,477,599 | 10 | 2014-01-31T10:22:05Z | 21,532,251 | 9 | 2014-02-03T16:16:01Z | [
"python",
"python-2.7",
"outlook-2010",
"win32com"
] | Outlook has some things to desire - like showing multiple month view
So I decided to give it a try by pulling out the event data via python (and then figure a way to display it nicely). Google is giving me pore results, but stackoverflow has been very helpful previously in regards to using win32com and outlook.
My go... | > From here I need help with looping through the events and read them.
Basically, all you have to do is to follow the COM API documentation from Microsoft. For example, the `Restrict()` method returns `AppointmentItem` objects which are documented at [AppointmentItem Object](http://msdn.microsoft.com/en-us/library/off... |
unicodecsv reader from unicode string not working? | 21,479,589 | 4 | 2014-01-31T11:59:14Z | 21,479,663 | 7 | 2014-01-31T12:03:39Z | [
"python",
"csv",
"unicode"
] | I'm having trouble reading in a unicode CSV string into python-unicodescv:
```
>>> import unicodecsv, StringIO
>>> f = StringIO.StringIO(u'é,é')
>>> r = unicodecsv.reader(f, encoding='utf-8')
>>> row = r.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/guy/test/.env/lib/... | The `unicodecsv` file reads and decodes **byte strings** for you. You are passing it `unicode` strings instead. On output, your unicode values are encoded to bytestrings for you, using the configured codec.
In addition, `cStringIO.StringIO` can only handle encoded bytestrings, while the pure-python `StringIO.StringIO`... |
social media link share in post django | 21,479,779 | 3 | 2014-01-31T12:09:02Z | 21,480,945 | 8 | 2014-01-31T13:13:33Z | [
"python",
"django",
"social"
] | I want to set social link in end of my post in template django.
how to use of social media link share in django post for share my post link in social web? | Check out django-social-share (<https://github.com/fcurella/django-social-share>) or django-socialsharing (<https://github.com/lettertwo/django-socialsharing>).
More can be found here: <https://www.djangopackages.com/grids/g/social/> |
django - import error: no module named views | 21,485,148 | 5 | 2014-01-31T16:32:07Z | 21,485,177 | 9 | 2014-01-31T16:33:44Z | [
"python",
"django",
"import",
"django-views"
] | I've been racking my brains and can't figure out why there should be an import error when 'views' is imported. I get the following message when I visit my index page:
```
"
Request Method: GET
Request URL: http://127.0.0.1:8000/moments/
Django Version: 1.6.1
Exception Type: ImportError
Exception Value:
No modul... | You prefixed your route names with a *relative* module name. Use an absolute name:
```
urlpatterns = patterns('',
url(r'^$', "moments_app.views.index", name='index'),
url(r'^$', "moments_app.views.choose_dataset", name='choose'),
url(r'^get_moments/', "moments_app.views.get_moments", name='get_moments'),
... |
High Memory Usage Using Python Multiprocessing | 21,485,319 | 10 | 2014-01-31T16:40:38Z | 21,613,370 | 23 | 2014-02-06T20:29:28Z | [
"python",
"performance",
"memory",
"multiprocessing"
] | I have seen a couple of posts on memory usage using Python Multiprocessing module. However the questions don't seem to answer the problem I have here. I am posting my analysis with the hope that some one can help me.
## Issue
I am using multiprocessing to perform tasks in parallel and I noticed that the memory consum... | I did a lot of research, and couldn't find a solution to fix the problem per se. But there is a decent work around that prevents the memory blowout for a small cost, worth especially on server side long running code.
The solution essentially was to restart individual worker processes after a fixed number of tasks. The... |
How to uninstall manually openerp module | 21,485,630 | 4 | 2014-01-31T16:54:53Z | 21,494,769 | 7 | 2014-02-01T06:08:54Z | [
"python",
"openerp"
] | I have installed a module on openerp v7 that I would like to uninstall.
Using the interface fails, i get an error during the uninstall process.
Is there a 'manual' way to uninstall a module ? Is it sufficient to remove the module folder under `addons/` or is there any other things to do, to make it in the cleanest wa... | Removing the module's code from `addons/`is not enough - this will break OpenERP.
**Solution 1 - Try to resolve the error you have during normal uninstall**
This method is recommended because OpenERP does the job cleanly. Look at the error you have during uninstallation and try to imagine what could be the problem. P... |
How to test session in flask resource | 21,486,400 | 8 | 2014-01-31T17:32:01Z | 21,486,582 | 9 | 2014-01-31T17:41:26Z | [
"python",
"unit-testing",
"session",
"flask"
] | I'd like to test a resource. The response of that depends on a parameter in session (logged)
To test this resource, I've wrote those tests:
```
import app
import unittest
class Test(unittest.TestCase):
def setUp(self):
self.app = app.app.test_client()
def test_without_session(self):
resp = se... | If you did not set a custom `app.session_interface`, then you forgot to set a [secret key](https://flask.readthedocs.org/en/latest/api/?highlight=session#flask.Flask.secret_key):
```
def setUp(self):
app.config['SECRET_KEY'] = 'sekrit!'
self.app = app.app.test_client()
```
This just sets a mock secret key for... |
Environment $PATH different when using venv | 21,486,528 | 2 | 2014-01-31T17:38:35Z | 21,488,010 | 13 | 2014-01-31T19:01:09Z | [
"python",
"osx",
"virtualenv",
"pycharm"
] | I'm using PyCharm on a mac (OSX mavericks) to run a simple script shown below. All it does is print the `PATH` variable. I have a virtualenv in the project directory. I added a Run Configuration in PyCharm and tried it with different Pythons:
```
# file mytest.py
import os
print "PATH: ", os.environ['PATH']
```
When ... | you should probably know that all environment variables are inherited.
When you define environment variable in your .bash\_profile it becomes available in your terminal (bash),
and in all processes that will be started from terminal (These processes will be children for the bash process).
That's why you are getting exp... |
Add x and y labels to a pandas plot | 21,487,329 | 43 | 2014-01-31T18:23:09Z | 21,487,560 | 71 | 2014-01-31T18:35:34Z | [
"python",
"matplotlib",
"pandas"
] | Suppose I have the following code that plots something very simple using pandas:
```
import pandas as pd
values = [[1,2], [2,5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])
df2.plot(lw=2,colormap='jet',marker='.',markersize=10,title='Video streaming dropout by category')
```
... | The `df.plot()` function returns a `matplotlib.axes.AxesSubplot` object. You can set the labels on that object.
```
In [4]: ax = df2.plot(lw=2,colormap='jet',marker='.',markersize=10,title='Video streaming dropout by category')
In [6]: ax.set_xlabel("x label")
Out[6]: <matplotlib.text.Text at 0x10e0af2d0>
In [7]: ax... |
Add x and y labels to a pandas plot | 21,487,329 | 43 | 2014-01-31T18:23:09Z | 21,487,868 | 7 | 2014-01-31T18:52:55Z | [
"python",
"matplotlib",
"pandas"
] | Suppose I have the following code that plots something very simple using pandas:
```
import pandas as pd
values = [[1,2], [2,5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])
df2.plot(lw=2,colormap='jet',marker='.',markersize=10,title='Video streaming dropout by category')
```
... | You can use do it like this:
```
import matplotlib.pyplot as plt
import pandas as pd
plt.figure()
values = [[1,2], [2,5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])
df2.plot(lw=2,colormap='jet',marker='.',markersize=10,title='Video streaming dropout by category')
plt.xlabel... |
Add x and y labels to a pandas plot | 21,487,329 | 43 | 2014-01-31T18:23:09Z | 27,520,877 | 7 | 2014-12-17T08:06:02Z | [
"python",
"matplotlib",
"pandas"
] | Suppose I have the following code that plots something very simple using pandas:
```
import pandas as pd
values = [[1,2], [2,5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])
df2.plot(lw=2,colormap='jet',marker='.',markersize=10,title='Video streaming dropout by category')
```
... | If you label the columns and index of your DataFrame, pandas will automatically supply appropriate labels:
```
import pandas as pd
values = [[1,2], [2,5]]
df = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])
df.columns.name = 'Type'
df.index.name = 'Index'
df.plot(lw=2, colormap='jet', ... |
Pandas graphing a timeseries, with vertical lines at selected dates | 21,488,085 | 7 | 2014-01-31T19:05:54Z | 21,489,607 | 9 | 2014-01-31T20:37:21Z | [
"python",
"matplotlib",
"pandas"
] | Consider this timeseries, the cumulative number of edits in a Wikipedia category.
```
In [555]:
cum_edits.head()
Out[555]:
2001-08-31 23:37:28 1
2001-09-01 05:09:28 2
2001-09-18 10:01:17 3
2001-10-27 06:52:45 4
2001-10-27 07:01:45 5
Name: edits, dtype: int64
In [565]:
cum_edits.tail()
Out[565]:
2014-01-... | Thanks to @TomAugspurger
The solution is to get your axes back, and then use `ax.vlines`.
```
ax = cum_edits.plot()
ymin, ymax = ax.get_ylim()
ax.vlines(x=dates, ymin=ymin, ymax=ymax-1, color='r')
```

One last niggle is that if the vlines are `ymax` long,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.