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 |
|---|---|---|---|---|---|---|---|---|---|
Matplotlib.pyplot : Save the plots into a pdf | 11,328,958 | 15 | 2012-07-04T12:17:35Z | 11,329,151 | 55 | 2012-07-04T12:30:04Z | [
"python",
"save",
"matplotlib"
] | ------ plotting module ------
```
def plotGraph(X,Y):
fignum = random.randint(0,sys.maxint)
plt.figure(fignum)
### Plotting arrangements ###
return fignum
```
------ plotting module ------
----- mainModule ----
```
import matplotlib.pyplot as plt
### tempDLStats, tempDLlabels are the arg... | For multiple plots in a single pdf file you can use [PdfPages](http://matplotlib.sourceforge.net/api/backend_pdf_api.html#matplotlib.backends.backend_pdf.PdfPages)
In the `plotGraph` function you should return the figure and than call `savefig` of the figure object.
------ plotting module ------
```
def plotGraph(X,... |
Restart python-script from within itself | 11,329,917 | 13 | 2012-07-04T13:19:22Z | 11,329,970 | 16 | 2012-07-04T13:22:16Z | [
"python"
] | I have a python-based GTK application that loads several modules. It is run from the (linux) terminal like so:
`./myscript.py --some-flag setting`
From within the program the user can download (using Git) newer versions.
If such exists/are downloaded, a button appear that I wish would restart the program with newly c... | You're looking for [`os.exec*()`](http://docs.python.org/library/os.html#os.execl). |
Get class name and contents using Beautiful Soup | 11,331,071 | 5 | 2012-07-04T14:31:24Z | 11,346,297 | 14 | 2012-07-05T14:22:08Z | [
"python",
"beautifulsoup"
] | Using Beautiful Soup module, how can I get data of a `div` tag whose class name is `feeditemcontent cxfeeditemcontent`? Is it:
```
soup.class['feeditemcontent cxfeeditemcontent']
```
or:
```
soup.find_all('class')
```
This is the HTML source:
```
<div class="feeditemcontent cxfeeditemcontent">
<div class="feed... | Beautiful Soup 4 treats the value of the "class" attribute as a list rather than a string, meaning jadkik94's solution can be simplified:
```
from bs4 import BeautifulSoup
def match_class(target):
def do_mat... |
Hook to add commands to distutils build? | 11,331,175 | 10 | 2012-07-04T14:37:46Z | 11,332,078 | 11 | 2012-07-04T15:38:34Z | [
"python",
"distutils"
] | I've added a custom distutils command to a setup.py script:
```
from distutils.command.build_py import build_py
cmdclass = {}
cmdclass['build_qt'] = BuildQt
cmdclass['build_py'] = build_py
setup(..., cmdclass=cmdclass, ...)
```
Is there a way to make it so that when running::
```
python setup.py build
```
this fi... | You can override `build`:
```
from distutils.command.build import build
class my_build(build):
def run(self):
self.run_command("build_qt")
build.run(self)
cmdclass['build'] = my_build
``` |
When should I use a class and when should I use a function? | 11,331,719 | 3 | 2012-07-04T15:12:35Z | 11,331,759 | 8 | 2012-07-04T15:15:25Z | [
"python"
] | When is a class more useful to use than a function? Is there any hard or fast rule that I should know about? Is it language dependent? I'm intending on writing a script for Python which will parse different types of json data, and my gut feeling is that I should use a class to do this, versus a function. | You should use a class when your routine needs to save state. Otherwise a function will suffice. |
How to use reduce with list of lists | 11,331,908 | 3 | 2012-07-04T15:26:57Z | 11,331,965 | 10 | 2012-07-04T15:30:06Z | [
"python",
"list",
"python-2.7"
] | What is wrong with the following?:
```
lss = reduce(list.extend, [[1],[2]], [])
```
causes:
```
Traceback (most recent call last):
File "<pyshell#230>", line 1, in <module>
lss = reduce(list.extend, [[1],[2]], [])
TypeError: descriptor 'extend' requires a 'list' object but received a 'NoneType'
```
I'm not su... | Try this instead:
```
lss = reduce(lambda acc, ele : acc + ele, [[1],[2]], [])
lss
> [1, 2]
```
The problem is that [`extend()`](http://docs.python.org/tutorial/datastructures.html) returns `None` (that's where the `NoneType` is coming from), and that won't work with what you want to do - the function passed to [`re... |
How to remove any URL within a string in Python | 11,331,982 | 9 | 2012-07-04T15:30:57Z | 11,332,580 | 20 | 2012-07-04T16:15:58Z | [
"python",
"regex",
"url",
"replace",
"python-2.7"
] | I want to remove all URLs inside a string (replace them with "")
I searched around but couldn't really find what I want.
Example:
```
text1
text2
http://url.com/bla1/blah1/
text3
text4
http://url.com/bla2/blah2/
text5
text6
http://url.com/bla3/blah3/
```
I want the result to be:
```
text1
text2
text3
text4
text5
te... | ***Python script:***
```
import re
text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE)
```
***Output:***
```
text1
text2
text3
text4
text5
text6
```
*Test this code [here](http://ideone.com/K3Cut).* |
Timestamp fields in django | 11,332,107 | 9 | 2012-07-04T15:40:15Z | 11,332,150 | 13 | 2012-07-04T15:43:28Z | [
"python",
"mysql",
"django"
] | I have a MySQL database, right now I'm generating all of the datetime fields as `models.DateTimeField`. Is there a way to get a `timestamp` instead? I want to be able to autoupdate on create and update etc.
The documentation on django doesn't have this? | There was actually a very good and informative article on this. Here:
<http://ianrolfe.livejournal.com/36017.html>
The solution on the page is slightly deprecated, so I did the following:
```
from django.db import models
from datetime import datetime
from time import strftime
class UnixTimestampField(models.DateTime... |
find row or column containing maximum value in numpy array | 11,332,205 | 5 | 2012-07-04T15:47:18Z | 11,332,581 | 7 | 2012-07-04T16:16:02Z | [
"python",
"numpy"
] | How do I find the row or column which contains the array-wide maximum value in a 2d numpy array? | If you only need one or the other:
```
np.argmax(np.max(x, axis=1))
```
for the column, and
```
np.argmax(np.max(x, axis=0))
```
for the row. |
NLTK Named Entity Recognition with Custom Data | 11,333,903 | 26 | 2012-07-04T18:24:08Z | 11,399,077 | 16 | 2012-07-09T16:16:25Z | [
"python",
"nlp",
"nltk",
"named-entity-recognition"
] | I'm trying to extract named entities from my text using NLTK. I find that NLTK NER is not very accurate for my purpose and I want to add some more tags of my own as well. I've been trying to find a way to train my own NER, but I don't seem to be able to find the right resources.
I have a couple of questions regarding N... | Are you committed to using NLTK/Python? I ran into the same problems as you, and had much better results using Stanford's named-entity recognizer: <http://nlp.stanford.edu/software/CRF-NER.shtml>. The process for training the classifier using your own data is very well-documented in the FAQ.
If you really need to use ... |
How to take out the column index name in dataframe | 11,334,098 | 2 | 2012-07-04T18:43:10Z | 11,335,177 | 8 | 2012-07-04T20:35:02Z | [
"python",
"pandas"
] | ```
Open High Low Close Volume Adj Close
Date
1990-01-02 00:00:00 35.25 37.50 35.00 37.25 6555600 8.70
1990-01-03 00:00:00 38.00 38.00 37.50 37.50 7444400 8.76
1990-01-04 00:00:00 38.25 38.75 37.25 37.63 7928800 8.79
19... | Short answer: you can't and it's not clear why this could ever "cause problems". The 'Date' name is naming the Index of the DataFrame, which is different from any of the columns. It gets printed with this offset specifically so you will not confuse it with a column of the frame. You would not slice into the date with `... |
How to take out the column index name in dataframe | 11,334,098 | 2 | 2012-07-04T18:43:10Z | 11,384,818 | 10 | 2012-07-08T16:39:58Z | [
"python",
"pandas"
] | ```
Open High Low Close Volume Adj Close
Date
1990-01-02 00:00:00 35.25 37.50 35.00 37.25 6555600 8.70
1990-01-03 00:00:00 38.00 38.00 37.50 37.50 7444400 8.76
1990-01-04 00:00:00 38.25 38.75 37.25 37.63 7928800 8.79
19... | Try using the `reset_index` method which moves the DataFrame's index into a column (which is what you want, I think). |
How can I tell if a value is a string or a list in Django templates? | 11,334,119 | 2 | 2012-07-04T18:45:37Z | 11,334,188 | 7 | 2012-07-04T18:54:14Z | [
"python",
"django",
"templates",
"django-templates"
] | I've got a tuple of values I'm iterating in a Django template (1.4). Some of the values are strings which must just print out, others are tuples containing strings, which must be iterated themselves to print out their values. Is there a way, within the template, that I can decide if a given value, as I iterate over the... | There's no builtin way to do so. A (somewhat dirty IMHO) workaround would be to implement a custom "is\_string" filter, but the best solution would be to preprocess the values in the view to make it an uniform list of tuples (or list).
for the filter solution:
```
@register.filter
def is_string(val):
return isins... |
Can't set class attributes in python using a method | 11,334,922 | 5 | 2012-07-04T20:08:38Z | 11,334,949 | 9 | 2012-07-04T20:10:38Z | [
"python",
"class",
"attributes"
] | Initialising the Foo object does run the method func(), but the value of self.a gets set to None anyway.
How can I get the following code to work?
```
#!/usr/bin/env python
class Foo(object):
def __init__(self, num):
self.a = self.func(num)
print self.a
def func(self, num):
self.a =... | You're resetting `self.a` to the return value of the function. Since the function returns nothing, the value gets set to `None`.
```
def __init__(self, num):
self.a = self.func(num) # return value of function is None
print self.a # self.a is now None
def func(self, num):
self.a = range(num) ... |
authentication with urllib3 | 11,335,825 | 2 | 2012-07-04T21:58:25Z | 11,388,614 | 7 | 2012-07-09T02:56:43Z | [
"python",
"authentication",
"urllib3"
] | I am trying to connect to a webpage using urllib3. The code is provided below.
```
import urllib3
http=urllib3.PoolManager()
fields={'username':'abc','password':'xyz')
r=http.request('GET',url,fields)
```
If we assume that url is some webpage which needs to be authenticated using username and password, am i using the... | Assuming you're trying to do [Basic Authentication](http://en.wikipedia.org/wiki/Basic_authentication), then you need to put the username and password encoded in an `authorization` header. Here's one way to do that using the [urllib3.util.make\_headers](https://github.com/shazow/urllib3/blob/release/urllib3/util/reques... |
OpenERP : fetch record with same name | 11,335,945 | 2 | 2012-07-04T22:17:32Z | 11,340,877 | 10 | 2012-07-05T08:52:12Z | [
"python",
"openerp"
] | How can I retrieve records that have the same value of name in openerp (or same other field)? | The solution of using a manual SQL query to group by `name` as suggested by Ruchir is probably the simplest, but a bit low-level. You can also do it using the `read_group()` API method that performs a similar `GROUP BY` query, but without bypassing access control mechanisms and model business logic.
The `read_group` m... |
Python GDAL package missing header file when installing via pip | 11,336,153 | 10 | 2012-07-04T22:53:00Z | 17,311,033 | 13 | 2013-06-26T03:26:51Z | [
"python",
"gdal"
] | I'm trying to install gdal from pip `pip install gdal` inside a virtual environment (Ubuntu). It fails because it cannot find `cpl_port.h`
```
extensions/gdal_wrap.cpp:2853:22: fatal error: cpl_port.h: No such file or directory
compilation terminated
```
However GDAL is installed correctly and the header file is loca... | As suggested in [the other thread](http://gis.stackexchange.com/a/64244/13609), exporting some shell variables before running pip worked flawlessly. A path for `*_INCLUDE_PATH` can be found with `gdal-config --cflags`.
```
# GDAL library must have been installed
sudo apt-get install libgdal-dev
# Set up pip and/or vi... |
Django - taking values from POST request | 11,336,548 | 27 | 2012-07-05T00:11:58Z | 11,336,576 | 7 | 2012-07-05T00:17:03Z | [
"python",
"django",
"post"
] | I have the following django template (http://IP/admin/start/ is assigned to a hypothetical view called view):
```
{% for source in sources %}
<tr>
<td>{{ source }}</td>
<td>
<form action="/admin/start/" method="post">
{% csrf_token %}
<input type="hidden" name="{{ source.title }}">
<in... | If you need to do something on the front end you can respond to the onsubmit event of your form. If you are just posting to admin/start you can access post variables in your view through the request object. request.POST which is a dictionary of post variables |
Django - taking values from POST request | 11,336,548 | 27 | 2012-07-05T00:11:58Z | 11,336,580 | 50 | 2012-07-05T00:18:01Z | [
"python",
"django",
"post"
] | I have the following django template (http://IP/admin/start/ is assigned to a hypothetical view called view):
```
{% for source in sources %}
<tr>
<td>{{ source }}</td>
<td>
<form action="/admin/start/" method="post">
{% csrf_token %}
<input type="hidden" name="{{ source.title }}">
<in... | Read about request objects that your views receive: <https://docs.djangoproject.com/en/dev/ref/request-response/#httprequest-objects>
Also your hidden field needs a reliable name and then a value:
```
<input type="hidden" name="title" value="{{ source.title }}">
```
Then in a view:
```
request.POST.get("title", "")... |
Python max-by function? | 11,337,023 | 8 | 2012-07-05T01:55:15Z | 11,337,033 | 13 | 2012-07-05T01:56:49Z | [
"python"
] | Example:
```
print max(chain_length(i) for i in xrange(1,10001))
```
This returns the maximum/biggest "chain\_length" (an arbitrary function), but what I want is the `i` value for input that produces the biggest value.
Is there a convenient way to do that? | ```
max(xrange(1, 10001), key=chain_length)
``` |
How to convert an image from np.uint16 to np.uint8? | 11,337,499 | 8 | 2012-07-05T03:23:36Z | 11,347,141 | 10 | 2012-07-05T15:04:44Z | [
"python",
"opencv",
"numpy"
] | I am creating an image so:
```
image = np.empty(shape=(height, width, 1), dtype = np.uint16)
```
After that I convert the image to BGR model:
```
image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
```
I'd like to convert the image now in a `dtype = np.uint8` in order to use that image with `cv2.threshold()` function. ... | You can use `cv2.convertScaleAbs` for this problem. See the [Documentation.](http://docs.opencv.org/modules/core/doc/operations_on_arrays.html?highlight=convertscale#convertscaleabs)
Check out the command terminal demo below :
```
>>> img = np.empty((100,100,1),dtype = np.uint16)
>>> image = cv2.cvtColor(img,cv2.COLO... |
Python negative zero slicing | 11,337,941 | 3 | 2012-07-05T04:42:47Z | 11,337,989 | 7 | 2012-07-05T04:51:13Z | [
"python",
"idioms",
"slice"
] | I often find myself having to work with the last n items in a sequence, where n may be 0. The problem is that trying to slice with `[-n:]` won't work in the case of `n == 0`, so awkward special case code is required. For example
```
if len(b):
assert(isAssignableSeq(env, self.stack[-len(b):], b))
newstack = s... | You can switch it from `L[-2:]` to `L[len(L)-2:]`
```
>>> L = [1,2,3,4,5]
>>> L[len(L)-2:]
[4, 5]
>>> L[len(L)-0:]
[]
``` |
Python Multiprocessing: What's the difference between map and imap? | 11,338,044 | 23 | 2012-07-05T04:59:53Z | 11,338,089 | 23 | 2012-07-05T05:07:00Z | [
"python",
"multiprocessing"
] | I'm trying to learn how to use Python's multiprocessing package, but I don't understand the difference between `map` and `imap`.
Is the difference that `map` returns, say, an actual array or set, while `imap` returns an iterator over an array or set? When would I use one over the other?
Also, I don't understand what ... | That is the difference. One reason why you might use imap instead of map is if you wanted to start processing the first few results without waiting for the rest to be calculated. map waits for every result before returning.
As for chunksize, it is sometimes more efficient to dole out work in larger quantities because ... |
How to remove the first and last item in a list? | 11,338,143 | 2 | 2012-07-05T05:15:58Z | 11,338,163 | 29 | 2012-07-05T05:18:33Z | [
"python"
] | I have the List
```
['Q 0006 005C 0078 0030 0030 0033 0034 ONE_OF 0002 ']
```
How do I remove the first element, `Q` and `0002`, the last element? | If your list is stored under `my_list` then this should work.
```
my_list = my_list[1:-1]
``` |
How to get integer values from a string in Python? | 11,339,210 | 16 | 2012-07-05T06:55:20Z | 11,339,230 | 35 | 2012-07-05T06:57:02Z | [
"python",
"string",
"integer"
] | Suppose I had a string
```
string1 = "498results should get"
```
Now I need to get only integer values from the string like `498`. Here I don't want to use `list slicing` because the integer values may increase like these examples:
```
string2 = "49867results should get"
string3 = "497543results should get"
```
So... | ```
>>> import re
>>> string1 = "498results should get"
>>> int(re.search(r'\d+', string1).group())
498
```
If there are multiple integers in the string:
```
>>> map(int, re.findall(r'\d+', string1))
[498]
``` |
How to get integer values from a string in Python? | 11,339,210 | 16 | 2012-07-05T06:55:20Z | 11,673,489 | 21 | 2012-07-26T16:08:30Z | [
"python",
"string",
"integer"
] | Suppose I had a string
```
string1 = "498results should get"
```
Now I need to get only integer values from the string like `498`. Here I don't want to use `list slicing` because the integer values may increase like these examples:
```
string2 = "49867results should get"
string3 = "497543results should get"
```
So... | An answer taken from [ChristopheD](http://stackoverflow.com/users/81179/christophed) here: <http://stackoverflow.com/a/2500023/1225603>
```
r = "456results string789"
s = ''.join(x for x in r if x.isdigit())
print int(s)
456789
``` |
Django - (OperationalError) FATAL: Ident authentication failed for user "username" | 11,339,917 | 2 | 2012-07-05T07:45:40Z | 11,344,294 | 16 | 2012-07-05T12:25:20Z | [
"python",
"django",
"postgresql",
"sqlalchemy"
] | I've written a simple sqlalchemy-django model, according to this manual: <http://lethain.com/replacing-django-s-orm-with-sqlalchemy/>, which worked for me pretty well.
My Django is connected to a remote postgresql database, with this settings:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgres... | Your `pg_hba.conf` is configured to use 'ident' authentication for connections from localhost (127.0.0.1). You need it to be changed to `md5` for your database and user combination. |
python string encode / decode | 11,339,955 | 34 | 2012-07-05T07:48:06Z | 11,339,995 | 61 | 2012-07-05T07:50:15Z | [
"python",
"python-2.7"
] | Here are my attempts with error messages. What am I doing wrong?
```
string.decode("ascii", "ignore")
```
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 37: ordinal not in range(128)
```
string.encode('utf-8', "ignore")
```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in po... | You can't decode a `unicode`, and you can't encode a `str`. Try doing it [the other way around](http://farmdev.com/talks/unicode/). |
python string encode / decode | 11,339,955 | 34 | 2012-07-05T07:48:06Z | 11,342,994 | 47 | 2012-07-05T11:02:38Z | [
"python",
"python-2.7"
] | Here are my attempts with error messages. What am I doing wrong?
```
string.decode("ascii", "ignore")
```
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 37: ordinal not in range(128)
```
string.encode('utf-8', "ignore")
```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in po... | Guessing at all the things omitted from the original question, but, assuming Python 2.x the key is to read the error messages carefully: in particular where you call 'encode' but the message says 'decode' and vice versa, but also the types of the values included in the messages.
In the first example `string` is of typ... |
python string encode / decode | 11,339,955 | 34 | 2012-07-05T07:48:06Z | 25,213,500 | 15 | 2014-08-08T23:05:56Z | [
"python",
"python-2.7"
] | Here are my attempts with error messages. What am I doing wrong?
```
string.decode("ascii", "ignore")
```
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 37: ordinal not in range(128)
```
string.encode('utf-8', "ignore")
```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in po... | Aside from getting `decode` and `encode` backwards, I think part of the answer here is actually *don't use the `ascii` encoding*. It's probably not what you want.
To begin with, think of `str` like you would a plain text file. It's just a bunch of bytes with no encoding actually attached to it. How it's interpreted is... |
Default window colour Tkinter and hex colour codes | 11,340,765 | 2 | 2012-07-05T08:44:47Z | 11,342,481 | 18 | 2012-07-05T10:30:10Z | [
"python",
"colors",
"tkinter",
"ttk"
] | I would like to know the default window colour in Tkinter when you simply create a window:
```
root = Tk()
```
If there is one, it is possible to set widgets to the same colour or use a hex colour code? (using rgb)
The colour code I have found for the 'normal' window is:
R = 240, G = 240, B = 237
Thanks. | Not sure exactly what you're looking for, but will this work?
```
import Tkinter
mycolor = '#%02x%02x%02x' % (64, 204, 208) # set your favourite rgb color
mycolor2 = '#40E0D0' # or use hex if you prefer
root = Tkinter.Tk()
root.configure(bg=mycolor)
Tkinter.Button(root, text="Press me!", bg=mycolor, fg='black',
... |
Changing the local variable of a function from within another function that is defined in said function.. Python | 11,343,070 | 2 | 2012-07-05T11:07:26Z | 11,343,093 | 7 | 2012-07-05T11:08:51Z | [
"python",
"function",
"variables",
"global",
"local"
] | Is there a way to access the local variable of a function from a function that is defined within said function?
Y is a tuple with strings, and I want whatever caps becomes when a condition is met to stay the same for the next call with the next item in y. I tried to use the built-in function global, but I guess that on... | Use [`nonlocal`](http://docs.python.org/py3k/reference/simple_stmts.html?highlight=nonlocal#the-nonlocal-statement) in Python 3.x:
```
def cap_sentence(y):
caps = "on"
def func(x):
nonlocal caps
if caps == "on":
caps = "off"
return x.capitalize()
elif "."... |
Python inspect.getargspec with built-in function | 11,343,191 | 5 | 2012-07-05T11:15:37Z | 11,343,229 | 10 | 2012-07-05T11:18:13Z | [
"python",
"function",
"methods",
"arguments",
"inspect"
] | I'm trying to figure out the arguments of a method retrieved from a module.
I found an `inspect` module with a handy function, `getargspec`.
It works for a function that I define, but won't work for functions from an imported module.
```
import math, inspect
def foobar(a,b=11): pass
inspect.getargspec(foobar) # this ... | It is impossible to get this kind of information for a function that is implemented in C instead of Python.
The reason for this is that there is no way to find out what arguments the method accepts except by parsing the (free-form) docstring since arguments are passed in a (somewhat) getarg-like way - i.e. it's imposs... |
Summing elements in a list | 11,344,827 | 23 | 2012-07-05T12:57:04Z | 11,344,839 | 63 | 2012-07-05T12:57:57Z | [
"python",
"list",
"sum"
] | Here is my code, I need to sum an undefined number of elements in the list. How to do this?
```
l = raw_input()
l = l.split(' ')
l.pop(0)
```
My input: `3 5 4 9`
After input I delete first element via `l.pop(0)`.
After `.split(' ')` my list is `['5', '4', '9']` and I need to sum all elements in this list.
In this ca... | You can sum numbers in a list simply with the [sum()](http://docs.python.org/library/functions.html#sum) built-in:
```
sum(your_list)
```
It will sum as many number items as you have. Example:
```
my_list = range(10, 17)
my_list
[10, 11, 12, 13, 14, 15, 16]
sum(my_list)
91
```
**For your specific case**:
For your... |
Turtle module has no attribute color? | 11,346,013 | 2 | 2012-07-05T14:05:25Z | 11,348,626 | 7 | 2012-07-05T16:29:01Z | [
"python",
"python-3.2",
"turtle-graphics"
] | When I try to run the first piece of sample code from the [Python documentation on `turtle`](http://docs.python.org/py3k/library/turtle.html#module-turtle):
```
from turtle import *
color('red', 'yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()
```... | You named your file "turtle.py" so when you `import turtle`, you are importing your own file instead of the stdlib module. Change the name of your program, and delete all the .pyc files in that directory. |
Renaming columns in pandas | 11,346,283 | 453 | 2012-07-05T14:21:15Z | 11,346,337 | 456 | 2012-07-05T14:23:27Z | [
"python",
"pandas",
"replace",
"dataframe",
"rename"
] | I have a data table using pandas and column labels that I need to edit to replace the original column labels.
I'd like to change the column names in a data table `A` where the original column names are:
```
['$a', '$b', '$c', '$d', '$e']
```
to
```
['a', 'b', 'c', 'd', 'e'].
```
I have the edited column names stor... | Just assign it to the `.columns` attribute:
```
>>> df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})
>>> df.columns = ['a', 'b']
>>> df
a b
0 1 10
1 2 20
``` |
Renaming columns in pandas | 11,346,283 | 453 | 2012-07-05T14:21:15Z | 11,354,850 | 773 | 2012-07-06T01:48:15Z | [
"python",
"pandas",
"replace",
"dataframe",
"rename"
] | I have a data table using pandas and column labels that I need to edit to replace the original column labels.
I'd like to change the column names in a data table `A` where the original column names are:
```
['$a', '$b', '$c', '$d', '$e']
```
to
```
['a', 'b', 'c', 'd', 'e'].
```
I have the edited column names stor... | ```
df = df.rename(columns={'$a': 'a', '$b': 'b'})
# OR
df.rename(columns={'$a': 'a', '$b': 'b'}, inplace=True)
```
<http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html> |
Renaming columns in pandas | 11,346,283 | 453 | 2012-07-05T14:21:15Z | 16,667,215 | 157 | 2013-05-21T09:58:59Z | [
"python",
"pandas",
"replace",
"dataframe",
"rename"
] | I have a data table using pandas and column labels that I need to edit to replace the original column labels.
I'd like to change the column names in a data table `A` where the original column names are:
```
['$a', '$b', '$c', '$d', '$e']
```
to
```
['a', 'b', 'c', 'd', 'e'].
```
I have the edited column names stor... | The [`rename`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html) method can take a function, for example:
```
In [11]: df.columns
Out[11]: Index([u'$a', u'$b', u'$c', u'$d', u'$e'], dtype=object)
In [12]: df.rename(columns=lambda x: x[1:], inplace=True)
In [13]: df.columns
Out[13]: ... |
Renaming columns in pandas | 11,346,283 | 453 | 2012-07-05T14:21:15Z | 22,657,894 | 53 | 2014-03-26T10:20:45Z | [
"python",
"pandas",
"replace",
"dataframe",
"rename"
] | I have a data table using pandas and column labels that I need to edit to replace the original column labels.
I'd like to change the column names in a data table `A` where the original column names are:
```
['$a', '$b', '$c', '$d', '$e']
```
to
```
['a', 'b', 'c', 'd', 'e'].
```
I have the edited column names stor... | Since you only want to remove the $ sign in all column names, you could just do:
```
df = df.rename(columns=lambda x: x.replace('$', ''))
```
OR
```
df.rename(columns=lambda x: x.replace('$', ''), inplace=True)
``` |
Renaming columns in pandas | 11,346,283 | 453 | 2012-07-05T14:21:15Z | 30,380,922 | 21 | 2015-05-21T17:48:33Z | [
"python",
"pandas",
"replace",
"dataframe",
"rename"
] | I have a data table using pandas and column labels that I need to edit to replace the original column labels.
I'd like to change the column names in a data table `A` where the original column names are:
```
['$a', '$b', '$c', '$d', '$e']
```
to
```
['a', 'b', 'c', 'd', 'e'].
```
I have the edited column names stor... | ```
old_names = ['$a', '$b', '$c', '$d', '$e']
new_names = ['a', 'b', 'c', 'd', 'e']
df.rename(columns=dict(zip(old_names, new_names)), inplace=True)
```
This way you can manually edit the `new_names` as you wish.
Works great when you need to rename only a few columns to correct mispellings, accents, remove special c... |
Renaming columns in pandas | 11,346,283 | 453 | 2012-07-05T14:21:15Z | 30,546,734 | 42 | 2015-05-30T13:24:05Z | [
"python",
"pandas",
"replace",
"dataframe",
"rename"
] | I have a data table using pandas and column labels that I need to edit to replace the original column labels.
I'd like to change the column names in a data table `A` where the original column names are:
```
['$a', '$b', '$c', '$d', '$e']
```
to
```
['a', 'b', 'c', 'd', 'e'].
```
I have the edited column names stor... | As documented in <http://pandas.pydata.org/pandas-docs/stable/text.html>:
```
df.columns = df.columns.str.replace('$','')
``` |
Getting SciPy quantiles to match Stata xtile function | 11,347,539 | 2 | 2012-07-05T15:25:36Z | 11,372,467 | 7 | 2012-07-07T05:17:27Z | [
"python",
"scipy",
"stata",
"quantile"
] | I've inherited some old Stata code (Stata11) that uses the `xtile` function to categorize observations in a vector by their quantiles (in this case, just the standard 5 quintiles, 20%, 40%, 60%, 80%, 100%).
I'm trying to replicate a piece of the code in Python and I am using the SciPy.stats.mstats function `mquantiles... | The scipy.stats.mquantiles documentation was poor and *wrong* in places, fixed now so that might be helpful...
<http://docs.scipy.org/scipy/docs/scipy.stats.mstats_basic.mquantiles/>. That process started when you pointed out the alpha/beta, alphap/betap discrepancy. Thank you.
The implementation of mquantiles follow ... |
system wide shortcut for Mac OS X | 11,347,862 | 2 | 2012-07-05T15:41:57Z | 11,349,005 | 7 | 2012-07-05T16:55:49Z | [
"python",
"objective-c",
"osx",
"qt",
"pyqt"
] | So I was asked to port some internal helper applications to Mac OS X 10.7.
Works all quite welll as the platform dependent code is minimal anyhow, but one application needs a system wide shortcut to function (i.e. [RegisterHotkey](http://msdn.microsoft.com/en-us/library/windows/desktop/ms646309%28v=vs.85%29.aspx) func... | I recently coded up an [extension](https://github.com/mjpieters/quodlibet_plugins/blob/master/events/osxmmkey.py) to [quodlibet](https://code.google.com/p/quodlibet/) capturing multimedia keys (since absorbed into quodlibet itself); for your setup the same process applies.
I used the Quartz [`CGEventTapCreate` hook](h... |
How to simplify this mass of similar ifs | 11,347,954 | 6 | 2012-07-05T15:46:17Z | 11,347,978 | 10 | 2012-07-05T15:48:05Z | [
"python"
] | I am trying to figure out how to simplify this piece of code. The logic for every if condition is basically the same so I want to get rid of the duplicate ifs:
```
if "video_codec" in profile:
self.video_codec = profile["video_codec"]
if "resolution_width" in profile:
self.resolution_wi... | ```
for key, value in profile.iteritems():
setattr(self, key, value)
```
Should do what you want |
How to simplify this mass of similar ifs | 11,347,954 | 6 | 2012-07-05T15:46:17Z | 11,348,023 | 7 | 2012-07-05T15:50:23Z | [
"python"
] | I am trying to figure out how to simplify this piece of code. The logic for every if condition is basically the same so I want to get rid of the duplicate ifs:
```
if "video_codec" in profile:
self.video_codec = profile["video_codec"]
if "resolution_width" in profile:
self.resolution_wi... | If you just want to copy all key/value pairs from `profile` to attributes in `self`, you can use the following:
```
self.__dict__.update(profile)
```
If there are some items in `profile` that you do not want to copy, then you can use the following:
```
for attr in ("video_codec", "resolution_width", "resolution_heig... |
Pandas bar plot with specific colors and legend location? | 11,348,183 | 11 | 2012-07-05T15:59:54Z | 11,384,667 | 12 | 2012-07-08T16:16:39Z | [
"python",
"legend",
"pandas"
] | I have a pandas DataFrame and I want to plot a bar chart that includes a legend.
```
import pylab as pl
from pandas import *
x = DataFrame({"Alpha": Series({1: 1, 2: 3, 3:2.5}), "Beta": Series({1: 2, 2: 2, 3:3.5})})
```
If I call plot directly, then it puts the legend above the plot:
```
x.plot(kind="bar")
```
If ... | If you want to add the legend manually, you have to ask the subplot for the elements of the bar plot:
```
In [17]: ax = x.plot(kind='bar', legend=False)
In [18]: patches, labels = ax.get_legend_handles_labels()
In [19]: ax.legend(patches, labels, loc='best')
Out[19]: <matplotlib.legend.Legend at 0x10b292ad0>
```
Al... |
Pandas bar plot with specific colors and legend location? | 11,348,183 | 11 | 2012-07-05T15:59:54Z | 28,917,065 | 10 | 2015-03-07T16:25:55Z | [
"python",
"legend",
"pandas"
] | I have a pandas DataFrame and I want to plot a bar chart that includes a legend.
```
import pylab as pl
from pandas import *
x = DataFrame({"Alpha": Series({1: 1, 2: 3, 3:2.5}), "Beta": Series({1: 2, 2: 2, 3:3.5})})
```
If I call plot directly, then it puts the legend above the plot:
```
x.plot(kind="bar")
```
If ... | The most succinct way to go is:
```
x.plot(kind="bar").legend(bbox_to_anchor=(1.2, 0.5))
```
or in general
```
x.plot(kind="bar").legend(*args, **kwargs)
``` |
find common elements in lists | 11,348,347 | 18 | 2012-07-05T16:09:20Z | 11,348,386 | 30 | 2012-07-05T16:12:07Z | [
"python",
"algorithm",
"list",
"set",
"discrete-mathematics"
] | I'm trying to write a piece of code that can automatically factor an expression. For example,
if I have two lists [1,2,3,4] and [2,3,5], the code should be able to find the common elements in the two lists, [2,3], and combine the rest of the elements together in a new list, being [1,4,5].
From this post: [Python: How ... | Use the symmetric difference operator for `set`s (aka the XOR operator):
```
>>> set([1,2,3]) ^ set([3,4,5])
set([1, 2, 4, 5])
``` |
find common elements in lists | 11,348,347 | 18 | 2012-07-05T16:09:20Z | 32,066,723 | 10 | 2015-08-18T07:56:41Z | [
"python",
"algorithm",
"list",
"set",
"discrete-mathematics"
] | I'm trying to write a piece of code that can automatically factor an expression. For example,
if I have two lists [1,2,3,4] and [2,3,5], the code should be able to find the common elements in the two lists, [2,3], and combine the rest of the elements together in a new list, being [1,4,5].
From this post: [Python: How ... | You can use Intersection concept to deal with this kind of problems.
```
b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
set(b1).intersection(b2)
Out[22]: {4, 5}
```
Best thing about using this code is it works pretty fast for large data also. I have b1 with 607139 and b2 with 296029 elements when i use this logic I get my... |
how can I set the last modified time of a file from python? | 11,348,953 | 19 | 2012-07-05T16:50:57Z | 11,349,041 | 30 | 2012-07-05T16:59:06Z | [
"python",
"unix",
"last-modified"
] | I have a python script that downloads a file over FTP using [ftplib](http://docs.python.org/library/ftplib.html).
My current download code looks just like the example in the ftp lib docs:
```
ftp.retrbinary('RETR README', open('README', 'wb').write)
```
Now I have a requirement that the file downloaded over FTP need... | If you want to do this directly from python, you're looking for `os.utime`. The [docs](http://docs.python.org/library/os.html#os.utime) can give you more info. |
Python file open/close everytime vs keeping it open until the process is finished | 11,349,020 | 6 | 2012-07-05T16:56:54Z | 11,349,501 | 12 | 2012-07-05T17:32:25Z | [
"python",
"file-io"
] | I have about 50 GB of text file and I am checking the first few characters each line and writing those to other files specified for that beginning text.
For example.
my input contains:
```
cow_ilovecow
dog_whreismydog
cat_thatcatshouldgotoreddit
dog_gotitfromshelter
...............
```
So, I want to process them in ... | You should definitely try to open/close the file as less as possible
Because even comparing with file read/write, file open/close is far more expensive
Consider two code blocks:
```
f=open('test1.txt', 'w')
for i in range(1000):
f.write('\n')
f.close()
```
and
```
for i in range(1000):
f=open('test2.txt', ... |
How to wrap every method of a class? | 11,349,183 | 9 | 2012-07-05T17:09:11Z | 11,350,487 | 8 | 2012-07-05T18:38:19Z | [
"python",
"wrapping"
] | I'd like to wrap every method of a particular class in python, and I'd like to do so by editing the code of the class minimally. How should I go about this? | An elegant way to do it is described in Michael Foord's Voidspace blog in an entry about what metaclasses are and how to use them in the section titled [*A Method Decorating Metaclass*](http://www.voidspace.org.uk/python/articles/metaclasses.shtml#a-method-decorating-metaclass). Simplifying it slightly and applying it ... |
When processing CSV data, how do I ignore the first line of data? | 11,349,333 | 49 | 2012-07-05T17:20:17Z | 11,349,363 | 23 | 2012-07-05T17:22:48Z | [
"python",
"csv"
] | I am asking Python to print the minimum number from a column of CSV data, but the top row is the column number, and I don't want Python to take the top row into account. How can I make sure Python ignores the first line?
This is the code so far:
```
import csv
with open('all16.csv', 'rb') as inf:
incsv = csv.rea... | Just call `incsv.next()` after creating the reader object to skip the first line. |
When processing CSV data, how do I ignore the first line of data? | 11,349,333 | 49 | 2012-07-05T17:20:17Z | 11,349,417 | 18 | 2012-07-05T17:26:10Z | [
"python",
"csv"
] | I am asking Python to print the minimum number from a column of CSV data, but the top row is the column number, and I don't want Python to take the top row into account. How can I make sure Python ignores the first line?
This is the code so far:
```
import csv
with open('all16.csv', 'rb') as inf:
incsv = csv.rea... | You would normally use `next(incsv)` which advances the iterator one row, so you skip the header. The other (say you wanted to skip 30 rows) would be:
```
from itertools import islice
for row in islice(incsv, 30, None):
# process
``` |
When processing CSV data, how do I ignore the first line of data? | 11,349,333 | 49 | 2012-07-05T17:20:17Z | 11,350,095 | 52 | 2012-07-05T18:11:23Z | [
"python",
"csv"
] | I am asking Python to print the minimum number from a column of CSV data, but the top row is the column number, and I don't want Python to take the top row into account. How can I make sure Python ignores the first line?
This is the code so far:
```
import csv
with open('all16.csv', 'rb') as inf:
incsv = csv.rea... | You could use the`csv`module's [**`Sniffer`**](https://docs.python.org/2/library/csv.html?highlight=sniffer#csv.Sniffer) class to detect whether a header row is present and the built-in`next()`function to skip over it if necessary:
```
import csv
with open('all16.csv', 'rb') as inf:
has_header = csv.Sniffer().has... |
When processing CSV data, how do I ignore the first line of data? | 11,349,333 | 49 | 2012-07-05T17:20:17Z | 11,350,146 | 17 | 2012-07-05T18:15:26Z | [
"python",
"csv"
] | I am asking Python to print the minimum number from a column of CSV data, but the top row is the column number, and I don't want Python to take the top row into account. How can I make sure Python ignores the first line?
This is the code so far:
```
import csv
with open('all16.csv', 'rb') as inf:
incsv = csv.rea... | To skip the first line just call:
```
next(inf)
```
Files in Python are iterators over lines. |
When processing CSV data, how do I ignore the first line of data? | 11,349,333 | 49 | 2012-07-05T17:20:17Z | 27,557,394 | 7 | 2014-12-18T23:16:50Z | [
"python",
"csv"
] | I am asking Python to print the minimum number from a column of CSV data, but the top row is the column number, and I don't want Python to take the top row into account. How can I make sure Python ignores the first line?
This is the code so far:
```
import csv
with open('all16.csv', 'rb') as inf:
incsv = csv.rea... | In a similar use case I had to skip annoying lines before the line with my actual column names. This solution worked nicely. Read the file first, then pass the list to `csv.DictReader`.
```
with open('all16.csv') as tmp:
# Skip first line (if any)
next(tmp, None)
# {line_num: row}
data = dict(enumerat... |
subprocess.call env var | 11,350,669 | 6 | 2012-07-05T18:51:02Z | 11,352,013 | 10 | 2012-07-05T20:21:36Z | [
"python",
"environment-variables",
"call",
"subprocess",
"popen"
] | I'm using Popen because I need the env, like this:
```
Popen(
["boto-rsync", "..."],
env={"PATH":"/Library/Frameworks/Python.framework/Versions/2.7/bin/"},
)
```
The problem is `Popen` runs the command as a new thread. Is there any way that I could pass the `env` to `subprocess.call` or prevent `Popen` fr... | You can use `env` with call in the exact same way as with `popen`:
```
subprocess.call(
["boto-rsync", "..."],
env={"PATH":"/Library/Frameworks/Python.framework/Versions/2.7/bin/"},
)
``` |
pandas + dataframe - select by partial string | 11,350,770 | 82 | 2012-07-05T18:57:34Z | 11,531,402 | 157 | 2012-07-17T21:52:18Z | [
"python",
"pandas"
] | I have a `DataFrame` with 4 columns of which 2 contain string values. I was wondering if there was a way to select rows based on a partial string match against a particular column?
In other words, a function or lambda function that would do something like
```
re.search(pattern, cell_in_question)
```
returning a bool... | Based on github issue [#620](https://github.com/pydata/pandas/issues/620), it looks like you'll soon be able to do the following:
```
df[df['A'].str.contains("hello")]
```
Update: [vectorized string methods (i.e., Series.str)](http://pandas.pydata.org/pandas-docs/stable/text.html#text-string-methods) are available in... |
pandas + dataframe - select by partial string | 11,350,770 | 82 | 2012-07-05T18:57:34Z | 22,992,568 | 13 | 2014-04-10T15:36:14Z | [
"python",
"pandas"
] | I have a `DataFrame` with 4 columns of which 2 contain string values. I was wondering if there was a way to select rows based on a partial string match against a particular column?
In other words, a function or lambda function that would do something like
```
re.search(pattern, cell_in_question)
```
returning a bool... | Quick note: if you want to do selection based on a partial string contained in the index, try the following:
```
df['stridx']=df.index
df[df['stridx'].str.contains("Hello|Britain")]
``` |
pandas + dataframe - select by partial string | 11,350,770 | 82 | 2012-07-05T18:57:34Z | 26,849,064 | 45 | 2014-11-10T17:05:17Z | [
"python",
"pandas"
] | I have a `DataFrame` with 4 columns of which 2 contain string values. I was wondering if there was a way to select rows based on a partial string match against a particular column?
In other words, a function or lambda function that would do something like
```
re.search(pattern, cell_in_question)
```
returning a bool... | I am using pandas 0.14.1 on macos in ipython notebook. I tried the proposed line above:
```
df[df['A'].str.contains("Hello|Britain")]
```
and got an error:
```
"cannot index with vector containing NA / NaN values"
```
but it worked perfectly when an "==True" condition was added, like this:
```
df[df['A'].str.conta... |
pandas + dataframe - select by partial string | 11,350,770 | 82 | 2012-07-05T18:57:34Z | 26,851,412 | 8 | 2014-11-10T19:26:27Z | [
"python",
"pandas"
] | I have a `DataFrame` with 4 columns of which 2 contain string values. I was wondering if there was a way to select rows based on a partial string match against a particular column?
In other words, a function or lambda function that would do something like
```
re.search(pattern, cell_in_question)
```
returning a bool... | Say you have the following `DataFrame`:
```
>>> df = pd.DataFrame([['hello', 'hello world'], ['abcd', 'defg']], columns=['a','b'])
>>> df
a b
0 hello hello world
1 abcd defg
```
You can always use the `in` operator in a lambda expression to create your filter.
```
>>> df.apply(lambda x:... |
Named tuple and optional keyword arguments | 11,351,032 | 107 | 2012-07-05T19:16:08Z | 11,351,182 | 15 | 2012-07-05T19:25:29Z | [
"python",
"optional-arguments",
"namedtuple"
] | I'm trying to convert a longish hollow "data" class into a named tuple. My class currently looks like this:
```
class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
```
After conversion to `namedtuple` it looks like:
```
fr... | I'm not sure if there's an easy way with just the built-in namedtuple. There's a nice module called [recordtype](http://pypi.python.org/pypi/recordtype/) that has this functionality:
```
>>> from recordtype import recordtype
>>> Node = recordtype('Node', [('val', None), ('left', None), ('right', None)])
>>> Node(3)
No... |
Named tuple and optional keyword arguments | 11,351,032 | 107 | 2012-07-05T19:16:08Z | 11,351,850 | 74 | 2012-07-05T20:10:15Z | [
"python",
"optional-arguments",
"namedtuple"
] | I'm trying to convert a longish hollow "data" class into a named tuple. My class currently looks like this:
```
class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
```
After conversion to `namedtuple` it looks like:
```
fr... | Wrap it in a function.
```
NodeT = namedtuple('Node', 'val left right')
def Node(val, left=None, right=None):
return NodeT(val, left, right)
``` |
Named tuple and optional keyword arguments | 11,351,032 | 107 | 2012-07-05T19:16:08Z | 16,721,002 | 94 | 2013-05-23T18:10:31Z | [
"python",
"optional-arguments",
"namedtuple"
] | I'm trying to convert a longish hollow "data" class into a named tuple. My class currently looks like this:
```
class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
```
After conversion to `namedtuple` it looks like:
```
fr... | I subclassed namedtuple and overrode the `__new__` method:
```
from collections import namedtuple
class Node(namedtuple('Node', ['value', 'left', 'right'])):
__slots__ = ()
def __new__(cls, value, left=None, right=None):
return super(Node, cls).__new__(cls, value, left, right)
```
This preserves an i... |
Named tuple and optional keyword arguments | 11,351,032 | 107 | 2012-07-05T19:16:08Z | 18,348,004 | 177 | 2013-08-21T02:40:32Z | [
"python",
"optional-arguments",
"namedtuple"
] | I'm trying to convert a longish hollow "data" class into a named tuple. My class currently looks like this:
```
class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
```
After conversion to `namedtuple` it looks like:
```
fr... | Set `Node.__new__.__defaults__` (or `Node.__new__.func_defaults` before Python 2.6) to the default values.
```
>>> from collections import namedtuple
>>> Node = namedtuple('Node', 'val left right')
>>> Node.__new__.__defaults__ = (None,) * len(Node._fields)
>>> Node()
Node(val=None, left=None, right=None)
```
You can... |
Named tuple and optional keyword arguments | 11,351,032 | 107 | 2012-07-05T19:16:08Z | 21,290,909 | 9 | 2014-01-22T18:23:13Z | [
"python",
"optional-arguments",
"namedtuple"
] | I'm trying to convert a longish hollow "data" class into a named tuple. My class currently looks like this:
```
class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
```
After conversion to `namedtuple` it looks like:
```
fr... | Here is a more compact version inspired by justinfay's answer:
```
from collections import namedtuple
from functools import partial
Node = namedtuple('Node', ('val left right'))
Node.__new__ = partial(Node.__new__, left=None, right=None)
``` |
Named tuple and optional keyword arguments | 11,351,032 | 107 | 2012-07-05T19:16:08Z | 29,756,101 | 9 | 2015-04-20T18:53:55Z | [
"python",
"optional-arguments",
"namedtuple"
] | I'm trying to convert a longish hollow "data" class into a named tuple. My class currently looks like this:
```
class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
```
After conversion to `namedtuple` it looks like:
```
fr... | This is [an example straight from the docs](https://docs.python.org/3/library/collections.html#collections.namedtuple):
> Default values can be implemented by using \_replace() to customize a
> prototype instance:
>
> ```
> >>> Account = namedtuple('Account', 'owner balance transaction_count')
> >>> default_account = ... |
Enclose a variable in single quotes in Python | 11,351,043 | 5 | 2012-07-05T19:16:29Z | 11,351,115 | 16 | 2012-07-05T19:21:37Z | [
"python"
] | How do I enclose a variable within single quotations in python? It's probably very simple but I can't seem to get it! I need to url-encode the variable `term`. `Term` is entered in a form by a user and is passed to a function where it is url-encoded `term=urllib.quote(term)`. If the user entered "apple computer" as the... | There are three ways:
1. string concatenation
```
term = urllib.quote("'" + term + "'")
```
2. old-style string formatting
```
term = urllib.quote("'%s'" % (term,))
```
3. new-style string formatting
```
term = urllib.quote("'{}'".format(term))
``` |
How to get XML tag value in Python | 11,351,183 | 4 | 2012-07-05T19:25:34Z | 11,351,275 | 10 | 2012-07-05T19:31:31Z | [
"python",
"xml",
"parsing",
"dom",
"xml-parsing"
] | I have some XML in a unicode-string variable in Python as follows:
```
<?xml version='1.0' encoding='UTF-8'?>
<results preview='0'>
<meta>
<fieldOrder>
<field>count</field>
</fieldOrder>
</meta>
<result offset='0'>
<field k='count'>
<value><text>6</text></value>
</field>
</result>
<... | With lxml:
```
import lxml
# xmlstr is your xml in a string
root = lxml.fromstring(xmlstr)
textelem = root.find('result/field/value/text')
print textelem.text
```
Edit: But I imagine there could be more than one result...
```
import lxml
# xmlstr is your xml in a string
root = lxml.fromstring(xmlstr)
results = root.... |
nltk tokenization and contractions | 11,351,290 | 7 | 2012-07-05T19:32:58Z | 11,354,795 | 7 | 2012-07-06T01:39:05Z | [
"python",
"nlp",
"nltk"
] | I'm tokenizing text with nltk, just sentences fed to wordpunct\_tokenizer. This splits contractions (e.g. 'don't' to 'don' +" ' "+'t') but I want to keep them as one word. I'm refining my methods for a more measured and precise tokenization of text, so I need to delve deeper into the nltk tokenization module beyond sim... | Which tokenizer you use really depends on what you want to do next. As inspectorG4dget said, some part-of-speech taggers handle split contractions, and in that case the splitting is a good thing. But maybe that's not what you want. To decide which tokenizer is best, consider what you need for the next step, and then su... |
Mock patching from/import statement in Python | 11,351,382 | 13 | 2012-07-05T19:38:42Z | 11,351,511 | 16 | 2012-07-05T19:47:36Z | [
"python",
"python-mock"
] | I am trying to get mock.patch to work on the following piece of sample code:
```
from mock import patch
from collections import defaultdict
with patch('collections.defaultdict'):
d = defaultdict()
print 'd:', d
```
This outputs the following:
```
d: defaultdict(None, {})
```
Which means that defaultdict was no... | If you're patching something in the same module, you can use `__main__`:
```
from mock import patch
from collections import defaultdict
with patch('__main__.defaultdict'):
d = defaultdict()
print 'd:', d
```
If you're mocking something for an imported module, however, you'll want to use that module's name so... |
How to make Django's DateTimeField optional? | 11,351,619 | 22 | 2012-07-05T19:55:24Z | 11,351,661 | 12 | 2012-07-05T19:58:16Z | [
"python",
"django"
] | I am trying to implement a to-do-list website to practice using Django. In models.py, I have a class called `Item` to represent a to-do item. In it, I have the following line:
```
due_date = models.DateTimeField(required=False)
```
due\_date is meant to be an optional field in case the user has a deadline for some to... | Use
`due_date = models.DateTimeField(null=True, blank=True)`
Check [Field Options](https://docs.djangoproject.com/en/dev/ref/models/fields/#field-options) for more information. |
How to make Django's DateTimeField optional? | 11,351,619 | 22 | 2012-07-05T19:55:24Z | 11,351,690 | 36 | 2012-07-05T19:59:48Z | [
"python",
"django"
] | I am trying to implement a to-do-list website to practice using Django. In models.py, I have a class called `Item` to represent a to-do item. In it, I have the following line:
```
due_date = models.DateTimeField(required=False)
```
due\_date is meant to be an optional field in case the user has a deadline for some to... | "required" is a valid argument for Django forms. For models, you want the keyword args `blank=True` (for the admin) and `null=True` (for the database). |
Getting a users entire twitter timeline with tweepy | 11,351,711 | 10 | 2012-07-05T20:01:13Z | 11,353,411 | 7 | 2012-07-05T22:30:44Z | [
"python",
"twitter",
"tweepy"
] | I am trying to retrieve a list that contains the entire contents of my personal twitter statuses with python and tweepy.
I have successfully authenticated via OAuth but cannot seem to recieve more than about 800 status updates from twitter. My twitter bio page says I have over 2000 tweets. I am well within the 3200 tw... | You need to specify include\_rts=True as a parameter to api.user\_timeline; retweets are not included by default. If you retweet a lot of things, this is likely where your missing tweets have gone. |
Converting a dict into a list | 11,351,874 | 4 | 2012-07-05T20:12:15Z | 11,351,913 | 11 | 2012-07-05T20:15:02Z | [
"python"
] | I have
```
{key1:value1, key2:value2, etc}
```
I want it to become:
```
[key1,value1,key2,value2] , if certain keys match certain criteria.
```
How can i do it as pythonically as possible?
Thanks! | This should do the trick:
```
[y for x in dict.items() for y in x]
```
For example:
```
dict = {'one': 1, 'two': 2}
print([y for x in dict.items() for y in x])
```
This will print:
```
['two', 2, 'one', 1]
``` |
Finding moving average from data points in Python | 11,352,047 | 26 | 2012-07-05T20:24:25Z | 11,352,216 | 65 | 2012-07-05T20:37:47Z | [
"python",
"plot",
"sum",
"average"
] | I am playing in Python a bit again, and I found a neat book with examples. One of the examples is to plot some data. I have a .txt file with two columns and I have the data. I plotted the data just fine, but in the exercise it says: Modify your program further to calculate and plot the running average of the data, defi... | Best One common way to apply a moving/sliding average (or any other sliding window function) to a signal is by using `numpy.convolve()`.
```
def movingaverage(interval, window_size):
window = numpy.ones(int(window_size))/float(window_size)
return numpy.convolve(interval, window, 'same')
```
Here, interval is ... |
Finding moving average from data points in Python | 11,352,047 | 26 | 2012-07-05T20:24:25Z | 11,352,259 | 20 | 2012-07-05T20:41:10Z | [
"python",
"plot",
"sum",
"average"
] | I am playing in Python a bit again, and I found a neat book with examples. One of the examples is to plot some data. I have a .txt file with two columns and I have the data. I plotted the data just fine, but in the exercise it says: Modify your program further to calculate and plot the running average of the data, defi... | A moving average is a convolution, and numpy will be faster than most pure python operations. This will give you the 10 point moving average.
```
import numpy as np
smoothed = np.convolve(data, np.ones(10)/10)
```
I would also **strongly** suggest using the great pandas package if you are working with timeseries data... |
Iterate through list and handle StopIteration in Python beautifully | 11,352,099 | 6 | 2012-07-05T20:28:08Z | 11,352,119 | 12 | 2012-07-05T20:30:19Z | [
"python",
"list",
"iterator",
"stopiteration"
] | I am trying to iterate through a list, and I need to perform specific operation when and only when the iteration reached the end of the list, see example below:
```
data = [1, 2, 3]
data_iter = data.__iter__()
try:
while True:
item = data_iter.next()
try:
do_stuff(item)
bre... | You can use `else` after a for loop, and the code within that `else` is only executed if you did not `break` out of the for loop:
```
data = [1, 2, 3]
for item in data:
try:
do_stuff(item)
break # we just need to do stuff with the first successful item
except Exception:
handle_errors(i... |
NameError: name 'UTC' is not defined | 11,353,640 | 4 | 2012-07-05T22:57:27Z | 11,353,692 | 8 | 2012-07-05T23:02:25Z | [
"python",
"datetime"
] | The output of `datetime.datetime.now()` outputs in my native timezone of UTC-8. I'd like to convert that to an appropriate timestamp with a tzinfo of UTC.
```
from datetime import datetime, tzinfo
x = datetime.now()
x = x.replace(tzinfo=UTC)
```
^ outputs NameError: name 'UTC' is not defined
`x.replace(tzinfo=<UTC>)... | You'll need to use an additional library such as `pytz`. Python's `datetime` module doesn't include any `tzinfo` classes, including UTC, and certainly not your local timezone. |
Python: Unable to Render Tex in Matplotlib | 11,354,149 | 17 | 2012-07-05T23:58:08Z | 11,357,765 | 26 | 2012-07-06T07:32:49Z | [
"python",
"matplotlib",
"osx-snow-leopard",
"tex"
] | I recently upgraded my laptop to Snow Leopard, updated TeX to Version 3.1415926 (TeX Live 2011/MacPorts 2011\_5), and installed Python 2.7.3. After all these installs, I ran macport selfupdate and macport upgrade outdated. However, now when I try to use TeX in matplotlib, I receive the following:
```
LaTeX was not abl... | The error message says you're missing the `type1cm` package. It seems that [MacPorts includes it as part of `texlive-latex-extra`](https://trac.macports.org/wiki/TeXLivePackages). |
Read lines containing integers from a file in Python? | 11,354,544 | 6 | 2012-07-06T00:55:20Z | 11,354,551 | 11 | 2012-07-06T00:56:26Z | [
"python",
"file-io",
"casting"
] | I have a file format like this:
```
9 8 1
3 4 1
...
...
```
Now, I want to get each line as three integers.
When I used
```
for line in f.readlines():
print line.split(" ")
```
The script printed this:
```
['9', '8', '1\r\n']
['3', '4', '1\r\n']
...
...
```
How can I get each line as three integers? | Using the code you have and addressing your specific question of how to convert your list to integers:
You can iterate through each line and convert the strings to `int` with the following example using [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions):
Given:
```
line =['... |
Return in Recursive Function | 11,356,168 | 11 | 2012-07-06T05:11:55Z | 11,358,249 | 13 | 2012-07-06T08:06:06Z | [
"python",
"recursion",
"return"
] | I have just started learning python (v3.2.3) and have encountered an odd problem about the `return` in this function:
```
def test(x):
if x > 9 :
test(x - 10)
else:
print('real value',x)
return x
x = int(input())
y = test(x)
print('this should be real value',y)
```
When I run it, I ge... | You invoke `test(45)`. This tests whether `45 > 9`, which is true, so it invokes `test(35)` (45 - 10), without returning its result. The same thing happens with `test(25)` and `test(15)`, until finally `test(5)` is invoked.
This prints 'real value 5', and then returns 5. But returning a result from a function **always... |
looking for more pythonic apporach | 11,357,655 | 3 | 2012-07-06T07:24:51Z | 11,357,684 | 9 | 2012-07-06T07:26:50Z | [
"python"
] | Just wrote this function...
```
def nrofleadingchars(stringtotest, testchar='\t'):
count = 0
for c in stringtotest:
if c == testchar:
count = count + 1
else:
return count
return count
```
However does not feel pythonic 'enough', suggestions? | ```
import itertools
def nrofleadingchars(stringtotest, testchar='\t'):
return len(list(itertools.takewhile(lambda x: x == testchar, stringtotest)))
```
Due to the need to construct a list, this could be less efficient for things with very large prefixes. If I were going to potentially be dealing with such, I'd p... |
Why is __getattribute__ not invoked on an implicit __getitem__-invocation? | 11,360,020 | 7 | 2012-07-06T09:59:38Z | 11,360,083 | 11 | 2012-07-06T10:02:54Z | [
"python",
"magic-methods"
] | While trying to wrap arbitrary objects, I came across a problem with dictionaries and lists. Investigating, I managed to come up with a simple piece of code whose behaviour I simply do not understand. I hope some of you can tell me what is going on:
```
>>> class Cl(object): # simple class that prints (and suppresses)... | Magic `__methods__()` are treated specially: They are internally assigned to "slots" in the type data structure to speed up their look-up, and they are only looked up in these slots. If the slot is empty, you get the error message you got.
See [Special method lookup for new-style classes](http://docs.python.org/refere... |
What is the EAFP principle in Python? | 11,360,858 | 58 | 2012-07-06T10:55:04Z | 11,360,880 | 83 | 2012-07-06T10:56:31Z | [
"python",
"principles"
] | What is meant by "using the EAFP principle" in Python? Could you provide any examples? | From the [glossary](http://docs.python.org//glossary.html#term-eafp):
> Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of m... |
Output data from all columns in a dataframe in pandas | 11,361,985 | 42 | 2012-07-06T12:12:49Z | 11,362,056 | 27 | 2012-07-06T12:18:26Z | [
"python",
"numpy",
"pandas"
] | I have a csv file with the name `params.csv`. I opened up `ipython qtconsole` and created a pandas dataframe using:
```
import pandas
paramdata = pandas.read_csv('params.csv', names=paramnames)
```
where, `paramnames` is a python list of string objects. Example of `paramnames` (the length of actual list is 22):
```
... | There is too much data to be displayed on the screen, therefore a summary is displayed instead.
If you want to output the data anyway (it won't probably fit on a screen and does not look very well):
```
print paramdata.values
```
converts the dataframe to its numpy-array matrix representation.
```
paramdata.columns... |
Output data from all columns in a dataframe in pandas | 11,361,985 | 42 | 2012-07-06T12:12:49Z | 11,366,429 | 9 | 2012-07-06T16:50:17Z | [
"python",
"numpy",
"pandas"
] | I have a csv file with the name `params.csv`. I opened up `ipython qtconsole` and created a pandas dataframe using:
```
import pandas
paramdata = pandas.read_csv('params.csv', names=paramnames)
```
where, `paramnames` is a python list of string objects. Example of `paramnames` (the length of actual list is 22):
```
... | you can also use `DataFrame.head(x)` / `.tail(x)` to display the first / last x rows of the DataFrame. |
Output data from all columns in a dataframe in pandas | 11,361,985 | 42 | 2012-07-06T12:12:49Z | 13,237,914 | 79 | 2012-11-05T18:13:42Z | [
"python",
"numpy",
"pandas"
] | I have a csv file with the name `params.csv`. I opened up `ipython qtconsole` and created a pandas dataframe using:
```
import pandas
paramdata = pandas.read_csv('params.csv', names=paramnames)
```
where, `paramnames` is a python list of string objects. Example of `paramnames` (the length of actual list is 22):
```
... | Use:
```
pandas.set_option('display.max_columns', 7)
```
This will force Pandas to display the 7 columns you have. Or more generally:
```
pandas.set_option('display.max_columns', None)
```
which will force it to display any number of columns.
Explanation: the default for `max_columns` is `0`, which tells Pandas to... |
Output data from all columns in a dataframe in pandas | 11,361,985 | 42 | 2012-07-06T12:12:49Z | 16,789,834 | 16 | 2013-05-28T10:32:51Z | [
"python",
"numpy",
"pandas"
] | I have a csv file with the name `params.csv`. I opened up `ipython qtconsole` and created a pandas dataframe using:
```
import pandas
paramdata = pandas.read_csv('params.csv', names=paramnames)
```
where, `paramnames` is a python list of string objects. Example of `paramnames` (the length of actual list is 22):
```
... | I know this is an old question, but I have just had a similar problem and I think what I did would work for you too.
I used the to\_csv() method and wrote to stdout:
```
import sys
paramdata.to_csv(sys.stdout)
```
This should dump the whole dataframe whether it's nicely-printable or not, and you can use the to\_csv... |
Output data from all columns in a dataframe in pandas | 11,361,985 | 42 | 2012-07-06T12:12:49Z | 19,973,722 | 8 | 2013-11-14T09:18:43Z | [
"python",
"numpy",
"pandas"
] | I have a csv file with the name `params.csv`. I opened up `ipython qtconsole` and created a pandas dataframe using:
```
import pandas
paramdata = pandas.read_csv('params.csv', names=paramnames)
```
where, `paramnames` is a python list of string objects. Example of `paramnames` (the length of actual list is 22):
```
... | In `ipython`, I use this to print a part of the dataframe that works quite well (prints the first 100 rows):
```
print paramdata.head(100).to_string()
``` |
What does "from ... import ..." mean in simple bonehead terms? | 11,362,061 | 4 | 2012-07-06T12:18:53Z | 11,362,198 | 10 | 2012-07-06T12:27:04Z | [
"python"
] | ```
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could two on one line too, how?
input = open(from_file)
indata = input.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" %... | If you do `import sys`, you'll get to access the functions and variables in the module sys via `sys.foo` or `sys.bar()`. This can get a lot of typing, especially if using something from submodules (e.g. I often have to access `django.contrib.auth.models.User`).
To avoid such this redundancy, you can bring one, many or ... |
error in deploying a project using scrapyd | 11,362,511 | 4 | 2012-07-06T12:48:04Z | 11,380,881 | 7 | 2012-07-08T05:28:23Z | [
"python",
"scrapy",
"scrapyd"
] | I had multiple spiders in my project folder and want to run all the spiders at once, so i decided to run them using scrapyd service.
I have started doing this by seeing [here](http://scrapy.readthedocs.org/en/0.7/topics/scrapyd.html)
First of all i am in current project folder
1. I had opened the `scrapy.cfg` file an... | From scrapyd service documentation: (http://scrapy.readthedocs.org/en/latest/topics/scrapyd.html?highlight=scrapyd)
> You can define targets by adding them to your projectâs scrapy.cfg
> file... Hereâs an example of defining a new target scrapyd2 with
> restricted access through HTTP basic authentication:
```
[de... |
Getting "newline inside string" while reading the csv file in Python? | 11,362,667 | 7 | 2012-07-06T12:57:30Z | 14,176,870 | 12 | 2013-01-05T22:01:50Z | [
"python",
"django",
"csv",
"python-2.7"
] | I have this utils.py file in Django Architecture:
```
def range_data(ip):
r = []
f = open(os.path.join(settings.PROJECT_ROOT, 'static', 'csv ',
'GeoIPCountryWhois.csv'))
for num,row in enumerate(csv.reader(f)):
if row[0] <= ip <= row[1]:
r.append([r[4]])
... | had similar problem earlier today, there was an end quote missing from a line and the solution is by instructing `reader` to perform no special processing of quote characters (`quoting=csv.QUOTE_NONE`). |
how to install python-mode.el for emacs | 11,363,089 | 10 | 2012-07-06T13:26:23Z | 11,363,336 | 10 | 2012-07-06T13:40:27Z | [
"python",
"emacs"
] | I am using ubuntu 1.10. I have downloaded python-mode.el from launchpad and placed it in emacs.d/plugins/.
Now how do I install python-mode.el ? | Try this
```
(add-to-list 'load-path "~/.emacs.d/plugins")
(require 'python-mode)
``` |
Sorting a list containing lists | 11,364,045 | 3 | 2012-07-06T14:21:38Z | 11,364,137 | 9 | 2012-07-06T14:26:31Z | [
"python",
"list",
"sorting",
"dictionary"
] | I have an algorithm that generates a list containing an unknown number of sublists, with each sublist having an unknown number of string elements as well as one floating point number. I need these sublists sorted inside of the main list according to this float. Also, the order of the strings in the sublists are not be ... | The [`sort` method](http://docs.python.org/library/stdtypes.html#mutable-sequence-types) has a handy `key` keyword argument, that let's you specify a function to call to determine on what information a list should be sorted.
Sorting your lists is as easy as writing a function that returns the float value contained in ... |
Why are slice and range upper-bound exclusive? | 11,364,533 | 16 | 2012-07-06T14:49:36Z | 11,364,711 | 20 | 2012-07-06T14:59:44Z | [
"python",
"language-design",
"slice"
] | Disclaimer: I am not asking *if* the upper-bound `stop`argument of `slice()`and `range()` is exclusive or *how* to use these functions.
Calls to the `range`and `slice`functions, as well as the slice notation `[start:stop]` all refer to sets of integers.
```
range([start], stop[, step])
slice([start], stop[, step])
``... | The [documentation](http://docs.python.org/release/3.1.4/tutorial/introduction.html) implies this has a few useful properties:
```
word[:2] # The first two characters
word[2:] # Everything except the first two characters
```
> Hereâs a useful invariant of slice operations: `s[:i] + s[i:]` equals `s`.
>
> For ... |
Why are slice and range upper-bound exclusive? | 11,364,533 | 16 | 2012-07-06T14:49:36Z | 21,481,885 | 8 | 2014-01-31T13:59:43Z | [
"python",
"language-design",
"slice"
] | Disclaimer: I am not asking *if* the upper-bound `stop`argument of `slice()`and `range()` is exclusive or *how* to use these functions.
Calls to the `range`and `slice`functions, as well as the slice notation `[start:stop]` all refer to sets of integers.
```
range([start], stop[, step])
slice([start], stop[, step])
``... | Here's the [opinion](https://plus.google.com/115212051037621986145/posts/YTUxbXYZyfi) of some Google+ user:
> [...] I was swayed by the elegance of half-open intervals. Especially the
> invariant that when two slices are adjacent, the first slice's end
> index is the second slice's start index is just too beautiful to... |
Unable to define custom downloader middleware in Scrapy | 11,364,815 | 7 | 2012-07-06T15:06:05Z | 11,367,858 | 14 | 2012-07-06T18:37:32Z | [
"python",
"scrapy"
] | I am attempting to set up a custom downloader middleware class in Scrapy. I suspect that I've missed something obvious, but I've read over the docs a few times and have found no solutions. I'm getting a bit frustrated with what should be an extremely simple task, so hopefully someone will be able to provide me with som... | ```
DOWNLOADER_MIDDLEWARES = { 'myproject.middlewares.TestDownloader': 400 }
```
For this to work, create file `middlewares.py` inside `myproject` folder, and in that file put your downloader middleware class called `TestDownloader`.
Or having `middlewares` folder with `__init__.py` inside it, you can put put your do... |
Upload images/video to google cloud storage using Google App Engine | 11,364,878 | 4 | 2012-07-06T15:09:29Z | 11,370,498 | 10 | 2012-07-06T22:32:44Z | [
"python",
"google-app-engine",
"google-cloud-storage"
] | I have read the question from [Sending images to google cloud storage using google app engine](http://stackoverflow.com/questions/9237747/sending-images-to-google-cloud-storage-using-google-app-engine).
However, the codes in the answer that the file will upload to Blobstore first, so the file can not be exceeded 32MB.... | easy since 1.7.0
```
upload_url = blobstore.create_upload_url('/upload_handler', gs_bucket_name='my_bucket')
```
Will upload straight to Google Storage and return you blob keys that point to the uploads in Cloud Storage. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.