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
TfidfVectorizer in sklearn how to specifically INCLUDE words
19,753,945
4
2013-11-03T14:19:46Z
19,754,197
14
2013-11-03T14:49:26Z
[ "python", "machine-learning", "nlp", "scikit-learn" ]
I have some questions about the `TfidfVectorizer`. It is unclear to me how the words are selected. We can give a minimum support, but after that, what will decide which features will be selected (e.g. higher support more chance)? If we say `max_features = 10000`, do we always get the same? If we say `max_features = 12...
You are asking several separate questions. Let me answer them separately: **"It is unclear to me how the words are selected."** From the [documentation](https://github.com/mbatchkarov/scikit-learn/blob/master/sklearn/feature_extraction/text.py): ``` max_features : optional, None by default If not None, build a v...
Flask app dont start on heroku server
19,754,262
4
2013-11-03T14:56:25Z
19,755,169
15
2013-11-03T16:30:46Z
[ "python", "heroku", "flask", "flask-restless" ]
I'm trying to deploy a Flask app with Heroku. It's simple API. Works great local with foreman but I get error (log is below) when starts on heroku. This is my app code (I know it's but looking in one block, but I have problems to split it to files): ``` import flask import flask.ext.sqlalchemy import flask.ext.restle...
Is there actually a running dyno called `web`? It looks like you might have forgotten to [scale your web dyno](https://devcenter.heroku.com/articles/error-codes#h14-no-web-dynos-running): Add an entry like this in your Procfile: ``` heroku ps:scale web=1 ``` You can use ``` heroku ps ``` to confirm that your `web`...
Keyboard shortcuts broken running interactive Python Console from a script
19,754,458
14
2013-11-03T15:14:48Z
19,754,609
33
2013-11-03T15:28:13Z
[ "python", "shell" ]
You can start an interactive console from inside a script with following code: ``` import code # do something here vars = globals() vars.update(locals()) shell = code.InteractiveConsole(vars) shell.interact() ``` When I run the script like so: ``` $ python my_script.py ``` an interactive console opens: ``` Pytho...
Check out [`readline`](http://docs.python.org/2/library/readline.html) and [`rlcompleter`](http://docs.python.org/2/library/rlcompleter.html): ``` import code import readline import rlcompleter # do something here vars = globals() vars.update(locals()) readline.set_completer(rlcompleter.Completer(vars).complete) rea...
How to Understand and Parse the Default Python Object Representations
19,754,918
4
2013-11-03T16:03:57Z
20,829,077
7
2013-12-29T19:16:12Z
[ "python", "built-in", "repr" ]
When you print an object in Python, and `__repr__` and `__str__` are not defined by the user, Python converts the objects to string representations, delimited with angle brackets... ``` <bound method Shell.clear of <Shell object at 0x112f6f350>> ``` The problem is rendering this in a web browser in strings that also ...
You can play with the `__builtin__`s (before importing anything). I found that replacing `__builtin__.repr` does *not* work, but replacing `__builtin__.object` does. Here's how it can be done. Say you have a module defining classes: ``` # foo.py class Foo(object): pass ``` In your *main* script, do: ``` # main....
Getting the difference (delta) between two lists of dictionaries
19,755,376
10
2013-11-03T16:51:11Z
19,755,445
18
2013-11-03T16:57:30Z
[ "python", "list", "dictionary", "delta" ]
I have the following Python data structures: ``` data1 = [{'name': u'String 1'}, {'name': u'String 2'}] data2 = [{'name': u'String 1'}, {'name': u'String 2'}, {'name': u'String 3'}] ``` I'm looking for the best way to get the delta between the two lists. Is there anything in Python that's as convenient as the JavaScr...
How about this: ``` >>> [x for x in data2 if x not in data1] [{'name': u'String 3'}] ``` **Edit**: If you need symmetric difference you can use : ``` >>> [x for x in data1 + data2 if x not in data1 or x not in data2] ``` or ``` >>> [x for x in data1 if x not in data2] + [y for y in data2 if y not in data1] ``` *...
Getting the difference (delta) between two lists of dictionaries
19,755,376
10
2013-11-03T16:51:11Z
19,755,464
10
2013-11-03T16:59:17Z
[ "python", "list", "dictionary", "delta" ]
I have the following Python data structures: ``` data1 = [{'name': u'String 1'}, {'name': u'String 2'}] data2 = [{'name': u'String 1'}, {'name': u'String 2'}, {'name': u'String 3'}] ``` I'm looking for the best way to get the delta between the two lists. Is there anything in Python that's as convenient as the JavaScr...
Use [`itertools.filterfalse`](http://docs.python.org/3.3/library/itertools.html#itertools.filterfalse): ``` import itertools r = list(itertools.filterfalse(lambda x: x in data1, data2)) + list(itertools.filterfalse(lambda x: x in data2, data1)) assert r == [{'name': 'String 3'}] ```
Python -- matplotlib elliptic curves
19,756,043
4
2013-11-03T17:54:56Z
19,757,132
9
2013-11-03T19:35:45Z
[ "python", "python-2.7", "matplotlib", "elliptic-curve", "finite-field" ]
I'm teaching myself about matplotlib and Python and I'm having a difficult time plotting an equation for an elliptic curve. I have the equation down but I'm not doing the `y^2` This is as much trouble as I was able to get myself into so far: ``` from mpl_toolkits.axes_grid.axislines import SubplotZero import matplotl...
Yes, you're right, you're not doing `y^2`. To plot elliptic curve in matplotlib I used this code (tested in Python 3): ``` import numpy as np import matplotlib.pyplot as plt def main(): a = -1 b = 1 y, x = np.ogrid[-5:5:100j, -5:5:100j] plt.contour(x.ravel(), y.ravel(), pow(y, 2) - pow(x, 3) - x * a ...
What's the Ruby equivalent of Python's defaultdict?
19,757,412
8
2013-11-03T20:00:24Z
19,757,540
14
2013-11-03T20:12:28Z
[ "python", "ruby", "hash", "dictionary", "autovivification" ]
In Python, I can make a hash where each element has a default value when it's first referenced (also know as "autovivification"). Here's an example: ``` from collections import defaultdict d = defaultdict(int) d["new_key"] += 1 print d ``` Printing the dict shows the value for "new\_key" is 1. What's the equivalent ...
You can assign a default value using [`default=`](http://ruby-doc.org/core-2.0.0/Hash.html#method-i-default-3D): ``` d.default = 0 ``` Note that this won't really autovivify though, it just makes `d[:new_key]` return a zero without actually adding a `:new_key` key. `default=` can also cause problems if you intend to ...
Pre-populating a BooleanField as checked (WTForms)
19,758,112
4
2013-11-03T21:04:25Z
19,758,464
7
2013-11-03T21:39:09Z
[ "python", "flask", "wtforms" ]
For the life of me, I can't figure out how to pre-populate a BooleanField with WTForms. I have a field called "active". It defaults to being not checked, and it's not required. So I set it up like... ``` class QuestionForm(Form): question = TextField('Question', [validators.Required()]) slug = TextField('Slug'...
If you have an object you can use it to populate your form like `form = QuestionForm(obj=my_obj)`. If you only want to set the active attribute use `form = QuestionForm(active=True)`.
python: rename single column header in pandas dataframe
19,758,364
57
2013-11-03T21:28:48Z
19,758,398
94
2013-11-03T21:32:01Z
[ "python", "pandas", "dataframe" ]
I've got a dataframe called `data`. How would I rename the only one column header? For example `gdp` to `log(gdp)`? ``` data = y gdp cap 0 1 2 5 1 2 3 9 2 8 7 2 3 3 4 7 4 6 7 7 5 4 8 3 6 8 2 8 7 9 9 10 8 6 6 4 9 10 10 7 ```
``` data.rename(columns={'gdp':'log(gdp)'}, inplace=True) ``` The [`rename`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html#pandas.DataFrame.rename) show that it accepts a dict as a param for `columns` so you just pass a dict with a single entry. Also see [related](http://stackover...
Convert a space delimited file to comma separated values file in python
19,759,423
5
2013-11-03T23:19:52Z
19,759,560
10
2013-11-03T23:35:03Z
[ "python", "csv", "numpy" ]
I am very new to Python. I know that this has already been asked, and I apologise, but the difference in this new situation is that spaces between strings are not equal. I have a file, named **coord**, that contains the following space delimited strings: ``` 1 C 6.00 0.000000000 1.342650315 0.000000...
You can use csv: ``` import csv with open(ur_infile) as fin, open(ur_outfile, 'w') as fout: o=csv.writer(fout) for line in fin: o.writerow(line.split()) ```
Does python have Matlab's `ans` variable that captures returned value not stored in any variable?
19,759,912
5
2013-11-04T00:20:45Z
19,759,926
8
2013-11-04T00:21:57Z
[ "python", "matlab" ]
If you are familiar with Matlab, there is a global variable `ans` that captures the first return value of a function that is not assigned to any particular variable. Is there any matching construct in Python?
You’re looking for `_`: ``` >>> 1+1 2 >>> _ 2 >>> def f(x): ... return x+1 ... >>> f(3) 4 >>> _ 4 ```
Resetting the expiration time for a cookie in Flask
19,760,486
7
2013-11-04T01:45:35Z
19,795,394
12
2013-11-05T17:46:03Z
[ "python", "session", "flask" ]
I'm using the the Python web framework Flask. I use sessions in my app. For my app called `main`, I've got the setting `main.permanent_session_lifetime = timedelta(days=5)`, so that a user will remain logged in for 5 days after logging in. But even an active user will be logged out after 5 days. I would like the expira...
You can renew the session to the client at each request using a `@before_request` handler. Try the following: ``` @app.before_request def func(): session.modified = True ```
How to use the reduce function on a list of tuples?
19,763,132
6
2013-11-04T07:09:39Z
19,763,148
9
2013-11-04T07:11:35Z
[ "python", "list", "tuples", "reduce" ]
I have this this list of tuple: ``` a = [(1, 2), (1, 4), (1, 6)] ``` I would like to use the reduce function in order to get this result: ``` (3, 12) ``` I tried: ``` x = reduce(lambda x, y: x+y, a) ``` But i get an error...I want to add up all the elements in the first index of each tuple, then add up the ...
If you want the output of a `reduce` to be a tuple, all the intermediate results should also be a tuple. ``` a = [(1, 2), (1, 4), (1, 6)] print reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), a) ``` **Output** ``` (3, 12) ``` **Edit:** If you want to get `(0, 0)` when the list is empty ``` a = [] print reduce(lamb...
Python script gives `: No such file or directory`
19,764,710
28
2013-11-04T09:23:14Z
19,765,741
46
2013-11-04T10:26:16Z
[ "python", "hashbang" ]
I have several python scripts which work just fine but one script has (as of this morning) started giving me this error if I try to run it from the bash: > : No such file or directory I am able to run the 'broken' script by doing `python script_name.py` and after looking around a bit the general idea that I picked up...
From the comments above it looks like you have dos line endings, and so the hashbang line is not properly processed. Line ending style are not shown with `:set list` in Vim because that option is only used when reading/writing the file. In memory line endings are always that, line-endings. The line ending style used f...
Cant send email via python using gmail - smtplib.SMTPException: SMTP AUTH extension not supported by server
19,765,073
2
2013-11-04T09:47:01Z
19,769,702
12
2013-11-04T14:19:43Z
[ "python", "email", "python-2.7", "smtp", "smtplib" ]
I just want to send an email in python with an attachment ``` import smtplib, os from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders def send_mail(send_from, send_to, subject, te...
You need a call to `starttls()` before you login: ``` smtp = smtplib.SMTP('smtp.gmail.com:587') smtp.starttls() smtp.login('[email protected]', 'fu') ``` Also, your `send_from` should be a `str`, not a `list`: ``` send_from='[email protected]' ``` Note that `smtp.starttls()` calls `smtp.ehlo()` implicitly: > If there has be...
Real time matplotlib plot is not working while still in a loop
19,766,100
5
2013-11-04T10:48:40Z
19,766,857
17
2013-11-04T11:34:04Z
[ "python", "matplotlib", "real-time" ]
I want to create a real time graph plotting program which takes input from serial port. Initially, I had tried a lot of code that posted on websites, but none of them worked. So, I decided to write code on my own by integrating pieces of code I've seen on the websites. But the problem is the graph will pop out only whe...
**Here is the solution add this `plt.pause(0.0001)` in your loop as below:** ``` import matplotlib.pyplot as plt import time import random from collections import deque import numpy as np # simulates input from serial port def random_gen(): while True: val = random.randint(1,10) yield val ...
Replacing Numpy elements if condition is met
19,766,757
6
2013-11-04T11:27:02Z
19,767,068
7
2013-11-04T11:45:58Z
[ "python", "arrays", "numpy", "conditional" ]
I have a large numpy array that I need to manipulate so that each element is changed to either a 1 or 0 if a condition is met (will be used as a pixel mask later). There are about 8 million elements in the array and my current method takes too long for the reduction pipeline: ``` for (y,x), value in numpy.ndenumerate(...
``` >>> import numpy as np >>> a = np.random.randint(0, 5, size=(5, 4)) >>> a array([[4, 2, 1, 1], [3, 0, 1, 2], [2, 0, 1, 1], [4, 0, 2, 3], [0, 0, 0, 2]]) >>> b = a < 3 >>> b array([[False, True, True, True], [False, True, True, True], [ True, True, True, True], ...
numpy loadtxt data type
19,767,190
4
2013-11-04T11:54:31Z
19,767,343
9
2013-11-04T12:02:36Z
[ "python", "numpy" ]
I am trying to load data set that looks like this: ``` Algeria,73.131000,6406.8166213983,0.1 Angola,51.093000,5519.1831786593,2 Argentina,75.901000,15741.0457726686,0.5 Armenia,74.241000,4748.9285847709,0.1 ``` etc. At the end, I will need only columns 1 and 2. I won't need country names and the last column. Essentia...
Check [numpy's](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html) documentation. ``` x, y = np.loadtxt(c, delimiter=',', usecols=(1, 2), unpack=True) ``` The `usecols` parameter should get your job done.
Django can't find libssl on OS X Mavericks
19,767,569
2
2013-11-04T12:15:59Z
27,529,847
10
2014-12-17T16:09:19Z
[ "python", "django", "osx", "postgresql" ]
I'm trying to get Django running on OS X Mavericks and I've encountered a bunch of errors along the way, the latest way being that when run`python manage.py runserver` to see if everything works, I get this error, which I believe means that it misses libssl: > ImportError: dlopen(/Library/Frameworks/Python.framework/V...
This worked for me. ``` brew unlink openssl && brew link openssl --force ``` This will recreate correctly all the links to libssl 1.0 which was already installed.
Python Assign value to variable during condition in while Loop
19,767,891
5
2013-11-04T12:39:00Z
19,767,911
13
2013-11-04T12:40:37Z
[ "python", "while-loop", "variable-assignment" ]
A simple question about Python syntax. I want to assign a value from a function to a variable during the condition for a while loop. When the value returned from the function is false, the loop should break. I know how to do it in PHP. ``` while (($data = fgetcsv($fh, 1000, ",")) !== FALSE) ``` However when I try a s...
You cannot use assignment in an expression. Assignment is itself a statement, and you cannot combine Python statements. This is an explicit choice made by the language designers; it is all too easy to accidentally use one `=` and assign, where you meant to use two `==` and test for equality. Move the assignment *into...
Python Assign value to variable during condition in while Loop
19,767,891
5
2013-11-04T12:39:00Z
19,767,980
8
2013-11-04T12:45:15Z
[ "python", "while-loop", "variable-assignment" ]
A simple question about Python syntax. I want to assign a value from a function to a variable during the condition for a while loop. When the value returned from the function is false, the loop should break. I know how to do it in PHP. ``` while (($data = fgetcsv($fh, 1000, ",")) !== FALSE) ``` However when I try a s...
You can't do that in Python, no assignment in expressions. At least that means you won't accidentally type == instead of = or the other way around and have it work. Traditional Python style is to just use while True and break: ``` while True: data = fgetcsv(fh, 1000, ",") if not data: break # Use ...
Unable to perform click action in selenium python
19,769,532
7
2013-11-04T14:11:30Z
19,786,501
7
2013-11-05T10:15:12Z
[ "python", "selenium", "javascript-events", "click" ]
I'm writing a test script using selenium in python. I have a web-page containing a tree-view object like this: ![enter image description here](http://i.stack.imgur.com/zOz6z.jpg) I want to traverse over the menu to go to the desired directory. Respective HTML code for plus/minus indications is this: ``` <a onclick="...
After some tries like `.execute_script("changeTree();")`, `.submit()`, etc, I have solved the issue by using the `ActionChains` class. Now, I can click in all elements that they have java-script events as `onclick`. The code that I have used is this: ``` from selenium import webdriver driver = webdriver.Firefox() driv...
Can't install discount with pip: error: command 'cc' failed with exit status 1
19,769,648
10
2013-11-04T14:17:17Z
22,470,165
21
2014-03-18T04:06:11Z
[ "python", "django", "virtualenv", "pip", "osx-mavericks" ]
I am running into many problems when trying to install the `discount` package on osx 10.9 Mavericks. I'm working with the django framework. My steps are (while having a virtualenv activated): ``` pip install discount ``` Then I get: ``` . . . 1 error generated. error: command 'cc' failed with exit status 1 -----...
Try: `sudo ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install discount` This seems to be an issue with LLVM in XCode 5.1 as mentioned here: [Can't install mysql gem on OS X](http://stackoverflow.com/questions/22312583/cant-install-mysql-gem-on-os-x)
Find index positions where 3D-array meets MULTIPLE conditions
19,770,361
5
2013-11-04T14:52:47Z
19,771,171
7
2013-11-04T15:32:16Z
[ "python", "arrays", "numpy" ]
I have a 3D-array consisting of several numbers within each band. Is there a function that returns the index positions where the array meets MULTIPLE conditions? I tried the following: ``` index_pos = numpy.where( array[:,:,0]==10 and array[:,:,1]==15 and array[:,:,2]==30) ``` It returns the error: ``` ValueErr...
You actually have a special case where it would be simpler and more efficient to do the following: Create the data: ``` >>> arr array([[[ 6, 9, 4], [ 5, 2, 1], [10, 15, 30]], [[ 9, 0, 1], [ 4, 6, 4], [ 8, 3, 9]], [[ 6, 7, 4], [ 0, 1, 6], [ ...
Why are named tuples always tracked by python's GC?
19,770,515
3
2013-11-04T15:00:03Z
19,771,538
7
2013-11-04T15:50:13Z
[ "python", "garbage-collection" ]
As we (or at least I) learned in [this answer](http://stackoverflow.com/questions/19391648/keeping-large-dictionary-in-python-affects-application-performance/19391867#19391867) simple tuples that only contain immutable values are not tracked by python's garbage collector, once it figures out that they can never be invo...
The only comment about this that I could find is in the `gcmodule.c` file of the Python sources: > **NOTE:** about untracking of mutable objects. > Certain types of container cannot participate in a reference cycle, and so do not need to be tracked by the garbage collector. > Untracking these objects reduces the cost ...
How to use unidecode in python (3.3)
19,771,751
6
2013-11-04T16:00:10Z
19,771,799
8
2013-11-04T16:02:30Z
[ "python", "unicode", "encoding" ]
I'm trying to remove all non-ascii characters from a text document. I found a package that should do just that, <https://pypi.python.org/pypi/Unidecode> It should accept a string and convert all non-ascii characters to the closest ascii character available. I used this same module in perl easily enough by just calling...
The `unidecode` module accepts *unicode* string values and *returns* a unicode string in Python 3. You are giving it binary data instead. Decode to unicode or open the input text file in textmode, and encode the result to ASCII before writing it to a file, or open the output text file in text mode. Quoting from the mo...
Django REST Framework Creating custom user
19,772,457
15
2013-11-04T16:37:17Z
19,806,796
9
2013-11-06T08:01:50Z
[ "python", "django", "django-models", "django-rest-framework" ]
I'm new in Django realm but see there is a lot of "magic" there. I'm using Django REST Framework and creating app that will allow free user registration. My user needs some additional fields that are not available in Django user. So I googled for extending User. There is an idea that this should be done by creating som...
Okay, a couple of things. You want to create a `OneToOneField` for your user model extension. ``` class MyUser(models.Model): user = models.OneToOneField(User) city = models.CharField(max_length=50, blank=True, default='') ``` Now, the power of Django Rest Framework, is you can build your serializer, to take ...
Django REST Framework Creating custom user
19,772,457
15
2013-11-04T16:37:17Z
26,622,292
8
2014-10-29T03:24:30Z
[ "python", "django", "django-models", "django-rest-framework" ]
I'm new in Django realm but see there is a lot of "magic" there. I'm using Django REST Framework and creating app that will allow free user registration. My user needs some additional fields that are not available in Django user. So I googled for extending User. There is an idea that this should be done by creating som...
So apparently I don't have enough reputation to post a comment under an answer. But to elaborate on what Kevin Stone described, if you model is something like the following: ``` class AppUser(models.Model): user = models.OneToOneField(User) ban_status = models.BooleanField(default=False) ``` You can do someth...
Flask-WTForms throws error for IntegerField instead of failing validation
19,772,494
2
2013-11-04T16:38:27Z
19,772,648
12
2013-11-04T16:45:28Z
[ "python", "flask", "wtforms", "flask-wtforms" ]
When I create a form using wtf\_forms and Flask-WTF and use the IntegerField input, I can't use it in combination with the Length validator If I remove the Length restriction then it works fine. Surely I should be able to apply a Length validation to an IntegerField? Python Code. ``` from flask_wtf import Form from ...
The error below means that you are trying to check the length of an integer which is not allowed by python. If you want to check length, then it must be a string. IntegerField() however by definition is an integer ``` object of type 'int' has no len() ``` You need to create something like below. NumberRange takes a r...
gevent: downside to spawning large number of greenlets?
19,772,530
12
2013-11-04T16:40:19Z
19,826,733
16
2013-11-07T02:11:55Z
[ "python", "limit", "gevent", "spawning" ]
Following on from my question in the comment to [this answer](http://stackoverflow.com/a/16433061/348501) to the question ["Gevent pool with nested web requests"](http://stackoverflow.com/q/15322701/348501): Assuming one has a large number of tasks, is there any downside to using gevent.spawn(...) to spawn all of them...
It's just cleaner and a good practice when dealing with a lot of stuff. I ran into this a few weeks ago I was using gevent spawn to verify a bunch of emails against DNS on the order of 30k :). ``` from gevent.pool import Pool import logging rows = [ ... a large list of stuff ...] CONCURRENCY = 200 # run 200 greenlets ...
Django many-to-many generic relationship
19,772,800
8
2013-11-04T16:52:41Z
19,822,118
8
2013-11-06T20:26:52Z
[ "python", "django", "django-models" ]
I think I need to create a 'many-to-many generic relationship'. I have two types of Participants: ``` class MemberParticipant(AbstractParticipant): class Meta: app_label = 'participants' class FriendParticipant(AbstractParticipant): """ Abstract participant common information shared for all rewa...
Your approach is exactly the right way to do it given your existing tables. While there's nothing official ([this discussion](http://python.6.x6.nabble.com/Generic-ManyToMany-Functionality-td476651.html), involving a core developer in 2007, appears not to have gone anywhere), I did find this [blog post](http://charlesl...
What's the maximum number of repetitions allowed in a Python regex?
19,773,621
12
2013-11-04T17:35:32Z
19,773,725
14
2013-11-04T17:41:36Z
[ "python", "regex" ]
In Python 2.7 and 3, the following works: ``` >>> re.search(r"a{1,9999}", 'aaa') <_sre.SRE_Match object at 0x1f5d100> ``` but this gives an error: ``` >>> re.search(r"a{1,99999}", 'aaa') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/re.py", line 142, in search...
A quick manual binary search revealed the answer, specifically 65535: ``` >>> re.search(r"a{1,65535}", 'aaa') <_sre.SRE_Match object at 0x2a9a68> >>> >>> re.search(r"a{1,65536}", 'aaa') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/7.3/l...
Python dictionary replace values
19,773,669
8
2013-11-04T17:37:59Z
19,773,721
12
2013-11-04T17:40:59Z
[ "python", "python-3.x", "dictionary" ]
I have a dictionary with 20 000 plus entries with at the moment simply the unique word and the number of times the word was used in the source text (Dante's Divine Comedy in Italian). I would like to work through all entries replacing the value with an actual definition as I find them. Is there a simple way to iterate...
You cannot select on specific values (or types of values). You'd either make a reverse index (map numbers back to (lists of) keys) or you have to loop through *all* values every time. If you are processing numbers in arbitrary order anyway, you may as well loop through all items: ``` for key, value in inputdict.items...
Django REST Framework - Separate permissions per methods
19,773,869
17
2013-11-04T17:48:48Z
19,784,496
21
2013-11-05T08:21:57Z
[ "python", "django", "rest", "permissions", "django-rest-framework" ]
I am writing an API using Django REST Framework and I am wondering if can specify permissions per method when using class based views. [Reading the documentation](http://django-rest-framework.org/api-guide/permissions.html#setting-the-permission-policy) I see that is quite easy to do if you are writing function based ...
Permissions are applied to the entire View class, but you can take into account aspects of the request (like the method such as GET or POST) in your authorization decision. See the built-in `IsAuthenticatedOrReadOnly` as an example: ``` SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class IsAuthenticatedOrReadOnly(BasePe...
Django REST Framework - Separate permissions per methods
19,773,869
17
2013-11-04T17:48:48Z
21,428,671
19
2014-01-29T10:45:33Z
[ "python", "django", "rest", "permissions", "django-rest-framework" ]
I am writing an API using Django REST Framework and I am wondering if can specify permissions per method when using class based views. [Reading the documentation](http://django-rest-framework.org/api-guide/permissions.html#setting-the-permission-policy) I see that is quite easy to do if you are writing function based ...
I've come across the same problem when using CBV's, as i have fairly complex permissions logic depending on the request method. The solution i came up with was to use the third party 'rest\_condition' app listed at the bottom of this page <http://www.django-rest-framework.org/api-guide/permissions> <https://github.c...
multiplying in a list python
19,774,581
4
2013-11-04T18:31:02Z
19,774,773
10
2013-11-04T18:43:09Z
[ "python", "list" ]
I am doing some homework and I am stuck. I supposed to write a code in Python 3, that reads a text file that is like a bill with an amount of numbers. I am supposed to write the code so it will calculate the total amount. I figured that a bill(simple example) will contain a number and the a prise. like: ``` 2 10$ 1 1...
The problem in your code is likely that you keep resetting `sums` for every number in the list. So you basically keep forgetting the sums you previously collected. The same applies to `start` and `nxt`. If you move these definition outside of the loop, and also fix the `summor.append(t)` to `sums.append(t)` it should a...
How to correctly implement the mapping protocol in Python?
19,775,685
5
2013-11-04T19:40:15Z
19,775,773
11
2013-11-04T19:45:10Z
[ "python" ]
I'm using python-spidermonkey, which internally uses PyMapping\_Check to identify if the object being used as a global (in rt.new\_context(global)) implements the mapping protocol. (This is basically a dictionary passed to python-spidermonkey so that javascript has limited access to python variables.) There's no offic...
The [`collections.abc`](http://docs.python.org/3.3/library/collections.abc.html#collections-abstract-base-classes) module defines the interfaces for things like `Mapping`, `Sequence`, and so on. By inheriting from the abstract base classes in that module, you get default implementations of some of the methods. So to b...
Use and meaning of "in" in an if statement in python
19,775,692
7
2013-11-04T19:40:43Z
19,775,766
22
2013-11-04T19:44:32Z
[ "python" ]
In an example from Zed Shaw's *Learn Python the Hard Way*, one of the exercises displays the following code: ``` next = raw_input("> ") if "0" in next or "1" in next: how_much = int(next) ``` I'm having a hard time understanding the meaning of "in" in this statement. I'm used to using if statements, such as in ja...
It depends on what `next` is. If it's a string (as in your example), then `in` checks for substrings. ``` >>> "in" in "indigo" True >>> "in" in "violet" False >>> "0" in "10" True >>> "1" in "10" True ``` If it's a different kind of iterable (list, tuple, dictionary...), then `in` checks for membership. ``` >>> "in...
Python range() and zip() object type
19,777,612
15
2013-11-04T21:36:14Z
19,777,642
14
2013-11-04T21:37:50Z
[ "python", "python-3.x", "iterator" ]
I understand how functions like `range()` and `zip()` can be used in a for loop. However I expected `range()` to output a list - much like `seq` in the unix shell. If I run the following code: ``` a=range(10) print(a) ``` The output is `range(10)`, suggesting it's not a list but a different type of object. `zip()` ha...
In Python 3.x., [`range`](http://docs.python.org/3.2/library/functions.html#range) returns a range object instead of a list like it did in Python 2.x. Similarly, [`zip`](http://docs.python.org/3.2/library/functions.html#zip) now returns a zip object instead of a list. To get these objects as lists, put them in [`list`...
Python range() and zip() object type
19,777,612
15
2013-11-04T21:36:14Z
19,777,643
28
2013-11-04T21:37:55Z
[ "python", "python-3.x", "iterator" ]
I understand how functions like `range()` and `zip()` can be used in a for loop. However I expected `range()` to output a list - much like `seq` in the unix shell. If I run the following code: ``` a=range(10) print(a) ``` The output is `range(10)`, suggesting it's not a list but a different type of object. `zip()` ha...
You must be using python 3. They used to behave as you were suggesting in python 2.x, but they were changed to [generator](https://wiki.python.org/moin/Generators)-like objects which produce the elements on demand rather than expand an entire list into memory. One advantage was greater efficiency in their typical use-...
How to detect end of file in Python after iterating the file object with "for" statement
19,778,322
4
2013-11-04T22:17:17Z
19,778,381
13
2013-11-04T22:20:43Z
[ "python" ]
I know to iterate a file line by line, I can use construct like this: ``` for line in file: do stuff ``` But if I also have a **break** statement somewhere inside the **for**, once I am out of the **for** block, how do I tell if it is the **break** that take me out of the **for** construct *OR* it is the because ...
you could use `for..else` ``` for line in f: if bar(line): break else: # will only be called if for loop terminates (all lines read) baz() ``` [source](http://psung.blogspot.com/2007/12/for-else-in-python.html) > the else suite is executed after the for, but only if the for > terminates normally (not by a ...
Django REST Framework serializer field required=false
19,780,731
19
2013-11-05T01:58:48Z
19,784,306
22
2013-11-05T08:09:35Z
[ "python", "django", "rest", "django-rest-framework" ]
from the documentation: > read\_only > Set this to True to ensure that the field is used when serializing a representation, but is not used when updating an instance during deserialization. > > Defaults to False > > required > Normally an error will be raised if a field is not supplied during deserialization. Set to f...
Yeah, I ran into this issue at some point as well. You need to also update the validation exclusions. ``` class FavoriteListSerializer(serializers.ModelSerializer): owner = serializers.IntegerField(required=False) class Meta: model = models.FavoriteList def get_validation_exclusions(self): ...
In a gevent appliction, how can I kill all greenlets that have been started?
19,780,869
7
2013-11-05T02:16:32Z
20,027,162
13
2013-11-17T04:22:58Z
[ "python", "gevent" ]
I have a gevent application that spawns multiple greenlets across multiple modules. I want to be able to gracefully shutdown the application (either internally or by catching `SIGTERM`, for instance), allowing greenlets to terminate nicely by catching `GreenletExit` and executing `finally:` clauses. If I had the a of ...
According to [another SO answer](http://stackoverflow.com/questions/12510648/in-gevent-how-can-i-dump-stack-traces-of-all-running-greenlets), it's possible "to iterate through all the objects on the heap and search for greenlets." So, I imagine this ought to work: ``` import gc import gevent from greenlet import green...
How do you remove the column name row from a pandas DataFrame?
19,781,609
6
2013-11-05T03:46:31Z
19,782,137
19
2013-11-05T04:55:42Z
[ "python", "pandas" ]
Say I import the following excel spreadsheet into a df ``` Val1 Val2 Val3 1 2 3 5 6 7 9 1 2 ``` How do I delete the column name row (in this case Val1, Val2, Val3) so that I can export a csv with no column names, just the data? I have tried df.drop and df.ix[1:] and have not been successful wi...
You can write to csv without the header using `header=False` and without the index using `index=False`. If desired, you also can modify the separator using `sep`. CSV example with no header row, omitting the header row: ``` df.to_csv('filename.csv', header=False) ``` TSV (tab-separated) example, omitting the index c...
How to stop/terminate a python script from running?
19,782,075
8
2013-11-05T04:46:46Z
19,782,093
10
2013-11-05T04:49:43Z
[ "python", "execution", "terminate", "termination" ]
I wrote a program in IDLE to tokenize text files and it starts to tokeniza 349 text files! How can I stop it? How can I stop a running Python program?
To stop your program, just press `Control` + `C`.
Creating a multiline graph using Vincent
19,783,064
2
2013-11-05T06:25:43Z
20,064,690
8
2013-11-19T06:28:56Z
[ "python", "pandas", "vega", "vincent" ]
I am attempting to create a multiline graph using Vincent. I have a csv file with the following layout: ``` ,wk1,wk2,wk3,wk4,wk5,wk6,wk7,wk8,wk9 Tom J,97,65,82,65,101,84,79,71,83 Lisa R,95,87,95,65,61,78,93,95,56 Rich F,51,111,50,119,84,77,73,84,60 Anne E,63,68,89,70,95,80,56,75,82 Dan M,83,95,36,115,79,79,65,55,69 M...
There are a couple issues here: the first is that Vincent (naively) assumes that line charts are going to take linear scales, when in this case we actual need an ordinal scale. The second issue is that the dataframe needs to be transposed so that the weeks are on the index. So, to get the plot you're looking for: ``` ...
Python: Remove exif info from images
19,786,301
5
2013-11-05T10:05:28Z
23,249,933
15
2014-04-23T16:14:09Z
[ "python", "image-processing", "python-imaging-library", "exif", "exiftool" ]
In order to reduce the size of images to be used in a website, I reduced the quality to 80-85%. This decreases the image size up to quite an extent. To reduce the size further without compromising the quality, my friend pointed out that raw images from camera have a lot of meta data called as exif info. Since there is...
``` import Image image_file = open('image_file.jpeg') image = Image.open(image_file) # next 3 lines strip exif data = list(image.getdata()) image_without_exif = Image.new(image.mode, image.size) image_without_exif.putdata(data) image_without_exif.save('image_file_without_exif.jpeg') ```
copy file, keep permissions and owner
19,787,348
11
2013-11-05T10:57:17Z
19,934,914
14
2013-11-12T16:43:13Z
[ "python", "file-permissions" ]
The docs of shutil tells me: > Even the higher-level file copying functions (shutil.copy(), shutil.copy2()) can’t copy all file metadata. On POSIX platforms, this means that file owner and group are lost as well as ACLs How can I keep the file owner and group if I need to copy a file in python? The process runs on...
You perhaps could use `os.stat` to get the `guid` and `uid` like in [this answer](http://stackoverflow.com/a/1861970/248065) and then reset the `uid` and `guid` after coping using [`os.chown`](http://docs.python.org/2/library/os#os.chown).
copy file, keep permissions and owner
19,787,348
11
2013-11-05T10:57:17Z
19,936,371
7
2013-11-12T17:51:58Z
[ "python", "file-permissions" ]
The docs of shutil tells me: > Even the higher-level file copying functions (shutil.copy(), shutil.copy2()) can’t copy all file metadata. On POSIX platforms, this means that file owner and group are lost as well as ACLs How can I keep the file owner and group if I need to copy a file in python? The process runs on...
You can use the `subprocess` module: ``` from subprocess import Popen p = Popen(['cp','-p','--preserve',src,dest]) p.wait() ```
Expanding English language contractions in Python
19,790,188
9
2013-11-05T13:32:22Z
19,790,352
11
2013-11-05T13:39:52Z
[ "python", "nlp", "nltk" ]
The English language has [a couple of contractions](http://en.wikipedia.org/wiki/Wikipedia%3aList_of_English_contractions). For instance: ``` you've -> you have he's -> he is ``` These can sometimes cause headache when you are doing natural language processing. Is there a Python library, which can expand these contra...
You don't need a library, it is possible to do with reg exp for example. ``` >>> import re >>> contractions_dict = { ... 'didn\'t': 'did not', ... 'don\'t': 'do not', ... } >>> contractions_re = re.compile('(%s)' % '|'.join(contractions_dict.keys())) >>> def expand_contractions(s, contractions_dict=contraction...
Expanding English language contractions in Python
19,790,188
9
2013-11-05T13:32:22Z
19,794,953
14
2013-11-05T17:20:48Z
[ "python", "nlp", "nltk" ]
The English language has [a couple of contractions](http://en.wikipedia.org/wiki/Wikipedia%3aList_of_English_contractions). For instance: ``` you've -> you have he's -> he is ``` These can sometimes cause headache when you are doing natural language processing. Is there a Python library, which can expand these contra...
I made that wikipedia contraction-to-expansion page into a python dictionary (see below) Note, as you might expect, that you definitely want to use double quotes when querying the dictionary: ![enter image description here](http://i.stack.imgur.com/1BeI3.png) Also, I've left multiple options in as in the wikipedia p...
Python Global Variable with thread
19,790,570
19
2013-11-05T13:50:46Z
19,790,803
29
2013-11-05T14:01:50Z
[ "python", "multithreading" ]
How do I share a global variable with thread? My Python code example is: ``` from threading import Thread import time a = 0 #global variable def thread1(threadname): #read variable "a" modify by thread 2 def thread2(threadname): while 1: a += 1 time.sleep(1) thread1 = Thread( target=thread...
You just need to declare `a` as a global in `thread2`, so that you aren't modifying an `a` that is local to that function. ``` def thread2(threadname): global a while True: a += 1 time.sleep(1) ``` In `thread1`, you don't need to do anything special, as long as you don't try to modify the valu...
Python Global Variable with thread
19,790,570
19
2013-11-05T13:50:46Z
19,790,994
17
2013-11-05T14:11:13Z
[ "python", "multithreading" ]
How do I share a global variable with thread? My Python code example is: ``` from threading import Thread import time a = 0 #global variable def thread1(threadname): #read variable "a" modify by thread 2 def thread2(threadname): while 1: a += 1 time.sleep(1) thread1 = Thread( target=thread...
In a function: ``` a += 1 ``` will be interpreted by the compiler as `assign to a => Create local variable a`, which is not what you want. It will probably fail with a `a not initialized` error since the (local) a has indeed not been initialized: ``` >>> a = 1 >>> def f(): ... a += 1 ... >>> f() Traceback (most...
Splitting dataframe into multiple dataframes
19,790,790
15
2013-11-05T14:01:13Z
19,791,302
17
2013-11-05T14:28:44Z
[ "python", "split", "pandas", "dataframe" ]
I have a very large dataframe (around 1 million rows) with data from an experiment (60 respondents). I would like to split the dataframe into 60 dataframes (a dataframe for each participant). In the dataframe (called = data) there is a variable called 'name' which is the unique code for each participant. I have tried...
Can I ask why not just do it by slicing the data frame. Something like ``` #create some data with Names column data = pd.DataFrame({'Names': ['Joe', 'John', 'Jasper', 'Jez'] *4, 'Ob1' : np.random.rand(16), 'Ob2' : np.random.rand(16)}) #create unique list of names UniqueNames = data.Names.unique() #create a data fram...
Splitting dataframe into multiple dataframes
19,790,790
15
2013-11-05T14:01:13Z
19,809,616
8
2013-11-06T10:29:02Z
[ "python", "split", "pandas", "dataframe" ]
I have a very large dataframe (around 1 million rows) with data from an experiment (60 respondents). I would like to split the dataframe into 60 dataframes (a dataframe for each participant). In the dataframe (called = data) there is a variable called 'name' which is the unique code for each participant. I have tried...
Firstly your approach is inefficient because the appending to the list on a row by basis will be slow as it has to periodically grow the list when there is insufficient space for the new entry, list comprehensions are better in this respect as the size is determined up front and allocated once. However, I think fundam...
numpy array to list conversion issue
19,791,223
4
2013-11-05T14:24:04Z
19,791,590
9
2013-11-05T14:41:55Z
[ "python", "arrays", "numpy" ]
For some reason, `evalRow(list(array([0, 1, 0, 0, 0])))` and `evalRow([0, 1, 0, 0, 0])` give different results. However if I use `magicConvert` (here to debug this) instead of `list` to go from numpy array to list it works as expected. Is this a bug in numpy? ``` def magicConvert(a): ss = str(list(a))[1:-1] return...
The difference in the behaviour is due to the fact that doing `list(some_array)` returns a list of `numpy.int64`, while, doing the conversion via the string representation (or equivalently using the `tolist()` method) returns a list of python's `int`s: ``` In [21]: import numpy as np In [22]: ar = np.array([1,2,3]) ...
How to use leastsq function from scipy.optimize in python to fit both a straight line and a quadratic line to data sets x and y
19,791,581
3
2013-11-05T14:41:33Z
28,242,456
7
2015-01-30T18:33:35Z
[ "python", "numpy", "scipy", "least-squares" ]
How would i fit a straight line and a quadratic to the data set below using the leastsq function from scipy.optimize? I know how to use polyfit to do it. But i need to use leastsq function. Here are the x and y data sets: x: 1.0,2.5,3.5,4.0,1.1,1.8,2.2,3.7 y: 6.008,15.722,27.130,33.772,5.257,9.549,11.098,28.828 Can...
The leastsq() method finds the set of parameters that minimize the error function ( difference between yExperimental and yFit). I used a tuple to pass the parameters and lambda functions for the linear and quadratic fits. leastsq starts from a first guess ( initial Tuple of parameters) and tries to minimize the error ...
Using the with statement in Python 2.5: SyntaxError?
19,791,640
4
2013-11-05T14:44:26Z
19,791,675
19
2013-11-05T14:46:23Z
[ "python", "syntax", "with-statement" ]
I have the following python code, its working fine with python 2.7, but I want to run it on python 2.5. I am new to Python, I tried to change the script multiple times, but i always I got syntax error. The code below throws a `SyntaxError: Invalid syntax`: ``` #!/usr/bin/env python import sys import re file = sys.ar...
Python 2.5 doesn't support the `with` statement yet. To use it in Python 2.5, you'll have to import it from `__future__`: ``` ## This shall be at the very top of your script ## from __future__ import with_statement ``` Or, as in the previous versions, you can do the procedure manually: ``` myfile = open(file) try: ...
Regex for removing data in parenthesis
19,794,051
6
2013-11-05T16:36:30Z
19,794,089
8
2013-11-05T16:38:20Z
[ "python", "regex", "python-2.7" ]
I'm trying to remove the parenthesis areas of these strings below, but I can't get a regex working :( ### Data: ``` x (LOC) ds ds (32C) d'ds ds (LeC) ds-d da(LOQ) 12345 (deC) ``` ### Regex tried: ``` [ \(\w+\)] ``` ### Regex101: <http://regex101.com/r/bD8fE2> ### Example code ``` items = ["x (LOC)", "ds ds (32C...
Remove the square brackets; you are not matching a character class: ``` item = re.sub(r" \(\w+\)", "", item) ``` Demo: ``` >>> items = ["x (LOC)", "ds ds (32C)", "d'ds ds (LeC)", "ds-d da(LOQ)", "12345 (deC)"] >>> for item in items: ... print re.sub(r" \(\w+\)", "", item) ... x ds ds d'ds ds ds-d da(LOQ) 12345 ...
Flask Python Buttons
19,794,695
10
2013-11-05T17:07:27Z
19,794,878
37
2013-11-05T17:16:59Z
[ "python", "html", "button", "flask" ]
Im trying to create two buttons on a page. Each one I would like to carry out a different python script on the server. So far I have only managed to get/collect one button using ``` def contact(): form = ContactForm() if request.method == 'POST': return 'Form posted.' elif request.method == 'GET': ret...
Give your two buttons the same name and different values: ``` <input type="submit" name="submit" value="Do Something"> <input type="submit" name="submit" value="Do Something Else"> ``` Then in your Flask view function you can tell which button was used to submit the form: ``` def contact(): if request.method == ...
Flask Python Buttons
19,794,695
10
2013-11-05T17:07:27Z
27,952,991
7
2015-01-14T21:42:58Z
[ "python", "html", "button", "flask" ]
Im trying to create two buttons on a page. Each one I would like to carry out a different python script on the server. So far I have only managed to get/collect one button using ``` def contact(): form = ContactForm() if request.method == 'POST': return 'Form posted.' elif request.method == 'GET': ret...
The appropriate way for doing this: Put `watch` and `download` buttons into your template. ``` @app.route('/') def index() if form.validate_on_submit(): if 'download' in request.form: pass elif 'watch' in request.form: pass ... etc ```
How to convert a list to jsonarray in python
19,795,012
11
2013-11-05T17:23:57Z
19,795,051
25
2013-11-05T17:25:26Z
[ "python", "json" ]
I have a row in following format: ``` row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]] ``` Now, what I want is to write the following in the file: ``` [1,[0.1,0.2],[[1234,1],[134,2]]] ``` Basically converting above into a jsonarray? Is there an inbuilt method, function in python to "dump" array into json array? Also not...
Use the [`json` module](http://docs.python.org/2/library/json.html) to produce JSON output: ``` import json with open(outputfilename, 'wb') as outfile: json.dump(row, outfile) ``` This writes the JSON result directly to the file (replacing any previous content if the file already existed). If you need the JSON ...
python string format calling a function
19,796,123
11
2013-11-05T18:29:31Z
19,797,066
10
2013-11-05T19:20:13Z
[ "python", "python-3.x", "format" ]
Is there a way to format with the new format syntax a string from a function call? for example: ``` "my request url was {0.get_full_path()}".format(request) ``` so it calls the function `get_full_path` function **inside** the string and not as a parameter in the format function. EDIT: Here is another example that wi...
Not sure if you can modify the object, but you could modify or wrap the object to make the functions properties. Then they would look like attributes, and you could do it as ``` class WrapperClass(originalRequest): @property def full_name(self): return super(WrapperClass, self).full_name() "{0.full_na...
supervisord for python 3?
19,796,883
17
2013-11-05T19:10:55Z
19,824,994
26
2013-11-06T23:23:36Z
[ "python", "python-3.x", "supervisord" ]
Want to use [supervisord](https://pypi.python.org/pypi/supervisor) to control the processes for my Python 3 project. It is specifically stated that "Supervisor is known to work with Python 2.4 or later but will not work under any version of Python 3". Any suggestions for supervisor replacement for Python 3?
The *upcoming* 4.0 release of Supervisord [will support Python 2 and 3](https://github.com/Supervisor/supervisor/issues/510) (3.2 and up). Until then, you could use the [`supervisor-py3k` fork](https://github.com/palmkevin/supervisor-py3k). Or simply run `supervisord` with Python 2; your Python 3 codebase is otherwise...
What is a self-written decorator (like @login_required) actually doing?
19,797,709
5
2013-11-05T19:55:07Z
19,799,538
12
2013-11-05T21:39:21Z
[ "python", "login", "flask", "wrap" ]
In my Flask-App, I have defined a view-function like this: ``` @app.route("/some/restricted/stuff") @login_required def main(): return render_template("overview.html", stuff = getstuff() ) ``` Where the decorator gets defined as: ``` def login_required(something): @wraps(something) ...
Welcome to Python! That's a lot of great questions. Let's take them one at a time. Also, just a point of fair warning. This topic makes your head spin for awhile before it all clicks together. For reference, here is your example decorator and function being decorated: ``` # Decorator Function def login_required(somet...
creating Matlab cell arrays in python
19,797,822
4
2013-11-05T20:01:18Z
19,799,062
7
2013-11-05T21:11:55Z
[ "python", "matlab", "scipy" ]
I'm trying to create a Matlab cell array in python and save it as a .mat file, but am running into problems when all the cells contain 2 values: ``` import scipy.io as sio twoValues = {'a': array([[array([[2, 2]]), array([[3, 3]])]])} sio.savemat('test.mat',twoValues) ``` In Matlab: ``` load('test.mat') >>> a a(:,...
When you do this: ``` a = np.array([[np.array([[2, 2]]), np.array([[3, 3]])]]) ``` the final call to `np.array` actually concatenates the inner two, so you get one array at the end: ``` >>> a array([[[[2, 2]], [[3, 3]]]]) >>> a.shape (1, 2, 1, 2) ``` But to mimic a [cell array](http://www.mathworks.com/he...
Convert pandas DataFrame to a nested dict
19,798,112
14
2013-11-05T20:17:41Z
19,900,276
17
2013-11-11T06:37:44Z
[ "python", "pandas" ]
I'm Looking for a generic way of turning a DataFrame to a nested dictionary This is a sample data frame ``` name v1 v2 v3 0 A A1 A11 1 1 A A2 A12 2 2 B B1 B12 3 3 C C1 C11 4 4 B B2 B21 5 5 A A2 A21 6 ``` The number of columns may differ and so does the c...
I don't understand why there isn't a `B2` in your dict. I'm also not sure what you want to happen in the case of repeated column values (every one except the last, I mean.) Assuming the first is an oversight, we could use recursion: ``` def recur_dictify(frame): if len(frame.columns) == 1: if frame.values....
Difference between map, applymap and apply methods in Pandas
19,798,153
114
2013-11-05T20:20:14Z
19,798,528
140
2013-11-05T20:40:33Z
[ "python", "numpy", "pandas", "vectorization" ]
Can you tell me when to use these vectorization methods with basic examples? I see that `map` is a `Series` method whereas the rest are `DataFrame` methods. I got confused about `apply` and `applymap` methods though. Why do we have two methods for applying a function to a DataFrame? Again, simple examples which illustr...
Straight from Wes McKinney's [Python for Data Analysis](http://shop.oreilly.com/product/0636920023784.do) book, pg. 132 (I highly recommended this book): > Another frequent operation is applying a function on 1D arrays to each column or row. DataFrame’s apply method does exactly this: ``` In [116]: frame = DataFram...
Difference between map, applymap and apply methods in Pandas
19,798,153
114
2013-11-05T20:20:14Z
20,687,887
7
2013-12-19T17:21:38Z
[ "python", "numpy", "pandas", "vectorization" ]
Can you tell me when to use these vectorization methods with basic examples? I see that `map` is a `Series` method whereas the rest are `DataFrame` methods. I got confused about `apply` and `applymap` methods though. Why do we have two methods for applying a function to a DataFrame? Again, simple examples which illustr...
@jeremiahbuddha mentioned that apply works on row/columns, while applymap works element-wise. But it seems you can still use apply for element-wise computation.... ``` frame.apply(np.sqrt) Out[102]: b d e Utah NaN 1.435159 NaN Ohio 1.098164 0.51059...
Python Pandas - how to do group by on a multiindex
19,798,229
3
2013-11-05T20:24:35Z
19,798,349
8
2013-11-05T20:31:39Z
[ "python", "pandas" ]
Below is my dataframe. I made some transformations to create the category col and dropped the original col is was derived. Now I need to do a group by to remove the dups e.g. Love and Fashion can be rolled up via a groupby sum. ``` df.colunms = array([category, clicks, revenue, date, impressions, size], dtype=object) ...
You can create the index on the existing dataframe. With the subset of data provided, this works for me: ``` import pandas df = pandas.DataFrame.from_dict( { 'category': {0: 'Love', 1: 'Love', 2: 'Fashion', 3: 'Fashion', 4: 'Hair', 5: 'Movies', 6: 'Movies', 7: 'Health', 8: 'Health', 9: 'Celebs', 10: 'Celebs',...
Unable to parse TAB in JSON files
19,799,006
16
2013-11-05T21:09:05Z
19,799,355
24
2013-11-05T21:29:07Z
[ "python", "json" ]
I am running into a parsing problem when loading JSON files that seem to have the **TAB** character in them. When I go to <http://jsonlint.com/>, and I enter the part with the TAB character: ``` { "My_String": "Foo bar. Bar foo." } ``` The validator complains with: ``` Parse error on line 2: { "My_String": ...
From [JSON standard](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf): > Insignificant whitespace is allowed before or after any token. The > whitespace characters are: character tabulation (U+0009), line feed > (U+000A), carriage return (U+000D), and space (U+0020). Whitespace is > not allow...
Leaving values blank if not passed in str.format
19,799,609
10
2013-11-05T21:43:16Z
19,799,784
10
2013-11-05T21:52:45Z
[ "python" ]
I've run into a fairly simple issue that I can't come up with an elegant solution for. I'm creating a string using `str.format` in a function that is passed in a `dict` of substitutions to use for the format. I want to create the string and format it with the values if they're passed and leave them blank otherwise. E...
Here is one option which uses [`collections.defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict): ``` >>> from collections import defaultdict >>> kwargs = {"name": "mark"} >>> template = "My name is {0[name]} and I'm really {0[adjective]}." >>> template.format(defaultdict(str, kwarg...
Leaving values blank if not passed in str.format
19,799,609
10
2013-11-05T21:43:16Z
19,800,610
12
2013-11-05T22:47:52Z
[ "python" ]
I've run into a fairly simple issue that I can't come up with an elegant solution for. I'm creating a string using `str.format` in a function that is passed in a `dict` of substitutions to use for the format. I want to create the string and format it with the values if they're passed and leave them blank otherwise. E...
You can follow the recommendation in [PEP 3101](http://www.python.org/dev/peps/pep-3101/) and subclass Formatter: ``` import string class BlankFormatter(string.Formatter): def __init__(self, default=''): self.default=default def get_value(self, key, args, kwds): if isinstance(key, str): ...
Convert datetime to Unix timestamp and convert it back in python
19,801,727
58
2013-11-06T00:19:14Z
19,801,806
34
2013-11-06T00:27:09Z
[ "python", "datetime", "timestamp" ]
I have `dt = datetime(2013,9,1,11)`, and I would like to get a Unix timestamp of this datetime object. When I do `dt - datetime(1970,1,1)).total_seconds()` I got the timestamp `1378033200`. When converting it back using `datetime.fromtimestamp` I got `datetime.datetime(2013, 9, 1, 6, 0)`. The hour doesn't match. Wha...
What you missed here is timezones. Presumably you've five hours off UTC, so 2013-09-01T11:00:00 local and 2013-09-01T06:00:00Z are the same time. You need to read the top of the [`datetime`](http://docs.python.org/3.3/library/datetime.html) docs, which explain about timezones and "naive" and "aware" objects. If your...
Convert datetime to Unix timestamp and convert it back in python
19,801,727
58
2013-11-06T00:19:14Z
19,801,863
34
2013-11-06T00:32:51Z
[ "python", "datetime", "timestamp" ]
I have `dt = datetime(2013,9,1,11)`, and I would like to get a Unix timestamp of this datetime object. When I do `dt - datetime(1970,1,1)).total_seconds()` I got the timestamp `1378033200`. When converting it back using `datetime.fromtimestamp` I got `datetime.datetime(2013, 9, 1, 6, 0)`. The hour doesn't match. Wha...
Rather than this expression to create a POSIX timestamp from `dt`, ``` (dt - datetime(1970,1,1)).total_seconds() ``` Use this: ``` int(dt.strftime("%s")) ``` I get the right answer in your example using the second method. EDIT: Some followup... After some comments (see below), I was curious about the lack of suppo...
Convert datetime to Unix timestamp and convert it back in python
19,801,727
58
2013-11-06T00:19:14Z
27,914,405
50
2015-01-13T03:21:47Z
[ "python", "datetime", "timestamp" ]
I have `dt = datetime(2013,9,1,11)`, and I would like to get a Unix timestamp of this datetime object. When I do `dt - datetime(1970,1,1)).total_seconds()` I got the timestamp `1378033200`. When converting it back using `datetime.fromtimestamp` I got `datetime.datetime(2013, 9, 1, 6, 0)`. The hour doesn't match. Wha...
**solution is** ``` import time import datetime d = datetime.date(2015,1,5) unixtime = time.mktime(d.timetuple()) ```
How can I do the following comparison without having to write 20 if-statements or making 20 lists/dictionaries?
19,802,024
4
2013-11-06T00:50:20Z
19,802,070
11
2013-11-06T00:55:43Z
[ "python", "list", "dictionary" ]
This problem is related to biology, so for those who know what amino acids and codons are, that's great! For those who don't, I have tried my best to phrase it so that you can understand what I am talking about. So I have a list of codons, also can be called 3-letter strings, that are composed of a combination of the ...
You can set a dictionary up like this: ``` codon_lookup = { 'ATT':'Isoleucine', 'ATC':'Isoleucine', 'ATA':'Isoleucine', 'CTT':'Leucine', 'CTC':'Leucine', 'CTA':'Leucine', # ... etc } ``` then you can make queries like ``` codon_lookup['ATT'] ``` Which will give you ``` 'Isoleucine' `...
emacs Flycheck "Configured syntax checker python-flake8 cannot be used"
19,803,033
5
2013-11-06T02:35:00Z
19,814,036
10
2013-11-06T13:58:44Z
[ "python", "osx", "emacs", "homebrew", "flycheck" ]
New emacs/python user here. I'm trying to set up `flycheck` to work (and use `flake8`). This is the relevant part in my `init.el`: ``` (require 'python-mode) (add-to-list 'auto-mode-alist '("\\.py$" . python-mode)) (add-hook 'python-mode-hook 'flycheck-mode) ``` When I open a `python` file my modeline includes `Py...
Do `M-: (executable-find "flake8")`. If it says `nil`, add `/usr/local/bin` to your `exec-path`. On OS X GUI applications do not inherit variables from the shell configuration and thus have a different `$PATH`. Hence, being able to run `flake8` in the terminal doesn't imply, that Emacs is able to find it as well. You...
Python Optional Argument Pair
19,805,170
5
2013-11-06T06:01:28Z
19,817,681
8
2013-11-06T16:40:30Z
[ "python", "argparse" ]
I'm using the `argparse` module to get two optional command line arguments: ``` parser.add_argument('start_date', nargs='?', metavar='START DATE', help='start date in YYYY-MM-DD') parser.add_argument('end_date', nargs='?', metavar='END DATE', help='end date in YYYY-MM-DD') ``` wh...
The closest I can come up with is: ``` parser=argparse.ArgumentParser() parser.add_argument('--dates', nargs=2, metavar=('START DATE','END_DATE'), help='start date and end date in YYYY-MM-DD') print(parser.format_help()) ``` which produces ``` usage: stock19805170.py [-h] [--dates START DATE END_D...
Python sub process Ctrl+C
19,807,134
19
2013-11-06T08:25:51Z
19,807,536
13
2013-11-06T08:49:37Z
[ "python" ]
Given the following code: ``` try: subprocess.Popen(ExternalProcess, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True).communicate() except KeyboardInterrupt: exit(0) ``` If during the execution of `ExternalProcess`(which is not a python script) one presses the `Ctrl`+`C` command, what exactly is going o...
As far as I understand, once you fork/exec a process, it inherits the parent's [process group](http://en.wikipedia.org/wiki/Process_group). That means, that `SIGINT` (which is the result of `Ctrl+C` and the cause of `KeyboardInterrupt`) will be sent to both the child and the parent. Here is an example: File `a.py`: ...
django admin inline many to many custom fields
19,807,757
8
2013-11-06T09:03:45Z
21,570,815
14
2014-02-05T07:12:45Z
[ "python", "django", "django-forms", "django-admin", "django-1.5" ]
Hi I am trying to customize my inlines in django admin. Here are my models: ``` class Row(models.Model): name = models.CharField(max_length=255) class Table(models.Model): rows = models.ManyToManyField(Row, blank=True) name = models.CharField(max_length=255) def __unicode__(self): return sel...
``` class RowInline(admin.TabularInline): model = Table.rows.through fields = ['name'] ``` This presents a problem because Table.rows.through represents an intermediate model. If you would like to understand this better have a look at your database. You'll see an intermediate table which references this model....
finding duplicates in a list of lists
19,811,418
22
2013-11-06T11:51:28Z
19,811,505
10
2013-11-06T11:55:16Z
[ "python", "list", "python-2.7" ]
I am using Python 2.7 and am trying to de-duplicate a list of lists and merge the values of the duplicates. Right now I have: ``` original_list = [['a', 1], ['b', 1], ['a', 1], ['b', 1], ['b', 2], ['c', 2], ['b', 3]] ``` I want to match on the first element of each nested list and then add the values of the second e...
If the order doesnt matter, you can use this ``` original_list = [['a', 1], ['b', 1], ['a', 1], ['b', 1], ['b', 2], ['c', 2], ['b', 3]] myDict = {} for first, second in original_list: myDict[first] = myDict.get(first, 0) + second result = [[key, value] for key, value in myDict.items()] print result ``` Or you can...
finding duplicates in a list of lists
19,811,418
22
2013-11-06T11:51:28Z
19,811,538
14
2013-11-06T11:57:27Z
[ "python", "list", "python-2.7" ]
I am using Python 2.7 and am trying to de-duplicate a list of lists and merge the values of the duplicates. Right now I have: ``` original_list = [['a', 1], ['b', 1], ['a', 1], ['b', 1], ['b', 2], ['c', 2], ['b', 3]] ``` I want to match on the first element of each nested list and then add the values of the second e...
``` >>> from collections import Counter >>> lst = [['a', 1], ['b', 1], ['a', 1], ['b', 1], ['b', 2], ['c', 2], ['b', 3]] >>> c = Counter(x for x, c in lst for _ in xrange(c)) Counter({'b': 7, 'a': 2, 'c': 2}) >>> map(list, c.iteritems()) [['a', 2], ['c', 2], ['b', 7]] ``` Or alternatively, without repeating each ite...
finding duplicates in a list of lists
19,811,418
22
2013-11-06T11:51:28Z
19,811,554
13
2013-11-06T11:58:28Z
[ "python", "list", "python-2.7" ]
I am using Python 2.7 and am trying to de-duplicate a list of lists and merge the values of the duplicates. Right now I have: ``` original_list = [['a', 1], ['b', 1], ['a', 1], ['b', 1], ['b', 2], ['c', 2], ['b', 3]] ``` I want to match on the first element of each nested list and then add the values of the second e...
## SOLUTION Use `collections.Counter`: ``` from collections import Counter original_list = [['a', 1], ['b', 1], ['a', 1], ['b', 1], ['b', 2], ['c', 2], ['b', 3]] result = Counter() for k, v in original_list: result.update({k:v}) map(list, result.items()) # [['a', 2], ['c', 2], ['b', 7]] ``` ## FINDINGS So, lo...
finding duplicates in a list of lists
19,811,418
22
2013-11-06T11:51:28Z
19,811,646
27
2013-11-06T12:02:56Z
[ "python", "list", "python-2.7" ]
I am using Python 2.7 and am trying to de-duplicate a list of lists and merge the values of the duplicates. Right now I have: ``` original_list = [['a', 1], ['b', 1], ['a', 1], ['b', 1], ['b', 2], ['c', 2], ['b', 3]] ``` I want to match on the first element of each nested list and then add the values of the second e...
Lots of good answers, but they all use rather more code than I would for this, so here's my take, for what it's worth: ``` totals = {} for k,v in original_list: totals[k] = totals.get(k,0) + v # totals = {'a': 2, 'c': 2, 'b': 7} ``` Once you have a dict like that, from any of these answers, you can use `items` to ...
How to mock a decorated function
19,812,570
10
2013-11-06T12:50:10Z
19,812,961
9
2013-11-06T13:09:44Z
[ "python", "unit-testing", "mocking", "decorator", "monkeypatching" ]
For testing reasons, I need to be able to mock the inner/original function of a decorated one which is used somewhere else: In mydecorator.py: ``` def my_decorator(f): def wrapped_f(): print "decorated" f() return wrapped_f @my_decorator def function_to_be_mocked(): print 'original' de...
Python applies the decorator when loading the module so setting `function_to_be_mocked` to `mock_function` in `test_decoratorated_mocked` would indeed change that function into an undecorated function. You'd need to manually add the decorator again if you wish to mock `function_to_be_mocked`: ``` mydecorator.function...
Disable ipython console in pycharm
19,814,560
8
2013-11-06T14:22:48Z
24,925,478
10
2014-07-24T05:02:09Z
[ "python", "ide", "ipython", "pycharm" ]
I use the PyCharm community edition and also ipython. PyCharm automatically recognizes ipython and sets it as the default console ([PyCharm webhelp link](http://www.jetbrains.com/pycharm/webhelp/ipython.html)), so when in debugging mode, it accepts to runs ipython magic commands, like `list?` or `ls` or `%timeit`. It ...
Go in `File --> Default Settings`, click `console` , Uncheck `Use IPython, if available` then go in `File --> Settings`, uncheck `Use IPython, if available` `Default Settings` and `Settings` are two different options in `File` menu so make sure to follow both **i am using PyCharm version 3.4 and after doing both the...
Converting binary file into PIL Image datatype in Google App Engine
19,816,033
2
2013-11-06T15:27:25Z
19,816,086
7
2013-11-06T15:29:56Z
[ "python", "html", "image", "google-app-engine", "python-imaging-library" ]
I am using Google App Engine with Python and Jinja for the templates. In my HTML template, I have this piece of code, which allows the user to choose a file (Image): ``` <form action="/step2" enctype="multipart/form-data" method="post"> <input type="file" name="datafile" size="40"> <input type="sub...
Put the string in a `StringIO` object: ``` from cStringIO import StringIO imgfile = StringIO(self.request.get('datafile')) img = Image.open(imgfile) ``` All PIL needs is a file-like object; `StringIO` provides this source the actual data from the given string. In the other direction, have `PIL` write to a `StringIO...
no acceptable C compiler found in $PATH when installing python
19,816,275
60
2013-11-06T15:38:19Z
19,816,363
22
2013-11-06T15:42:07Z
[ "python", "compiler-errors", "virtualenv" ]
I'm trying to install new python environment on my shared hosting. I follow the steps written in [this post](http://stackoverflow.com/questions/1534210/use-different-python-version-with-virtualenv): ``` mkdir ~/src wget http://www.python.org/ftp/python/2.7.1/Python-2.7.1.tgz tar -zxvf Python-2.7.1.tar.gz cd Python-2.7...
You will need to run ``` sudo apt-get install build-essential ``` first assuming you're on a debain/ubuntu system
no acceptable C compiler found in $PATH when installing python
19,816,275
60
2013-11-06T15:38:19Z
19,816,655
141
2013-11-06T15:54:48Z
[ "python", "compiler-errors", "virtualenv" ]
I'm trying to install new python environment on my shared hosting. I follow the steps written in [this post](http://stackoverflow.com/questions/1534210/use-different-python-version-with-virtualenv): ``` mkdir ~/src wget http://www.python.org/ftp/python/2.7.1/Python-2.7.1.tgz tar -zxvf Python-2.7.1.tar.gz cd Python-2.7...
gcc compiler is not in your `$PATH` it means either you dont have gcc installed or it's not in your $PATH variable to install gcc use this: (run as root) redhat base: ``` yum groupinstall "Development tools" ``` Debian base: ``` apt-get install build-essential ```
no acceptable C compiler found in $PATH when installing python
19,816,275
60
2013-11-06T15:38:19Z
23,250,453
38
2014-04-23T16:40:43Z
[ "python", "compiler-errors", "virtualenv" ]
I'm trying to install new python environment on my shared hosting. I follow the steps written in [this post](http://stackoverflow.com/questions/1534210/use-different-python-version-with-virtualenv): ``` mkdir ~/src wget http://www.python.org/ftp/python/2.7.1/Python-2.7.1.tgz tar -zxvf Python-2.7.1.tar.gz cd Python-2.7...
you need to run ``` yum install gcc ```
no acceptable C compiler found in $PATH when installing python
19,816,275
60
2013-11-06T15:38:19Z
31,246,388
20
2015-07-06T12:51:52Z
[ "python", "compiler-errors", "virtualenv" ]
I'm trying to install new python environment on my shared hosting. I follow the steps written in [this post](http://stackoverflow.com/questions/1534210/use-different-python-version-with-virtualenv): ``` mkdir ~/src wget http://www.python.org/ftp/python/2.7.1/Python-2.7.1.tgz tar -zxvf Python-2.7.1.tar.gz cd Python-2.7...
**for Ubuntu / Debian :** ``` # sudo apt-get install build-essential ``` **For RHEL/CentOS** ``` #rpm -qa | grep gcc # yum install gcc glibc glibc-common gd gd-devel -y ``` or ``` # yum groupinstall "Development tools" -y ``` More details refer the [link](http://thelinuxfaq.com/74-error-no-acceptable-c-compiler-...
How to retrieve colorbar instance from figure in matplotlib
19,816,820
8
2013-11-06T16:00:49Z
19,817,573
7
2013-11-06T16:36:13Z
[ "python", "matplotlib", "colorbar" ]
all. I want to update the colorbar of a figure when the imagedata is changed. So something like: ``` img = misc.lena() fig = plt.figure() ax = plt.imshow(im) plt.colorbar(ax) newimg = img+10*np.randn(512,512) def update_colorbar(fig,ax,newimg): cbar = fig.axes[1] ax.set_data(newimg) cbar.update_normal(ax)...
First off, I think you're getting a bit confused between the axes (basically, the plot), the figure, the scalar mappable (the image, in this case), and the colorbar instance. The `figure` is the window that the plot is in. It's the top-level container. Each figure usually has one or more `axes`. These are the plots/s...
Django error: TypeError: 'NoneType' object has no attribute '__getitem__'
19,816,994
4
2013-11-06T16:08:45Z
19,817,028
13
2013-11-06T16:10:29Z
[ "python", "django" ]
Using Django (new to it and new to Python in general) to do a very basic contacts database. Trying to add a record via the Admin pages to a Contributor table, the model code for which is: ``` class Contributor(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length...
You're printing in your `__unicode__` method, instead of returning the string.
Extract row with maximum value in a group pandas dataframe
19,818,756
12
2013-11-06T17:30:08Z
19,818,942
19
2013-11-06T17:40:10Z
[ "python", "pandas" ]
A similar question is asked here: [Python : How can I get the Row which has the max value in goups making groupby?](http://stackoverflow.com/questions/15705630/python-how-can-i-get-the-row-which-has-the-max-value-in-goups-making-groupby) However, I just need one record per group even if there are more than one record ...
You can use `first` ``` In [14]: df.groupby('Mt').first() Out[14]: Sp Value count Mt s1 a 1 3 s2 c 3 5 s3 f 6 6 ``` # Update Set `as_index=False` to achieve your goal ``` In [28]: df.groupby('Mt', as_index=False).first() Out[28]: Mt Sp Value count 0 s1 ...
Extract row with maximum value in a group pandas dataframe
19,818,756
12
2013-11-06T17:30:08Z
19,819,118
11
2013-11-06T17:48:19Z
[ "python", "pandas" ]
A similar question is asked here: [Python : How can I get the Row which has the max value in goups making groupby?](http://stackoverflow.com/questions/15705630/python-how-can-i-get-the-row-which-has-the-max-value-in-goups-making-groupby) However, I just need one record per group even if there are more than one record ...
To get first occurence of maximum `count` you can use [pandas.DataFrame.idxmax()](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.idxmax.html) function: ``` >>> df.iloc[df.groupby(['Mt']).apply(lambda x: x['count'].idxmax())] Mt Sp Value count 0 s1 a 1 3 3 s2 d 4 10 5 s...
Converting hex to int in python
19,819,863
5
2013-11-06T18:28:19Z
19,819,883
19
2013-11-06T18:29:12Z
[ "python", "hex", "ascii" ]
I am reading in 8-bit values from an ADC over USB to my computer. A python script runs on my computer and continuously displays the 8-bit values, which are in hex form. However, when the hex code corresponds to an ASCII code, python will display the ASCII character instead of the raw hex code. What do I need to do to ...
``` ord('\xff') ``` should give you what you want `\x##` represents a single byte or character, if you will, whereas `"FF"` is a string of two characters that can then be processed with `int(my_string,16)` but when you have a single character you probably want `ord` you can see this by asking something like `len('\x...
Typeerror: object.__new__() takes no parameters (help)
19,821,214
2
2013-11-06T19:38:01Z
19,821,235
10
2013-11-06T19:39:19Z
[ "python", "typeerror" ]
I'm simply trying to make a code that generates dice (in python). Here's the code: ``` import random class Dice: def _init_(self, number_dice): self._dice = [6] * number_dice def roll_dice(self): for d in range(len(self._dice)): self._dice[d] = random.randit(1, 6) ...
You need *two* underscores before and after `__init__`: ``` def __init__(self, number_dice): self._dice= [6] *number_dice ``` Otherwise, Python treats that method as a custom one and not the special [`__init__`](http://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do) constructor method.
How to filter numpy array by list of indices?
19,821,425
2
2013-11-06T19:50:13Z
19,821,466
8
2013-11-06T19:52:43Z
[ "python", "numpy", "scipy", "nearest-neighbor", "lidar" ]
I am relatively new to python and have been trying to learn how to use numpy and scipy. I have a numpy array comprised of LAS data [x, y, z, intensity, classification]. I have created a cKDTree of points and have found nearest neighbors using [query\_ball\_point](http://docs.scipy.org/doc/scipy/reference/generated/scip...
ummmm Its hard to tell whats being asked (thats quite the wall of text) ``` filter_indices = [1,3,5] print numpy.array([11,13,155,22,0xff,32,56,88])[filter_indices] ``` may be what you are asking