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 |
|---|---|---|---|---|---|---|---|---|---|
Create set of random JPGs | 10,901,049 | 4 | 2012-06-05T16:23:18Z | 10,901,092 | 10 | 2012-06-05T16:26:04Z | [
"python",
"jpeg"
] | Here's the scenario, I want to create a set of random, small jpg's - anywhere between 50 bytes and 8k in size - the actual visual content of the jpeg is irrelevant as long as they're valid. I need to generate a thousand or so, and they all have to be unique - even if they're only different by a single pixel. Can I just... | If the images can be only random noise, so you could generate an array using `numpy.random` and save them using PIL's `Image.save`.
This example might be expanded, including ways to avoid a (very unlikely) repetition of patterns:
```
import numpy, Image
for n in xrange(10):
a = numpy.random.rand(30,30,3) * 255
... |
Range values to pseudocolor | 10,901,085 | 7 | 2012-06-05T16:25:47Z | 10,902,473 | 11 | 2012-06-05T18:03:59Z | [
"python",
"colors",
"floating-point"
] | I have a certain array of floats (in Python) that might range from 0 to 100. I want to create a pseudo-color image so that the colors vary from green (corresponding to 0) to red (100). This is similar to pcolor from matplotlib. However, I do not want to use pcolor.
Is there a function like pseudocolorForValue(val,(min... | You could write your own function that converted 0..100 to 0..120 degrees and then used that value as the H (or angle) of a color in the HLS (or HSV) colorspace. This could then be converted into an RGB color for display purposes.
**Update:**
Good news, turns out that Python has colorspace conversion routines in its ... |
Slice Assignment with a String in a List | 10,902,601 | 10 | 2012-06-05T18:15:10Z | 10,902,694 | 7 | 2012-06-05T18:22:30Z | [
"python",
"string",
"indexing",
"slice"
] | I did quite a bit of perusing, but I don't have a definite answer for the *concept* that I'm trying to understand.
In Python, if I take a list, such as:
```
L1=['muffins', 'brownies','cookies']
```
And then attempted to replace the first pointer to an object in the list, namely 'muffins' by using the code:
```
L1[0... | If you specify a slice, the righthand side is presumed to be a list/tuple (actually, any iterable - but watch out for generators that produce an indefinite number of values).
To replace an item in a list, use:
```
my_list[0] = "cake"
```
(You could also do
```
my_list[0:1] = ["cake"]
```
if you really want to use ... |
Slice Assignment with a String in a List | 10,902,601 | 10 | 2012-06-05T18:15:10Z | 10,902,696 | 14 | 2012-06-05T18:22:38Z | [
"python",
"string",
"indexing",
"slice"
] | I did quite a bit of perusing, but I don't have a definite answer for the *concept* that I'm trying to understand.
In Python, if I take a list, such as:
```
L1=['muffins', 'brownies','cookies']
```
And then attempted to replace the first pointer to an object in the list, namely 'muffins' by using the code:
```
L1[0... | Two important points:
1. Slice assignment takes *an iterable* on the right-hand side, and replaces the elements of the slice with the objects produced by the iterable.
2. In Python, strings are iterable: iterating over a string yields its characters.
Thus
```
L1[0:1] = 'cake'
```
replaces the first element of `L1` ... |
Scripting Bridge vs PyObjC vs py2app | 10,902,671 | 6 | 2012-06-05T18:21:11Z | 10,903,455 | 7 | 2012-06-05T19:14:52Z | [
"python",
"cocoa",
"py2app",
"scripting-bridge"
] | I am just starting to learn about integrating Python and Mac OS apps. (I want to call some methods from Cocoa to Python.) I've ran into these terminologies -- Scripting Bridge, PyObjC, and py2app. What's the difference? Is PyObjC an example of a scripting bridge? And when does py2app come into play? | The short version: PyObjC is the way you call Mac OS X APIs, Scripting Bridge is the way you talk to other apps' scripting interfaces. In more detail:
PyObjC is a bridge between the Python language and the Objective C runtime (and the set of Cocoa wrappers built trivially on top of that bridge, and some nice convenien... |
When my code sorts the inputs, why doesn't it work in certain scenarios? | 10,903,164 | 3 | 2012-06-05T18:53:37Z | 10,903,186 | 10 | 2012-06-05T18:55:17Z | [
"python",
"sorting",
"input"
] | I am new to Python.
First, the code is supposed to take an input (in the form of "x/y/z" where x,y, and z are any positive integer) and split it into three different variables.
```
input = raw_input()
a, b, c = input.split("/", 2)
```
I want the second part of my code to take these three variables and sort them based... | The issue is that you are sorting strings, and expecting them to be sorted like integers. First convert your list of strings to a list of ints if you would like numerical sorting.
```
>>> sorted(['23', '9', '2'])
['2', '23', '9']
>>> sorted(map(int, ['23', '9', '2']))
[2, 9, 23]
```
Here is how you could rewrite your... |
Python MySQLdb WHERE SQL LIKE | 10,903,497 | 4 | 2012-06-05T19:17:36Z | 10,903,587 | 18 | 2012-06-05T19:24:02Z | [
"python",
"mysql",
"mysql-python"
] | I have recently started to learn Python and MySQL for web purposes and I have run into a following problem :
I want to pull out from a mysql database one record that contains any text that I enter in param section, howerver I am running into following problem when making a query:
```
traceback (most recent call last)... | Directly inserting the data into the SQL string is not the best way to do this, as it is prone to [SQL injection](http://en.wikipedia.org/wiki/SQL_injection). You should change it to this:
`c.execute("SELECT * FROM data WHERE params LIKE %s LIMIT 1", ("%" + param + "%",))` |
Python : smtplib sendmail function | 10,904,418 | 2 | 2012-06-05T20:26:35Z | 10,904,593 | 7 | 2012-06-05T20:41:17Z | [
"python",
"google-app-engine",
"sendmail",
"smtplib"
] | i have an activation mail sending script as follows.
```
#!/usr/bin/python
__author__ = 'Amyth Arora (***@gmail.com)'
import smtplib
import string
import sys
import random
from email.MIMEText import MIMEText
def generate_activation_key(size=64, chars=string.ascii_lowercase + string.digits):
return ''.join(rando... | App Engine does not allow the users to send emails using the smtplib library. Instead you need to use the api provided. The documentation can be found here: <https://developers.google.com/appengine/docs/python/mail> |
Check condition before method call | 10,904,521 | 5 | 2012-06-05T20:34:47Z | 10,905,397 | 7 | 2012-06-05T21:41:07Z | [
"python"
] | I have a class named Server which can be started and stopped. Certain methods should not be called unless the Server is started, in which case a NotConnectedException should be raised. Is there a way to call a method before every method in a class and determine if class variable \_started is set to True?
I tried using... | Remember what decorators *are*:
```
@decorate
def foo(...):
...
```
is exactly equivalent to:
```
def foo(...):
...
foo = decorate(foo)
```
The decorator is called on the *function*, so calling the first parameter *self* makes no sense. Also, the decorator is called on the function when it is defined, and w... |
Django 1.2: How to connect pre_save signal to class method | 10,904,799 | 6 | 2012-06-05T20:55:34Z | 11,647,745 | 7 | 2012-07-25T10:30:19Z | [
"python",
"django",
"signals",
"python-2.7",
"django-1.2"
] | I am trying to define a "before\_save" method in certain classes in my django 1.2 project. I'm having trouble connecting the signal to the class method in models.py.
```
class MyClass(models.Model):
....
def before_save(self, sender, instance, *args, **kwargs):
self.test_field = "It worked"
```
I've t... | A working example with *classmethod*:
```
class MyClass(models.Model):
#....
@classmethod
def before_save(cls, sender, instance, *args, **kwargs):
instance.test_field = "It worked"
pre_save.connect(MyClass.before_save, sender=MyClass)
```
There's also a great decorator to handle signal connection... |
Adding inline many to many objects in Django admin | 10,904,848 | 9 | 2012-06-05T20:58:25Z | 10,999,074 | 18 | 2012-06-12T14:46:04Z | [
"python",
"django",
"django-forms",
"django-admin"
] | I'm fairly new to Django and having read the documentation on its relational models and inline admin forms ([docs on InlineModelAdmin](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects)) I'm struggling to figure out if the following is possible out of the box, or if I should roll my own ... | The default widget for Many-to-many field in admin or widgets with [`filter_vertical`](https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.filter_vertical) or `filter_horizontal` property allows you to add new item. There is a green "+" sign near the field to open a popup window and... |
What is "Introspection-based code completion"? | 10,905,503 | 5 | 2012-06-05T21:50:45Z | 10,905,528 | 7 | 2012-06-05T21:52:14Z | [
"python",
"ide"
] | I'm looking at various IDEs for python. Looking at the official [list](http://wiki.python.org/moin/IntegratedDevelopmentEnvironments) the IDEs are categorized based on '**introspection based code completion**'.
What does introspection based code completion mean?
Thanks. | It means the IDE uses introspection to figure out what methods and variables are accessible from a given object, then allows quick code completion, usually by providing a list of options after you type a period following a symbol. |
Django: How to save original filename in FileField? | 10,905,674 | 11 | 2012-06-05T22:07:08Z | 10,916,212 | 8 | 2012-06-06T14:24:29Z | [
"python",
"django"
] | I want the filenames to be random and therefore I use `upload_to` function which returns a random filename like so:
```
from uuid import uuid4
import os
def get_random_filename(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (str(uuid4()), ext)
return os.path.join('some/path/', file... | The posted code normally works, perhaps the actual code is
```
class FooModel(models.Model):
filename = models.CharField(max_length=128)
file = models.FileField(upload_to=get_random_filename)
```
Note the switching of the ordering of the fields above.
This won't work because: the `upload_to()` is invoked by ... |
Why does PHP just work with Ajax but Python doesn't? | 10,906,051 | 4 | 2012-06-05T22:44:31Z | 10,906,282 | 12 | 2012-06-05T23:16:43Z | [
"php",
"python",
"ajax"
] | Building a PHP script that responds to an Ajax request is as easy as:
```
<?php
$command = $_POST["command"];
if ($command == "say_hello") {
$name = $_POST["name"];
echo json_encode(array("message" => "Hello, " . $name));
}
?>
```
and, at least if you're using jQuery on the client side, and if you speci... | > But with Python it's not that simple. Or at least I haven't figured out how to make it that simple. If I just try to "print" a response (paralleling PHP's "echo" statement above) the client doesn't get anything back.
I might have some of the details wrong, but I'll try to explain why this is the case. Firstly, the P... |
Does pytest support "default" markers? | 10,906,817 | 4 | 2012-06-06T00:29:15Z | 10,916,403 | 8 | 2012-06-06T14:34:57Z | [
"python",
"py.test"
] | I am using pytest to test python models for embedded systems. Features to be tested vary by platform. ( I'm using 'platform' in this context to mean an embedded system type, not an OS type).
The most straightforward way to organize my tests would be to allocate them to directories based on platform type.
```
/platfor... | Let's tackle the full problem. I think you can put a conftest.py file along with your tests and it will take care to skip all non-matching tests (non-marked tests will always match and thus never get skipped). Here i am using **sys.platform** but i am sure you have a different way to compute your platform value.
```
#... |
Python numpy addition error | 10,907,917 | 6 | 2012-06-06T03:45:36Z | 10,908,035 | 7 | 2012-06-06T04:06:15Z | [
"python",
"numpy"
] | I'm getting a very odd error using a basic shortcut method in python. It seems, unless I'm being very stupid, I get different values for A = A + B, and A += B. Here is my code:
```
def variance(phi,sigma,numberOfIterations):
variance = sigma
for k in range(1,numberOfIterations):
phik = np.linalg.matrix... | The culprit is:
```
variance = sigma
```
If you change that to:
```
variance = sigma.copy()
```
You'll see the correct result.
This is because `+=` actually performs a (more efficient) in-place addition⦠And since both `variance` and `sigma` reference the same array, *both* will be updated. For example:
```
>>>... |
How to convert pandas dataframe so that index is the unique set of values and data is the count of each value? | 10,908,295 | 5 | 2012-06-06T04:46:19Z | 10,916,118 | 16 | 2012-06-06T14:19:52Z | [
"python",
"pandas"
] | I have data from multiple choice questions and it is formatted like so:
```
Sex Qu1 Qu2 Qu3
Name
Bob M 1 2 1
John M 3 3 5
Alex M 4 1 2
Jen F 3 2 4
Mary F 4 3 4
```
The data is a rating from 1 to 5 for the 3 multiple choice questions. I want rearrange the dat... | `Series.value_counts` gives you the histogram you're looking for:
```
In [9]: df['Qu1'].value_counts()
Out[9]:
4 2
3 2
1 1
```
So, apply this function to each of those 3 columns:
```
In [13]: table = df[['Qu1', 'Qu2', 'Qu3']].apply(lambda x: x.value_counts())
In [14]: table
Out[14]:
Qu1 Qu2 Qu3
1 ... |
How to apply theme to PyGTK Application | 10,908,752 | 9 | 2012-06-06T05:45:52Z | 10,916,008 | 12 | 2012-06-06T14:14:21Z | [
"python",
"gtk",
"themes",
"pygtk"
] | **Is it possible to apply this [GTK+ theme](http://gnome-look.org/content/show.php/Elegant+Brit?content=74553&PHPSESSID=1ec9ce6534c48632d0ebc64a2a3ee830) in my PyGTK application?**
Can I apply the theme programatically? Ie, to apply the theme do I use a PyGTK function or do I have to find where PyGTK is installed on m... | If you download the first package from your link, the one that's labelled "(GTK & Metacity themes)" you should get a tar.gz archive. Unpack the archive into some folder like `/home/jake/.themes`.
Then in your pygtk code, before you initialize your widgets(I would do it right after you import pygtk and gtk in your code)... |
Extracting a zipfile to memory? | 10,908,877 | 18 | 2012-06-06T05:59:10Z | 10,909,016 | 26 | 2012-06-06T06:13:42Z | [
"python",
"memory",
"zip",
"zipfile",
"stringio"
] | How do I extract a zip to memory?
My attempt (returning `None` on `.getvalue()`):
```
from zipfile import ZipFile
from StringIO import StringIO
def extract_zip(input_zip):
return StringIO(ZipFile(input_zip).extractall())
``` | `extractall` extracts to the file system, so you won't get what you want. To extract a file in memory, use the `read` method.
If you really need the full content in memory, you could do something like:
```
def extract_zip(input_zip):
input_zip=ZipFile(input_zip)
return {name: input_zip.read(name) for name in ... |
Extracting a zipfile to memory? | 10,908,877 | 18 | 2012-06-06T05:59:10Z | 10,909,949 | 7 | 2012-06-06T07:30:20Z | [
"python",
"memory",
"zip",
"zipfile",
"stringio"
] | How do I extract a zip to memory?
My attempt (returning `None` on `.getvalue()`):
```
from zipfile import ZipFile
from StringIO import StringIO
def extract_zip(input_zip):
return StringIO(ZipFile(input_zip).extractall())
``` | Frequently working with archive i would recommend making a tool for comfortly working with in-memory archives. Something like this:
```
import zipfile
import StringIO
class InMemoryZip(object):
def __init__(self):
# Create the in-memory file-like object for working w/imz
self.in_memory_zip = StringI... |
PyCharm can't find the right paths if I open a directory that is not the Django root | 10,909,857 | 31 | 2012-06-06T07:24:14Z | 10,910,526 | 71 | 2012-06-06T08:15:46Z | [
"python",
"django",
"pycharm"
] | Our projects are usually structured:
```
/project-name
/src
/django-project-name
etc..
readme.md
requirements.txt
```
If I open `/project-name` instead of `/django-project-name` PyCharm underlines my imports saying they can't find and it tries to reference imports as `src.django-project-name.app_name.mode... | I fixed it by going to `File -> Preferences -> Project Structure` selecting the `/django-project-name` in the tree and clicking `sources` to add it. |
Simulating /dev/random on Windows | 10,913,614 | 7 | 2012-06-06T11:48:29Z | 10,913,695 | 12 | 2012-06-06T11:53:57Z | [
"python",
"windows",
"linux",
"random"
] | I'm trying to port python code from linux to windows right now. In various places random numbers are generateted by reading from /dev/random. Is there a way to simulate /dev/random on Windows?
I'm looking for a solution that would keep the code useable on linux... | If you are using Python, why do you care about the specific implementation? Just use [the `random` module](http://docs.python.org/library/random.html) and let it deal with it.
Beyond that, (if you can't rely on software state) [`os.urandom`](http://docs.python.org/library/os.html#os.urandom) provides os-based random v... |
Simulating /dev/random on Windows | 10,913,614 | 7 | 2012-06-06T11:48:29Z | 10,913,699 | 7 | 2012-06-06T11:54:29Z | [
"python",
"windows",
"linux",
"random"
] | I'm trying to port python code from linux to windows right now. In various places random numbers are generateted by reading from /dev/random. Is there a way to simulate /dev/random on Windows?
I'm looking for a solution that would keep the code useable on linux... | You could call [random.SystemRandom](http://docs.python.org/library/random.html#random.SystemRandom) instead. This will use [CryptGenRandom](http://en.wikipedia.org/wiki/CryptGenRandom) on Windows and /dev/urandom on Linux.
Otherwise, there's always Cygwin's /dev/random? |
What Unix tool to quickly add/remove some text to a Python script? | 10,915,248 | 6 | 2012-06-06T13:31:07Z | 10,915,290 | 12 | 2012-06-06T13:34:05Z | [
"python",
"git",
"unix",
"flask"
] | I'm developing an application using [Flask](http://flask.pocoo.org/).
I want a quick, automated way to add and remove `debug=True` to the main function call:
Development:
```
app.run(debug=True)
```
Production:
```
app.run()
```
For security reasons, as I might expose private/sensitive information about the app i... | That is not the way to go! My recommendation is to create some configuration Python module (let us say, `config.py`) with some content such as:
```
DEBUG = True
```
Now, in our current code, write this:
```
import config
app.run(debug=config.DEBUG)
```
Now, when you run in production, just change `DEBUG` from `True... |
How can I make a custom conversion from an object to a dict? | 10,915,532 | 4 | 2012-06-06T13:48:10Z | 10,915,714 | 11 | 2012-06-06T13:57:32Z | [
"python"
] | I have a Python class that stores some fields and has some properties, like
```
class A(object):
def __init__(self, x, y):
self.x = x
self.y = y
@property
def z(self):
return self.x+1
```
What changes do I need to make to the class so that I can do
```
>>> a = A(1,5)
>>> dict(a)
{'y':5, 'z':2}
```... | Add an `__iter__()` method to your class that returns an iterator of the object's items as key-value pairs. Then you can pass your object instance directly to the `dict()` constructor, as it accepts a sequence of key-value pairs.
```
def __iter__(self):
for key in "y", "z":
yield key, getattr(self, key)
``... |
Matplotlib: imshow in 3d plot | 10,917,495 | 7 | 2012-06-06T15:37:57Z | 10,919,730 | 10 | 2012-06-06T18:10:43Z | [
"python",
"3d",
"plot",
"matplotlib"
] | In the plot below, taken from matplotlib's gallery, contourf is used to create a 2d plot beneath the 3d one. My question is, is it possible to use imshow to do the same thing? I would like the colors in the 2d plot to be smoother.
Making the 2d plot seems to be possible because contourf accepts a zdir argument, while ... | Just specify the levels= option for the contourf, e.g.
```
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt,numpy as np
plt.clf()
fig = plt.figure(1)
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contourf(X,... |
Efficient FIFO queue for arbitrarily sized chunks of bytes in Python | 10,917,581 | 13 | 2012-06-06T15:43:36Z | 10,917,767 | 8 | 2012-06-06T15:55:23Z | [
"python"
] | How do I implement a FIFO buffer to which I can efficiently add arbitrarily sized chunks of bytes to the head and from which I can efficiently pop arbitrarily sized chunks of bytes from the tail?
Background:
I have a class that reads bytes from file-like objects in chunks of arbitrary size and is itself a file-like o... | **Update**: Here's an implementation of the circular buffer technique from [vartec's answer](http://stackoverflow.com/a/10917913/21475) (building on my original answer, preserved below for those curious):
```
from cStringIO import StringIO
class FifoFileBuffer(object):
def __init__(self):
self.buf = Strin... |
Efficient FIFO queue for arbitrarily sized chunks of bytes in Python | 10,917,581 | 13 | 2012-06-06T15:43:36Z | 10,917,913 | 13 | 2012-06-06T16:05:00Z | [
"python"
] | How do I implement a FIFO buffer to which I can efficiently add arbitrarily sized chunks of bytes to the head and from which I can efficiently pop arbitrarily sized chunks of bytes from the tail?
Background:
I have a class that reads bytes from file-like objects in chunks of arbitrary size and is itself a file-like o... | > I have currently implemented this with a StringIO object. Writing new
> bytes to the end of the StringIO object is fast, but removing bytes
> from the beginning is very slow, because a new StringIO object, that
> holds a copy of the entire previous buffer minus the first chunk of
> bytes, must be created.
Actually t... |
concatenate path - platform independent - "/" , "\" | 10,918,682 | 20 | 2012-06-06T16:56:40Z | 10,918,698 | 41 | 2012-06-06T16:57:40Z | [
"python"
] | In python I have variables `base_dir` and `filename`. I would like to concatenate them to obtain `fullpath`. But under windows I should use `\` and for POSIX `/` .
```
fullpath = "%s/%s" % ( base_dir, filename ) # for Linux
```
How to make it platform independent?
**Duplicate**: [Platform-independent file paths?](ht... | You want to use [os.path.join()](http://docs.python.org/library/os.path.html?highlight=os.path.join#os.path.join) for this.
The strength of using this rather than string concatenation etc is that it is aware of the various OS specific issues, such as path separators. Examples:
```
import os
```
Under **Windows 7**:
... |
concatenate path - platform independent - "/" , "\" | 10,918,682 | 20 | 2012-06-06T16:56:40Z | 10,918,705 | 16 | 2012-06-06T16:58:07Z | [
"python"
] | In python I have variables `base_dir` and `filename`. I would like to concatenate them to obtain `fullpath`. But under windows I should use `\` and for POSIX `/` .
```
fullpath = "%s/%s" % ( base_dir, filename ) # for Linux
```
How to make it platform independent?
**Duplicate**: [Platform-independent file paths?](ht... | Use [`os.path.join()`](http://docs.python.org/library/os.path.html#os.path.join):
```
import os
fullpath = os.path.join(base_dir, filename)
```
The [os.path](http://docs.python.org/library/os.path.html) module contains all of the methods you should need for platform independent path manipulation, but in case you need... |
Is it good practice to use the same variable for different things inside a function | 10,919,379 | 3 | 2012-06-06T17:45:52Z | 10,919,404 | 8 | 2012-06-06T17:47:57Z | [
"python",
"variables",
"coding-style"
] | In a function like the following:
```
def foo(case):
if case == 1:
my_var = []
# then do something with my_var
elif case == 2:
my_var = {}
# then do something with my_var
```
Since the variable `my_var` lives in different cases, so it shouldn't cause a problem at runtime. But i... | It may be confusing for other people who work on the same code. Several style guides also discourage reusing the same variable name for different purposes. If you can avoid it then you should, although there can also be good reasons to deviate from this rule. Are they really the same thing? One is a list of items, the ... |
How to install a module use pip for specific version of? | 10,919,569 | 43 | 2012-06-06T17:59:06Z | 10,919,761 | 25 | 2012-06-06T18:13:31Z | [
"python",
"pip"
] | On Ubuntu 10.04 by default Python 2.6 is installed, then I have installed Python 2.7. How can I use `pip install` to install packages for Python 2.7.
For example:
```
pip install beautifulsoup4
```
by default installs BeautifulSoup for Python 2.6
When I do:
```
import bs4
```
in Python 2.6 it works, but in Python... | Use a version of `pip` installed against the Python instance you want to install new packages to.
In many distributions, there may be separate `python2.6-pip` and `python2.7-pip` packages, invoked with binary names such as `pip-2.6` and `pip-2.7`. If pip is not packaged in your distribution for the desired target, you... |
How to install a module use pip for specific version of? | 10,919,569 | 43 | 2012-06-06T17:59:06Z | 25,123,329 | 47 | 2014-08-04T16:30:10Z | [
"python",
"pip"
] | On Ubuntu 10.04 by default Python 2.6 is installed, then I have installed Python 2.7. How can I use `pip install` to install packages for Python 2.7.
For example:
```
pip install beautifulsoup4
```
by default installs BeautifulSoup for Python 2.6
When I do:
```
import bs4
```
in Python 2.6 it works, but in Python... | Alternatively, since `pip` itself is written in python, you can just call it with the python version you want to install the package for:
```
python2.7 /usr/bin/pip install foo
``` |
How to install a module use pip for specific version of? | 10,919,569 | 43 | 2012-06-06T17:59:06Z | 36,498,901 | 7 | 2016-04-08T11:53:20Z | [
"python",
"pip"
] | On Ubuntu 10.04 by default Python 2.6 is installed, then I have installed Python 2.7. How can I use `pip install` to install packages for Python 2.7.
For example:
```
pip install beautifulsoup4
```
by default installs BeautifulSoup for Python 2.6
When I do:
```
import bs4
```
in Python 2.6 it works, but in Python... | You can *execute* pip module for a specific python version using the corresponding python:
Python 2.6:
```
python2.6 -m pip install beautifulsoup4
```
Python 2.7
```
python2.7 -m pip install beautifulsoup4
``` |
averaging list of lists python | 10,919,664 | 13 | 2012-06-06T18:04:42Z | 10,919,689 | 12 | 2012-06-06T18:07:23Z | [
"python"
] | I have a list of lists:
something like:
```
data = [[240, 240, 239],
[250, 249, 237],
[242, 239, 237],
[240, 234, 233]]
```
And I want to average this out like
```
[average_column_1, average_column_2, average_column_3]
```
My piece of code is like not very elegant.
It is the naive way of go... | Use `zip()`, like so:
```
averages = [sum(col) / float(len(col)) for col in zip(*data)]
```
`zip()` takes multiple iterable arguments, and returns slices of those iterables (as tuples), until one of the iterables cannot return anything more. In effect, it performs a transpose operation, akin to matrices.
```
>>> dat... |
averaging list of lists python | 10,919,664 | 13 | 2012-06-06T18:04:42Z | 10,919,690 | 23 | 2012-06-06T18:07:24Z | [
"python"
] | I have a list of lists:
something like:
```
data = [[240, 240, 239],
[250, 249, 237],
[242, 239, 237],
[240, 234, 233]]
```
And I want to average this out like
```
[average_column_1, average_column_2, average_column_3]
```
My piece of code is like not very elegant.
It is the naive way of go... | Pure Python:
```
from __future__ import division
def mean(a):
return sum(a) / len(a)
a = [[240, 240, 239],
[250, 249, 237],
[242, 239, 237],
[240, 234, 233]]
print map(mean, zip(*a))
```
printing
```
[243.0, 240.5, 236.5]
```
NumPy:
```
a = numpy.array([[240, 240, 239],
[25... |
averaging list of lists python | 10,919,664 | 13 | 2012-06-06T18:04:42Z | 10,919,699 | 15 | 2012-06-06T18:07:59Z | [
"python"
] | I have a list of lists:
something like:
```
data = [[240, 240, 239],
[250, 249, 237],
[242, 239, 237],
[240, 234, 233]]
```
And I want to average this out like
```
[average_column_1, average_column_2, average_column_3]
```
My piece of code is like not very elegant.
It is the naive way of go... | ```
data = [[240, 240, 239],
[250, 249, 237],
[242, 239, 237],
[240, 234, 233]]
avg = [float(sum(col))/len(col) for col in zip(*data)]
# [243.0, 240.5, 236.5]
```
This works because `zip(*data)` will give you a list with the columns grouped, the `float()` call is only necessary on Python 2.x, ... |
Change Konsole title via Python | 10,919,696 | 4 | 2012-06-06T18:07:43Z | 10,919,862 | 7 | 2012-06-06T18:20:18Z | [
"python",
"console",
"kde",
"konsole"
] | How can I change the Konsole title in Python?
I found this code:
```
>>> import sys
>>> sys.stdout.write("\x1b]2;test\x07")
```
But it only works with Gnome terminal, not Konsole (on Kubuntu). | I would give `"\x1b]0;test\x07"` a try (note the `0` instead of `2`).
There is [an open bug](https://bugs.kde.org/show_bug.cgi?id=231405) about Konsole not correctly treating xterm escape sequences; maybe it won't work at all until it is fixed. |
What to do with pyc files when Django or python is used with Mercurial? | 10,920,423 | 7 | 2012-06-06T18:58:42Z | 10,922,062 | 13 | 2012-06-06T20:49:26Z | [
"python",
"django",
"mercurial",
"pyc"
] | Just started to use Mercurial. Wow, nice application. I moved my database file out of the code directory, but I was wondering about the `.pyc` files. I didn't include them on the initial commit. The documentation about the `.hgignore` file includes an example to exclude `*.pyc`, so I think I'm on the right track.
I am... | As mentioned in ms4py's answer, \*.pyc are compiled files that will be regenerated on the fly. You wouldn't want to include these when distributing a project.
However, if it happens you have modules that existed before when you roll back changes and \*.pyc files are left lying around, strange bugs can appear as pyc fi... |
Validating Select Fields in Flask WTF Forms | 10,921,473 | 4 | 2012-06-06T20:11:05Z | 10,921,521 | 9 | 2012-06-06T20:13:44Z | [
"python",
"flask",
"wtforms"
] | I am using Flask-WTF forms and I have the following code:
in forms.py
```
class DealForm( Form ):
country = SelectField( 'Country' )
```
in main.py
```
if not form.validate_on_submit():
form = DealForm()
form.country.choices = [('us','USA'),('gb','Great Britain'),('ru','Russia')]
return render_temp... | You need to set the choices before calling `validate_on_submit()`.
Since they are static do it when creating the Form class:
```
class DealForm(Form):
country = SelectField('Country', choices=[
('us','USA'),('gb','Great Britain'),('ru','Russia')])
```
If you wanted to set them after creating the form ins... |
Unexpected result after using generator expression | 10,921,851 | 2 | 2012-06-06T20:35:41Z | 10,921,888 | 7 | 2012-06-06T20:38:17Z | [
"python"
] | I am trying to filter some data I am working with to take out some artifacts such as negative numbers and errors in my measuring devices. I have been playing with the idea of using a generator to do this. I am using Python 2.7.2
```
testlist = [12,2,1,1,1,0,-3,-3,-1]
gen = (i for i, x in enumerate(testlist) if x < ... | When you remove items from your list, the indexes of the items after it change (they are all shifted down by one). As a result, the generator will skip over some items. Try adding some more print statements so that you can see what is going on:
```
for i in gen:
print i
print testlist
testlist.... |
Numpy: Sorting a multidimensional array by a multidimensional array | 10,921,893 | 11 | 2012-06-06T20:38:41Z | 10,922,358 | 9 | 2012-06-06T21:11:17Z | [
"python",
"numpy",
"slice"
] | Forgive me if this is redundant or super basic. I'm coming to Python/Numpy from R and having a hard time flipping things around in my head.
I have a n dimensional array which I want to sort using another n dimensional array of index values. I know I could wrap this in a loop but it seems like there should be a really ... | I can't think of how to work this in N dimensions yet, but here is the 2D version:
```
>>> a = np.random.standard_normal(size=(2,5))
>>> a
array([[ 0.72322499, -0.05376714, -0.28316358, 1.43025844, -0.90814293],
[ 0.7459107 , 0.43020728, 0.05411805, -0.32813465, 2.38829386]])
>>> i = np.array([[0,1,2,4,3],[... |
Python's sum vs. NumPy's numpy.sum | 10,922,231 | 22 | 2012-06-06T21:01:38Z | 10,922,744 | 30 | 2012-06-06T21:43:54Z | [
"python",
"performance",
"numpy",
"python-3.x"
] | What are the differences in performance and behavior between using Python's native `sum` function and NumPy's `numpy.sum`? `sum` works on NumPy's arrays and `numpy.sum` works on Python lists and they both return the same effective result (haven't tested edge cases such as overflow) but different types.
```
>>> import ... | I got curious and timed it. `numpy.sum` seems much faster for numpy arrays, but much slower on lists.
```
import numpy as np
import timeit
x = range(1000)
# or
#x = np.random.standard_normal(1000)
def pure_sum():
return sum(x)
def numpy_sum():
return np.sum(x)
n = 10000
t1 = timeit.timeit(pure_sum, numbe... |
Sort A List of Tuples By Lowest Value | 10,922,879 | 2 | 2012-06-06T21:55:58Z | 10,922,895 | 7 | 2012-06-06T21:57:45Z | [
"python"
] | Supposed I have a list of tuples:
```
my_list = [(1, 4), (3, 0), (6, 2), (3, 8)]
```
How do I sort this list by the minimum value in the tuple, regardless of position? My final list will be as follows:
```
my_sorted_list = [(3, 0), (1, 4), (6, 2), (3, 8)]
``` | You can take advantage of the `key` parameter, to either `.sort` or `sorted`:
```
>>> my_list = [(1, 4), (3, 0), (6, 2), (3, 8)]
>>> sorted(my_list, key=min)
[(3, 0), (1, 4), (6, 2), (3, 8)]
``` |
Assigning to columns in NumPy? | 10,923,212 | 13 | 2012-06-06T22:26:47Z | 10,923,259 | 25 | 2012-06-06T22:32:26Z | [
"python",
"matlab",
"numpy"
] | How could the following MATLAB code be written using NumPy?
```
A = zeros(5, 100);
x = ones(5,1);
A(:,1) = x;
```
Assigning to rows seems to work easily, but I couldn't find an example of assigning an array to a column of another array. | Use `a[:,1] = x[:,0]`. You need `x[:,0]` to select the column of x as a single numpy array. If you have the choice of how to format x, it's better to not make it a 2-dimensional array in the first place, but just a regular (row) array:
```
>>> a
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
... |
setting the default string value of Python's collections.defaultdict | 10,923,334 | 23 | 2012-06-06T22:40:04Z | 10,923,347 | 45 | 2012-06-06T22:41:33Z | [
"python",
"collections"
] | I am using Python 3.2.3 and want to change the default returned string value:
```
from collections import defaultdict
d=defaultdict(str)
d["NonExistent"]
```
The value returned is `''`. How can I change this so that when a key is not found, `"unknown"` is returned instead of the empty string? | The argument to defaultdict is a function (or rather, a callable object) that returns the default value. So you can pass in a lambda that returns your desired default.
```
>>> from collections import defaultdict
>>> d = defaultdict(lambda: 'My default')
>>> d['junk']
'My default'
```
Edited to explain lambda:
lambda... |
How can I run my python script in the background on a schedule? | 10,924,309 | 2 | 2012-06-07T00:51:07Z | 10,924,364 | 11 | 2012-06-07T01:00:01Z | [
"python",
"linux",
"service"
] | I have a small python script that creates a graph of data pulled from MySQL. I'm trying to figure out a way to run the script in the background all time on a regular basis. I've tried a number of things:
1. A Cron Job that runs the script
2. A loop timer
3. Using the & command to run the script in the background
Thes... | Why don't you try to make your script into a proper daemon. This [link](http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python) is a good place to start.
```
import os
import subprocess
import time
from daemon import runner
class App():
def __init__(self):
self.stdin_path = '/dev/n... |
Is it possible to include subdirectories using dist utils (setup.py) as part of package data? | 10,924,885 | 8 | 2012-06-07T02:30:25Z | 22,442,340 | 20 | 2014-03-16T20:12:53Z | [
"python",
"install",
"distutils",
"setup.py"
] | Basically my python package is setup like:
```
module
\_examples
\_folder1
\_file1.py
\_file2.py
\_folder2
\_file1.py
\_file2.py
```
Basically I want to just use:
```
package_data = {
'module': ['examples/*'],
},
```
because my project always has people adding examples and I wa... | I believe what you're looking for is something like this for you `setup.py`, which will recursively find any packages in the project, also be sure and include `__init__.py` files to subdirectories for each package you want.
```
from setuptools import setup, find_packages
setup(name='MySoftware',
packages=find_pac... |
Cannot easy_install readline for Python 2.7.3 on Mac Os Lion | 10,925,507 | 4 | 2012-06-07T04:04:04Z | 22,968,109 | 9 | 2014-04-09T16:07:12Z | [
"python",
"osx-lion",
"readline",
"easy-install"
] | I am trying to install the python readline module. I have already installed readline via homebrew.
If I type
```
easy_install readline
```
I get
```
Downloading http://pypi.python.org/packages/source/r/readline/readline-6.2.2.tar.gz#md5=ad9d4a5a3af37d31daf36ea917b08c77
Processing readline-6.2.2.tar.gz
Writing /var/f... | There is a new solution to this problem in Pypi, `pip install gnureadline`.
<https://pypi.python.org/pypi/gnureadline>
The root issue is libedit (BSD-licensed) vs. Gnu Readline (GPL-licensed) . Apple would rather provide incompatible BSD code, than provide compatible code that has GPL restrictions. |
Why can't I use string functions inside map()? | 10,925,895 | 5 | 2012-06-07T04:57:50Z | 10,925,925 | 14 | 2012-06-07T05:00:41Z | [
"python",
"string",
"map",
"python-3.x"
] | The following example shows the error I am getting when trying to use a string function inside a function call to map. I need help with why this happening. Thanks.
```
>>> s=["this is a string","python python python","split split split"]
>>> map(split,s)
Traceback (most recent call last):
File "<pyshell#16>", line 1... | It will work fine if you use `str.split()`
I.e,
```
s = ["this is a string","python python python","split split split"]
map(str.split, s)
```
gives:
```
[['this', 'is', 'a', 'string'],
['python', 'python', 'python'],
['split', 'split', 'split']]
```
The error message states: **`NameError: name 'split' is not def... |
Efficient and fast Python While loop while using sleep() | 10,926,328 | 15 | 2012-06-07T05:49:15Z | 10,926,766 | 28 | 2012-06-07T06:33:30Z | [
"python",
"while-loop",
"pyserial"
] | I am attempting to communicate with a device over serial using Pyserial. As commands need to be continually sent, they have to be placed in a while loop in Python.
I am currently using this code, and have taken a look at [python process takes 100% CPU](http://stackoverflow.com/questions/9349588/python-process-takes-10... | The slow CPU wasting part is the "do serial sending". The while loop with just a short sleep will use negligible CPU.
Can you show the serial sending code. There may be a way to speed that up.
On this rather slow CPU I see this:
```
import time
while True: time.sleep(0.2) # 0% CPU
while True: time.sleep(0.02) ... |
Setting the position on a button in Python? | 10,927,234 | 8 | 2012-06-07T07:11:42Z | 10,937,799 | 17 | 2012-06-07T18:35:00Z | [
"python",
"tkinter",
"row"
] | I just wrote a code that creates a window (using TKinter) and displays one working button.
```
b = Button(master, text="get", width=10, command=callback)
```
But i would like to have multiple buttons underneath this one.
How do you set the row and column of the button?
I tried to add `row = 0, column = 0,` but that ... | Causing a widget to appear requires that you position it using with what Tkinter calls "geometry managers". The three managers are [grid](http://effbot.org/tkinterbook/grid.htm), [pack](http://effbot.org/tkinterbook/pack.htm) and [place](http://effbot.org/tkinterbook/place.htm). Each has strengths and weaknesses. These... |
Getting gcc failed error while installing scrapy | 10,927,492 | 4 | 2012-06-07T07:31:05Z | 10,929,013 | 13 | 2012-06-07T09:20:37Z | [
"python",
"scrapy"
] | When i am installing scrapy then i am getting the below error (**command 'gcc' failed with exit status 1**). I am using Centos, and yes i have the latest version of gcc installed. But i am not sure why i am getting this error. I tried googling it but could'nt find a solution
> OpenSSL/crypto/crypto.c: In function âi... | You don't have the required C library to compile this module.
For lxml, you have to install the following packages.
```
sudo yum install python-devel libxml2-devel libxslt-devel
```
To resolve OpenSSL problem with Scrapy, install `pyOpenSSL`
```
sudo yum install pyOpenSSL
```
Note: These are the package names for f... |
redis-py with gevent | 10,928,481 | 20 | 2012-06-07T08:42:31Z | 10,929,704 | 17 | 2012-06-07T10:08:23Z | [
"python",
"redis",
"gevent"
] | Can redis-py library be used with gevent ?
Does anyone have experience running redis-py library with gevent? Is there a working example?
Do they play nice together? Are there any precautions or hacks to get them to work at scale?
The question in another words:
to make redis-py connections use gevent greenlets , do ... | Yes, redis-py works fine with gevent.
You can check my answer to the following question: you will find an example and some remarks.
[redis + gevent - Poor performance - what am I doing wrong?](http://stackoverflow.com/questions/10656953/redis-gevent-poor-performance-what-am-i-doing-wrong/10663498#10663498)
The main ... |
Homebrew Python and writing to /Library/Python/2.7/site-packages/? | 10,928,914 | 8 | 2012-06-07T09:13:46Z | 11,966,255 | 10 | 2012-08-15T08:36:00Z | [
"python",
"homebrew"
] | Is there a definitive guide for how to install Homebrew's Python properly, along with pip, virtualenv, virtualenvwrapper etc.?
I've read the following pages:
<https://github.com/mxcl/homebrew/wiki/Homebrew-and-Python>
<http://osxastrotricks.wordpress.com/2012/05/02/python-setup-with-homebrew/>
<http://skipperkong... | Meanwhile, homebrew's python has evolved:
* Python installed via brew no longer tries to write to `/Library/Python`.
* Homebrew's Python now always uses its own site-packages.
* pip (and distribute) is installed automatically.
* The "--framework" option is not needed. Homebrew defaults to it now.
* XQuartz is needed (... |
How to restrict setting an attribute outside of constructor? | 10,929,004 | 2 | 2012-06-07T09:19:51Z | 10,929,077 | 7 | 2012-06-07T09:24:53Z | [
"python",
"variable-assignment",
"setattr"
] | I want to forbid further assignments on some attributes of a class after it was initialized. For instance; no one can explicitly assign any value to 'ssn' (social security number) property after the Person instance 'p' has been initialized. **\_*setattr*\_** is also being called while assigning the value inside **\_*in... | The usual way is to use a "private" attribute starting with an underscore, and a read-only property for public access:
```
import operator
class Person(object):
def __init__(self, name, ssn):
self.name = name
self._ssn = ssn
ssn = property(operator.attrgetter("_ssn"))
```
Note that this does ... |
how to select two nodes (pairs of nodes) randomly from a graph that are NOT connected, Python, networkx | 10,929,269 | 3 | 2012-06-07T09:38:05Z | 10,934,843 | 8 | 2012-06-07T15:23:49Z | [
"python",
"nodes",
"networkx"
] | I want to extract two nodes from a graph, the catch being that they shouldnt be connected i.e. no direct edge exists between them. i know i can get random edges using "random.choice(g.edges())" but this would give me random nodes that are connected. I want pairs of nodes that are NOT connected (a pair of unconnected ed... | Simple! :)
Grab a random node - then pick a random node from the list of nodes excluding neighbours and itself. Code to illustrate is below. :)
```
import networkx as nx
from random import choice
# Consider this graph
#
# 3
# |
# 2 - 1 - 5 - 6
# |
# 4
g = nx.Graph()
g.add_edge(1,2)
g.add_edge(1,3)
... |
Which is the most efficient way to iterate through a list in python? | 10,929,724 | 6 | 2012-06-07T10:09:57Z | 10,929,743 | 8 | 2012-06-07T10:11:15Z | [
"python",
"performance",
"list"
] | Say I have a list of items:
```
x = [1, 2, 3, 4, 5]
```
I need to perform some functions for each of these items. In a certain case, I need to return the index of an item.
Which is the best and most efficient way?
```
for item in list:
....
```
or
```
for i in range(len(list)):
....
``` | ```
for item in list:
```
its obviously the one with fewer function calls.
If you want to get the index of items as you go use [enumerate](http://docs.python.org/library/functions.html#enumerate) like this
```
for pos, item in enumerate(collection):
``` |
Print program usage example with argparse module | 10,930,635 | 18 | 2012-06-07T11:11:03Z | 10,930,713 | 28 | 2012-06-07T11:16:05Z | [
"python",
"argparse"
] | I am trying to learn how to use python's `argparse` module. Currently my python script is:
```
parser = argparse.ArgumentParser(description='My first argparse attempt',
add_help=True)
parser.add_argument("-q", action ="store", dest='argument',
help="First argument")
... | Use [`parser.epilog`](http://docs.python.org/library/argparse.html#epilog) to display something after the generated `-h` text.
```
parser = argparse.ArgumentParser(
description='My first argparse attempt',
epilog='Example of use')
output = parser.parse_args()
```
prints:
```
My first argparse attempt
optio... |
Regular expression dictionary in python | 10,931,044 | 3 | 2012-06-07T11:36:28Z | 10,931,193 | 7 | 2012-06-07T11:49:24Z | [
"python",
"regex",
"performance",
"mapping"
] | Is it possible to implement a dictionary with keys as regular expressions and actions (with parameters) as values?
for e.g.
1. `key = "actionname 1 2", value = "method(1, 2)"`
2. `key = "differentaction par1 par2", value = "appropriate_method(par1, par2)"`
User types in the key, i need to execute the matching method... | Yes, it's perfectly possible:
```
import re
dict = {}
dict[re.compile('actionname (\d+) (\d+)')] = method
dict[re.compile('differentaction (\w+) (\w+)')] = appropriate_method
def execute_method_for(str):
#Match each regex on the string
matches = (
(regex.match(str), f) for regex, f in dict.iteritems()... |
using dictConfig in python logging, need to create a logger with a different file than defined in dict. | 10,931,423 | 9 | 2012-06-07T12:05:15Z | 10,931,747 | 11 | 2012-06-07T12:24:42Z | [
"python",
"logging"
] | I have a LOG\_SETTINGS dict that looks like:
```
LOG_SETTINGS = {
'version': 1,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'level': 'INFO',
'formatter': 'detailed',
'stream': 'ext://sys.stdout',
},
'file': {
'class': 'logging.handlers.RotatingFileHa... | firstly, empty your logger handlers `logger.handlers = []` then add another handler.
```
logger2 = logging.getLogger('extensive')
logfile = logging.FileHandler("test.log")
logger2.handlers = []
logger2.addHandler(logfile)
``` |
What possible improvements can be made to a palindrome program? | 10,932,054 | 4 | 2012-06-07T12:45:15Z | 10,932,131 | 9 | 2012-06-07T12:49:50Z | [
"python",
"palindrome"
] | I am just learning programming in Python for fun. I was writing a palindrome program and I thought of how I can make further improvements to it.
First thing that came to my mind is to prevent the program from having to go through the entire word both ways since we are just checking for a palindrome. Then I realized th... | I think the best way to improvise write a palindrome checking function in Python is as follows:
```
def is_palindrome(s):
return s == s[::-1]
```
(Add the `lower()` call as required.) |
would like to get count of files in home dir in python | 10,933,234 | 2 | 2012-06-07T13:50:56Z | 10,933,309 | 8 | 2012-06-07T13:55:48Z | [
"python"
] | I saw this [Count the number of files in a directory using python](http://stackoverflow.com/questions/2632205/count-the-number-of-files-in-a-directory-using-python)
and have this:
```
import os, os.path
print len([name for name in os.listdir(os.path.expanduser("~")) if os.path.isfile(name)])
```
but it always retur... | At the moment, you're calling `os.path.isfile("somefile.ext")`. You need to call `os.path.isfile("~/somefile.ext")`.
```
import os
homedir = os.path.expanduser("~")
print len([
name
for name in os.listdir(homedir)
if os.path.isfile(os.path.join(homedir, name))
])
```
Or more concisely:
```
print sum(
... |
python: why does calling echo with subprocess return WindowsError 2? | 10,933,354 | 3 | 2012-06-07T13:58:35Z | 10,933,428 | 10 | 2012-06-07T14:02:54Z | [
"python",
"windows",
"subprocess"
] | In my program, I have a function runScript():
```
def runScript():
subprocess.call(['echo', 'hello'])
```
I have seen many similar examples in the Python documentation, so I assumed this would work. However, when I call this function in my program, it returns a WindowsError.
```
WindowsError: [Error 2] The system ca... | The `echo` command is built in to the Windows shell, `cmd.exe`. It is not an external program that can be called without the shell. Therefore, your `subprocess.call()` needs to specify `shell=True`.
```
subprocess.call('echo hello', shell=True)
```
(Also, the shell will handle splitting up the command for you, so I'v... |
Invalid syntax using dict comprehension | 10,933,601 | 5 | 2012-06-07T14:12:35Z | 10,933,682 | 17 | 2012-06-07T14:17:55Z | [
"python",
"syntax-error",
"dictionary-comprehension"
] | Given a list of floats named 'x', I would like to create a dict mapping each x in x[1:-1] to it's neighbors using a dict comprehension. I have tried the following line :
```
neighbours = {x1:(x0,x2) for (x0,x1,x2) in zip(x[:-2],x[1:-1],x[2:])}
```
However, the syntax seems to be invalid. What am I doing wrong? | [Dict comprehensions](https://www.python.org/dev/peps/pep-0274/) are only available in Python 2.7 upwards. For earlier versions, you need the `dict()` constructor with a generator:
```
dict((x1, (x0,x2)) for (x0,x1,x2) in zip(x[:-2],x[1:-1],x[2:]))
``` |
how to read a csv file in reverse order in python | 10,933,838 | 4 | 2012-06-07T14:28:24Z | 10,933,932 | 14 | 2012-06-07T14:33:55Z | [
"python",
"csv"
] | I know how to do for a .txt file... but now I get some troubles for a .csv file. How can I read a csv file from the bottom in python? | Pretty much the same way as for a text file: read the whole thing into a list and then go backwards:
```
import csv
with open('test.csv', 'r') as textfile:
for row in reversed(list(csv.reader(textfile))):
print ', '.join(row)
```
If you want to get fancy, you could write a lot of code that reads blocks st... |
Python: turning a tuple from return statement into a string | 10,934,519 | 2 | 2012-06-07T15:06:23Z | 10,934,596 | 7 | 2012-06-07T15:10:51Z | [
"python",
"return",
"tuples"
] | I've been working on HTTLCS and am having some difficulty finishing up the problem.
Solving a problem was not much of an issue, but I have trouble returning my result as a string rather than the tuple data type.
Here is my code:
```
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)... | It's because you're using commas in your return statement, which Python is interpreting as a tuple. Try using `format()` instead:
```
def wordCount(paragraph):
splited = paragraph.split()
wordnum = len(splited)
eWord = []
for aWord in splited:
if "e" in aWord:
eWord.append(aWord)
... |
Tornado : support multiple Application on same IOLoop | 10,934,864 | 5 | 2012-06-07T15:24:41Z | 10,935,309 | 8 | 2012-06-07T15:49:21Z | [
"python",
"web-applications",
"tornado"
] | I'm wondering if it is possible in the [Tornado](http://www.tornadoweb.org) framework to register multiple [Application](http://www.tornadoweb.org/documentation/web.html#application-configuration) on the same IOLoop ?
Something like
```
application1 = web.Application([
(r"/", MainPageHandler),
])
http_server = ht... | The simple thing is if you were to bind your applications to different ports:
```
...
http_server = httpserver.HTTPServer(application1)
http_server.listen(8080) # NOTE - port 8080
...
http_server2 = httpserver.HTTPServer(application2)
http_server2.listen(8081) # NOTE - port 8081
ioloop.IOLoop.instance().start()... |
Way to access resource files in python | 10,935,127 | 20 | 2012-06-07T15:38:44Z | 10,935,674 | 11 | 2012-06-07T16:11:51Z | [
"python"
] | What is the proper way to access resources in python programs.
Basically in many of my python modules I end up writing code like that:
```
DIRNAME = os.path.split(__file__)[0]
(...)
template_file = os.path.join(DIRNAME, "template.foo")
```
Which is OK but:
* It will break if I will start to use python zip ... | You'll want to look at using either [get\_data](http://docs.python.org/library/pkgutil.html) in the stdlib or [pkg\_resources](http://packages.python.org/distribute/pkg_resources.html) from setuptools/distribute. Which one you use probably depends on whether you're already using distribute to package your code as an eg... |
How to create identity matrix with numpy | 10,935,629 | 5 | 2012-06-07T16:08:49Z | 10,958,143 | 12 | 2012-06-09T03:30:15Z | [
"python",
"numpy"
] | How do I create an identity *matrix* with numpy?
Is there a simpler syntax than
```
numpy.matrix(numpy.identity(n))
``` | Here's a simpler syntax:
```
np.matlib.identity(n)
```
And here's an even simpler syntax that runs much faster:
```
In [1]: n = 1000
In [2]: timeit np.matlib.identity(n)
100 loops, best of 3: 8.78 ms per loop
In [3]: timeit np.matlib.eye(n)
1000 loops, best of 3: 695 us per loop
``` |
How to escape % in a query using python's sqlalchemy's execute() and pymysql? | 10,935,854 | 13 | 2012-06-07T16:23:21Z | 11,005,651 | 19 | 2012-06-12T22:14:00Z | [
"python",
"mysql",
"sqlalchemy"
] | My query is:
```
result = connection.execute(
"select id_number from Table where string like '_stringStart%' limit 1;")
```
gives the error:
```
query = query % escaped_args
TypeError: not enough arguments for format string
```
A quick google said to use %% instead of % but that doesn't work either. How do... | Since this is a literal string, you're better off using a bound parameter here (illustrated using [`text()`](http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.text)):
```
from sqlalchemy import text
connection.execute(
text("select * from table where "
"string like :stri... |
Python coding style | 10,936,164 | 3 | 2012-06-07T16:42:59Z | 10,936,172 | 9 | 2012-06-07T16:43:50Z | [
"python",
"coding-style"
] | I've been reading various python coding style guides, some answers on SO, etc. but none of them mentions some maybe not that important questions, but I would like to know if there is a preferred way for doing this:
In case I have a dictionary, which style would be better to use:
```
dict_name = {'test': 'somevalue',
... | You can't go wrong with looking at the [**PEP 8** - The Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/) for guidance on how to write readable Python code. Highly recommended. |
Scikit-learn model parameters unavailable? If so what ML workbench alternative? | 10,936,183 | 4 | 2012-06-07T16:44:19Z | 10,946,069 | 7 | 2012-06-08T09:15:44Z | [
"python",
"machine-learning",
"scikit-learn"
] | I am doing machine learning using scikit-learn as recommended in [this question](http://stackoverflow.com/questions/7326958/python-machine-learning-library). To my surprise, it does not appear to provide access to the actual models it trains. For example, if I create an SVM, linear classifier or even a decision tree, i... | The fitted model parameters are stored directly as attributes on the model instance. There is a specific naming convention for those fitted parameters: they all end with a trailing underscore as opposed to user-provided constructor parameters (a.k.a. hyperparameters) which don't.
The type of the fitted attributes is a... |
Can a python @classmethod be inherited? | 10,936,205 | 4 | 2012-06-07T16:46:18Z | 10,936,254 | 13 | 2012-06-07T16:49:08Z | [
"python",
"inheritance",
"class-method"
] | For example, I have a base class and a derived class:
```
>>> class Base:
... @classmethod
... def myClassMethod(klass):
... pass
...
>>> class Derived:
... pass
...
>>> Base.myClassMethod()
>>> Derived.myClassMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: c... | Yes, they can be inherited.
If you want to inherit members, you need to tell python about the inheritance!
```
>>> class Derived(Base):
... pass
```
It's good practice to make your `Base` class inherit from object (but it will work without you doing so):
```
>>> class Base(object):
... ...
``` |
Why does a python module act like a singleton? | 10,936,709 | 7 | 2012-06-07T17:21:05Z | 10,936,915 | 14 | 2012-06-07T17:35:51Z | [
"python",
"singleton"
] | I create a dictionary from a remote database as part of my application run. This process is pretty I/O heavy, so I've decided to create a "singleton" instance of this dictionary and just call it as it is needed in my application.
The code looks like (in `Dictionaries.py`):
```
state_code_dict = None
def get_state_co... | This is the Python Language Reference's description of [how importing a module works](http://docs.python.org/reference/simple_stmts.html#the-import-statement):
> (1) find a module, and initialize it *if necessary*; (2) define a name or names in the local namespace
(Emphasis added.) Here, *initializing* a module means... |
Why does a python module act like a singleton? | 10,936,709 | 7 | 2012-06-07T17:21:05Z | 10,937,012 | 8 | 2012-06-07T17:42:58Z | [
"python",
"singleton"
] | I create a dictionary from a remote database as part of my application run. This process is pretty I/O heavy, so I've decided to create a "singleton" instance of this dictionary and just call it as it is needed in my application.
The code looks like (in `Dictionaries.py`):
```
state_code_dict = None
def get_state_co... | I voted larsmans answer, i just wanted to add an example.
**hello.py:**
```
hi = 'hello'
print(hi)
def print_hi():
print(hi)
```
**ipython session:**
```
In [1]: from hello import print_hi
hello
In [2]: print_hi()
hello
In [3]: from hello import print_hi
In [4]: import hello
In [5]: hello.print_hi()
hello... |
Rearranging Matrix Elements with Numpy | 10,936,767 | 5 | 2012-06-07T17:26:05Z | 10,937,086 | 8 | 2012-06-07T17:48:54Z | [
"python",
"matrix",
"numpy"
] | I have a NumPy matrix which I've simplified to exemplify:
```
a b c d e f
A = [[0, 1, 2, 3, 4, 5],
b [1, 0, 3, 4, 5, 6],
c [2, 3, 0, 5, 6, 7],
d [3, 4, 5, 0, 7, 8],
e [4, 5, 6, 7, 0, 9],
f [5, 6, 7, 8, 9, 0]]
```
where the number at the "intersections" is important, but their order i... | **edit:** I just stumbled across a NumPy solution that uses [advanced indexing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing):
```
# a b c d e f
A = numpy.array([[0, 1, 2, 3, 4, 5],
[1, 0, 3, 4, 5, 6],
[2, 3, 0, 5, 6, 7],
... |
How to check type of files without extensions in python? | 10,937,350 | 33 | 2012-06-07T18:06:40Z | 10,937,430 | 8 | 2012-06-07T18:12:45Z | [
"python"
] | I have a folder full of files and these doesn't have an extension. How can I check file types? I want to check the file type and change the filename accordingly. Let's assume a function `filetype(x)` returns file type like `png`. I want to do this:
```
files = os.listdir(".")
for f in files:
os.rename(f, f+filetyp... | On unix and linux there is the [`file`](http://www.cyberciti.biz/faq/linuxunix-determine-file-type/) command to guess file types. There's even a [windows port](http://gnuwin32.sourceforge.net/packages/file.htm).
From the [man page](http://unixhelp.ed.ac.uk/CGI/man-cgi?file):
> File tests each argument in an attempt t... |
How to check type of files without extensions in python? | 10,937,350 | 33 | 2012-06-07T18:06:40Z | 10,937,927 | 36 | 2012-06-07T18:43:54Z | [
"python"
] | I have a folder full of files and these doesn't have an extension. How can I check file types? I want to check the file type and change the filename accordingly. Let's assume a function `filetype(x)` returns file type like `png`. I want to do this:
```
files = os.listdir(".")
for f in files:
os.rename(f, f+filetyp... | There are Python libraries that can recognize files based on their content (usually a header / magic number) and that don't rely on the file name or extension.
If you're addressing many different file types, you can use [`python-magic`](https://github.com/ahupp/python-magic). That's just a Python binding for the well-... |
How to check type of files without extensions in python? | 10,937,350 | 33 | 2012-06-07T18:06:40Z | 24,433,682 | 19 | 2014-06-26T14:51:07Z | [
"python"
] | I have a folder full of files and these doesn't have an extension. How can I check file types? I want to check the file type and change the filename accordingly. Let's assume a function `filetype(x)` returns file type like `png`. I want to do this:
```
files = os.listdir(".")
for f in files:
os.rename(f, f+filetyp... | The [Python Magic](https://github.com/ahupp/python-magic) library provides the functionality you need.
You can install the library with `pip install python-magic` and use it as follows:
```
>>> import magic
>>> magic.from_file('iceland.jpg')
'JPEG image data, JFIF standard 1.01'
>>> magic.from_file('iceland.jpg', m... |
Loading a file into a numpy array with python | 10,937,918 | 4 | 2012-06-07T18:43:30Z | 10,938,021 | 9 | 2012-06-07T18:49:45Z | [
"python",
"csv",
"file-io",
"numpy"
] | So I'm very green with Python and am trying to learn by replicating some matlab code I've written. I have a part where, in matlab, I load a data file that's tab-delimited. The syntax
```
x = load(data.txt)
```
Takes the tab delimited data and put them into cells of a matrix labeled x.
Is there a way to do this in py... | If you're using Python for MATLAB-like purposes you're going to want to be using [NumPy](http://numpy.scipy.org/) (and scipy); in particular, you should read [NumPy for MATLAB Users](http://www.scipy.org/NumPy_for_Matlab_Users).
If you have comma-delimited data, you can use `numpy.loadtxt` to read it (after installing... |
Loading a file into a numpy array with python | 10,937,918 | 4 | 2012-06-07T18:43:30Z | 10,940,038 | 16 | 2012-06-07T21:18:16Z | [
"python",
"csv",
"file-io",
"numpy"
] | So I'm very green with Python and am trying to learn by replicating some matlab code I've written. I have a part where, in matlab, I load a data file that's tab-delimited. The syntax
```
x = load(data.txt)
```
Takes the tab delimited data and put them into cells of a matrix labeled x.
Is there a way to do this in py... | There are several methods, choose one that is most suitable for your application.
If you are working with [numpy](http://numpy.scipy.org/), it may be a good idea to use the numpy's [`load`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.load.html), [`loadtxt`](http://docs.scipy.org/doc/numpy/reference/gener... |
Python: Interpreter returns Objects/Functions instead of evaluating | 10,938,066 | 4 | 2012-06-07T18:52:12Z | 10,938,104 | 18 | 2012-06-07T18:55:25Z | [
"python"
] | I am using python-3.2.3 64bit and I am seeing some strange behavior.
For Example when using the interpreter:
The Input
```
>>> range(10)
```
results in the Output
```
range(0, 10)
```
when it should print
```
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
Simmilary Input
```
>>> l = range(10)
>>> f = filter( lambda x: x<2,... | Nothing is wrong. `range()` is Py3.x yields items 1 at a time like generators unlike its behaviour in Py2.x that was to generate a list right then and there and then return it to you. Wrap your call to `range(10)` in a call to `list()` and you'll get what you expect. |
Can't get single \ in python | 10,938,256 | 9 | 2012-06-07T19:05:27Z | 10,938,284 | 18 | 2012-06-07T19:06:50Z | [
"python"
] | I'm trying to learn python, and I'm pretty new at it, and I can't figure this one part out.
Basically, what I'm doing now is something that takes the source code of a webpage, and takes out everything that isn't words.
Webpages have a lot of \n and \t, and I want something that will find \ and delete everything betwee... | `\` is an escape character; it either gives characters a special meaning or takes said special meaning away. Right now, it's escaping the closing single quote and treating it as a literal single quote. You need to escape it with itself to insert a literal backslash:
```
def removebackslash(source):
while(source.fi... |
Can't get single \ in python | 10,938,256 | 9 | 2012-06-07T19:05:27Z | 10,938,318 | 7 | 2012-06-07T19:09:08Z | [
"python"
] | I'm trying to learn python, and I'm pretty new at it, and I can't figure this one part out.
Basically, what I'm doing now is something that takes the source code of a webpage, and takes out everything that isn't words.
Webpages have a lot of \n and \t, and I want something that will find \ and delete everything betwee... | Try using replace:
```
str.replace(old, new[, count])
```
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
So in your case:
```
my_text = my_text.replace('\n', '')
my_text = my_text.replace('\t'... |
How many concurrent requests does a single Flask process receive? | 10,938,360 | 40 | 2012-06-07T19:12:19Z | 13,929,101 | 60 | 2012-12-18T08:36:03Z | [
"python",
"flask",
"wsgi",
"gunicorn"
] | I'm building an app with Flask, but I don't know much about WSGI and it's HTTP base, Werkzeug. When I start serving a Flask application with gunicorn and 4 worker processes, does this mean that I can handle 4 concurrent requests?
I do mean concurrent requests, and not requests per second or anything else.
Thanks! | When running the development server you get running `app.run()`, you get a single synchronous process, which means at most 1 requests being processed at a time.
By sticking Gunicorn in front of it in its default configuration and simply increasing the number of `--workers`, what you get is essentially a number of proc... |
How can I calculate the nearest positive semi-definite matrix? | 10,939,213 | 6 | 2012-06-07T20:16:21Z | 10,940,283 | 19 | 2012-06-07T21:40:03Z | [
"python",
"matrix",
"numpy"
] | I'm coming to Python from R and trying to reproduce a number of things that I'm used to doing in R using Python. The Matrix library for R has a very nifty function called `nearPD()` which finds the closest positive semi-definite (PSD) matrix to a given matrix. While I could code something up, being new to Python/Numpy ... | I don't think there is a library which returns the matrix you want, but here is a "just for fun" coding of neareast positive semi-definite matrix algorithm from Higham (2000)
```
import numpy as np,numpy.linalg
def _getAplus(A):
eigval, eigvec = np.linalg.eig(A)
Q = np.matrix(eigvec)
xdiag = np.matrix(np.... |
How can I calculate the nearest positive semi-definite matrix? | 10,939,213 | 6 | 2012-06-07T20:16:21Z | 18,542,094 | 9 | 2013-08-30T22:03:00Z | [
"python",
"matrix",
"numpy"
] | I'm coming to Python from R and trying to reproduce a number of things that I'm used to doing in R using Python. The Matrix library for R has a very nifty function called `nearPD()` which finds the closest positive semi-definite (PSD) matrix to a given matrix. While I could code something up, being new to Python/Numpy ... | I would submit a non-iterative approach. This is slightly modified from [Rebonato and Jackel (1999)](http://www.quarchome.org/correlationmatrix.pdf) (page 7-9). Iterative approaches can take a long time to process on matrices of more than a few hundred variables.
```
import numpy as np
def nearPSD(A,epsilon=0):
n ... |
How do I get the name from a named tuple in python? | 10,939,758 | 6 | 2012-06-07T20:57:44Z | 10,939,786 | 9 | 2012-06-07T20:59:54Z | [
"python"
] | I create a named tuple like this:
```
from collections import namedtuple
spam = namedtuple('eggs', 'x, y, z')
ham = spam(1,2,3)
```
Then I can access elements of ham with e.g.
```
>>> ham.x
1
>>> ham.z
3
```
In the interpreter,
```
>>> ham
eggs(x=1, y=2, z=3)
```
But what if I just want to get 'eggs'? The only wa... | You can get the `__name__` attribute of the class:
```
>>> type(ham).__name__
'eggs'
```
(Here using [the `type()` builtin](http://docs.python.org/library/functions.html#type) to get the class). |
Installing Python 2.7 on SLES 11 | 10,940,296 | 10 | 2012-06-07T21:41:53Z | 11,371,726 | 19 | 2012-07-07T02:07:31Z | [
"python",
"python-2.7",
"suse"
] | Has anyone been able to successfully install Python 2.7 on SLES 11 SP1? If so, how? I have tried several methods to install as follows:
1. Tried building from source -- this turns out to be exceedingly tedious and beyond my patience and skill level.
2. Tried using PythonBrew, but it gave up with errors.
3. Tried insta... | Building from source is the most appropriate answer. Your patience will pay significant dividends.
A script like the following should be sufficient ([credit](https://github.com/bngsudheer/bangadmin/blob/master/linux/centos/6/x86_64/build-python-27.sh)):
```
#!/bin/bash
# Install Python 2.7.12 alternatively
zypper ins... |
scikit-learn CART String Data | 10,940,483 | 3 | 2012-06-07T22:00:24Z | 10,949,895 | 7 | 2012-06-08T13:34:11Z | [
"python",
"machine-learning",
"scikit-learn"
] | Are you able to train a DecisionTreeClassifier with string data?
When I try to use String data I get a ValueError: could not converter string to float
`clf = DecisionTreeClassifier()
clf.fit([['asdf', '1'], ['asdf', '0']], ['2', '3'])` | You need to transform string-valued features to numeric ones in a NumPy array; [`DictVectorizer`](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.DictVectorizer.html) does that for you.
```
samples = [['asdf', '1'], ['asdf', '0']]
# turn the samples into dicts
samples = [dict(enumerate(samp... |
Python "join" on both sides of strings? | 10,941,112 | 5 | 2012-06-07T23:10:09Z | 10,941,132 | 9 | 2012-06-07T23:13:00Z | [
"python",
"string",
"list"
] | ```
l = ['1','2','3']
goal = ['<li>1</li>','<li>2</li>']
```
How can I get `goal` from `l`?
I'm playing with list comprehensions but it's messy! | Try string formatting and list comprehension, like so.
```
goal = ['<li>{0}</li>'.format(x) for x in l]
``` |
Convert list of tuples to list? | 10,941,229 | 13 | 2012-06-07T23:25:27Z | 10,941,237 | 32 | 2012-06-07T23:26:39Z | [
"python"
] | How do I convert
```
[(1,), (2,), (3,)]
```
to
```
[1, 2, 3]
``` | Using simple [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions):
```
e = [(1,), (2,), (3,)]
[i[0] for i in e]
```
will give you:
```
[1, 2, 3]
``` |
Convert list of tuples to list? | 10,941,229 | 13 | 2012-06-07T23:25:27Z | 10,941,261 | 29 | 2012-06-07T23:29:32Z | [
"python"
] | How do I convert
```
[(1,), (2,), (3,)]
```
to
```
[1, 2, 3]
``` | @Levon's solution works perfectly for your case.
As a side note, if you have variable number of elements in the tuples, you can also use `chain` from `itertools`.
```
>>> a = [(1, ), (2, 3), (4, 5, 6)]
>>> from itertools import chain
>>> list(chain(a))
[(1,), (2, 3), (4, 5, 6)]
>>> list(chain(*a))
[1, 2, 3, 4, 5, 6]
... |
Convert list of tuples to list? | 10,941,229 | 13 | 2012-06-07T23:25:27Z | 10,941,335 | 11 | 2012-06-07T23:40:43Z | [
"python"
] | How do I convert
```
[(1,), (2,), (3,)]
```
to
```
[1, 2, 3]
``` | Here is another alternative if you can have a variable number of elements in the tuples:
```
>>> a = [(1,), (2, 3), (4, 5, 6)]
>>> [x for t in a for x in t]
[1, 2, 3, 4, 5, 6]
```
This is basically just a shortened form of the following loops:
```
result = []
for t in a:
for x in t:
result.append(x)
``` |
Python: how to check that if an item is in a list efficiently? | 10,941,479 | 3 | 2012-06-07T23:59:57Z | 10,941,613 | 8 | 2012-06-08T00:18:14Z | [
"python",
"list"
] | I have a list of strings (words like), and, while I am parsing a text, I need to check if a word belongs to the group of words of my current list.
However, my input is pretty big (about 600 millions lines), and checking if an element belongs to a list is a O(n) operation according to the Python documentation.
My code... | You might consider a [trie](http://en.wikipedia.org/wiki/Trie) or a [DAWG](http://en.wikipedia.org/wiki/Directed_acyclic_word_graph) or a database. There are several Python implementations of the same.
Here is some relative timings for you to consider of a set vs a list:
```
import timeit
import random
with open('/u... |
Python: Converting a list into a dictionary? | 10,942,743 | 2 | 2012-06-08T03:31:07Z | 10,942,766 | 8 | 2012-06-08T03:34:47Z | [
"python"
] | I have a list:
```
['100 ug/ml', '50 ug/ml', '25 ug/ml', '12.5 ug/ml', '6.25 ug/ml', '3.125 ug/ml',
'1.5625 ug/ml', '0 ug/ml']
```
and I want to make it into a dictionary where these numbers are keys with empty values:
```
growth_data = {'100 ug/ml': '', '50 ug/ml': '', '25 ug/ml': '', etc...}
``` | You're looking for the `dict.fromkeys()` method. The first parameter is the list (or iterable) that you want to use as the keys in your dictionary; the second (optional) one is the value for each key. If you give no second argument, `None` will be the value of each key. Be careful with using a mutable object (like `[]`... |
numpy.max or max ? Which one is faster? | 10,943,088 | 18 | 2012-06-08T04:31:55Z | 10,943,125 | 7 | 2012-06-08T04:37:12Z | [
"python",
"numpy",
"runtime",
"max",
"min"
] | In python, which one is faster ?
```
numpy.max(), numpy.min()
```
or
```
max(), min()
```
My list/array length varies from 2 to 600. Which one should I use to save some run time ? | It's probably best if you use something like the Python [timeit module](http://docs.python.org/library/timeit.html) to test it for yourself. That way you can test your own data in your own environment, rather than relying on third parties with various test data and environments which aren't necessarily representative o... |
numpy.max or max ? Which one is faster? | 10,943,088 | 18 | 2012-06-08T04:31:55Z | 10,943,451 | 27 | 2012-06-08T05:22:00Z | [
"python",
"numpy",
"runtime",
"max",
"min"
] | In python, which one is faster ?
```
numpy.max(), numpy.min()
```
or
```
max(), min()
```
My list/array length varies from 2 to 600. Which one should I use to save some run time ? | Well from my timings it follows if you already have numpy array `a` you should use `a.max` (the source tells it's the same as `np.max` if `a.max` available). But if you have built-in list then most of the time takes *converting* it into np.ndarray => that's why `max` is better in your timings.
In essense: if `np.ndarr... |
pandas reindex DataFrame with datetime objects | 10,943,478 | 10 | 2012-06-08T05:24:57Z | 10,943,545 | 19 | 2012-06-08T05:34:25Z | [
"python",
"dataframe",
"pandas",
"reindex"
] | Is it possible to reindex a pandas DataFrame using a column made up of datetime objects?
I have a DataFrame `df` with the following columns:
```
Int64Index: 19610 entries, 0 to 19609
Data columns:
cntr 19610 non-null values #int
datflt 19610 non-null values #float
dtstamp ... | It sounds like you don't want reindex. Somewhat confusingly `reindex` is not for defining a new index, exactly; rather, it looks for rows that have the specified indices. So if you have a DataFrame with index `[0, 1, 2]`, then doing a `reindex([2, 1, 0])` will return the rows in reverse order. Doing something like `rei... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.