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
Pyopencl: difference between to_device and Buffer
13,396,443
8
2012-11-15T11:18:42Z
13,543,288
12
2012-11-24T16:50:43Z
[ "python", "numpy", "opencl", "pyopencl" ]
Let ``` import pyopencl as cl import pyopencl.array as cl_array import numpy a = numpy.random.rand(50000).astype(numpy.float32) mf = cl.mem_flags ``` What is the difference between ``` a_gpu = cl.Buffer(self.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=a) ``` and ``` a_gpu = cl_array.to_device(self.ctx, self.queu...
Buffers are CL's version of `malloc`, while `pyopencl.array.Array` is a workalike of numpy arrays on the compute device. So for the second version of the first part of your question, you may write `a_gpu + 2` to get a new arrays that has 2 added to each number in your array, whereas in the case of the `Buffer`, PyOpen...
Fill countries in python basemap
13,397,022
13
2012-11-15T11:53:36Z
16,449,797
11
2013-05-08T20:40:09Z
[ "python", "matplotlib", "matplotlib-basemap" ]
Hi I am trying to plot a map using pythons basemap with some countries filled in a certain colour. Is there a quick and easy solution out there??
As has already been said by @unutbu, Thomas' post [here](http://www.geophysique.be/2011/01/27/matplotlib-basemap-tutorial-07-shapefiles-unleached/) is exactly what you are after. Should you want to do this with Cartopy, the corresponding code (in v0.7) can be adapted from <http://scitools.org.uk/cartopy/docs/latest/tu...
Fill countries in python basemap
13,397,022
13
2012-11-15T11:53:36Z
16,563,397
9
2013-05-15T11:06:22Z
[ "python", "matplotlib", "matplotlib-basemap" ]
Hi I am trying to plot a map using pythons basemap with some countries filled in a certain colour. Is there a quick and easy solution out there??
Inspired by the answer from pelson, I post the solution I have. I will leave it up to you which works best, so I will not accept any answer at the moment. ``` #! /usr/bin/env python import sys import os from pylab import * from mpl_toolkits.basemap import Basemap import matplotlib as mp from shapelib import ShapeFil...
Python subprocess.call and subprocess.Popen stdout
13,398,261
12
2012-11-15T13:17:52Z
13,398,339
32
2012-11-15T13:22:20Z
[ "python", "subprocess" ]
So I noticed `subprocess.call` while it waits for the command to finish before proceeding with the python script, I have no way of getting the stdout, except with `subprocess.Popen`. Are there any alternative function calls that would wait until it finishes? (I also tried `Popen.wait`) NOTE: I'm trying to avoid `os.sy...
I am using the following construct, although you might want to avoid `shell=True`. This gives you the output and error message for any command, and the error code as well: ``` process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PI...
Python subprocess.call and subprocess.Popen stdout
13,398,261
12
2012-11-15T13:17:52Z
13,398,382
7
2012-11-15T13:24:50Z
[ "python", "subprocess" ]
So I noticed `subprocess.call` while it waits for the command to finish before proceeding with the python script, I have no way of getting the stdout, except with `subprocess.Popen`. Are there any alternative function calls that would wait until it finishes? (I also tried `Popen.wait`) NOTE: I'm trying to avoid `os.sy...
If your process gives a huge stdout and no stderr, `communicate()` might be the wrong way to go due to memory restrictions. Instead, ``` process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # wait for the process to termina...
Python subprocess.call and subprocess.Popen stdout
13,398,261
12
2012-11-15T13:17:52Z
13,398,498
9
2012-11-15T13:31:25Z
[ "python", "subprocess" ]
So I noticed `subprocess.call` while it waits for the command to finish before proceeding with the python script, I have no way of getting the stdout, except with `subprocess.Popen`. Are there any alternative function calls that would wait until it finishes? (I also tried `Popen.wait`) NOTE: I'm trying to avoid `os.sy...
``` subprocess.check_output(...) ``` calls the process, raises if its error code is nonzero, and otherwise returns its stdout. It's just a quick shorthand so you don't have to worry about `PIPE`s and things.
Unpickling python objects with a changed module path
13,398,462
10
2012-11-15T13:29:26Z
13,398,680
11
2012-11-15T13:41:33Z
[ "python", "import", "pickle" ]
I'm trying to integrate a project `Project A` built by a colleague into another python project. Now this colleague has not used relative imports in his code but instead done ``` from packageA.moduleA import ClassA from packageA.moduleA import ClassB ``` and consequently pickled the classes with `cPickle`. For neatnes...
You'll need to create an alias for the pickle import to work; the following to the `__init__.py` file of the `WrapperPackage` package: ``` from .packageA import * # Ensures that all the modules have been loaded in their new locations *first*. from . import packageA # imports WrapperPackage/packageA import sys sys.mod...
Apache SSL vs Python Simple HTTP Server SSL security questions
13,398,996
3
2012-11-15T13:58:49Z
13,436,369
7
2012-11-18T00:44:45Z
[ "python", "apache", "security", "ssl", "webserver" ]
I've always used the Apache Webserver when creating SSL based websites. It seems like the Python HTTP Server library can handle SSL based services too, provided you have the certificates. I'm not as certain the Python webserver can provide services as secure and safe as Apache, but since I'm unable to find out more abo...
Both Apache and Python are using the OpenSSL libraries, so from just this one very simple feature, they should be almost identical. (kind of a strange question... why are you not taking into consideration all of the other security implications of this change?) That being said, HTTP daemons are pretty complex and the s...
When I run the setuptools .egg "as if it were a shell script", what's actually happening?
13,399,118
4
2012-11-15T14:05:00Z
13,399,213
7
2012-11-15T14:10:13Z
[ "python", "shell", "setuptools", "easy-install" ]
From reading [this documentation](http://pypi.python.org/pypi/setuptools#cygwin-mac-os-x-linux-other), I've built a mental model of what the command `sh setuptools-0.6c11-py2.7.egg`actually does, but it's very incomplete and I'm still mystified by a few aspects. My mental model goes something like this: 1. When this ...
Egg files are simply zip-compressed directories containing Python packages, modules and a little metadata, with a `.egg` extension. The zip format is flexible; it will ignore anything at the start of the file that *isn't* part of the zipfile. The zipfile is detected by finding a series of characters (`PK` and two more...
The preferred way to set matplotlib figure/axes properties
13,399,293
19
2012-11-15T14:14:53Z
13,683,825
10
2012-12-03T13:01:38Z
[ "python", "matplotlib", "idioms" ]
Say I have a matplotlib axes called `ax`, and I want to set several of its properties. Currently, I do it like this: ``` ax.set_yscale('log') ax.set_xlim([0,10]) ax.set_xlabel('some label') ``` But it gets tedious after a while. Then I ran into this method: ``` ax.set(yscale='log', xlim=[0,10], xlabel='some label') ...
[Pyplot tutorial](http://matplotlib.org/users/pyplot_tutorial.html) appears to recommend `ax.set_xxx()` functions, but also mentions `.setp(xxx=)`. On the other hand, `.set(xxx=)` function is not used and `.setp(xxx=)`, while documented, is not used in any examples ([Pyplot API](http://matplotlib.org/api/pyplot_api))....
How to find out when subprocess has terminated after using os.kill()?
13,399,734
8
2012-11-15T14:37:52Z
13,402,639
7
2012-11-15T17:09:02Z
[ "python", "django", "subprocess" ]
I have a Python program (precisely, a Django application) that starts a subprocess using [`subprocess.Popen`](http://docs.python.org/2.7/library/subprocess.html#subprocess.Popen). Due to architecture constraints of my application, I'm not able to use [`Popen.terminate()`](http://docs.python.org/2.7/library/subprocess.h...
The usual way to check if a process is still running is to kill() it with signal '0'. It does nothing to a running job and raises an `OSError` exception with `errno=ESRCH` if the process does not exist. ``` [jajcus@lolek ~]$ sleep 1000 & [1] 2405 [jajcus@lolek ~]$ python Python 2.7.3 (default, May 11 2012, 11:57:22) ...
Unpack binary data with python
13,401,600
4
2012-11-15T16:12:46Z
13,402,471
8
2012-11-15T16:59:26Z
[ "python", "arrays", "struct", "unpack", "uint16" ]
I would like to unpack an array of binary data to `uint16` data with Python. Internet is full of examples using `struct.unpack` but only examples dealing with binary array of size 4. Most of these examples are as follow (`B` is a binary array from a file) ``` U = struct.unpack("HH",B[0:4]); ``` So i tried to unpack...
Use array.fromstring or array.fromfile (see <http://docs.python.org/2/library/array.html> ): ``` import array U = array.array("H") U.fromstring(B) ```
Watch for a variable change in python
13,402,847
10
2012-11-15T17:21:02Z
13,404,866
10
2012-11-15T19:40:06Z
[ "python", "debugging", "introspection", "pdb" ]
There is large python project where one attribute of one class just have wrong value in some place. It should be sqlalchemy.orm.attributes.InstrumentedAttribute, but when I run tests it is constant value, let's say string. There is some way to run python program in debug mode, and run some check (if variable changed ...
Well, here is a sort of *slow* approach. It can be modified for watching for local variable change (just by name). Here is how it works: we do sys.settrace and analyse the value of obj.attr each step. The tricky part is that we receive `'line'` events (that some line was executed) before line is executed. So, when we n...
Python global variables don't seem to work across modules
13,403,357
5
2012-11-15T17:55:29Z
13,403,400
8
2012-11-15T17:59:02Z
[ "python", "global-variables" ]
## Code I'd like to use a global variable in other modules with having changes to its value "propagated" to the other modules. a.py: ``` x="fail" def changeX(): global x x="ok" ``` b.py: ``` from a import x, changeX changeX() print x ``` If I run b.py, I'd want it to print "ok", but it really prints "fail...
In short: you can't make it print "ok" without modifying the code. `from a import x, changeX` is equivalent to: ``` import a x = a.x changeX = a.changeX ``` In other words, `from a import x` doesn't create an `x` that indirects to `a.x`, it creates a new global variable `x` in the `b` module with the *current* value...
Python IMAP search for partial subject
13,403,790
4
2012-11-15T18:26:05Z
13,404,390
9
2012-11-15T19:06:33Z
[ "python", "imap" ]
I'm trying to fetch all emails whose subject starts with "New Order" but I can't seem to figure it out. Currently I can search for an exact match with a setup like so... ``` result, data = M.uid('search', None, '(HEADER Subject "Subject Here")') ``` However this won't retrieve any messages that aren't an exact match....
According to the [IMAP RFC](http://tools.ietf.org/html/rfc3501#section-6.4.4) `SEARCH` should do all of its matching as substring matches: > In all search keys that use strings, a message matches the key if > the string is a substring of the field. The matching is > case-insensitive. Therefore, a search ``` M.uid('s...
T-test in Pandas (Python)
13,404,468
21
2012-11-15T19:11:57Z
13,413,842
30
2012-11-16T09:34:21Z
[ "python", "pandas", "scipy", "statistics", "hypothesis-test" ]
If i want to calculate the mean of two categories in Pandas, I can do like this: ``` data = {'Category': ['cat2','cat1','cat2','cat1','cat2','cat1','cat2','cat1','cat1','cat1','cat2'], 'values': [1,2,3,1,2,3,1,2,3,5,1]} my_data = DataFrame(data) my_data.groupby('Category').mean() Category: values: cat1...
it depends what sort of t-test you want to do (one sided or two sided dependent or independent) but it should be as simple as: ``` from scipy.stats import ttest_ind cat1 = my_data[my_data['Category']=='cat1'] cat2 = my_data[my_data['Category']=='cat2'] ttest_ind(cat1['values'], cat2['values']) >>> (1.492728992570694...
Inherited class variable modification in Python
13,404,476
16
2012-11-15T19:12:25Z
13,404,513
8
2012-11-15T19:15:14Z
[ "python", "python-2.7" ]
I'd like to have a child class modify a class variable that it inherits from its parent. I would like to do something along the lines of: ``` class Parent(object): foobar = ["hello"] class Child(Parent): # This does not work foobar = foobar.extend(["world"]) ``` and ideally have: ``` Child.foobar = ["h...
You should not use mutable values in your class variables. Set such values on the *instance* instead, using the `__init__()` instance initializer: ``` class Parent(object): def __init__(self): self.foobar = ['Hello'] class Child(Parent): def __init__(self): super(Child, self).__init__() ...
Inherited class variable modification in Python
13,404,476
16
2012-11-15T19:12:25Z
13,404,537
20
2012-11-15T19:16:55Z
[ "python", "python-2.7" ]
I'd like to have a child class modify a class variable that it inherits from its parent. I would like to do something along the lines of: ``` class Parent(object): foobar = ["hello"] class Child(Parent): # This does not work foobar = foobar.extend(["world"]) ``` and ideally have: ``` Child.foobar = ["h...
Assuming you want to have a separate list in the subclass, not modify the parent class's list (which seems pointless since you could just modify it in place, or put the expected values there to begin with): ``` class Child(Parent): foobar = Parent.foobar + ['world'] ``` Note that this works independently of inher...
Pandas rolling apply with missing data
13,405,611
8
2012-11-15T20:27:19Z
13,407,863
7
2012-11-15T23:09:07Z
[ "python", "pandas", "missing-data", "rolling-computation" ]
I want to do a rolling computation on missing data. Sample Code: *(For sake of simplicity I'm giving an example of a rolling sum but I want to do something more generic.)* ``` foo = lambda z: z[pandas.notnull(z)].sum() x = np.arange(10, dtype="float") x[6] = np.NaN x2 = pandas.Series(x) pandas.rolling_apply(...
``` In [7]: pandas.rolling_apply(x2, 3, foo, min_periods=2) Out[7]: 0 NaN 1 1 2 3 3 6 4 9 5 12 6 9 7 12 8 15 9 24 ```
Convert an image RGB->Lab with python
13,405,956
22
2012-11-15T20:49:54Z
13,408,814
7
2012-11-16T00:49:14Z
[ "python", "numpy", "scipy", "python-imaging-library", "color-space" ]
What is the preferred way of doing the conversion using PIL/Numpy/SciPy today?
Edit: Sample pyCMS code: ``` from PIL import Image import pyCMS im = Image.open(...) im2 = pyCMS.profileToProfile(im, pyCMS.createProfile("sRGB"), pyCMS.createProfile("LAB")) ``` Edit: Pillow, the PIL fork, seems to have pyCMS built in. You might use pyCMS (<http://www.cazabon.com/pyCMS/>) which works with PIL image...
Convert an image RGB->Lab with python
13,405,956
22
2012-11-15T20:49:54Z
13,423,989
29
2012-11-16T20:32:13Z
[ "python", "numpy", "scipy", "python-imaging-library", "color-space" ]
What is the preferred way of doing the conversion using PIL/Numpy/SciPy today?
Since 2010 when the [linked question](http://stackoverflow.com/questions/3228361/using-pil-and-numpy-to-convert-an-image-to-lab-array-modify-the-values-and-then) was asked the corresponding code moved from scipy to a separate toolkit: <http://scikit-image.org/> So here's the code I was actually looking for: ``` from ...
Convert an image RGB->Lab with python
13,405,956
22
2012-11-15T20:49:54Z
16,020,102
9
2013-04-15T16:22:13Z
[ "python", "numpy", "scipy", "python-imaging-library", "color-space" ]
What is the preferred way of doing the conversion using PIL/Numpy/SciPy today?
I've found this code in [adobe cookbook](http://cookbooks.adobe.com/post_Useful_color_equations__RGB_to_LAB_converter-14227.html) and adapted for python. It doesn't require any third-party modules or components: ``` def rgb2lab ( inputColor ) : num = 0 RGB = [0, 0, 0] for value in inputColor : value ...
sqlalchemy: why can't I update to func.now(), but can use 'now()'?
13,406,480
9
2012-11-15T21:24:46Z
13,443,905
10
2012-11-18T19:46:34Z
[ "python", "sql", "database", "datetime", "sqlalchemy" ]
...when I try to do a query that looks like this: ``` Session().query(MyMappedClass).update({MyMappedClass.time:func.now()}) ``` I get: ``` InvalidRequestError: Could not evaluate current criteria in Python. Specify 'fetch' or False for the synchronize_session parameter. ``` But if I do: ``` Session().query(MyMapp...
this is explained in the [documentation for update()](http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.update.params.synchronize_session) > synchronize\_session – > > chooses the strategy to update the attributes on objects in the > session. Valid values are: > > False - don’t synchro...
Python image library, how to compress image into desired file size?
13,407,717
6
2012-11-15T22:56:01Z
13,407,861
7
2012-11-15T23:08:59Z
[ "python", "image", "compression" ]
I got a requirement to compress any uploaded images less than 500kb in file size, I have searched on google and all I can see is: ``` >>> foo = foo.resize((160,300),Image.ANTIALIAS) >>> foo.save("path\\to\\save\\image_scaled.jpg",quality=95) ``` If I go with this approach I will have to check if the image is less t...
JPEG compression is not predictable beforehand. The method you described, compress & measure & try again, is the only way I know. You can try compressing a number of typical images with different quality settings to get an idea of the optimum starting point, plus a way of guessing how changes to the setting will affec...
sorting list of tuples by arbitrary key
13,408,919
9
2012-11-16T01:04:45Z
13,408,941
11
2012-11-16T01:08:41Z
[ "python" ]
``` order = ['w','x','a','z'] [(object,'a'),(object,'x'),(object,'z'),(object,'a'),(object,'w')] ``` How do I sort the above list of tuples by the second element according the the key list provided by 'order'? UPDATE on 11/18/13: I found a much better approach to a variation of this question where the keys are certa...
You can use `sorted`, and give as the `key` a function that returns the index of the second value of each tuple in the `order` list. ``` >>> sorted(mylist,key=lambda x: order.index(x[1])) [('object', 'w'), ('object', 'x'), ('object', 'a'), ('object', 'a'), ('object', 'z')] ``` Beware, this fails whenever a value fro...
How to say... match when field is a number... in mongodb?
13,409,386
12
2012-11-16T02:09:51Z
13,409,546
30
2012-11-16T02:32:48Z
[ "python", "mongodb" ]
So I have a field called 'city' in my results...the results are corrupted, some times it's an actual name, sometimes it's a number. The following code displays all the records... ``` db.zips.aggregate([{$project : {city:{$substr:["$city",0,1]}}},{$sort : {city : 1}} ]) ``` I need to modify this line to display only t...
Use the [`$type`](http://docs.mongodb.org/manual/reference/operator/type/) operator in your `$match`: ``` db.zips.aggregate([ {$project : {city:{$substr:["$city",0,1]}}}, {$sort : {city : 1}}, {$match: {city: {$type: 16}}} // city is a 32-bit integer ]); ``` There isn't a single type value for numbe...
How to say... match when field is a number... in mongodb?
13,409,386
12
2012-11-16T02:09:51Z
22,272,309
17
2014-03-08T17:02:05Z
[ "python", "mongodb" ]
So I have a field called 'city' in my results...the results are corrupted, some times it's an actual name, sometimes it's a number. The following code displays all the records... ``` db.zips.aggregate([{$project : {city:{$substr:["$city",0,1]}}},{$sort : {city : 1}} ]) ``` I need to modify this line to display only t...
Why not to use $regex? ``` db.zips.aggregate([ {$project : {city:{$substr:["$city",0,1]}}}, {$sort : {city : 1}}, {$match: {city:{$regex:'[0-9]'}}} ]) ```
How can I format timedelta for display
13,409,682
7
2012-11-16T02:54:30Z
13,409,708
12
2012-11-16T02:57:30Z
[ "python" ]
My script calculate the difference in 2 time. Like this: ``` lasted = datetime.strptime(previous_time, FMT) - datetime.strptime(current_time, FMT) ``` It returns me a timedelta object. Currently, it gives me difference in seconds. How can I format it for display nicely? e.g. convert "121" to "00:02:01"? Thank you.
Have you tried using `str()`? ``` >>> a = datetime.now() >>> b = datetime.now() - a >>> b datetime.timedelta(0, 6, 793600) >>> str(b) '0:00:06.793600' ``` Alternatively, you can use string formatting: ``` >>> a = datetime.now() >>> b = datetime.now() - a >>> s = b.total_seconds() >>...
AttributeError: 'long' object has no attribute 'fetchall'
13,410,982
5
2012-11-16T05:26:18Z
13,411,358
10
2012-11-16T06:06:28Z
[ "python", "mysql", "flask" ]
I'm attempting to execute some sql using the mysql-flask python extension. The below code always returns a long for some reason. ``` stringify = lambda x : '"' + x + '"' if request.method == 'POST': sql = "select * from users where username = " + stringify(request.form['username']) user = g.db.cursor()...
You are trying to call a method on the result of `Cursor.execute`, which the [DB-API specification](http://www.python.org/dev/peps/pep-0249/) says is undefined (the implementation you're using appears to be returning an integer). Instead, you want to call `fetchall` on the cursor object. Something like: ``` cursor = g...
Delete column from pandas DataFrame
13,411,544
360
2012-11-16T06:26:40Z
13,415,772
17
2012-11-16T11:33:47Z
[ "python", "pandas", "design", "dataframe", "magic-methods" ]
When deleting a column in a DataFrame I use: ``` del df['column_name'] ``` and this works great. Why can't I use: ``` del df.column_name ``` *As you can access the column/Series as `df.column_name`, I expect this to work.*
It's good practice to always use the `[]` notation, one reason is that attribute notation (`df.column_name`) does not work for numbered indices: ``` In [1]: df = DataFrame([[1, 2, 3], [4, 5, 6]]) In [2]: df[1] Out[2]: 0 2 1 5 Name: 1 In [3]: df.1 File "<ipython-input-3-e4803c0d1066>", line 1 df.1 ...
Delete column from pandas DataFrame
13,411,544
360
2012-11-16T06:26:40Z
13,485,766
205
2012-11-21T03:12:31Z
[ "python", "pandas", "design", "dataframe", "magic-methods" ]
When deleting a column in a DataFrame I use: ``` del df['column_name'] ``` and this works great. Why can't I use: ``` del df.column_name ``` *As you can access the column/Series as `df.column_name`, I expect this to work.*
It's difficult to make `del df.column_name` work simply as the result of syntactic limitations in Python. `del df[name]` gets translated to `df.__delitem__(name)` under the covers by Python
Delete column from pandas DataFrame
13,411,544
360
2012-11-16T06:26:40Z
18,145,399
695
2013-08-09T11:12:09Z
[ "python", "pandas", "design", "dataframe", "magic-methods" ]
When deleting a column in a DataFrame I use: ``` del df['column_name'] ``` and this works great. Why can't I use: ``` del df.column_name ``` *As you can access the column/Series as `df.column_name`, I expect this to work.*
The best way to do this in pandas is to use [drop](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html): ``` df = df.drop('column_name', 1) ``` where `1` is the *axis* number (`0` for rows and `1` for columns.) To delete the column without having to reassign `df` you can do: ``` df.drop...
Delete column from pandas DataFrame
13,411,544
360
2012-11-16T06:26:40Z
22,596,982
70
2014-03-23T20:57:57Z
[ "python", "pandas", "design", "dataframe", "magic-methods" ]
When deleting a column in a DataFrame I use: ``` del df['column_name'] ``` and this works great. Why can't I use: ``` del df.column_name ``` *As you can access the column/Series as `df.column_name`, I expect this to work.*
``` df.drop([Column Name or list],inplace=True,axis=1) ``` will delete one or more columns inplace.
Delete column from pandas DataFrame
13,411,544
360
2012-11-16T06:26:40Z
31,431,997
23
2015-07-15T13:37:23Z
[ "python", "pandas", "design", "dataframe", "magic-methods" ]
When deleting a column in a DataFrame I use: ``` del df['column_name'] ``` and this works great. Why can't I use: ``` del df.column_name ``` *As you can access the column/Series as `df.column_name`, I expect this to work.*
## Drop by index delete first, second and fourth columns: ``` df.drop(df.columns[[0,1,3]], axis=1, inplace=True) ``` delete first column: ``` df.drop(df.columns[[0]], axis=1, inplace=True) ``` There is an optional parameter `inplace` so that the original data can be modified without creating a copy. ## Popped [C...
Delete column from pandas DataFrame
13,411,544
360
2012-11-16T06:26:40Z
34,576,537
14
2016-01-03T12:29:49Z
[ "python", "pandas", "design", "dataframe", "magic-methods" ]
When deleting a column in a DataFrame I use: ``` del df['column_name'] ``` and this works great. Why can't I use: ``` del df.column_name ``` *As you can access the column/Series as `df.column_name`, I expect this to work.*
A nice addition is the ability to **drop columns only if they exist**, this way you can cover more use cases, and it will only drop the existing columns from the labels passed to it: simply add **errors='ignore'** ,e.g: ``` df.drop(['col_name_1','col_name_2',...,'col_name_N'],inplace=True,axis=1,errors='ignore') ``` ...
Delete column from pandas DataFrame
13,411,544
360
2012-11-16T06:26:40Z
37,000,877
12
2016-05-03T09:48:51Z
[ "python", "pandas", "design", "dataframe", "magic-methods" ]
When deleting a column in a DataFrame I use: ``` del df['column_name'] ``` and this works great. Why can't I use: ``` del df.column_name ``` *As you can access the column/Series as `df.column_name`, I expect this to work.*
The actual question posed, missed by most answers here is: ### Why can't I use `del df.column_name`? At first we need to understand the problem, which requires us to dive into [*python magic methods*](http://www.rafekettler.com/magicmethods.html). As Wes points out in his answer `del df['column']` maps to the python...
Python ElementTree module: How to ignore the namespace of XML files to locate matching element when using the method "find", "findall"
13,412,496
51
2012-11-16T07:53:17Z
15,641,319
25
2013-03-26T15:44:24Z
[ "python", "namespaces", "find", "elementtree", "findall" ]
I want to use the method of "findall" to locate some elements of the source xml file in the ElementTree module. However, the source xml file (test.xml) has namespace. I truncate part of xml file as sample: ``` <?xml version="1.0" encoding="iso-8859-1"?> <XML_HEADER xmlns="http://www.test.com"> <TYPE>Updates</TYPE...
If you remove the xmlns attribute from the xml before parsing it then there won't be a namespace prepended to each tag in the tree. ``` import re xmlstring = re.sub(' xmlns="[^"]+"', '', xmlstring, count=1) ```
Python ElementTree module: How to ignore the namespace of XML files to locate matching element when using the method "find", "findall"
13,412,496
51
2012-11-16T07:53:17Z
20,104,763
9
2013-11-20T19:07:52Z
[ "python", "namespaces", "find", "elementtree", "findall" ]
I want to use the method of "findall" to locate some elements of the source xml file in the ElementTree module. However, the source xml file (test.xml) has namespace. I truncate part of xml file as sample: ``` <?xml version="1.0" encoding="iso-8859-1"?> <XML_HEADER xmlns="http://www.test.com"> <TYPE>Updates</TYPE...
The answers so far explicitely put the namespace value in the script. For a more generic solution, I would rather extract the namespace from the xml: ``` def get_namespace(element): m = re.match('\{.*\}', element.tag) return m.group(0) if m else '' ``` And use it in find method: ``` namespace = get_namespace(tre...
Python ElementTree module: How to ignore the namespace of XML files to locate matching element when using the method "find", "findall"
13,412,496
51
2012-11-16T07:53:17Z
25,920,989
32
2014-09-18T19:37:36Z
[ "python", "namespaces", "find", "elementtree", "findall" ]
I want to use the method of "findall" to locate some elements of the source xml file in the ElementTree module. However, the source xml file (test.xml) has namespace. I truncate part of xml file as sample: ``` <?xml version="1.0" encoding="iso-8859-1"?> <XML_HEADER xmlns="http://www.test.com"> <TYPE>Updates</TYPE...
Instead of modifying the XML document itself, it's best to parse it and then modify the tags in the result. This way you can handle multiple namespaces and namespace aliases: ``` from StringIO import StringIO import xml.etree.ElementTree as ET # instead of ET.fromstring(xml) it = ET.iterparse(StringIO(xml)) for _, el...
Python: Writing to a File
13,412,513
3
2012-11-16T07:54:35Z
13,412,537
7
2012-11-16T07:57:22Z
[ "python" ]
I've been having trouble with this for a while. How do I open a file in python and continue writing to it but not overwriting what I had written before? For instance: The code below will write 'output is OK'. Then the next few lines will overwrite it and it will just be 'DONE' But I want both 'output is OK' 'DONE' i...
Open the file in append mode. It will be created if it does not exist and it will be opened at its end for further writing if it does exist: ``` with open('out.log', 'a') as f: f.write('output is ') # some work s = 'OK.' f.write(s) f.write('\n') # some other work with open('out.log', 'a') as f: ...
Creating labels where line appears in matplotlib figure
13,413,112
6
2012-11-16T08:43:51Z
13,418,339
13
2012-11-16T14:14:34Z
[ "python", "matplotlib", "labels" ]
I have a figure created in matplotlib (time-series data) over which are a series of ``` matplotlib.pyplot.axvline ``` lines. I would like to create labels on the plot that appear close to (probably on the RHS of the line and towards the top of the figure) these vertical lines.
You can use something like ``` plt.axvline(10) plt.text(10.1,0,'blah',rotation=90) ``` you might have to play around with the x and y value in `text` to get it to align properly. You can find the more complete documentation [here](http://matplotlib.org/users/text_props.html).
How do I catch an exception for a module that I've not fully imported?
13,413,258
3
2012-11-16T08:54:45Z
13,413,339
9
2012-11-16T09:00:02Z
[ "python", "exception", "try-catch" ]
Normally, if I imported `socket`, I would be able to easily catch exceptions: ``` >>> import socket >>> try: ... socket.gethostbyname('hello') ... except socket.gaierror: ... print('oops') ... oops ``` But if I just import `socket.gethostbyname`, it won't work: ``` >>> from socket import gethostbyname >>> tr...
If you do not want to import the full module you can simply import the exception aswell. PEP8 states that you are allowed to do. ``` from socket import gethostbyname, gaierror ``` <http://www.python.org/dev/peps/pep-0008/#imports>
How to drop rows of Pandas dataframe whose value of certain column is NaN
13,413,590
157
2012-11-16T09:17:22Z
13,413,845
156
2012-11-16T09:34:38Z
[ "python", "pandas", "dataframe" ]
I have a df : ``` >>> df STK_ID EPS cash STK_ID RPT_Date 601166 20111231 601166 NaN NaN 600036 20111231 600036 NaN 12 600016 20111231 600016 4.3 NaN 601009 20111231 601009 NaN NaN 601939 20111231 601939 2.5 NaN 000001 20111231 000001 NaN NaN ``` Then I ju...
Don't `drop`. Just take rows where `EPS` is **finite**: ``` df = df[np.isfinite(df['EPS'])] ```
How to drop rows of Pandas dataframe whose value of certain column is NaN
13,413,590
157
2012-11-16T09:17:22Z
13,434,501
240
2012-11-17T20:27:33Z
[ "python", "pandas", "dataframe" ]
I have a df : ``` >>> df STK_ID EPS cash STK_ID RPT_Date 601166 20111231 601166 NaN NaN 600036 20111231 600036 NaN 12 600016 20111231 600016 4.3 NaN 601009 20111231 601009 NaN NaN 601939 20111231 601939 2.5 NaN 000001 20111231 000001 NaN NaN ``` Then I ju...
This question is already resolved, but... ...also consider the solution suggested by Wouter in [his original comment](http://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas-dataframe-whose-value-of-certain-column-is-nan/13434501#comment18328797_13413590). The ability to handle missing data, including `...
How to drop rows of Pandas dataframe whose value of certain column is NaN
13,413,590
157
2012-11-16T09:17:22Z
23,235,618
42
2014-04-23T05:37:45Z
[ "python", "pandas", "dataframe" ]
I have a df : ``` >>> df STK_ID EPS cash STK_ID RPT_Date 601166 20111231 601166 NaN NaN 600036 20111231 600036 NaN 12 600016 20111231 600016 4.3 NaN 601009 20111231 601009 NaN NaN 601939 20111231 601939 2.5 NaN 000001 20111231 000001 NaN NaN ``` Then I ju...
I know this has already been answered, but just for the sake of a purely pandas solution to this specific question as opposed to the general description from Aman (which was wonderful) and in case anyone else happens upon this: ``` import pandas as pd df = df[pd.notnull(df['EPS'])] ```
How to drop rows of Pandas dataframe whose value of certain column is NaN
13,413,590
157
2012-11-16T09:17:22Z
34,082,664
9
2015-12-04T07:01:56Z
[ "python", "pandas", "dataframe" ]
I have a df : ``` >>> df STK_ID EPS cash STK_ID RPT_Date 601166 20111231 601166 NaN NaN 600036 20111231 600036 NaN 12 600016 20111231 600016 4.3 NaN 601009 20111231 601009 NaN NaN 601939 20111231 601939 2.5 NaN 000001 20111231 000001 NaN NaN ``` Then I ju...
You could use dataframe method [notnull](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.notnull.html) or inverse of [isnull](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isnull.html), or [numpy.isnan](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.isna...
brackets around print in python
13,415,181
3
2012-11-16T10:57:33Z
13,415,304
8
2012-11-16T11:04:12Z
[ "python", "printing" ]
I have this line of code in python ``` print 'hello world' ``` against ``` print ('hello world') ``` can someone tell me the difference between the two? I used it in a a simple code ``` var = 3 if var > 2: print 'hello' ``` it fails for checking strictly for all values for var. But if I define the code as ...
For Python 2, it makes no difference. There, `print` is a statement and `'hello'` and `('hello')` are its argument. The latter gets simplified to just `'hello'` and as such it’s identical. In Python 3, the print statement was removed in favor of a print function. Functions are invoked using braces, so they are actua...
Split a list into chunks of varying length
13,415,805
4
2012-11-16T11:36:21Z
13,415,853
13
2012-11-16T11:39:06Z
[ "python", "list", "iterator" ]
Given a sequence of items and another sequence of chunk lengths, how can I split the sequence into chunks of the required lengths? ``` a = range(10) l = [3, 5, 2] split_lengths(a, l) == [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]] ``` Ideally a solution would work with both `a` and `l` as general iterables, not just on lists...
Use [`itertools.islice`](http://docs.python.org/2/library/itertools.html#itertools.islice) on an iterator of the list. ``` In [12]: a = range(10) In [13]: b = iter(a) In [14]: from itertools import islice In [15]: l = [3, 5, 2] In [16]: [list(islice(b, x)) for x in l] Out[16]: [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]] ...
laying out a large graph with graphviz
13,417,411
27
2012-11-16T13:17:47Z
13,420,913
26
2012-11-16T16:50:51Z
[ "python", "graphviz" ]
My daughters have made a game not unlike tic-tac-toe. Of course as I played it with them I started brute-forcing it in my head... So at lunchtime I made a quick little Python script to 'solve' the game. And I wanted to see the results graphically, so I generated a dot file of all legal moves: [I've pasted the data he...
Try this: ``` sfdp -x -Goverlap=scale -Tpng data.dot > data.png ``` The `-Goverlap` preserves the layout but uniformly scales things up until there are no more node overlaps. I was able to get a ~77MB PNG that looks like this when you zoom out. ![enter image description here](http://i.stack.imgur.com/L4LJ3.png)
laying out a large graph with graphviz
13,417,411
27
2012-11-16T13:17:47Z
24,561,831
7
2014-07-03T19:24:33Z
[ "python", "graphviz" ]
My daughters have made a game not unlike tic-tac-toe. Of course as I played it with them I started brute-forcing it in my head... So at lunchtime I made a quick little Python script to 'solve' the game. And I wanted to see the results graphically, so I generated a dot file of all legal moves: [I've pasted the data he...
you could still use the neato but modify the .dot file putting: [splines=true overlap=false] And your file should look like this: ``` digraph luffarschack { graph [splines=true overlap=false]; node [shape=none]; ...here your nodes; ...here your edges; } ``` It should work if you just put in ...
assigning a value to members in a list in python
13,417,843
2
2012-11-16T13:45:19Z
13,417,878
11
2012-11-16T13:47:08Z
[ "python", "list" ]
i have a list , lets say : ``` test = [False, False, 2, False, False, False, 3, False, False] ``` and i want to assign every member of this list to False unless this member is equal to 2 so the result should be : ``` test = [False, False, 2, False, False, False, False, False, False] ``` i tried : ``` test = [False...
It's ``` [False if i !=2 else 2 for i in test] ``` Otherwise, you're skipping the whole element when it's equal to 2.
What is wrong in my Django & jQuery AJAX form submission setup?
13,418,172
2
2012-11-16T14:05:04Z
13,418,457
7
2012-11-16T14:21:23Z
[ "javascript", "jquery", "python", "ajax", "django" ]
I know, you have read questions like this a thousand times or even more often, and I have also read these questions and their answers, but I simply cannot get my AJAX form to work correctly using jQuery on the client side and Django on the server side. Also, I was not able to find a stupid simple step-by-step tutorial ...
The clue is in the console: it's showing that it's appending `[object Object]` to the URL it's POSTing to. I suspect that that's the representation of the whole object that you've passed to the `$.post` function. This is because unlike the `$.ajax` function, `$.post` doesn't take an object, it takes individual paramet...
Get name of primary field of Django model
13,418,405
20
2012-11-16T14:18:02Z
13,419,091
24
2012-11-16T14:59:32Z
[ "python", "django", "django-models" ]
In Django, every model has a pseudo attribute `pk`, that points to the field that is declared as primary key. ``` class TestModel(models.Model): payload = models.Charfield(max_length=200) ``` In this model, the `pk` attribute would point to the implicit `id` field, that is generated if no field is declared to be ...
You will also have an attribute "name" on the pk-attribute. This seems to hold the name of the Field. ``` CustomPK._meta.pk.name ``` In my case I get the value "id" as result (like it should). :-)
Python, how to deal with A(a) when type(a) is yet A
13,419,340
4
2012-11-16T15:13:59Z
13,419,371
11
2012-11-16T15:15:44Z
[ "python", "class", "idempotent" ]
I need to create a class that mimics this behavior (in mathematics, we say *list*, *dict*, are "idempotent"): ``` >>> list(list([3,4])) [3, 4] >>> dict({'a':1,'b':2}) {'a':1,'b':2} ``` So, if *A* is my class, I want to write ``` >>> a = A(1) >>> b = A(a) >>> b == a True ``` I imagine my class A has to look like thi...
What you are looking for is the [`__new__()`](http://mail.python.org/pipermail/tutor/2008-April/061426.html) method, which takes is run **before** the class is constructed, as opposed to `__init__()`, which takes place after. With `__new__()` you can hook in and replace the object being created. ``` def __new__(cls, x...
Pycharm - How do I access the "Watches" pane?
13,419,659
5
2012-11-16T15:33:56Z
13,421,664
8
2012-11-16T17:38:48Z
[ "python", "pycharm" ]
I'm somewhat new to Pycharm, and I suppose this should be an easy question, but I'm not finding the answer anywhere... The Pycharm documentation has instructions for adding/editing items in the Watches pane, but the documentation assumes the Watches pane is already open, so it skips the step on how to open/access it. ...
In the Debug pane, on the left side, 7th from the top, there is a "Restore Layout" button that unhides the Watches panel. [![screenshot](http://i.stack.imgur.com/M3tKi.png)](http://i.stack.imgur.com/M3tKi.png)
pandas dataframe, copy by value
13,419,822
5
2012-11-16T15:43:15Z
13,420,016
21
2012-11-16T15:55:06Z
[ "python", "pandas" ]
I noticed a bug in my program and the reason it is happening is because it seems that pandas is copying by reference a pandas dataframe instead of by value. I know immutable objects will always be passed by reference but pandas dataframe is not immutable so I do not see why it is passing by reference. Can anyone provid...
All functions in Python are "pass by reference", there is no "pass by value". If you want to make an explicit copy of a pandas object, try `new_frame = frame.copy()`.
Why is Pypy's deque so slow?
13,421,326
12
2012-11-16T17:17:15Z
13,421,804
17
2012-11-16T17:48:37Z
[ "python", "deque", "pypy" ]
Here is a (slightly messy) attempt at [Project Euler Problem 49](http://projecteuler.net/problem=49). I should say outright that the `deque` was not a good choice! My idea was that shrinking the set of primes to test for membership would cause the loop to accelerate. However, when I realised that I should have used a ...
The slow part is `inc1 in primes and inc2 in primes`. I'll look at why PyPy is so slow (thanks for the performance bug report, basically). Note that as you mentioned the code can be made incredibly faster (both on PyPy and on CPython) --- in this case, just by copying the `primes` deque into a set just before the `for`...
Missing configuration keys for 'webapp2_extras.sessions': ['secret_key']
13,421,614
4
2012-11-16T17:34:50Z
13,421,704
13
2012-11-16T17:41:51Z
[ "python", "google-app-engine", "webapp2" ]
I added webapp2 sessions to my project on appengine which uses webapp2 for request handling and django for templates. Following [this page](http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html), I added the following to my script ``` import webapp2 from webapp2_extras import sessions class BaseHandle...
You need to include this config somewhere, such as in the WSGI app you create: ``` app = webapp2.WSGIApplication([('/path', MyHandler), config=config, debug=True) ```
Socket isn't working in Python
13,422,356
2
2012-11-16T18:31:07Z
13,422,437
10
2012-11-16T18:36:38Z
[ "python" ]
I've been trying out the 'socket' module in Python but whenever I attempt to run this code : ``` import socket import sys host = '192.168.1.1' port = 23 try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except: print "socket() failed" sys.exit(1) ``` Then it dies. Here is the error without...
``` import socket ``` [looks into the current directory before Python's standard library](http://docs.python.org/2/library/sys.html#sys.path). And since your file is called `socket.py`, it is itself imported instead of the [socket](http://docs.python.org/3/library/socket.html) standard library module. Rename (don't co...
Python: required kwarg, which exception to raise?
13,422,601
20
2012-11-16T18:49:11Z
13,422,624
21
2012-11-16T18:51:18Z
[ "python", "exception" ]
One way to ensure that a method is called with a particular kwarg would be like: ``` def mymethod(self, *args, **kwargs): assert "required_field" in kwargs ``` Raising an `AssertionError` doesn't seem like the most appropriate thing to do. Is there an agreed upon builtin exception to handle this with a nice error...
``` >>> def foo(bar): pass ... >>> foo() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() missing 1 required positional argument: 'bar' ``` I'd just go with TypeError..
Python: required kwarg, which exception to raise?
13,422,601
20
2012-11-16T18:49:11Z
13,422,627
12
2012-11-16T18:51:32Z
[ "python", "exception" ]
One way to ensure that a method is called with a particular kwarg would be like: ``` def mymethod(self, *args, **kwargs): assert "required_field" in kwargs ``` Raising an `AssertionError` doesn't seem like the most appropriate thing to do. Is there an agreed upon builtin exception to handle this with a nice error...
The standard library seems to like to raise `TypeError` when it gets the wrong number of arguments. That's essentially your problem, so I'd raise that. That said, `**kwargs` essentially fill in for default arguments most of the time, so having a required default argument seems a little surprising/confusing. Note that...
IPython support on Emacs 24.x
13,422,653
7
2012-11-16T18:53:25Z
19,065,879
7
2013-09-28T10:26:09Z
[ "python", "emacs", "ipython" ]
I am confused about the integration of IPython with Emacs. Starting with Emacs 24, Emacs ships with it's own `python.el`. Does this file have support for IPython or just for Python? Also, the [Emacswiki](http://emacswiki.org/emacs/PythonProgrammingInEmacs) talks about a file called `IPython.el` (although the link it p...
The new `python.el` (shipped with Emacs version 24.3) does support IPython. You need to add the following lines to your `init.el` file (instructions copied from `python.el`): ``` (require 'python) (setq python-shell-interpreter "ipython" python-shell-interpreter-args "--pylab" python-shell-prompt-regexp "In \\[[...
Django: How to limit number of objects returned from a model
13,422,689
3
2012-11-16T18:55:46Z
13,422,738
9
2012-11-16T18:59:41Z
[ "python", "django" ]
I have a list of "news" headlines in a database with the following fields: ID, Title, Date. I want to get the ten latest ones (or retrieve all of them if there are less than ten). Something like: ``` news = News.objects.order_by("date").first(10) ```
This is what you need to do: ``` news = News.objects.order_by("-date")[:10] ``` There are a couple of interesting things going on here. First, to get the lastest news, you need Descending order. (Thats the "-date" part) [0] The second part is LIMITing the resultset[1]. This shares the same interface as Python lists...
Why does PyImport_Import fail to load a module from the current directory?
13,422,764
8
2012-11-16T19:00:54Z
13,424,007
14
2012-11-16T20:33:26Z
[ "python", "linux", "python-2.7", "python-embedding" ]
I'm trying to run the [embedding example](http://docs.python.org/2/extending/embedding.html#pure-embedding) and I can't load a module from the current working directory unless I explicitly add it to `sys.path` then it works: ``` PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\".\")"); ``` Shoul...
You need to call `PySys_SetArgv(int argc, char **argv, int updatepath)` for the relative imports to work. This will add the path of the script being executed to `sys.path` if `updatepath` is `0` (refer to the [docs](http://docs.python.org/2/c-api/init.html#PySys_SetArgvEx) for more information). The following should d...
Argparse subparser: hide metavar in command listing
13,423,540
8
2012-11-16T19:58:23Z
13,429,281
10
2012-11-17T09:21:55Z
[ "python", "argparse" ]
I'm using the Python argparse module for command line subcommands in my program. My code basically looks like this: ``` import argparse parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(title="subcommands", metavar="<command>") subparser = subparsers.add_parser("this", help="do this") subparser =...
I solved it by adding a new HelpFormatter that just removes the line if formatting a PARSER action: ``` class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter): def _format_action(self, action): parts = super(argparse.RawDescriptionHelpFormatter, self)._format_action(action) if action.n...
python regular expression match
13,423,624
10
2012-11-16T20:03:39Z
13,423,687
24
2012-11-16T20:07:36Z
[ "python", "regex", "python-2.7" ]
``` import re str="x8f8dL:s://www.qqq.zzz/iziv8ds8f8.dafidsao.dsfsi" str2=re.match("[a-zA-Z]*//([a-zA-Z]*)",str) print str2.group() current result=> error expected => wwwqqqzzz ``` I want to extract the string "wwwqqqzzz" ,how i do that? May be there is a lot dots Such as ``` "whatever..s#$@.d.:af//wwww.xxx.yn.zs...
`match` tries to match the **entire** string. Use `search` instead. The following pattern would then match your requirements: ``` m = re.search(r"//([^/]*)", str) print m.group(1) ``` Basically, we are looking for `/`, then consume as many non-slash characters as possible. And those non-slash characters will be captu...
Computing N Grams using Python
13,423,919
8
2012-11-16T20:26:35Z
13,424,002
12
2012-11-16T20:33:15Z
[ "python", "nlp", "nltk", "n-gram" ]
I needed to compute the Unigrams, BiGrams and Trigrams for a text file containing text like: "Cystic fibrosis affects 30,000 children and young adults in the US alone Inhaling the mists of salt water can reduce the pus and infection that fills the airways of cystic fibrosis sufferers, although side effects include a n...
Assuming input is a string contains space separated words, like `x = "a b c d"` you can use the following function (edit: see the last function for a possibly more complete solution): ``` def ngrams(input, n): input = input.split(' ') output = [] for i in range(len(input)-n+1): output.append(input[i:i+n]) ...
Computing N Grams using Python
13,423,919
8
2012-11-16T20:26:35Z
13,431,956
13
2012-11-17T15:26:00Z
[ "python", "nlp", "nltk", "n-gram" ]
I needed to compute the Unigrams, BiGrams and Trigrams for a text file containing text like: "Cystic fibrosis affects 30,000 children and young adults in the US alone Inhaling the mists of salt water can reduce the pus and infection that fills the airways of cystic fibrosis sufferers, although side effects include a n...
Use NLTK (the Natural Language Toolkit) and use the functions to tokenize (split) your text into a list and then find bigrams and trigrams. ``` import nltk words = nltk.word_tokenize(my_text) my_bigrams = nltk.bigrams(words) my_trigrams = nltk.trigrams(words) ```
Computing N Grams using Python
13,423,919
8
2012-11-16T20:26:35Z
30,609,050
11
2015-06-03T00:53:49Z
[ "python", "nlp", "nltk", "n-gram" ]
I needed to compute the Unigrams, BiGrams and Trigrams for a text file containing text like: "Cystic fibrosis affects 30,000 children and young adults in the US alone Inhaling the mists of salt water can reduce the pus and infection that fills the airways of cystic fibrosis sufferers, although side effects include a n...
A short Pythonesque solution from this [blog](http://locallyoptimal.com/blog/2013/01/20/elegant-n-gram-generation-in-python/): ``` def find_ngrams(input_list, n): return zip(*[input_list[i:] for i in range(n)]) ``` Usage: ``` >>> input_list = ['all', 'this', 'happened', 'more', 'or', 'less'] >>> find_ngrams(input_...
What does the object declaration mean in a python class, and should I use it?
13,424,365
4
2012-11-16T21:02:18Z
13,424,387
11
2012-11-16T21:04:17Z
[ "python", "oop", "inheritance" ]
# example #1: ``` class Person(object): pass ``` # example #2: ``` class Person: pass ``` What does the object declaration do? Should you use it? I have a bunch of programs with both of them and don't know the difference it is making. If anyone can explain this concept please.
In Python2, declaring `object` as the base class makes the class a [new-style class](http://www.python.org/doc/newstyle/). Otherwise, it is a "classic" class. Among the differences are that * Properties only work with new-style classes * new-style classes have the [`mro` method](http://www.python.org/download/releases...
Python sets and interesction
13,424,632
2
2012-11-16T21:25:35Z
13,424,658
10
2012-11-16T21:27:32Z
[ "python" ]
I am using Python 2.5.4. From here: [Python -Intersection of multiple lists?](http://stackoverflow.com/questions/3852780/python-intersection-of-multiple-lists) I have this: ``` def intersect(*d): sets = iter(map(set, d)) result = sets.next() for s in sets: result = result.intersection(s) retur...
You need to pass the *contents* of your list as separate parameters: ``` intersect(*d) ``` What happens otherwise is that the *whole* list is being used as one set instead. The `*d` syntax indicates to Python that you want to use `d` as a sequence of parameters to the function, instead using the whole `d` list as jus...
Exit gracefully if file doesn't exist
13,424,926
13
2012-11-16T21:49:23Z
13,425,279
9
2012-11-16T22:20:35Z
[ "python", "python-idle" ]
I have following script in Python 3.2.3: ``` try: file = open('file.txt', 'r') except IOError: print('There was an error opening the file!') sys.exit() #more code that is relevant only if the file exists ``` How do I exit gracefully, if the file doesn't exist (or there is simply an error opening it)? I ...
This is a very graceful way to do it. The SystemExit traceback won't be printed outside of IDLE. Optionally you can use `sys.exit(1)` to indicate to the shell that the script terminated with an error. Alternatively you could do this in your "main" function and use `return` to terminate the application: ``` def main()...
Does python have a "use strict;" and "use warnings;" like in perl?
13,425,715
38
2012-11-16T23:01:51Z
13,473,229
41
2012-11-20T12:28:07Z
[ "python", "perl", "warnings", "strict" ]
I am learning perl and python... at the same time, not my by design but it has to be done. Question: In a perl script I use(see below) at the head of my txt. ``` #!/usr/bin/env perl use strict; use warnings; ``` Is there something I should be doing on routine for my python scripts?
To provide an answer that perhaps avoids a little of the commentary noise here, I'll try another one. The two pragmata in your original question really expand to: ``` use strict "vars"; use strict "refs"; use strict "subs"; use warnings; ``` To answer each in turn: * The effect of `use strict "vars"` is to cause a ...
How do I assign a dictionary value to a variable in Python?
13,426,030
7
2012-11-16T23:42:08Z
13,426,080
10
2012-11-16T23:47:29Z
[ "python", "variables", "dictionary", "variable-assignment", "key-value" ]
I'm an amateur when it comes to programming, but I'm trying my hand at Python. Basically what I want to be able to do is use math on a dictionary value. The only way I could think to do it would be to assign a dictionary value to a variable, then assign the new value to the dictionary. Something like this: ``` my_dict...
There are various mistakes in your code. First you forgot the `=` in the first line. Additionally in a dict definition you have to use `:` to separate the keys from the values. Next thing is that you have to define `new_variable` first before you can add something to it. This will work: ``` my_dictionary = {'foo' : ...
Reading rows from a CSV file in Python
13,428,318
5
2012-11-17T06:32:36Z
13,428,432
19
2012-11-17T06:48:42Z
[ "python", "csv" ]
I have a CSV file, here is a sample of what it looks like: ``` Year: Dec: Jan: 1 50 60 2 25 50 3 30 30 4 40 20 5 10 10 ``` I know how to read the file in and print each column (for ex. - `['Year', '1', '2', '3', etc]`). But what I actually want to do is read the rows, which would b...
Use the [`csv` module](http://docs.python.org/2/library/csv.html): ``` import csv with open("test.csv", "rb") as f: reader = csv.reader(f, delimiter="\t") for i, line in enumerate(reader): print 'line[{}] = {}'.format(i, line) ``` Output: ``` line[0] = ['Year:', 'Dec:', 'Jan:'] line[1] = ['1', '50',...
Best way to make Flask-Login's login_required the default
13,428,708
17
2012-11-17T07:38:15Z
13,451,233
22
2012-11-19T09:48:43Z
[ "python", "flask" ]
Like this question: [Best way to make Django's login\_required the default](http://stackoverflow.com/questions/2164069/best-way-to-make-djangos-login-required-the-default) I'm using `Flask-Login`'s [login\_required](http://packages.python.org/Flask-Login/#flaskext.login.login_required) decorator now. Is there anyway t...
I did this in my [instruments](https://github.com/MalphasWats/instruments) project. I use the `before_request` decorator: ``` @app.before_request def check_valid_login(): login_valid = 'user' in session # or whatever you use to check valid login if (request.endpoint and 'static' not in request.endpoi...
Getting Github individual file contributors
13,430,769
6
2012-11-17T12:55:06Z
19,200,303
7
2013-10-05T16:57:01Z
[ "python", "github", "python-sphinx", "github-api" ]
I am planning to build a plug-in for Sphinx documentation system plug-in which shows the names and Github profile links of the persons who have contributed to the documentation page. Github has this feature internally ![Contributors](http://i.stack.imgur.com/ihjR4.png) * Is it possible to get Github profile links of...
First, you can [show the commits for a given file](http://stackoverflow.com/questions/15831313/is-it-possible-to-get-commits-history-for-one-file-in-github-api): ``` https://api.github.com/repos/:owner/:repo/commits?path=PATH_TO_FILE ``` For instance: <https://api.github.com/repos/git/git/commits?path=README> Secon...
How does python interpret numbers with leading zeroes
13,431,324
10
2012-11-17T14:07:11Z
13,431,333
17
2012-11-17T14:08:31Z
[ "python" ]
I'm new with python, I'm using python 2.7 when I typed this on python shell: ``` print 01 print 010 print 0100 print 01000 ``` It gives this result ``` 1 8 64 512 ``` I tried to understand why it gave that but unfortunately I didn't get the point.
If a number starts with `0`, it is interpreted as octal, or base 8. Just do: ``` print 1 print 10 print 100 print 1000 ``` And your problem will be solved. More on octal: <http://en.wikipedia.org/wiki/Octal> Here is a way to understand octal easier: > octal 1 is decimal (normal numbers) 1 > > octal 2 : decimal 2 >...
How does python interpret numbers with leading zeroes
13,431,324
10
2012-11-17T14:07:11Z
13,431,410
8
2012-11-17T14:18:56Z
[ "python" ]
I'm new with python, I'm using python 2.7 when I typed this on python shell: ``` print 01 print 010 print 0100 print 01000 ``` It gives this result ``` 1 8 64 512 ``` I tried to understand why it gave that but unfortunately I didn't get the point.
Python interprets a number starting with `0` as `octal` which is `base 8`.You can work out the base using the binary string `10` as `b^1 === b` where `b` is the base. ``` # print the decimal value of the binary number 10 >>> print 0b10 2 # print the decimal value of the octal number 10 >>> print 010 8 # print the ...
Extract form key value pairs form html page in python or parse html page
13,432,626
5
2012-11-17T16:53:27Z
13,432,766
7
2012-11-17T17:09:44Z
[ "python", "html", "string", "parsing", "html-parsing" ]
I want to extract key value pairs of some form elements in a html page for example ``` name="frmLogin" method="POST" onSubmit="javascript:return validateAndSubmit();" action="TG_cim_logon.asp?SID=^YcMunDFDQUoWV32WPUMqPxeSxD4L_slp_rhc_rNvW7Fagp7FgH3l0uJR/3_slp_rhc_dYyJ_slp_rhc_vsPW0kJl&RegType=Lite_Home" ``` while th...
Use a parsing library such as [lxml.html](http://lxml.de/lxmlhtml.html) for parsing html. The library will have a simple way for you to get what you need, probably not taking more than a few steps: 1. load the page using the parser 2. choose the form element to operate on 3. ask for the data you want Example code: ...
Enter Interactive Mode In Python
13,432,717
23
2012-11-17T17:04:34Z
13,432,747
27
2012-11-17T17:07:47Z
[ "python", "interactive" ]
I'm running my Python program and have a point where it would be useful to jump in and see what's going on, and then step out again. Sort of like a temporary console mode. In Matlab, I'd use the [`keyboard`](http://www.mathworks.com/help/matlab/ref/keyboard.html) command to do this, but I'm not sure what the command i...
``` python -i myapp.py ``` This will execute `myapp.py` and drop you in the interactive shell. From there you can execute functions and check their output, with the whole environment (imports, etc.) of `myapp.py` loaded. For something more sophisticated - it would be better to use a debugger like `pdb`, setting a bre...
Enter Interactive Mode In Python
13,432,717
23
2012-11-17T17:04:34Z
13,432,868
21
2012-11-17T17:22:08Z
[ "python", "interactive" ]
I'm running my Python program and have a point where it would be useful to jump in and see what's going on, and then step out again. Sort of like a temporary console mode. In Matlab, I'd use the [`keyboard`](http://www.mathworks.com/help/matlab/ref/keyboard.html) command to do this, but I'm not sure what the command i...
`code.interact()` seems to work somehow: ``` >>> import code >>> def foo(): ... a = 10 ... code.interact(local=locals()) ... return a ... >>> foo() Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (Interactiv...
Enter Interactive Mode In Python
13,432,717
23
2012-11-17T17:04:34Z
13,432,887
7
2012-11-17T17:23:55Z
[ "python", "interactive" ]
I'm running my Python program and have a point where it would be useful to jump in and see what's going on, and then step out again. Sort of like a temporary console mode. In Matlab, I'd use the [`keyboard`](http://www.mathworks.com/help/matlab/ref/keyboard.html) command to do this, but I'm not sure what the command i...
You have options -- Python standard library or IPython. The Python standard library has a [`code`](http://docs.python.org/2.7/library/code.html) module which has an [`InteractiveConsole`](http://docs.python.org/2.7/library/code.html#code.InteractiveConsole) class whose purpose is to "Closely emulate the behavior of th...
Enter Interactive Mode In Python
13,432,717
23
2012-11-17T17:04:34Z
13,433,246
9
2012-11-17T18:02:23Z
[ "python", "interactive" ]
I'm running my Python program and have a point where it would be useful to jump in and see what's going on, and then step out again. Sort of like a temporary console mode. In Matlab, I'd use the [`keyboard`](http://www.mathworks.com/help/matlab/ref/keyboard.html) command to do this, but I'm not sure what the command i...
I use [`pdb`](http://docs.python.org/2/library/pdb.html) for this purpose. I realize Emil already mentioned this in his answer, but he did not include an example or elaborate on why it answers your question. ``` for thing in set_of_things: import pdb; pdb.set_trace() do_stuff_to(thing) ``` You can read and se...
Does performance differs between Python or C++ coding of OpenCV?
13,432,800
34
2012-11-17T17:14:44Z
13,433,330
73
2012-11-17T18:12:23Z
[ "c++", "python", "performance", "opencv" ]
I aim to start opencv little by little but first I need to decide which API of OpenCV is more useful. I predict that Python implementation is shorter but running time will be more dense and slow compared to the native C++ implementations. Is there any know can comment about performance and coding differences between th...
As mentioned in earlier answers, Python is slower compared to C++ or C. Python is built for its simplicity, portability and moreover, creativity where users need to worry only about their algorithm, not programming troubles. But here in OpenCV, there is something different. Python-OpenCV is just a wrapper around the o...
How can I send strings of data to an XBee with a python library?
13,436,471
3
2012-11-18T01:01:16Z
13,436,562
7
2012-11-18T01:17:42Z
[ "python", "xbee" ]
Which library should I be using, and how? [Python XBee](http://code.google.com/p/python-xbee) seems to be only able to send commands in API mode, and I can't find an example of anyone using it to send a string. Maybe I'm misunderstanding what API mode is, but I can't find a payload in the documentation... Are [Digi's...
If the Xbee is connected to the computer as a serial device you can just use a serial library such as [`pySerial`](http://pyserial.sourceforge.net). Here are some code snippets from a project I just finished. ``` # Connect to Xbee self.ser = serial.Serial(port, baud, timeout=timeout) # Send data (a string) self.ser.w...
How to redirect JVM output without tear up output from the application?
13,436,520
18
2012-11-18T01:09:52Z
13,436,846
9
2012-11-18T02:09:44Z
[ "java", "python", "linux", "jvm" ]
Recently I am writing some micro-benchmark code, so I have to print out the JVM behaviors along with my benchmark information. I use ``` -XX:+PrintCompilation -XX:+PrintGCDetails ``` and other options to get the JVM status. For benchmark information, I simply use `System.out.print()` method. Because I need to know th...
I would suggest taking a slight detour and looking at using Java Instrumentation APIs - use (write) a simple **Java Agent** to do this. From your benchmarking perspective, this will give you far more power as well. You could use your Java Agent to log everything (and hence there would be no contention between different...
Display all jinja object attributes
13,436,841
9
2012-11-18T02:09:19Z
13,437,270
7
2012-11-18T03:43:14Z
[ "python", "jinja2", "hyde" ]
Is there a way to display the name/content/functions of all attributes of a given object in a jinja template. This would make it easier to debug a template that is not acting as expected. I am building a website using the `hyde` framework and this would come in quite handy since I am still learning the intricacies of ...
I think you can implement a filter yourself, for example: ``` from jinja2 import * def show_all_attrs(value): res = [] for k in dir(value): res.append('%r %r\n' % (k, getattr(value, k))) return '\n'.join(res) env = Environment() env.filters['show_all_attrs'] = show_all_attrs # using the filter t...
Getting id names with beautifulsoup
13,437,251
3
2012-11-18T03:41:02Z
13,437,437
8
2012-11-18T04:16:40Z
[ "python", "beautifulsoup" ]
If I had the text: ``` text = '<span id="foo"></span> <div id="bar"></div>' ``` with text that can change (that might not have any ids), how could I use BeautifulSoup to get the id names regardless of tag name(returning ['foo','bar']). I'm not that experienced to BeautifulSoup and have been confused on doing this tas...
You need to get tag with id attributes then return values of id attributes to string e.g. ``` from BeautifulSoup import BeautifulSoup text = '<span id="foo"></span> <div id="bar"></div>' pool = BeautifulSoup(text) result = [] for tag in pool.findAll(True,{'id':True}) : result.append(tag['id']) ``` and result ```...
Animating Network Growth with NetworkX and Matplotlib
13,437,284
12
2012-11-18T03:45:01Z
13,571,425
8
2012-11-26T19:08:28Z
[ "python", "animation", "matplotlib", "networkx" ]
I would like to animate a graph that grows over time. This is what I have so far: ``` fig = plt.figure() ims = [] graph = nx.Graph() for i in range(50): // Code to modify Graph nx.draw(graph, pos=nx.get_node_attributes(graph,'Position')) im = plt.draw() self.ims.append([im]) ani = animation.ArtistAnim...
Upon review, that code wasn't nearly as relevant to this problem as I'd thought. However, I was able to use [this SO answer](http://stackoverflow.com/questions/6686550/how-to-animate-a-time-ordered-sequence-of-matplotlib-plots) and [this SO answer](http://stackoverflow.com/questions/12822762/pylab-ion-in-python-2-matpl...
Animating Network Growth with NetworkX and Matplotlib
13,437,284
12
2012-11-18T03:45:01Z
13,891,839
7
2012-12-15T11:39:55Z
[ "python", "animation", "matplotlib", "networkx" ]
I would like to animate a graph that grows over time. This is what I have so far: ``` fig = plt.figure() ims = [] graph = nx.Graph() for i in range(50): // Code to modify Graph nx.draw(graph, pos=nx.get_node_attributes(graph,'Position')) im = plt.draw() self.ims.append([im]) ani = animation.ArtistAnim...
An improved version of bretlance's. Hope it will be helpful. It will show **animations** but not **picture after picture**. Still don't know how the owner of the question [Animate drawing networkx edges](http://stackoverflow.com/questions/13223191/animate-drawing-networkx-edges) made use of matplotlib's animation ```...
How to run Scrapy from within a Python script
13,437,402
23
2012-11-18T04:09:49Z
14,267,403
13
2013-01-10T21:16:36Z
[ "python", "web-scraping", "web-crawler", "scrapy" ]
I'm new to Scrapy and I'm looking for a way to run it from a Python script. I found 2 sources that explain this: <http://tryolabs.com/Blog/2011/09/27/calling-scrapy-python-script/> <http://snipplr.com/view/67006/using-scrapy-from-a-script/> I can't figure out where I should put my spider code and how to call it from...
Though I haven't tried it I think the answer can be found within the [scrapy documentation](http://scrapy.readthedocs.org/en/0.16/topics/practices.html). To quote directly from it: ``` from twisted.internet import reactor from scrapy.crawler import Crawler from scrapy.settings import Settings from scrapy import log fr...
How to run Scrapy from within a Python script
13,437,402
23
2012-11-18T04:09:49Z
19,060,578
12
2013-09-27T21:45:55Z
[ "python", "web-scraping", "web-crawler", "scrapy" ]
I'm new to Scrapy and I'm looking for a way to run it from a Python script. I found 2 sources that explain this: <http://tryolabs.com/Blog/2011/09/27/calling-scrapy-python-script/> <http://snipplr.com/view/67006/using-scrapy-from-a-script/> I can't figure out where I should put my spider code and how to call it from...
In scrapy 0.19.x you should do this: ``` from twisted.internet import reactor from scrapy.crawler import Crawler from scrapy import log, signals from testspiders.spiders.followall import FollowAllSpider from scrapy.utils.project import get_project_settings spider = FollowAllSpider(domain='scrapinghub.com') settings =...
How to run Scrapy from within a Python script
13,437,402
23
2012-11-18T04:09:49Z
27,242,187
7
2014-12-02T05:01:16Z
[ "python", "web-scraping", "web-crawler", "scrapy" ]
I'm new to Scrapy and I'm looking for a way to run it from a Python script. I found 2 sources that explain this: <http://tryolabs.com/Blog/2011/09/27/calling-scrapy-python-script/> <http://snipplr.com/view/67006/using-scrapy-from-a-script/> I can't figure out where I should put my spider code and how to call it from...
When there are multiple crawlers need to be run inside one python script, the reactor stop needs to be handled with caution as the reactor can only be stopped once and cannot be restarted. However, I found while doing my project that using ``` os.system("scrapy crawl yourspider") ``` is the easiest. This will save m...
How to run Scrapy from within a Python script
13,437,402
23
2012-11-18T04:09:49Z
31,374,345
10
2015-07-13T01:39:37Z
[ "python", "web-scraping", "web-crawler", "scrapy" ]
I'm new to Scrapy and I'm looking for a way to run it from a Python script. I found 2 sources that explain this: <http://tryolabs.com/Blog/2011/09/27/calling-scrapy-python-script/> <http://snipplr.com/view/67006/using-scrapy-from-a-script/> I can't figure out where I should put my spider code and how to call it from...
All other answers reference Scrapy v0.x. According to [the updated docs](http://doc.scrapy.org/en/1.0/topics/practices.html), Scrapy 1.0 demands: ``` import scrapy from scrapy.crawler import CrawlerProcess class MySpider(scrapy.Spider): # Your spider definition ... process = CrawlerProcess({ 'USER_AGENT'...
The volume of a sphere?
13,437,591
3
2012-11-18T04:48:29Z
13,437,609
8
2012-11-18T04:51:51Z
[ "python" ]
The volume of a sphere with radius r is 4/3 π r3. What is the volume of a sphere with radius 5? Hint: 392.6 is wrong! ``` print (((4/3.0) * 3.14) * 5**3) ``` It gave me this ``` 523.333333333 ``` what's wrong??? python 2.7
Nothing is wrong, you have the correct answer. You may want to use `math.pi` instead of 3.14 however to increase precision of your answer. ``` >>> from __future__ import division # not necessary if using python 3 >>> 4/3*math.pi*5**3 523.59877559829886 ``` See the solution at [wolfram alpha](http://www.wolframalpha.c...
Mysterious KeyError
13,437,687
2
2012-11-18T05:09:25Z
13,437,704
8
2012-11-18T05:14:09Z
[ "python" ]
I'm studying for my CS test right now and trying to write code to, given the entire IMDB database in plaintext, find the actors with the most films in common. I'm pretty much done, I just keep hitting a strange KeyError. Here's my code: ![enter image description here](http://i.stack.imgur.com/a6PHV.png) The problem I...
When you do `other_people = people_and_their_movies`, you're not making a copy. You're making `other_people` point to the same object that `people_and_their_movies` points to. So when you do `del other_people[actor1]`, you delete the actor from *both* dicts (because they are the same). Instead, do `other_people = peop...
Python - Write to Excel Spreadsheet
13,437,727
61
2012-11-18T05:20:53Z
13,437,772
47
2012-11-18T05:32:43Z
[ "python", "excel", "csv", "spreadsheet" ]
I am new to Python. I need to write some data from my program to a spreadsheet. I've searched online and there seems to be many packages available (xlwt, XlsXcessive, openpyxl). Others suggest to write to a csv file (never used csv & don't really understand what it is). The program is very simple. I have two lists (fl...
``` import xlwt def output(filename, sheet, list1, list2, x, y, z): book = xlwt.Workbook() sh = book.add_sheet(sheet) variables = [x, y, z] x_desc = 'Display' y_desc = 'Dominance' z_desc = 'Test' desc = [x_desc, y_desc, z_desc] col1_name = 'Stimulus Time' col2_name = 'Reaction Tim...
Python - Write to Excel Spreadsheet
13,437,727
61
2012-11-18T05:20:53Z
13,437,855
44
2012-11-18T05:51:44Z
[ "python", "excel", "csv", "spreadsheet" ]
I am new to Python. I need to write some data from my program to a spreadsheet. I've searched online and there seems to be many packages available (xlwt, XlsXcessive, openpyxl). Others suggest to write to a csv file (never used csv & don't really understand what it is). The program is very simple. I have two lists (fl...
Use [DataFrame.to\_excel](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_excel.html) from [pandas](https://github.com/pydata/pandas). Pandas allows you to represent your data in functionally rich datastructures and will let you [read in](http://pandas.pydata.org/pandas-docs/stable/io.html#excel-...
Python - Write to Excel Spreadsheet
13,437,727
61
2012-11-18T05:20:53Z
13,438,050
24
2012-11-18T06:37:34Z
[ "python", "excel", "csv", "spreadsheet" ]
I am new to Python. I need to write some data from my program to a spreadsheet. I've searched online and there seems to be many packages available (xlwt, XlsXcessive, openpyxl). Others suggest to write to a csv file (never used csv & don't really understand what it is). The program is very simple. I have two lists (fl...
* **xlrd/xlwt** (standard): Python does not have this functionality in it's standard library, but I think of [xlrd/xlwt](http://www.python-excel.org/) as the "standard" way to read and write excel files. It is fairly easy to make a workbook, add sheets, write data/formulas, and format cells. If you need all of these th...