title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python BeautifulSoup findAll by "class" attribute
19,969,056
9
2013-11-14T03:36:31Z
19,970,460
13
2013-11-14T05:46:58Z
[ "python", "web-scraping", "beautifulsoup" ]
I want to do the following code, which is what BS documentation says to do, the only problem is that the word "class" isn't just a word. It can be found inside HTML, but it's also a python keyword which causes this code to throw an error. So how do I do the following? ``` soup.findAll('ul', class="score") ```
Your problem seems to be that you expect `find_all` in the soup to find an exact match for your string. [In fact](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class): > When you search for a tag that matches a certain CSS class, you’re > matching against any of its CSS classes: You can pro...
How to check a string for a special character?
19,970,532
5
2013-11-14T05:52:30Z
19,970,575
12
2013-11-14T05:55:37Z
[ "python", "string" ]
I can only use a string in my program if it contains no special characters except underscore `_`. How can I check this? I tried using unicodedata library. But the special characters just got replaced by standard characters.
You can use `string.punctuation` and `any` function like this ``` import string invalidChars = set(string.punctuation.replace("_", "")) if any(char in invalidChars for char in word): print "Invalid" else: print "Valid" ``` With this line ``` invalidChars = set(string.punctuation.replace("_", "")) ``` we are...
amplitude of numpy's fft results is to be multiplied by sampling period?
19,975,030
3
2013-11-14T10:18:23Z
19,976,162
7
2013-11-14T11:12:05Z
[ "python", "numpy", "fft", "dft" ]
I try to validate my understanding of Numpy's FFT with an example: the Fourier transform of `exp(-pi*t^2)` should be `exp(-pi*f^2)` when no scaling is applied on the direct transform. However, I find that to obtain this result I need to multiply the result of FFT by a factor `dt`, which is the time interval between tw...
Be careful, you are not computing the continuous time Fourier transform, computers work with discrete data, so does Numpy, if you take a look to [`numpy.fft.fft`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fft.html#numpy.fft.fft) documentation it says: > numpy.fft.fft(a, n=None, axis=-1)[source] > >...
What's the difference between `from django.conf import settings` and `import settings` in a Django project
19,976,115
19
2013-11-14T11:09:30Z
19,976,749
24
2013-11-14T11:41:56Z
[ "python", "django", "django-settings" ]
I'm reading up that most people do `from django.conf import settings` but I don't undertstand the difference to simply doing `import settings` in a django project file. Can anyone explain the difference?
`import settings` will import the first python module named `settings.py` found in `sys.path`, usually (in default django setups). It allows access only to your site defined settings file, which overwrites django default settings (`django.conf.global_settings`). So, if you try to access a valid django setting not spec...
django-rest-framework + django-polymorphic ModelSerialization
19,976,202
13
2013-11-14T11:13:31Z
19,976,203
15
2013-11-14T11:13:31Z
[ "python", "django", "django-rest-framework" ]
I was wondering if anyone had a Pythonic solution of combining Django REST framework with django-polymorphic. Given: ``` class GalleryItem(PolymorphicModel): gallery_item_field = models.CharField() class Photo(GalleryItem): custom_photo_field = models.CharField() class Video(GalleryItem): custom_image_f...
So far I only tested this for GET request, and this works: ``` class PhotoSerializer(serializers.ModelSerializer): class Meta: model = models.Photo class VideoSerializer(serializers.ModelSerializer): class Meta: model = models.Video class GalleryItemModuleSerializer(serializers.ModelSeria...
How can I filter a Haystack SearchQuerySet for None on an IntegerField
19,976,925
7
2013-11-14T11:51:14Z
22,576,854
10
2014-03-22T11:15:17Z
[ "python", "django", "django-haystack" ]
This is driving me a bit mad but seems like it should be simple. I'm using Django and Haystack and have a search index including an IntegerField which allows null. This is based on a related model in Django, but I don't think this matters. eg: ``` class ThingIndex(indexes.ModelSearchIndex, indexes.Indexable): gro...
If you are using ElasticSearch, the solution can be done without patching, just using native ElasticSearch: ``` from haystack.inputs import Raw self.searchqueryset.exclude(group = Raw("[* TO *]")) ``` Other way around, filter all documents that have non-emtpy group field: ``` from haystack.inputs import Raw self.sea...
hybrid property with join in sqlalchemy
19,979,303
3
2013-11-14T13:45:12Z
20,007,239
7
2013-11-15T17:38:41Z
[ "python", "sql", "sqlalchemy" ]
I have probably not grasped the use of `@hybrid_property` fully. But what I try to do is to make it easy to access a calculated value based on a column in another table and thus a join is required. So what I have is something like this (which works but is awkward and feels wrong): ``` class Item(): : @hybrid_proper...
One way or another you need to load or access `Action` rows either via join or via lazy load (note here it's not clear what `Event` vs. `Action` is, I'm assuming you have just `Item.actions -> Action`). The non-"expression" version of `days_ago` intends to function against `Action` objects that are relevant only to th...
What is Python's heapq module?
19,979,518
17
2013-11-14T13:54:16Z
19,979,723
34
2013-11-14T14:03:47Z
[ "python", "data-structures", "heap", "python-module" ]
I tried ["heapq"](https://docs.python.org/3/library/heapq.html) and arrived at the conclusion that my expectations differ from what I see on the screen. I need somebody to explain how it works and where it can be useful. From the book [Python Module of the Week](http://pymotw.com/2/articles/data_structures.html#sortin...
The `heapq` module maintains the *heap invariant*, which is not the same thing as maintaining the actual list object in sorted order. Quoting from the [`heapq` documentation](http://docs.python.org/2/library/heapq.html): > Heaps are binary trees for which every parent node has a value less than or equal to any of its...
What is Python's heapq module?
19,979,518
17
2013-11-14T13:54:16Z
19,979,730
16
2013-11-14T14:03:58Z
[ "python", "data-structures", "heap", "python-module" ]
I tried ["heapq"](https://docs.python.org/3/library/heapq.html) and arrived at the conclusion that my expectations differ from what I see on the screen. I need somebody to explain how it works and where it can be useful. From the book [Python Module of the Week](http://pymotw.com/2/articles/data_structures.html#sortin...
You are misunderstanding the heap data structure implementation. The `heapq` module is actually a variant of the [binary heap](https://en.wikipedia.org/wiki/Binary_heap) implementation, where heap elements are stored in a list, as described here: <https://en.wikipedia.org/wiki/Binary_heap#Heap_implementation> Quoting ...
What is Python's heapq module?
19,979,518
17
2013-11-14T13:54:16Z
31,211,895
10
2015-07-03T17:34:22Z
[ "python", "data-structures", "heap", "python-module" ]
I tried ["heapq"](https://docs.python.org/3/library/heapq.html) and arrived at the conclusion that my expectations differ from what I see on the screen. I need somebody to explain how it works and where it can be useful. From the book [Python Module of the Week](http://pymotw.com/2/articles/data_structures.html#sortin...
**Your book is wrong!** As you demonstrate, a heap is not a sorted list (though a sorted list is a heap). What is a heap? To quote Skiena's Algorithm Design Manual > Heaps are a simple and elegant data structure for efficiently supporting the priority queue operations insert and extract-min. They work by maintaining a...
Sorting Multi-Index to full depth (Pandas)
19,981,518
12
2013-11-14T15:22:38Z
19,982,756
8
2013-11-14T16:17:55Z
[ "python", "pandas" ]
I have a dataframe which Im loading from a csv file and then setting the index to few of its columns (usually two or three) by the set\_index method. The idea is to then access parts of the dataframe using several key combination, as such: ``` df.set_index(['fileName','phrase']) df.ix['somePath','somePhrase'] ``` App...
Its not really clear what you are asking. Multi-index docs are [here](http://pandas.pydata.org/pandas-docs/dev/indexing.html#hierarchical-indexing-multiindex) The OP needs to set the index, then sort in place ``` df.set_index(['fileName','phrase'],inplace=True) df.sortlevel(inplace=True) ``` Then access these levels...
Select elements of numpy array via boolean mask array
19,984,102
7
2013-11-14T17:16:54Z
19,984,234
12
2013-11-14T17:22:47Z
[ "python", "numpy", "indexing", "boolean", "mask" ]
I guess the answer is close at hand, but I can't see it :-( I have a boolean mask array of length n: ``` a = np.array([True, True, True, False, False]) ``` I have a 2d array with n columns: ``` b = np.array([[1,2,3,4,5], [1,2,3,4,5]]) ``` I want a new array which contains only the "True"-values, eg: ``` c = ([[1,...
You probably want something like this: ``` >>> a = np.array([True, True, True, False, False]) >>> b = np.array([[1,2,3,4,5], [1,2,3,4,5]]) >>> b[:,a] array([[1, 2, 3], [1, 2, 3]]) ``` Note that for this kind of indexing to work, it needs to be an `ndarray`, like you were using, not a `list`, or it'll interpret...
What can multiprocessing and dill do together?
19,984,152
24
2013-11-14T17:19:14Z
19,985,580
24
2013-11-14T18:35:19Z
[ "python", "multiprocessing", "pickle", "dill" ]
I would like to use the `multiprocessing` library in Python. Sadly `multiprocessing` uses `pickle` which doesn't support functions with closures, lambdas, or functions in `__main__`. All three of these are important to me ``` In [1]: import pickle In [2]: pickle.dumps(lambda x: x) PicklingError: Can't pickle <functio...
`multiprocessing` makes some bad choices about pickling. Don't get me wrong, it makes some good choices that enable it to pickle certain types so they can be used in a pool's map function. However, since we have `dill` that can do the pickling, multiprocessing's own pickling becomes a bit limiting. Actually, if `multip...
Does Django request.REQUEST.get() contain BOTH GET and POST parameters?
19,984,224
4
2013-11-14T17:22:07Z
19,984,344
7
2013-11-14T17:28:16Z
[ "python", "django", "post", "get" ]
Are the parameters in request.POST and request.GET BOTH in request.REQUEST ? Or i have to check for each of them ? I can't find a clear info in the documentation for both REQUEST/QueryDict. NB: Django 1.4 Final
No, this was possible in older versions but was depreciated in Django 1.7. For Django archeologists running ancient versions, keep reading. From the [documentation](https://docs.djangoproject.com/en/1.4/ref/request-response/#django.http.HttpRequest.REQUEST): HttpRequest.REQUEST For convenience, a dictionary-like obj...
Find least frequent value in dictionary
19,984,477
3
2013-11-14T17:34:53Z
19,984,587
7
2013-11-14T17:41:14Z
[ "python", "dictionary" ]
I'm working on a problem that asks me to return the least frequent value in a dictionary and I can't seem to work it out besides with a few different counts, but there aren't a set number of values in the dictionaries being provided in the checks. > For example, suppose the dictionary contains mappings from students' ...
Counting the members of a collection is the job of `collections.Counter`: ``` d={'Alyssa':22, 'Char':25, 'Dan':25, 'Jeff':20, 'Kasey':20, 'Kim':20, 'Mogran':25, 'Ryan':25, 'Stef':22} import collections print collections.Counter(d.values()).most_common()[-1][0] 22 ```
Numpy array of random matrices
19,984,596
5
2013-11-14T17:41:51Z
19,984,704
13
2013-11-14T17:46:42Z
[ "python", "numpy" ]
I'm new to python/numpy and I need to create an array containing matrices of random numbers. What I've got so far is this: ``` for i in xrange(samples): SPN[] = np.random.random((6,5)) * np.random.randint(0,100) ``` Which make sense for me as PHP developer but is not working for python. So how do I create a 3 di...
Both [`np.random.randint`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html) and [`np.random.uniform`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html), like most of the `np.random` functions, accept a `size` parameter, so in `numpy` we'd do it in one step: ``...
scikit .predict() default threshold
19,984,957
18
2013-11-14T18:00:48Z
19,989,086
7
2013-11-14T21:47:20Z
[ "python", "machine-learning", "classification", "scikit-learn" ]
I'm working on a classification problem with unbalanced classes (5% 1's). I want to predict the class, not the probability. In a binary classification problem, is scikit's `classifier.predict()` using `0.5` by default? If it doesn't, what's the default method? If it does, how do I change it? In scikit some classifier...
You seem to be confusing concepts here. Threshold is not a concept for a "generic classifier" - the most basic approaches are based on some tunable threshold, but most of the existing methods create complex rules for classification which cannot (or at least shouldn't) be seen as a thresholding. So first - one cannot a...
scikit .predict() default threshold
19,984,957
18
2013-11-14T18:00:48Z
19,997,567
13
2013-11-15T09:23:53Z
[ "python", "machine-learning", "classification", "scikit-learn" ]
I'm working on a classification problem with unbalanced classes (5% 1's). I want to predict the class, not the probability. In a binary classification problem, is scikit's `classifier.predict()` using `0.5` by default? If it doesn't, what's the default method? If it does, how do I change it? In scikit some classifier...
> is scikit's `classifier.predict()` using 0.5 by default? In probabilistic classifiers, yes. It's the only sensible threshold from a mathematical viewpoint, as others have explained. > What would be the way to do this in a classifier like MultinomialNB that doesn't support `class_weight`? You can set the `class_pri...
How do I create a Python set with only one element?
19,985,145
18
2013-11-14T18:11:31Z
19,985,165
14
2013-11-14T18:12:35Z
[ "python", "python-3.x", "set" ]
If I have a string, and want to create a set that initially contains *only* that string, is there a more Pythonic approach than the following? ``` mySet = set() mySet.add(myString) ``` The following gives me a set of the letters in `myString`: ``` mySet = set(myString) ```
For example, this easy way: ``` mySet = set([myString]) ```
How do I create a Python set with only one element?
19,985,145
18
2013-11-14T18:11:31Z
19,985,291
11
2013-11-14T18:18:55Z
[ "python", "python-3.x", "set" ]
If I have a string, and want to create a set that initially contains *only* that string, is there a more Pythonic approach than the following? ``` mySet = set() mySet.add(myString) ``` The following gives me a set of the letters in `myString`: ``` mySet = set(myString) ```
In 2.7 as well as 3.x, you can use: ``` mySet = {'abc'} ```
Why is Python class not recognizing static variable
19,985,758
8
2013-11-14T18:43:58Z
19,985,778
18
2013-11-14T18:45:12Z
[ "python", "class", "oop", "variables", "static" ]
I am trying to make a class in Python with static variables and methods (attributes and behaviors) ``` import numpy class SimpleString(): popSize = 1000 displaySize = 5 alphatbet = "abcdefghijklmnopqrstuvwxyz " def __init__(self): pop = numpy.empty(popSize, object) target = getTa...
You either need to access it with a `self.popSize` or `SimpleString.popSize`. When you declare a variable in a class in order for any of the instance functions to access that variable you will need to use `self` or the class name(in this case `SimpleString`) otherwise it will treat any variable in the function to be a ...
What does the $ mean when running commands?
19,986,306
4
2013-11-14T19:13:06Z
19,986,337
8
2013-11-14T19:14:33Z
[ "python", "command", "install", "dollar-sign" ]
I've been learning Python, and I keep running into the $ character in online documentation. Usually it goes something like this: `$ python ez_setup.py` (Yeah, I've been trying to install setup tools) I'm fairly certain that this command isn't for the python IDE or console, but I've tried windows cmd and it doesn't wo...
As of now, Python does not implement `$` in its syntax. So, it has nothing to do with Python. Instead, what you are seeing is the terminal prompt of a Unix-based system (Mac, Linux, etc.)
Rounding a number in python but keeping ending zeros
19,986,662
5
2013-11-14T19:32:41Z
19,986,686
8
2013-11-14T19:34:10Z
[ "python", "floating-point", "decimal", "rounding" ]
I've been working on a script that takes data from an XLS spreadsheet, rounds the numbers, and removes the decimal point, ex: 2606.89579999999 becomes 26069; However, I need the number to round to two decimal places even if there would be a trailing zero, so 2606.89579999999 should become 260690. I currently have it s...
As you are talking about trailing zeros, this is a question about representation as string, you can use ``` >>> "%.2f" % round(2606.89579999999, 2) '2606.90' ``` Or use modern style with `format` function: ``` >>> '{:.2f}'.format(round(2606.89579999999, 2)) '2606.90' ``` and remove point with `replace` or `translat...
Django: check if value in values_list with & without prefetch_related/select_related
19,987,954
7
2013-11-14T20:42:54Z
19,989,321
7
2013-11-14T22:01:59Z
[ "python", "django", "list", "orm" ]
I've observed this behavior and I don't quite understand. Let say I make a query: ``` result = model.objects.all() result_pks = result.values_list("id",flat=True) print result_pks ``` And I get: ``` [1,2,3,4] ``` Then I want to check if a certain value is in the list of pks returned: ``` val = 2 print val in resul...
Are you using Django 1.5? There was a bug that caused the `in` lookup to fail when using `prefetch_related`: [bug 20242](https://code.djangoproject.com/ticket/20242). This has been fixed in Django 1.6.
Cypher query in py2neo
19,989,994
3
2013-11-14T22:43:33Z
19,997,355
11
2013-11-15T09:13:00Z
[ "python", "neo4j", "py2neo" ]
How do I perform the functions of [`shortestPath()`](http://docs.neo4j.org/chunked/milestone/query-match.html#match-shortest-path) and [`allShortestPaths()`](http://docs.neo4j.org/chunked/milestone/query-match.html#match-all-shortest-paths) in py2neo? In Cypher, I'd execute something like: ``` START beginning=node(4)...
I don't want to steal jjaderberg's comment but here is how you could run your Cypher query with py2neo. As far as I know graph algorithms are not implemented. ``` query_string = "START beginning=node(4), end=node(452) MATCH p = shortestPath(beginning-[*..500]-end) RETURN p" result = ...
Run an OLS regression with Pandas Data Frame
19,991,445
35
2013-11-15T00:47:00Z
19,991,632
54
2013-11-15T01:05:30Z
[ "python", "pandas", "scikit-learn", "regression", "statsmodels" ]
I have a `pandas` data frame and I would like to able to predict the values of column A from the values in columns B and C. Here is a toy example: ``` import pandas as pd df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]}) ``` Id...
I think you can almost do exactly what you thought would be ideal, using the [statsmodels](http://statsmodels.sourceforge.net/) package which is one of `pandas`' optional dependencies (it's used for a few things in `pandas.stats`.) ``` >>> import pandas as pd >>> import statsmodels.formula.api as sm >>> df = pd.DataFr...
Run an OLS regression with Pandas Data Frame
19,991,445
35
2013-11-15T00:47:00Z
19,996,208
44
2013-11-15T08:00:23Z
[ "python", "pandas", "scikit-learn", "regression", "statsmodels" ]
I have a `pandas` data frame and I would like to able to predict the values of column A from the values in columns B and C. Here is a toy example: ``` import pandas as pd df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]}) ``` Id...
It's possible to do this with `pandas.stats.ols`: ``` >>> from pandas.stats.api import ols >>> df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]}) >>> res = ols(y=df['A'], x=df[['B','C']]) >>> res -------------------------Summary of Regression Analysis------------------...
Run an OLS regression with Pandas Data Frame
19,991,445
35
2013-11-15T00:47:00Z
20,019,449
9
2013-11-16T14:14:30Z
[ "python", "pandas", "scikit-learn", "regression", "statsmodels" ]
I have a `pandas` data frame and I would like to able to predict the values of column A from the values in columns B and C. Here is a toy example: ``` import pandas as pd df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]}) ``` Id...
> This would require me to reformat the data into lists inside lists, which seems to defeat the purpose of using pandas in the first place. No it doesn't, just convert to a NumPy array: ``` >>> data = np.asarray(df) ``` This takes constant time because it just creates a *view* on your data. Then feed it to scikit-le...
How would I access variables from one class to another?
19,993,795
5
2013-11-15T04:54:07Z
19,993,844
11
2013-11-15T04:59:33Z
[ "python", "class", "variables" ]
I am writing a program that is utilizing multiple classes. I have one class that is dedicated to determining values for a set of variables. I would then like to be able to access the values of those variables with other classes. My code looks as follows: ``` class ClassA(object): def __init__(self): self.v...
`var1` and `var2` are [instance variables](http://stackoverflow.com/questions/2714573/instance-variables-vs-class-variables-in-python). That means that you have to send the instance of `ClassA` to `ClassB` in order for ClassB to access it, i.e: ``` class ClassA(object): def __init__(self): self.var1 = 1 ...
A ThreadPoolExecutor inside a ProcessPoolExecutor
19,994,478
8
2013-11-15T05:58:21Z
20,183,265
9
2013-11-25T01:01:58Z
[ "python", "multithreading", "multiprocessing", "python-3.3", "concurrent.futures" ]
I am new to [the futures module](http://docs.python.org/3.3/library/concurrent.futures.html) and have a task that could benefit from parallelization; but I don't seem to be able to figure out exactly how to setup the function for a thread and the function for a process. I'd appreciate any help anyone can shed on the ma...
I'll give you working code that mixes processes with threads for solving the problem, but it's not what you're expecting ;-) First thing is to make a mock program that doesn't endanger your real data. Experiment with something harmless. So here's the start: ``` class Particle: def __init__(self, i): self.i...
Advanced List sorting Python
19,994,958
3
2013-11-15T06:35:52Z
19,995,051
7
2013-11-15T06:43:14Z
[ "python", "list", "sorting", "dictionary", "sorted" ]
I am trying to sort a dictionary which is in the form: ``` d = {'+A':234, '-B':212, 'A':454, '-C':991, '-A':124} ``` I want to sort it by key so that it is in the form: ``` +A, A, -A, +B, B, -B, etc ``` I have been trying to use `sorted(d, key=lambda x: (x[1], x[0]) if len(x) == 2 else x[0])` but I cannot seem to f...
One simple way to do it ``` rank = ['+A', 'A', '-A', '+B', 'B', '-B', ...] sorted(d.items(), key=lambda i: rank.index(i[0])) ``` If there are a lot of ranks, it'll be better to use a `dict` ``` rank = {'+A': 0, 'A': 1, '-A': 2, '+B': 3, 'B': 4, '-B': 5, ...} sorted(d.items(), key=lambda i: rank[i[0]]) ``` You can u...
Run manage.py from AWS EB Linux instance
19,997,343
6
2013-11-15T09:12:14Z
20,070,161
23
2013-11-19T11:21:51Z
[ "python", "django", "amazon-web-services" ]
How to run manage.py from AWS EB (Elastic Beanstalk) Linux instance? If I run it from '/opt/python/current/app', it shows the below exception. ``` Traceback (most recent call last): File "./manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named ...
How to run manage.py from AWS Elastic Beanstalk AMI. 1. SSH login to Linux 2. Run `source /opt/python/run/venv/bin/activate` 3. Run `source /opt/python/current/env` 4. Run `cd /opt/python/current/app` 5. Run `manage.py <commands>` Or, you can run command as like the below: 1. Run `cd /opt/python/current/app` 2. Run ...
Calculate Daily Returns with Pandas DataFrame
20,000,726
4
2013-11-15T12:06:30Z
20,000,984
9
2013-11-15T12:22:15Z
[ "python", "python-3.x", "pandas" ]
Here is my Pandas data frame: ``` prices = pandas.DataFrame([1035.23, 1032.47, 1011.78, 1010.59, 1016.03, 1007.95, 1022.75, 1021.52, 1026.11, 1027.04, 1030.58, 1030.42, 1036.24, 1015.00, 1015.20]) ``` Here is my `daily_return` function: ``` def daily_return(prices): return prices[:-1...
Because operations will do alignment on index, you can convert one of the DataFrames to array: ``` prices[:-1].values / prices[1:] - 1 ``` or ``` prices[:-1] / prices[1:].values - 1 ``` depends on what the index of the result you want. or use `shift()` method: ``` prices.shift(1) / prices - 1 ``` and: ``` price...
Calculate Daily Returns with Pandas DataFrame
20,000,726
4
2013-11-15T12:06:30Z
33,472,722
8
2015-11-02T07:35:52Z
[ "python", "python-3.x", "pandas" ]
Here is my Pandas data frame: ``` prices = pandas.DataFrame([1035.23, 1032.47, 1011.78, 1010.59, 1016.03, 1007.95, 1022.75, 1021.52, 1026.11, 1027.04, 1030.58, 1030.42, 1036.24, 1015.00, 1015.20]) ``` Here is my `daily_return` function: ``` def daily_return(prices): return prices[:-1...
Why not use the very convenient **`pct_change`** method provided by `pandas` by default: ``` import pandas as pd prices = pandas.DataFrame([1035.23, 1032.47, 1011.78, 1010.59, 1016.03, 1007.95, 1022.75, 1021.52, 1026.11, 1027.04, 1030.58, 1030.42, 1036.24, 1015.00, 1015.20]) daily_return = price...
How to get POSTed json in Flask?
20,001,229
73
2013-11-15T12:35:19Z
20,001,283
122
2013-11-15T12:38:35Z
[ "python", "json", "post", "flask" ]
I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the post with the [PostMan Chrome extension](https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm), and the JSON I post is simply `{"text":"lalala"}`. I try to read the JSON using t...
You need to set the request content type to `application/json` for the `.json` property to work; it'll be `None` otherwise. See the [Flask `Request` documentation](https://flask.readthedocs.org/en/latest/api/#flask.Request.json): > If the mimetype is `application/json` this will contain the parsed JSON data. Otherwise...
How to get POSTed json in Flask?
20,001,229
73
2013-11-15T12:35:19Z
33,379,392
12
2015-10-27T22:11:47Z
[ "python", "json", "post", "flask" ]
I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the post with the [PostMan Chrome extension](https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm), and the JSON I post is simply `{"text":"lalala"}`. I try to read the JSON using t...
This is the way I would do it and it should be ``` @app.route('/api/add_message/<uuid>', methods=['GET', 'POST']) def add_message(uuid): content = request.get_json(silent=True) print content return uuid ``` With `silent=True` set, the `get_json` function will fail silently when trying to retrieve the json...
How to get POSTed json in Flask?
20,001,229
73
2013-11-15T12:35:19Z
35,614,301
9
2016-02-24T22:15:57Z
[ "python", "json", "post", "flask" ]
I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the post with the [PostMan Chrome extension](https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm), and the JSON I post is simply `{"text":"lalala"}`. I try to read the JSON using t...
For reference, here's complete code for how to send json from a Python client: ``` import requests res = requests.post('http://localhost:5000/api/add_message/1234', json={"mytext":"lalala"}) if res.ok: print res.json() ``` The "json=" input will automatically set the content-type, as discussed here: [Post JSON us...
Dimension of data before and after performing PCA
20,001,509
5
2013-11-15T12:50:11Z
20,002,494
10
2013-11-15T13:45:06Z
[ "python", "numpy", "scikit-learn", "pca" ]
I'm attempting [kaggle.com's digit recognizer competition](http://www.kaggle.com/c/digit-recognizer) using Python and scikit-learn. After removing labels from the training data, I add each row in CSV into a list like this: ``` for row in csv: train_data.append(np.array(np.int64(row))) ``` I do the same for the t...
The [PCA](http://en.wikipedia.org/wiki/Principal_component_analysis) algorithm finds the eigenvectors of the data's covariance matrix. What are eigenvectors? Nobody knows, and nobody cares (just kidding!). What's important is that the first eigenvector is a vector parallel to the direction along which the data has the ...
How to scale images to screen size in Pygame
20,002,242
9
2013-11-15T13:31:10Z
20,002,295
21
2013-11-15T13:33:55Z
[ "python", "image", "background", "pygame", "scaling" ]
I was wondering how I would go about scaling the size of images in `pygame` projects to the resolution of the screen. For example, envisage the following scenario assuming windowed display mode for the time being; I assume full screen will be the same: * I have a `1600x900` background image which of course displays na...
You can scale the image with `pygame.transform.scale`: ``` import pygame picture = pygame.image.load(filename) picture = pygame.transform.scale(picture, (1280, 720)) ``` You can then get the bounding rectangle of `picture` with ``` rect = picture.get_rect() ``` and move the picture with ``` rect = rect.move((x, y)...
Print different precision by column with pandas.DataFrame.to_csv()?
20,003,290
15
2013-11-15T14:26:21Z
20,006,954
18
2013-11-15T17:23:09Z
[ "python", "csv", "numpy", "floating-point", "pandas" ]
## Question Is it possible to specify a float precision specifically for each column to be printed by the Python `pandas` package method [pandas.DataFrame.to\_csv](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_csv.html)? ## Background If I have a `pandas` dataframe that is arranged like this...
Change the type of column "vals" prior to exporting the data frame to a CSV file ``` df_data['vals'] = df_data['vals'].map(lambda x: '%2.1f' % x) df_data.to_csv(outfile, index=False, header=False, float_format='%11.6f') ```
Python how to read raw binary from a file? (audio/video/text)
20,004,859
3
2013-11-15T15:43:19Z
20,005,155
7
2013-11-15T15:56:05Z
[ "python", "python-2.7", "binary" ]
I want to read the raw binary of a file and put it into a string. Currently I am opening a file with the "rb" flag and printing the byte but it's coming up as ASCII characters (for text that is, for video and audio files it's giving symbols and gibberish). I'd like to get the raw 0's and 1's if possible. This needs to ...
What you are reading IS really the "raw binary" content of your "binary" file. Strange as it might seems, binary data are not "0's and 1's" but binary *words* (aka bytes, cf <http://en.wikipedia.org/wiki/Byte>) which have an integer (base 10) value and *can* be interpreted as ascii chars. Or as integers (which is how o...
Install a package and write to requirements.txt with pip
20,006,000
22
2013-11-15T16:37:02Z
29,679,231
8
2015-04-16T15:23:16Z
[ "python", "pip" ]
I'm searching for a way to install a package with pip, and write that package's version information to my project's requirements.txt file. For those familiar with [npm](https://npmjs.org/), it's essentially what `npm install --save` does. Using `pip freeze > requirements.txt` works great, but I've found that I forget ...
To get the version information, you can actually use pip freeze selectively after install. Here is a function that should do what you are asking for: ``` pip_install_save() { package_name=$1 requirements_file=$2 if [[ -z $requirements_file ]] then requirements_file='./requirements.txt' fi ...
What does "for x in y or z:" do in Python?
20,009,629
13
2013-11-15T20:04:14Z
20,009,664
15
2013-11-15T20:06:20Z
[ "python", "for-loop", "obfuscation", "fractals", "deobfuscation" ]
I'm trying to take apart and de-obfuscate this mandlebrot-generating python code: ``` _ = ( 255, lambda V ,B,c :c and Y(V*V+B,B, c ...
Doing: ``` for x in y or z: ``` is the same as: ``` for x in (y or z): ``` If `y` evaluates to `True`, the for-loop will iterate through it. Otherwise, it will iterate through `z`. Below is a demonstration: ``` >>> y = [1, 2, 3] >>> z = [4, 5, 6] >>> for x in y or z: ... print x ... 1 2 3 >>> y = [] # Empty l...
How to 'turn off' blurry effect of imshow() in matplotlib?
20,010,882
23
2013-11-15T21:26:22Z
20,010,912
29
2013-11-15T21:28:27Z
[ "python", "numpy", "matplotlib", "plot" ]
I want to make a color plot of probabilities however imshow generates blurry values for points which have zero probability. How can I get rid of this blurry periphery around real grid points? Example: ``` import numpy as np import matplotlib.pyplot as plt a=np.asarray([[ 0.00000000e+00 , 1.05824446e-01 , 2.0508613...
By default (which will be changed in mpl 2.0), `imshow` interpolates the data (as you would want to do for an image). All you need to do is tell it to not interpolate: ``` im = plt.imshow(..., interpolation='none') ``` `'nearest'` will also work for what you want. See [smoothing between pixels of imagesc\imshow in ma...
Fitting a Normal distribution to 1D data
20,011,122
14
2013-11-15T21:43:38Z
20,012,350
26
2013-11-15T23:19:43Z
[ "python", "numpy", "matplotlib", "scipy" ]
I have a 1 Dimentional array and I can compute the "mean" and "standard deviation" of this sample and plot the "Normal distribution" but I have a problems: I want to plot the data and Normal distribution in the same figure like below : I dont know how to plot both the "DATA" and the "Normal Distribution" any Idea ab...
You can use `matplotlib` to plot the histogram and the PDF (as in the link in @MrE's answer). For fitting and for computing the PDF, you can use `scipy.stats.norm`, as follows. ``` import numpy as np from scipy.stats import norm import matplotlib.pyplot as plt # Generate some data for this demonstration. data = norm...
Plot Normal distribution with Matplotlib
20,011,494
10
2013-11-15T22:09:03Z
20,011,745
11
2013-11-15T22:30:25Z
[ "python", "numpy", "matplotlib", "plot", "scipy" ]
please help me to plot the normal distribution of the folowing data: DATA: ``` import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172, 187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159, 161, 178, 175...
Assuming you're getting `norm` from `scipy.stats`, you probably just need to sort your list: ``` import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172, 187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159, ...
Plot Normal distribution with Matplotlib
20,011,494
10
2013-11-15T22:09:03Z
20,026,448
26
2013-11-17T02:25:21Z
[ "python", "numpy", "matplotlib", "plot", "scipy" ]
please help me to plot the normal distribution of the folowing data: DATA: ``` import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172, 187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159, 161, 178, 175...
You may try using `hist` to put your data info along with the fitted curve as below: ``` import numpy as np import scipy.stats as stats import pylab as pl h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172, 187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159, 161, 178, 1...
How to choose the value and label from Django ModelChoiceField queryset
20,012,533
3
2013-11-15T23:35:55Z
20,012,573
14
2013-11-15T23:39:52Z
[ "python", "html", "django", "forms", "model" ]
I was trying to create a django form and one of my field contain a ModelChoiceField ``` class FooForm(forms.Form): person = forms.ModelChoiceField(queryset=Person.objects.filter(is_active=True).order_by('id'), required=False) age = forms.IntegerField(min_value=18, max_value=99, required=False) ``` When I tr...
From the Django docs: <https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField> > The `__unicode__` (`__str__` on Python 3) method of the model will be > called to generate string representations of the objects for use in > the field’s choices; to provide customized representations, su...
Using or in python
20,013,961
2
2013-11-16T02:38:47Z
20,013,965
7
2013-11-16T02:39:37Z
[ "python", "syntax" ]
New to coding, having problems making foolproof input for program: ``` answer=input(x) while (answer != "yes") or (answer != "no"): answer=input("must be 'yes' or 'no' answer") ``` The while loop never stops, regardless of input. What am I doing wrong?
Everything is either not yes *or* not no. You want `and`.
Using or in python
20,013,961
2
2013-11-16T02:38:47Z
20,013,967
8
2013-11-16T02:40:17Z
[ "python", "syntax" ]
New to coding, having problems making foolproof input for program: ``` answer=input(x) while (answer != "yes") or (answer != "no"): answer=input("must be 'yes' or 'no' answer") ``` The while loop never stops, regardless of input. What am I doing wrong?
Here is what I would use: ``` while answer not in ("yes", "no"): ``` Right now, your code is running continually because `answer` will *always* be not `"yes"` or not `"no"`. --- Also, if you want, you can add [`.lower()`](http://docs.python.org/2.7/library/stdtypes.html#str.lower) like so: ``` while answer.lower()...
Read file data without saving it in Flask
20,015,550
21
2013-11-16T06:35:20Z
20,017,830
32
2013-11-16T11:23:59Z
[ "python", "flask" ]
I am writing my first flask application. I am dealing with file uploads, and basically what I want is to read the data/content of the uploaded file without saving it and then print it on the resulting page. Yes, I am assuming that the user uploads a text file always. Here is the simple upload function i am using: ```...
`FileStorage` contains `stream` field. This object must extend IO or file object, so it must contain `read` and other similar methods. `FileStorage` also extend `stream` field object attributes, so you can just use `file.read()` instead `file.stream.read()`. Also you can use `save` argument with `dst` parameter as `Str...
Tornado streaming HTTP response as AsyncHTTPClient receives chunks
20,018,684
6
2013-11-16T12:53:41Z
20,053,021
16
2013-11-18T16:41:18Z
[ "python", "asynchronous", "tornado" ]
I'm trying to write a Tornado request handler which makes asynchronous HTTP requests, and returns data to the client as it receives it from it's async requests. Unfortunately, I'm unable to get Tornado to return any data to the client until all of it's Async HTTPRequests have completed. A demo of my request handler is...
Decorate your method with `gen.coroutine` and yield a list of futures. Here's a simple example: ``` from tornado import gen, web, httpclient class StreamingHandler(web.RequestHandler): @web.asynchronous @gen.coroutine def get(self): client = httpclient.AsyncHTTPClient() self.write('some o...
Django: Map data from an external APIs into a model?
20,019,783
3
2013-11-16T14:52:29Z
20,021,491
7
2013-11-16T17:32:47Z
[ "python", "django", "json", "api", "rest" ]
I am pulling in some JSON data from various external APIs. Their data may be structured like this: ``` "game": { "title": "Super Mario Bros. 3", "release": "1989", "players": 3, .. } ``` However, I'd like to store this directly in my database via this model: ``` class Game(models.Model): name = m...
You can create classmethod (or place it in model manager <https://docs.djangoproject.com/en/dev/ref/models/instances/#creating-objects>): ``` class Game(models.Model): name = models.CharField() debut = models.DateField() max_players = models.IntegerField() @classmethod def create_from_j(cls, game)...
FFT result; amplitude-phase relation
20,020,334
4
2013-11-16T15:43:10Z
20,021,301
7
2013-11-16T17:13:47Z
[ "python", "numpy" ]
I want to amplify audio input at specific frequencies, and I use `numpy.fft`. So my question is: When changing the amplitudes of the signal, what happens with phase? For example, if I multiply amplitudes in some frequency range, by some factor, let's say 2, do I need to change the phases, and if so, what should I do ...
You shouldn't need the change the phase for something like this. More likely the problem is that you need to be a bit more gentle about applying the boost. It sounds like you are taking some frequency window and multiplying by a constant while leaving everything else unchanged. This will cause ringing in the time domai...
Playing mp3 song on python
20,021,457
17
2013-11-16T17:28:56Z
20,021,547
17
2013-11-16T17:38:06Z
[ "python", "audio", "mp3" ]
I want to play my song (mp3) from python, can you give me a simplest command to do that? This is not correct: ``` import wave w = wave.open("e:/LOCAL/Betrayer/Metalik Klinik1-Anak Sekolah.mp3","r") ```
You may try this, simplistic but not the best method maybe. ``` from pygame import mixer # Load the required library mixer.init() mixer.music.load('e:/LOCAL/Betrayer/Metalik Klinik1-Anak Sekolah.mp3') mixer.music.play() ``` Please note that the support for `MP3` is limited ([as told in the docs](http://www.pygame.or...
Playing mp3 song on python
20,021,457
17
2013-11-16T17:28:56Z
25,899,180
25
2014-09-17T19:51:40Z
[ "python", "audio", "mp3" ]
I want to play my song (mp3) from python, can you give me a simplest command to do that? This is not correct: ``` import wave w = wave.open("e:/LOCAL/Betrayer/Metalik Klinik1-Anak Sekolah.mp3","r") ```
Grab the [VLC Python module](https://wiki.videolan.org/Python_bindings), vlc.py, which provides full support for libVLC and pop that in site-packages. Then: ``` >>> import vlc >>> p = vlc.MediaPlayer("file:///path/to/track.mp3") >>> p.play() ``` And you can stop it with: ``` >>> p.stop() ``` That module offers plen...
Function for rotating 2d objects?
20,023,209
4
2013-11-16T20:07:03Z
20,024,348
11
2013-11-16T21:50:57Z
[ "python", "function", "rotation", "2d", "physics" ]
Is it possible to write a function in python that could rotate any 2d structure with the arguments being only the coordinates (x,y) of the points in the structure? Additional arguments would be included for axis, speed and direction. To my understanding it would only be possible by calculating point distance from symm...
I have written such a function to use in pygame before. It is kinda self-explanatory but feel free to ask the parts that require clarification. Here is my code: ``` import math def rotatePolygon(polygon,theta): """Rotates the given polygon which consists of corners represented as (x,y), around the ORIGIN, cloc...
How to split a byte string into separate bytes in python
20,024,490
5
2013-11-16T22:04:01Z
20,024,532
7
2013-11-16T22:07:45Z
[ "python", "split", "byte", "bytearray" ]
Ok so I've been using python to try create a waveform image and I'm getting the raw data from the `.wav` file using `song = wave.open()` and `song.readframes(1)`, which returns : ``` b'\x00\x00\x00\x00\x00\x00' ``` What I want to know is how I split this into three separate bytes, e.g. `b'\x00\x00'`, `b'\x00\x00'`, `...
You can use slicing on `byte` objects: ``` >>> value = b'\x00\x01\x00\x02\x00\x03' >>> value[:2] b'\x00\x01' >>> value[2:4] b'\x00\x02' >>> value[-2:] b'\x00\x03' ``` When handling these frames, however, you probably also want to know about [`memoryview()` objects](http://docs.python.org/3/library/stdtypes.html#memor...
Vectorizing a Pandas dataframe for Scikit-Learn
20,024,584
11
2013-11-16T22:12:45Z
20,024,879
8
2013-11-16T22:44:23Z
[ "python", "pandas", "scikit-learn" ]
Say I have a dataframe in Pandas like the following: ``` > my_dataframe col1 col2 A foo B bar C something A foo A bar B foo ``` where rows represent instances, and columns input features (not showing the target label, but this would be for a classification task), i.e. I trying to buil...
First, I don't get where in your sample array are features, and where observations. Second, `DictVectorizer` holds no data, and is only about transformation utility and metadata storage. After transformation it stores features names and mapping. It returns a numpy array, used for further computations. Numpy array (fea...
Vectorizing a Pandas dataframe for Scikit-Learn
20,024,584
11
2013-11-16T22:12:45Z
20,032,254
8
2013-11-17T15:08:33Z
[ "python", "pandas", "scikit-learn" ]
Say I have a dataframe in Pandas like the following: ``` > my_dataframe col1 col2 A foo B bar C something A foo A bar B foo ``` where rows represent instances, and columns input features (not showing the target label, but this would be for a classification task), i.e. I trying to buil...
Take a look at `sklearn-pandas` which provides exactly what you're looking for. The corresponding Github repo is [here](https://github.com/paulgb/sklearn-pandas).
How to union two subqueries in SQLAlchemy and postgresql
20,024,744
5
2013-11-16T22:29:30Z
20,032,394
8
2013-11-17T15:21:39Z
[ "python", "postgresql", "python-2.7", "sqlalchemy", "union" ]
Raw SQL desired: ``` SELECT id FROM (SELECT some_table.id FROM some_table WHERE some_table.some_field IS NULL) AS subq1 UNION (SELECT some_table.id WHERE some_table.some_field IS NOT NULL) LIMIT 10; ``` Here is the python code: ``` import sqlalchemy SOME_TABLE = sqlalchemy.Table( 'some_table', sqlalc...
i used a little bit different approach: ``` # the first subquery, select all ids from SOME_TABLE where some_field is not NULL s1 = select([SOME_TABLE.c.id]).where(SOME_TABLE.c.some_field != None) # the second subquery, select all ids from SOME_TABLE where some_field is NULL s2 = select([SOME_TABLE.c.id]).where(SOME_T...
How to Pretty Print a CSV file in Python
20,025,235
9
2013-11-16T23:28:05Z
20,025,236
10
2013-11-16T23:28:05Z
[ "python", "csv" ]
How can I pretty print a CSV file using Python, not any external tool? For example I have this CSV file: ``` title1|title2|title3|title4 datalongdata|datalongdata|data|data data|data|data|datalongdatadatalongdatadatalongdatadatalongdatadatalongdata data|data'data|dat ``` I would like to transform it to visually loo...
### Usage: **pretty.pretty\_file(*filename*, \*\*\*options\*)** Reads a CSV file and prints visually the data as table to a new file. *filename*, is the given CSV file. The optional \*\*\*options\* keyword arguments is the union of Python's Standard Library [csv](http://docs.python.org/2/library/csv.html) module [Dia...
Inconsistent comprehension syntax?
20,025,280
11
2013-11-16T23:33:42Z
20,025,305
16
2013-11-16T23:37:02Z
[ "python", "if-statement", "python-3.x", "list-comprehension" ]
I just stumbled over what seems to be a flaw in the python syntax-- or else I'm missing something. See this: ``` [x for x in range(30) if x % 2 == 0] ``` But this is a syntax error: ``` [x for x in range(30) if x % 2 == 0 else 5] ``` If you have an `else` clause, you have to write: ``` [x if x % 2 == 0 else 5 for...
You are *mixing* syntax here. There are **two** different concepts at play here: * List comprehension syntax. Here `if` acts as a filter; include a value in the iteration or not. There is no `else`, as that is the 'don't include' case already. * A [conditional expression](http://docs.python.org/2/reference/expressions...
Apply Function on DataFrame Index
20,025,325
17
2013-11-16T23:40:04Z
30,590,280
15
2015-06-02T07:47:14Z
[ "python", "pandas", "indexing", "dataframe" ]
What is the best way to apply a function over the index of a Pandas `DataFrame`? Currently I am using this verbose approach: ``` pd.DataFrame({"Month": df.reset_index().Date.apply(foo)}) ``` where `Date` is the name of the index and `foo` is the name of the function that I am applying.
As already suggested by HYRY in the comments, [Series.map](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html) is the way to go here. Just set the index to the resulting series. Simple example: ``` df = pd.DataFrame({'d': [1, 2, 3]}, index=['FOO', 'BAR', 'BAZ']) df d FOO 1 BAR ...
Append string to the start of each value in a said column of a pandas dataframe (elegantly)
20,025,882
10
2013-11-17T00:56:09Z
20,027,386
29
2013-11-17T05:00:19Z
[ "python", "pandas", "dataframe" ]
I would like to append a string to the start of each value in a said column of a pandas dataframe (elegantly). I already figured out how to kind-of do this and I am currently using: ``` df.ix[(df['col'] != False), 'col'] = 'str'+df[(df['col'] != False), 'col'] ``` This seems one hell of an inelegant thing to do - do ...
``` df['col'] = 'str' + df['col'].astype(str) ``` Example: ``` >>> df = pd.DataFrame({'col':['a',0]}) >>> df col 0 a 1 0 >>> df['col'] = 'str' + df['col'].astype(str) >>> df col 0 stra 1 str0 ```
Django CMS fails to syncdb or migrate
20,026,728
20
2013-11-17T03:09:19Z
20,026,776
41
2013-11-17T03:16:23Z
[ "python", "django", "django-cms", "django-syncdb" ]
I'm very new to django and in turn the django-cms app. I have followed the tutorial step by step: (from the [offical website](http://docs.django-cms.org/en/latest/getting_started/tutorial.html) ) on a new machine and have everything exactly as the tutorial does yet I still can't get anywhere. I get to the final step ...
I'm guessing that you are using the new Django 1.6. There the `sites` application is no longer included by default in your project. And as it seems the `django-cms` depends on it. You can add it easily to the list of enabled applications in your `settings.py` file, in the `INSTALLED_APPS` list: ``` INSTALLED_APPS = (...
Python won't import function
20,029,486
3
2013-11-17T10:11:39Z
20,029,503
11
2013-11-17T10:12:57Z
[ "python", "python-import" ]
I have a simple `time.py` file: ``` import datetime import time import re def cnvrt1(time): hr = int(re.split(":",time)[0]) min = int(re.split(":",time)[1]) sec = int(re.split(" ",re.split(':',time)[2])[0]) ampm = re.split(" ",re.split(':',time)[2])[1][0] zone = re.split(" ",re.split(':',time)[2])[...
You are using the wrong name. There is *already* a module named `time` in the standard library, and that module is probably already imported by other code you are using. You are even using `import time` in the code you posted here, which would otherwise create a circular import. The best option is to rename this modul...
No module named flask.ext.wtf
20,032,922
10
2013-11-17T16:06:49Z
20,033,411
13
2013-11-17T16:50:35Z
[ "python", "flask", "flask-wtforms" ]
I'm following @Miguel flask [mega tutorial](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms) which is great. In chapter 3 he talks about web forms and flaskWTF extension, installing the extension like this `sudo pip install Flask-WTF` resulted in > Successfully installed Flask-WTF Flask ...
You are probably using the import style from the older versions: ``` from flask.ext.wtf import Form, TextField, BooleanField from flask.ext.wtf import Required ``` The import style changed starting from 0.9.0 version. Be sure to update your imports: ``` from flask.ext.wtf import Form from wtforms.fields import TextF...
Python Pandas max value of selected columns
20,033,111
22
2013-11-17T16:22:56Z
20,033,232
36
2013-11-17T16:33:37Z
[ "python", "python-2.7", "pandas", "max" ]
``` data = {'name' : ['bill', 'joe', 'steve'], 'test1' : [85, 75, 85], 'test2' : [35, 45, 83], 'test3' : [51, 61, 45]} frame = pd.DataFrame(data) ``` I would like to add a new column that shows the max value for each row. desired output: ``` name test1 test2 test3 HighScore bill 75 75 85 85 ...
``` >>> frame['HighScore'] = frame[['test1','test2','test3']].max(axis=1) >>> frame name test1 test2 test3 HighScore 0 bill 85 35 51 85 1 joe 75 45 61 75 2 steve 85 83 45 85 ```
Cannot import GeoIP module in Django
20,033,552
5
2013-11-17T17:04:39Z
20,034,160
7
2013-11-17T17:57:50Z
[ "python", "django" ]
I'm using Django 1.5.5. settings.py: ``` GEOIP_PATH = os.path.join(PROJECT_DIR, 'geoIP') INSTALLED_APPS = (..,'django.contrib.gis',..) ``` views.py: ``` from django.contrib.gis import geoip print geoip.HAS_GEOIP ``` the print gives `false`. If I try one of the following I get a `ImportError: cannot import name G...
It looks like you don't have GeoIP installed system-wide. `django.contrib.gis.geoip` is just a wrapper around the GeoIP library, and it must be installed regardless. On OS X, if you use homebrew, just run `brew install geoip`. If not, you need to make sure the GeoIP lib is installed, and that you have `libGeoIP.dylib`...
How can I split a large file csv file (7GB) in Python
20,033,861
6
2013-11-17T17:31:40Z
20,034,041
17
2013-11-17T17:48:30Z
[ "python", "csv", "split" ]
I have a 7GB `csv` file which I'd like to split into smaller chunks, so it is readable and faster for analysis in Python on a notebook. I would like to grab a small set from it, maybe 250MB, so how can I do this?
You don't need Python to split a csv file. Using your shell: ``` $ split -l 100 data.csv ``` Would split `data.csv` in chunks of 100 lines.
Insert a link inside a pandas table
20,035,518
13
2013-11-17T20:07:36Z
20,043,785
12
2013-11-18T09:03:35Z
[ "python", "pandas", "ipython-notebook" ]
I'd like to insert a link (to a web page) inside a pandas table, so when it is displayed in ipython notebook, I could press the link. I tried the following: ``` In [1]: import pandas as pd In [2]: df = pd.DataFrame(range(5), columns=['a']) In [3]: df['b'] = df['a'].apply(lambda x: 'http://example.com/{0}'.format(x)...
I suppose you have to represent whole pandas object as [html object](http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Part%205%20-%20Rich%20Display%20System.ipynb), that is ``` In [1]: from IPython.display import HTML In [2]: df = pd.DataFrame(list(range(5)), columns=['a']) In [...
What is the purpose of Flask's context stacks?
20,036,520
63
2013-11-17T21:39:14Z
20,041,823
110
2013-11-18T06:51:56Z
[ "python", "flask" ]
I've been using the request/application context for some time without fully understanding how it works or why it was designed the way it was. What is the purpose of the "stack" when it comes to the request or application context? Are these two separate stacks, or are they both part of one stack? Is the request context ...
# Multiple Apps The application context (and its purpose) is indeed confusing until you realize that Flask can have multiple apps. Imagine the situation where you want to have a single WSGI Python interpreter run multiple Flask application. We're not talking Blueprints here, we're talking entirely different Flask appl...
What is the purpose of Flask's context stacks?
20,036,520
63
2013-11-17T21:39:14Z
20,043,255
11
2013-11-18T08:34:21Z
[ "python", "flask" ]
I've been using the request/application context for some time without fully understanding how it works or why it was designed the way it was. What is the purpose of the "stack" when it comes to the request or application context? Are these two separate stacks, or are they both part of one stack? Is the request context ...
Little addition **@Mark Hildreth**'s answer. Context stack look like `{thread.get_ident(): []}`, where `[]` called "stack" because used only `append` (`push`), `pop` and `[-1]` (`__getitem__(-1)`) operations. So context stack will keep actual data for thread or greenlet thread. `current_app`, `g`, `request`, `session...
Understanding NumPy's Convolve
20,036,663
17
2013-11-17T21:53:15Z
20,036,959
33
2013-11-17T22:21:19Z
[ "python", "python-2.7", "numpy", "convolution", "moving-average" ]
When calculating a simple moving average, `numpy.convolve` appears to do the job. **Question:** How is the calculation done when you use `np.convolve(values, weights, 'valid')`? When the docs mentioned `convolution product is only given for points where the signals overlap completely`, what are the 2 signals referrin...
Convolution is a mathematical operator primarily used in signal processing. Numpy simply uses this signal processing nomenclature to define it, hence the "signal" references. An array in numpy is a signal. The convolution of two signals is defined as the integral of the second signal reversed sweeping over the first si...
pandas - reading multiple JSON records into dataframe
20,037,430
9
2013-11-17T23:10:03Z
20,038,973
8
2013-11-18T02:16:31Z
[ "python", "json", "pandas" ]
I'd like to know if there is a memory efficient way of reading multi record JSON file ( each line is a JSON dict) into a pandas dataframe. Below is a 2 line example with working solution, I need it for potentially very large number of records. Example use would be to process output from Hadoop Pig JSonStorage function....
It's going to depend on the size of you DataFrames which is faster, but another option is to use join to smash your multi line "JSON" (Note: it's not valid json), into valid json and use read\_json: ``` In [11]: '[%s]' % ','.join(test.splitlines()) Out[11]: '[{"a":1,"b":2},{"a":3,"b":4}]' ``` For this tiny example th...
pandas - reading multiple JSON records into dataframe
20,037,430
9
2013-11-17T23:10:03Z
22,135,309
13
2014-03-02T23:47:40Z
[ "python", "json", "pandas" ]
I'd like to know if there is a memory efficient way of reading multi record JSON file ( each line is a JSON dict) into a pandas dataframe. Below is a 2 line example with working solution, I need it for potentially very large number of records. Example use would be to process output from Hadoop Pig JSonStorage function....
If you are trying to save memory, then reading the file a line at a time will be much more memory efficient: ``` with open('test.json') as f: data = pd.DataFrame(json.loads(line) for line in f) ``` Also, if you `import simplejson as json`, the compiled C extensions included with `simplejson` are much faster than ...
Trying to find majority element in a list
20,038,011
4
2013-11-18T00:20:21Z
20,038,135
9
2013-11-18T00:37:32Z
[ "python", "arrays", "hash", "hashcode" ]
I'm writing a function to find a majority in a Python list. Thinking that if I can write a hash function that can map every element to a single slot in the new array or to a unique identifier, perhaps for a dictionary, that should be the best and it should be undoable. I am not sure how to progress. My hash function i...
Python has a built-in class called `Counter` that will do this for you. ``` >>> from collections import Counter >>> c = Counter([1,2,3,4,3,3,2,4,5,6,1,2,3,4,5,1,2,3,4,6,5]) >>> c.most_common() [(3, 5), (2, 4), (4, 4), (1, 3), (5, 3), (6, 2)] >>> value, count = c.most_common()[0] >>> print value 3 ``` See the docs. <...
Why is this code working I took from a textbook for GUI Python?
20,039,354
3
2013-11-18T02:59:36Z
20,039,415
9
2013-11-18T03:09:27Z
[ "python", "user-interface" ]
Why isn't this working. This is straight from the text book. I'm getting an Attribute error saying self.\_area does not exist. ``` from Tkinter import * import math class CircleArea(Frame): def __init__(self): """Sets up a window and widgets.""" Frame.__init__(self) self.master.title("Cir...
The problem is that your indenting is wrong. `_area` and `main` are defined within `__init__`, which you don't want. Correct indenting is below (you don't need a `main` function). ``` from Tkinter import * import math class CircleArea(Frame): def __init__(self): """Sets up a window and widgets.""" ...
How to scrape a website that requires login first with Python
20,039,643
19
2013-11-18T03:35:54Z
20,039,870
23
2013-11-18T04:03:17Z
[ "python", "http", "cookies", "authorization", "scraper" ]
First of all, I think it's worth saying that, I know there are a bunch of similar questions but NONE of them works for me... I'm a newbie on Python, html and web scraper. I'm trying to scrape user information from a website which needs to login first. In my tests I use scraper my email settings from github as examples...
This works for me: ``` ##################################### Method 1 import mechanize import cookielib from BeautifulSoup import BeautifulSoup import html2text # Browser br = mechanize.Browser() # Cookie Jar cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) # Browser options br.set_handle_equiv(True) br.set_handl...
Python multiprocessing's Pool process limit
20,039,659
13
2013-11-18T03:37:09Z
20,039,881
17
2013-11-18T04:04:27Z
[ "python", "multiprocessing", "cpu-cores" ]
In using the Pool object from the multiprocessing module, is the number of processes limited by the number of CPU cores? E.g. if I have 4 cores, even if I create a Pool with 8 processes, only 4 will be running at one time?
You can ask for as many processes as you like. Any limit that may exist will be imposed by your operating system, not by `multiprocessing`. For example, ``` p = multiprocessing.Pool(1000000) ``` is likely to suffer an ugly death on any machine. I'm trying it on my box as I type this, and the OS is grinding my disk t...
Python multiprocessing's Pool process limit
20,039,659
13
2013-11-18T03:37:09Z
20,039,972
7
2013-11-18T04:15:04Z
[ "python", "multiprocessing", "cpu-cores" ]
In using the Pool object from the multiprocessing module, is the number of processes limited by the number of CPU cores? E.g. if I have 4 cores, even if I create a Pool with 8 processes, only 4 will be running at one time?
Yes. Theoritcally there is no limit on processes you can create for. but an insane amount of processes started atonce will cause death to the system because of the running out of the memory. Note processes occupy much larger foot print than threads as they don't use shared space between them but uses an individual spac...
How to install latest version of Django 1.5 using pip?
20,040,620
8
2013-11-18T05:19:52Z
20,040,680
13
2013-11-18T05:25:42Z
[ "python", "django", "pip" ]
I want to install django1.5x. So I tried: ``` pip install django ``` but `django1.6` gets installed. I tried again by: ``` pip install django==1.5 ``` but I got error: ``` Could not find any downloads that satisfy the requirement django==1.5 No distributions at all found for django==1.5 Storing complete log in /h...
``` pip install django=="1.5" ``` works for me ``` pip install django=="1.5" Downloading/unpacking django==1.5 Downloading Django-1.5.tar.gz (8.0MB): 8.0MB downloaded Running setup.py egg_info for package django ``` What version of Python are you using?
How to install latest version of Django 1.5 using pip?
20,040,620
8
2013-11-18T05:19:52Z
20,040,758
7
2013-11-18T05:31:59Z
[ "python", "django", "pip" ]
I want to install django1.5x. So I tried: ``` pip install django ``` but `django1.6` gets installed. I tried again by: ``` pip install django==1.5 ``` but I got error: ``` Could not find any downloads that satisfy the requirement django==1.5 No distributions at all found for django==1.5 Storing complete log in /h...
Specify version as `<1.6`: ``` pip install "Django<1.6" ``` This installs *Django 1.5.5* for now. **NOTE**: Don't forget the quotes. otherwise `<` is interpreted as redirection.
Python: Why different threads get their own series of values from one generator?
20,042,534
3
2013-11-18T07:44:36Z
20,042,559
9
2013-11-18T07:46:49Z
[ "python", "multithreading", "generator" ]
I'm learning multithreading in Python. I want to know how to provide data to multiple threads using generators. Here's what I wrote: ``` import threading data = [i for i in xrange(100)] def generator(): for i in data: yield i class CountThread(threading.Thread): def __init__(self, name...
You instantiate a new generator in each thread in `run` function with this: ``` for i in generator(): ``` each `generator` call returns a new instance of generator: ``` >>> data = [i for i in xrange(10)] >>> a, b = generator(), generator() >>> id(a), id(b) (37528032, 37527952) ``` Here `a` and `b` have different id...
How to pip or easy_install tkinter
20,044,559
11
2013-11-18T09:43:31Z
20,044,745
9
2013-11-18T09:52:40Z
[ "python", "python-2.7", "tkinter", "pip", "easy-install" ]
My Idle is throwing errors that and says tkinter can't be imported. Is there a simple way to install tkinter via pip or easy\_install? There seem to be a lot of package names flying around for this... This and other assorted variations with tkinter-pypy aren't working. ``` pip install python-tk ``` I'm on Windows ...
The Tkinter library is build in with every Python installation. And since you are on windows, I believe you installed python through the binaries on their website? if so, Then most probably you are typing the command wrong. It should be: `import Tkinter as tk` Note the capital T at the beginning of Tkinter. For Pyt...
'str' object has no attribute 'META'
20,045,175
4
2013-11-18T10:12:59Z
20,045,245
10
2013-11-18T10:15:59Z
[ "python", "django" ]
I am getting the error: ``` 'str' object has no attribute 'META' ``` The Traceback highlights this bit of code: ``` return render('login.html', c) ``` Where that bit of code is in my views.py: ``` from django.shortcuts import render from django.http import HttpResponseRedirect # allows us to redirect the browse...
First parameter to `render()` is `request` object, so update your line to ``` return render(request, 'login.html', c) ``` It is trying to refer `request.META`, but you are passing `'login.html'` string, hence that error.
How to subclass the default `db.Model` to use as a custom `Base` with SQLAlchemy
20,045,938
3
2013-11-18T10:51:43Z
20,046,068
7
2013-11-18T10:58:02Z
[ "python", "sqlite", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I have a flask application spread across modules with blueprints. Each module/blueprint has its own models.py file where models are defined. With my desktop applications, using SQLAlchemy API directly, I would subclass `object` to define a `Base` class with some columns (ex: `id`, `date_created` ..), which then would ...
Simply set [`__abstract__`](http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/declarative/api.html#abstract) to `True`: ``` class BaseModel(db.Model): __abstract__ = True ```
regex pattern in python for parsing HTML title tags
20,045,955
6
2013-11-18T10:52:28Z
20,046,030
10
2013-11-18T10:56:23Z
[ "python", "regex", "web-scraping" ]
I am learning to use both the `re` module and the `urllib` module in python and attempting to write a simple web scraper. Here's the code I've written to scrape just the title of websites: ``` #!/usr/bin/python import urllib import re urls=["http://google.com","https://facebook.com","http://reddit.com"] i=0 these_...
You are using a regular expression, and matching HTML with such expressions get too complicated, too fast. Use a HTML parser instead, Python has several to choose from. I recommend you use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/), a popular 3rd party library. BeautifulSoup example: ``` from bs4...
regex pattern in python for parsing HTML title tags
20,045,955
6
2013-11-18T10:52:28Z
20,046,224
10
2013-11-18T11:06:06Z
[ "python", "regex", "web-scraping" ]
I am learning to use both the `re` module and the `urllib` module in python and attempting to write a simple web scraper. Here's the code I've written to scrape just the title of websites: ``` #!/usr/bin/python import urllib import re urls=["http://google.com","https://facebook.com","http://reddit.com"] i=0 these_...
It is recommended that you use [beautiful soup](http://www.crummy.com/software/BeautifulSoup/) or other parser to parse html but if you *badly want regex the following piece of code would do the job* **The regex code::** ``` <title.*?>(.+?)</title> ``` ***How it works:*** ![Regular expression visualization](https:/...
Python doctests: test for None
20,047,519
12
2013-11-18T12:12:04Z
20,047,538
19
2013-11-18T12:13:05Z
[ "python", "doctest" ]
Using Python 2.7 I'm trying to test that the result of a particular function call is None I would expect these tests to pass (excuse the rather silly example) ``` def six_or_none(val): """ >>> six_or_none(6) 6 >>> six_or_none(4) None """ if val == 6: return 6 return None ``` H...
The Python interpreter *ignores* `None` return values, so doctests do the same. Test for `is None` instead: ``` >>> six_or_none(4) is None True ```
How to adjust the size of matplotlib legend box?
20,048,352
9
2013-11-18T12:55:57Z
20,049,202
36
2013-11-18T13:38:04Z
[ "python", "matplotlib", "legend" ]
I have a graph whose left upper corner is quite blank. So I decide to put my legend box there. However, I find the **items in legend** are very small and the **legend box itself** is also **quite small**. By "small", I mean something like this ![enter image description here](http://i.stack.imgur.com/ylMMM.png) **Ho...
To control the padding inside the legend (effectively making the legend box bigger) use the `borderpad` kwarg. For example, here's the default: ``` import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) fig, ax = plt.subplots() for i in range(1, 6): ax.plot(x, i*x + x, label='$y={i}x + {...
How to adjust the size of matplotlib legend box?
20,048,352
9
2013-11-18T12:55:57Z
20,049,208
8
2013-11-18T13:38:16Z
[ "python", "matplotlib", "legend" ]
I have a graph whose left upper corner is quite blank. So I decide to put my legend box there. However, I find the **items in legend** are very small and the **legend box itself** is also **quite small**. By "small", I mean something like this ![enter image description here](http://i.stack.imgur.com/ylMMM.png) **Ho...
When you call legend you can use the `prop` argument with a dict containing size. ``` plt.errorbar(x, y, yerr=err, fmt='-o', color='k', label = 'DR errors') plt.legend(prop={'size':50}) ``` E.g. ![change legend size](http://i.stack.imgur.com/6bW5c.png) See here for more info on [legend](http://matplotlib.org/api/leg...
pip-3.3 install MySQL-python
20,049,590
2
2013-11-18T13:57:57Z
20,049,681
12
2013-11-18T14:02:41Z
[ "python", "mysql", "django" ]
I am getting an error pip version pip-3.3 -V pip 1.4.1 from /usr/local/lib/python3.3/site-packages/pip-1.4.1-py3.3.egg (python 3.3) how to install MySQLdb in Python3.3 helpp.. ``` root@thinkpad:~# pip-3.3 install MySQL-python Downloading/unpacking MySQL-python Downloading MySQL-python-1.2.4.zip (113kB): 113kB do...
In python3 `ConfigParser` was renamed to `configparser`. It seems `MySQL-python` does not support python3. Try: ``` $ pip install PyMySQL ``` [PyMySQL](https://github.com/PyMySQL/PyMySQL) is a different module, but it supports python3.
Python unittest's assertDictContainsSubset recommended alternative
20,050,913
9
2013-11-18T15:01:09Z
21,213,251
7
2014-01-19T04:33:42Z
[ "python", "unit-testing" ]
I have some tests in Python written in unittest. I want to check that some of my dictionaries contain at least certain attributes equal to certain values. If there are extra values, that would be fine. `assertDictContainsSubset` would be perfect, except that it's deprecated. Is there a better thing that I should be usi...
If you were testing if dict A is a subset of dict B, I think I would write a function that tries to extract the content of dict A from dict B making a new dict C and then assertEqual(A,C). ``` def extractDictAFromB(A,B): return dict([(k,B[k]) for k in A.keys() if k in B.keys()]) ``` then you could just do ``` as...
Python function call speed
20,051,724
2
2013-11-18T15:39:08Z
20,051,802
7
2013-11-18T15:43:24Z
[ "python", "optimization" ]
I'm really confused with functions call speed in Python. First and second cases, nothing unexpected: ``` %timeit reduce(lambda res, x: res+x, range(1000)) ``` > 10000 loops, best of 3: 150 µs per loop ``` def my_add(res, x): return res + x %timeit reduce(my_add, range(1000)) ``` > 10000 loops, best of 3: 148 µs p...
`add` is implemented in C. ``` >>> from operator import add >>> add <built-in function add> >>> def my_add(res, x): ... return res + x ... >>> my_add <function my_add at 0x18358c0> ``` The reason that a straight `+` is faster is that `add` still has to call the Python VM's `BINARY_ADD` instruction as well as per...
np.mean() vs np.average() in Python NumPy?
20,054,243
48
2013-11-18T17:43:30Z
20,054,373
9
2013-11-18T17:50:46Z
[ "python", "numpy" ]
Title says it all. I notice that ``` In [30]: np.mean([1, 2, 3]) Out[30]: 2.0 In [31]: np.average([1, 2, 3]) Out[31]: 2.0 ``` However, there should be some differences, since after all they are two different functions. **What are the differences between them?**
`np.mean` always computes an arithmetic mean, and has some additional options for input and output (e.g. what datatypes to use, where to place the result). `np.average` can compute a weighted average if the `weights` parameter is supplied.
np.mean() vs np.average() in Python NumPy?
20,054,243
48
2013-11-18T17:43:30Z
20,054,396
55
2013-11-18T17:51:47Z
[ "python", "numpy" ]
Title says it all. I notice that ``` In [30]: np.mean([1, 2, 3]) Out[30]: 2.0 In [31]: np.average([1, 2, 3]) Out[31]: 2.0 ``` However, there should be some differences, since after all they are two different functions. **What are the differences between them?**
np.average takes an optional weight parameter. If it is not supplied they are equivalent. Take a look at the source code. np.mean: ``` try: mean = a.mean except AttributeError: return _wrapit(a, 'mean', axis, dtype, out) return mean(axis, dtype, out) ``` np.average: ``` ... if weights is None : avg = a....
Exposing C++ interface in boost python
20,054,822
5
2013-11-18T18:15:04Z
20,056,409
7
2013-11-18T19:45:58Z
[ "c++", "python", "boost-python" ]
Sample code to illustrate: ``` struct Base { virtual int foo() = 0; }; struct Derived : public Base { virtual int foo() { return 42; } }; Base* get_base() { return new Derived; } BOOST_PYTHON_MODULE(libTestMod) { py::class_<Base>("Base", py::no_init) .def("foo", py::pure_virtual(&Base::foo)); ...
Abstract C++ classes cannot be exposed in this manner to Boost.Python. The Boost.Python [tutorial](http://www.boost.org/doc/libs/1_55_0/libs/python/doc/tutorial/doc/html/python/exposing.html#python.class_virtual_functions) gives examples as to how to expose pure virtual functions. In short, when decorating methods with...
PYODBC to Pandas - DataFrame not working - Shape of passed values is (x,y), indices imply (w,z)
20,055,257
10
2013-11-18T18:38:30Z
20,059,818
20
2013-11-18T23:01:13Z
[ "python", "windows-8", "pandas", "64bit", "pyodbc" ]
I used pyodbc with python before but now I have installed it on a new machine ( win 8 64 bit, Python 2.7 64 bit, PythonXY with Spyder). Before I used to (at the bottom you can find more real examples): ``` columns = [column[0] for column in cursor.description] temp = cursor.fetchall() data = pandas.DataFrame(temp,col...
As of Pandas 0.12 (I believe) you can do: ``` import pandas import pyodbc sql = 'select * from table' cnn = pyodbc.connect(...) data = pandas.read_sql(sql, cnn) ``` Prior to 0.12, you could do: ``` import pandas from pandas.io.sql import read_frame import pyodbc sql = 'select * from table' cnn = pyodbc.connect(.....