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
Matlab range in Python
37,571,622
3
2016-06-01T14:31:28Z
37,571,844
7
2016-06-01T14:40:35Z
[ "python", "matlab", "numpy", "range" ]
I must translate some Matlab code into Python 3 and I often come across ranges of the form start:step:stop. When these arguments are all integers, I easily translate this command with np.arange(), but when some of the arguments are floats, especially the step parameter, I don't get the same output in Python. For exampl...
You don't actually need to add your entire step size to the max limit of `np.arange` but just a very tiny number to make sure that that max is enclose. For example the [machine epsilon](http://stackoverflow.com/a/19141711/1011724): ``` eps = np.finfo(np.float32).eps ``` adding `eps` will give you the same result as M...
Python 3.x multi line comment throws syntax error
37,571,974
2
2016-06-01T14:46:16Z
37,572,043
7
2016-06-01T14:48:37Z
[ "python", "indentation" ]
I'm working on a Python project and as of now, my code has over 400+ lines. At one point, I had to write a multi-line comment about a small bug which needs a work around, and the interpreter decided to throw a syntax error. According to the interpreter, the syntax error is occuring at **elif**. I re-checked my indenta...
This is an indentation error. Your "multi-line comment" (really multi-line string) must be indented under the `if` block just like anything else. `""" These kinds of things """` are not really comments in Python. You're just creating a string and then throwing the value away (not storing it anywhere). Since Python doe...
Generating random vectors of Euclidean norm <= 1 in Python?
37,577,803
11
2016-06-01T20:04:26Z
37,577,963
9
2016-06-01T20:14:50Z
[ "python", "numpy", "random" ]
More specifically, given a natural number d, how can I generate random vectors in R^d such that each vector x has Euclidean norm <= 1? Generating random vectors via numpy.random.rand(1,d) is no problem, but the likelihood of such a random vector having norm <= 1 is predictably bad for even not-small d. For example, ev...
Based on the Wolfram Mathworld article on [hypersphere point picking](http://mathworld.wolfram.com/HyperspherePointPicking.html) and [Nate Eldredge's answer](http://math.stackexchange.com/questions/87230/picking-random-points-in-the-volume-of-sphere-with-uniform-probability) to a similar question on math.stackexchange....
How can I set a default for star arguments?
37,587,389
4
2016-06-02T09:09:12Z
37,587,548
11
2016-06-02T09:16:19Z
[ "python", "python-3.x" ]
I have a function that accepts `*args`, but I would like to set a default tuple, in case none are provided. (This is not possible through `def f(*args=(1, 3, 5))`, which raises a `SyntaxError`.) What would be the best way to accomplish this? The intended functionality is shown below. ``` f() # I received 1, 2, 3! f(1...
You could check whether `args` are truthy in your function: ``` def g(*args): if not args: args = (1, 2, 3) return "I received {}!".format(', '.join(str(arg) for arg in args)) ``` If no `args` are passed to the function, it will result in a empty tuple, which evaluates to `False`.
Drop duplicates in pandas time series dataframe
37,602,233
3
2016-06-02T21:14:49Z
37,602,345
9
2016-06-02T21:22:20Z
[ "python", "pandas", "dataframe", "time-series" ]
I have time series data in a data frame that looks like this: ``` Index Time Value_A Value_B 0 1 A A 1 2 A A 2 2 B A 3 3 A A 4 5 A A ``` I want to drop duplicate in the Value\_A and Value\_B columns such that duplicates are only dropped until a differen...
The usual trick to detect contiguous groups is to compare something with a shifted version of itself. For example: ``` In [137]: cols = ["Value_A", "Value_B"] In [138]: df[~(df[cols] == df[cols].shift()).all(axis=1)] Out[138]: Time Value_A Value_B Index 0 1 A A 2 ...
Replacing python list elements with key
37,603,164
4
2016-06-02T22:28:57Z
37,603,292
9
2016-06-02T22:42:06Z
[ "python", "list", "key" ]
I have a list of non-unique strings: ``` list = ["a", "b", "c", "a", "a", "d", "b"] ``` I would like to replace each element with an integer key which uniquely identifies each string: ``` list = [0, 1, 2, 0, 0, 3, 1] ``` The number does not matter, as long as it is a unique identifier. So far all I can think to do...
This will guarantee uniqueness and that the id's are contiguous starting from `0`: ``` id_s = {c: i for i, c in enumerate(set(list))} li = [id_s[c] for c in list] ``` On a different note, you should not use `'list'` as variable name because it will shadow the built-in type `list`.
How to convert sort using cmp from python 2 to python 3?
37,603,757
5
2016-06-02T23:32:58Z
37,603,846
8
2016-06-02T23:43:58Z
[ "python", "sorting", "python2to3" ]
I'm trying to convert this code which is written in python 2 to python 3 ``` nums = ["30", "31"] num.sort(cmp=lambda x, y: cmp(y + x, x + y)) ``` Not sure how to do that in python 3 since cmp is removed (I believed) The result should be `["31", "30"]` instead of `["30", "31"]`
This is one of the rare cases where a comparator is much cleaner than a key function. I'd actually just reimplement `cmp`: ``` try: cmp except NameError: def cmp(x, y): if x < y: return -1 elif x > y: return 1 else: return 0 ``` and then use [`functoo...
When is hash(n) == n in Python?
37,612,524
94
2016-06-03T10:55:04Z
37,613,404
7
2016-06-03T11:38:23Z
[ "python", "python-2.7", "python-3.x", "hash" ]
I've been playing with Python's [hash function](https://docs.python.org/3/library/functions.html#hash). For small integers, it appears `hash(n) == n` always. However this does not extend to large numbers: ``` >>> hash(2**100) == 2**100 False ``` I'm not surprised, I understand hash takes a finite range of values. Wha...
Hash function returns **plain int** that means that returned value is greater than `-sys.maxint` and lower than `sys.maxint`, which means if you pass `sys.maxint + x` to it result would be `-sys.maxint + (x - 2)`. ``` hash(sys.maxint + 1) == sys.maxint + 1 # False hash(sys.maxint + 1) == - sys.maxint -1 # True hash(sy...
When is hash(n) == n in Python?
37,612,524
94
2016-06-03T10:55:04Z
37,614,051
76
2016-06-03T12:10:07Z
[ "python", "python-2.7", "python-3.x", "hash" ]
I've been playing with Python's [hash function](https://docs.python.org/3/library/functions.html#hash). For small integers, it appears `hash(n) == n` always. However this does not extend to large numbers: ``` >>> hash(2**100) == 2**100 False ``` I'm not surprised, I understand hash takes a finite range of values. Wha...
`2305843009213693951` is `2^61 - 1`. It's the largest Mersenne prime that fits into 64 bits. If you have to make a hash just by taking the value mod some number, then a large Mersenne prime is a good choice -- it's easy to compute and ensures an even distribution of possibilities. (Although I personally would never ma...
When is hash(n) == n in Python?
37,612,524
94
2016-06-03T10:55:04Z
37,614,182
64
2016-06-03T12:16:11Z
[ "python", "python-2.7", "python-3.x", "hash" ]
I've been playing with Python's [hash function](https://docs.python.org/3/library/functions.html#hash). For small integers, it appears `hash(n) == n` always. However this does not extend to large numbers: ``` >>> hash(2**100) == 2**100 False ``` I'm not surprised, I understand hash takes a finite range of values. Wha...
Based on python documentation in [`pyhash.c`](https://github.com/python/cpython/blob/master/Python/pyhash.c) file: > For numeric types, the hash of a number x is based on the reduction > of x modulo the prime `P = 2**_PyHASH_BITS - 1`. It's designed so that > `hash(x) == hash(y)` whenever x and y are numerically equal...
Given a list of n points, how can I generate a matrix that contains the distance from every point to every other point using numpy?
37,616,593
4
2016-06-03T14:08:47Z
37,616,731
7
2016-06-03T14:14:59Z
[ "python", "matlab", "numpy", "matrix" ]
Hey guys so i'm trying to rewrite the following matlab code in python: ``` repmat(points, 1, length(points)) - repmat(points', length(points),1); ``` `points` is an array that contain the radian value of several points. The above code gives me a matrix output like this: ``` 0 1 2 0 1 2 0 1 2 -1 0...
In MATLAB, you had to use `repmat` because you needed the arrays on the left and right side of the `-` to be the same size. With numpy, this does not have to be the case thanks to numpy's [automatic broadcasting](https://docs.scipy.org/doc/numpy-dev/user/quickstart.html#broadcasting-rules). Instead, you can simply subt...
Summing 2nd list items in a list of lists of lists
37,619,348
4
2016-06-03T16:28:34Z
37,619,560
7
2016-06-03T16:41:55Z
[ "python", "list", "list-comprehension" ]
My data is a list of lists of lists of varying size: ``` data = [[[1, 3],[2, 5],[3, 7]],[[1,11],[2,15]],.....]]] ``` What I want to do is return a list of lists with the values of the 2nd element of each list of lists summed - so, 3+5+7 is a list, so is 11+15, etc: ``` newdata = [[15],[26],...] ``` Or even just a l...
Try this one-line approach using list comprehension: ``` [sum([x[1] for x in i]) for i in data] ``` Output: ``` data = [[[1, 3],[2, 5],[3, 7]],[[1,11],[2,15]]] [sum([x[1] for x in i]) for i in data] Out[19]: [15, 26] ``` If you want the output to be a list of list, then use ``` [[sum([x[1] for x in i])] for i in d...
How can I make sense of the `else` statement in Python loops?
37,642,573
173
2016-06-05T13:41:04Z
37,643,193
29
2016-06-05T14:46:51Z
[ "python", "loops", "for-loop", "while-loop" ]
Many Python programmers are probably unaware that the syntax of `while` loops and `for` loops includes an optional `else:` clause: ``` for val in iterable: do_something(val) else: clean_up() ``` The body of the `else` clause is a good place for certain kinds of clean-up actions, and is executed on normal term...
When does an `if` execute an `else`? When its condition is false. It is exactly the same for the `while`/`else`. So you can think of `while`/`else` as just an `if` that keeps running its true condition until it evaluates false. A `break` doesn't change that. It just jumps of of the containing loop with no evaluation. T...
How can I make sense of the `else` statement in Python loops?
37,642,573
173
2016-06-05T13:41:04Z
37,643,265
20
2016-06-05T14:53:43Z
[ "python", "loops", "for-loop", "while-loop" ]
Many Python programmers are probably unaware that the syntax of `while` loops and `for` loops includes an optional `else:` clause: ``` for val in iterable: do_something(val) else: clean_up() ``` The body of the `else` clause is a good place for certain kinds of clean-up actions, and is executed on normal term...
This is what it essentially means: ``` for/while ...: if ...: break if there was a break: pass else: ... ``` It's a nicer way of writing of this common pattern: ``` found = False for/while ...: if ...: found = True break if not found: ... ``` The `else` clause will not be...
How can I make sense of the `else` statement in Python loops?
37,642,573
173
2016-06-05T13:41:04Z
37,643,296
19
2016-06-05T14:57:15Z
[ "python", "loops", "for-loop", "while-loop" ]
Many Python programmers are probably unaware that the syntax of `while` loops and `for` loops includes an optional `else:` clause: ``` for val in iterable: do_something(val) else: clean_up() ``` The body of the `else` clause is a good place for certain kinds of clean-up actions, and is executed on normal term...
If you think of your loops as a structure similar to this (somewhat pseudo-code): ``` loop: if condition then ... //execute body goto loop else ... ``` it might make a little bit more sense. A loop is essentially just an `if` statement that is repeated until the condition is `false`. And this is the importa...
How can I make sense of the `else` statement in Python loops?
37,642,573
173
2016-06-05T13:41:04Z
37,643,358
31
2016-06-05T15:02:49Z
[ "python", "loops", "for-loop", "while-loop" ]
Many Python programmers are probably unaware that the syntax of `while` loops and `for` loops includes an optional `else:` clause: ``` for val in iterable: do_something(val) else: clean_up() ``` The body of the `else` clause is a good place for certain kinds of clean-up actions, and is executed on normal term...
Better to think of it this way: The `else` block will **always** be executed if everything goes *right* in the preceding `for` block such that it reaches exhaustion. *Right* in this context will mean no `exception`, no `break`, no `return`. Any statement that hijacks control from `for` will cause the `else` block to b...
How can I make sense of the `else` statement in Python loops?
37,642,573
173
2016-06-05T13:41:04Z
37,644,460
192
2016-06-05T16:54:53Z
[ "python", "loops", "for-loop", "while-loop" ]
Many Python programmers are probably unaware that the syntax of `while` loops and `for` loops includes an optional `else:` clause: ``` for val in iterable: do_something(val) else: clean_up() ``` The body of the `else` clause is a good place for certain kinds of clean-up actions, and is executed on normal term...
(This is inspired by @Mark Tolonen's answer.) An `if` statement runs its `else` clause if its condition evaluates to false. Identically, a `while` loop runs the else clause if its condition evaluates to false. This rule matches the behavior you described: * In normal execution, the while loop repeatedly runs until t...
How can I make sense of the `else` statement in Python loops?
37,642,573
173
2016-06-05T13:41:04Z
37,658,079
13
2016-06-06T12:54:57Z
[ "python", "loops", "for-loop", "while-loop" ]
Many Python programmers are probably unaware that the syntax of `while` loops and `for` loops includes an optional `else:` clause: ``` for val in iterable: do_something(val) else: clean_up() ``` The body of the `else` clause is a good place for certain kinds of clean-up actions, and is executed on normal term...
My gotcha moment with the loop's `else` clause was when I was watching a talk by [Raymond Hettinger](http://stackoverflow.com/users/1001643/raymond-hettinger), who told a story about how he thought it should have been called `nobreak`. Take a look at the following code, what do you think it would do? ``` for i in rang...
common lisp equivalent of a python idiom
37,645,391
3
2016-06-05T18:32:40Z
37,645,615
7
2016-06-05T18:56:36Z
[ "python", "lisp", "common-lisp" ]
How do I run an equivalent of this Python command in Lisp ``` from lib import func ``` For example, I want to use the `split-sequence` package, and in particular I only want the `split-sequence` method from that package. Currently, I have to use it as `(split-sequence:split-sequence #\Space "this is a string")`. Bu...
What you want to do is simply: ``` (import 'split-sequence:split-sequence) ``` This works fine in a REPL, but if you want to organize your symbols, you'd better rely on packages. ``` (defpackage #:my-package (:use #:cl) (:import-from #:split-sequence #:split-sequence)) ``` The first ̀`spli...
How to classify blurry numbers with openCV
37,645,576
19
2016-06-05T18:52:26Z
37,645,912
18
2016-06-05T19:28:26Z
[ "python", "opencv", "edge-detection", "number-recognition" ]
I would like to capture the number from this kind of picture. [![enter image description here](http://i.stack.imgur.com/S8esF.png)](http://i.stack.imgur.com/S8esF.png) I tried multi-scale matching from the following link. <http://www.pyimagesearch.com/2015/01/26/multi-scale-template-matching-using-python-opencv/> A...
**Classifying Digits** You clarified in comments that you've already isolated the number part of the image pre-detection, so I'll start under that assumption. Perhaps you can approximate the perspective effects and "blurriness" of the number by treating it as a hand-written number. In this case, there is a famous dat...
Python-style variables in C++
37,651,358
3
2016-06-06T07:04:38Z
37,651,398
7
2016-06-06T07:06:53Z
[ "python", "c++", "types", "type-safety", "strong-typing" ]
I'm working on a C++ project and am trying to figure out how to make a "dynamic" variable. In Python, variables can have multiple types: ``` variable = 0 variable = "Hello" ``` In Java, this is also (somewhat) achievable: ``` Object o = 0; o = "Hello"; ``` From what I can find related to C++, there is no `object` ...
You can use [boost.variant](http://www.boost.org/doc/libs/1_61_0/doc/html/variant.html) library. Basic usage instructions [here](http://www.boost.org/doc/libs/1_61_0/doc/html/variant/tutorial.html#variant.tutorial.basic). In short, it would be something like ``` using var_t = boost::variant<bool,int,double,string, boo...
Modifying a dict during iteration
37,667,277
8
2016-06-06T21:38:10Z
37,667,331
7
2016-06-06T21:43:01Z
[ "python", "dictionary" ]
What's going on below ``` >>> d = {0:0} >>> for i in d: ... del d[i] ... d[i+1] = 0 ... print(i) ... 0 1 2 3 4 5 6 7 >>> ``` Why does the iteration stop at 8 without any error? Reproducible on both python2.7 and python 3.5.
The initial size of the key table in a dict is 8 elements. So `0`...`7` sets the 1st to 8th element and 8 sets the 1st element again, ending the loop. ### [Source: Objects/dictobject.c](https://github.com/python/cpython/blob/master/Objects/dictobject.c#L60) > /\* PyDict\_MINSIZE\_COMBINED is the starting size for any...
Recursively calling a Merge Sort algorithm
37,673,137
4
2016-06-07T07:31:54Z
37,673,197
7
2016-06-07T07:35:09Z
[ "python", "algorithm", "recursion" ]
I'm new to recursion, and currently writing a Merge Sort algorithm that compares the first elements of two lists and determines which one is smaller, then adds the smaller one to a new list. I'm trying to update the three lists after each comparison and have the function call itself again with the updated lists, but I...
Your code lead to infinite recursion. You should move `list1`,`list2` and `new_list` initialization outside of `merge_Sort` function. ``` def merge_Sort(list1, list2, new_list): for i in range(len(list1)): if list1[0] < list2[0]: new_list.append(list1[0]) list1.remove(list1[0]) ...
How to make Python generators as fast as possible?
37,675,026
4
2016-06-07T09:07:34Z
37,675,802
10
2016-06-07T09:43:13Z
[ "python", "python-3.x", "generator" ]
For writing an event-driven simulator, I'm relying on [simpy](https://simpy.readthedocs.io/en/latest/), which heavily uses Python generators. I'm trying to understand how to make generators as fast as possible, i.e., minimize the state save/restore overhead. I tried three alternatives 1. All state stored in a class in...
The generator actually retains the actual *call frames* when *yield* happens. It doesn't really affect performance whether you have 1 or 100 local variables. The performance difference really comes from how Python (here I am using the CPython a.k.a. the one that you'd download from <http://www.python.com/>, or have on...
List of tuple to string in Python
37,678,612
3
2016-06-07T11:50:45Z
37,678,648
11
2016-06-07T11:52:51Z
[ "python" ]
I have a list like this: ``` l = ['b', '7', 'a', 'e', 'a', '6', 'a', '7', '9', 'c', '7', 'b', '6', '9', '9', 'd', '7', '5', '2', '4', 'c', '7', '8', 'b', '3', 'f', 'f', '7', 'b', '9', '4', '4'] ``` and I want to make a string from it like this: ``` 7bea6a7ac9b796d957427cb8f37f9b44 ``` I did: ``` l = (zip(l[1:], l)...
You can concatenate each pair of letters, then `join` the whole result in a generator expression ``` >>> ''.join(i+j for i,j in zip(l[1::2], l[::2])) '7bea6a7ac9b796d957427cb8f37f9b44' ```
Timing Modular Exponentiation in Python: syntax vs function
37,686,000
4
2016-06-07T17:47:00Z
37,686,188
7
2016-06-07T17:57:11Z
[ "python", "python-2.7", "python-3.x" ]
In Python, if the builtin `pow()` function is used with 3 arguments, the last one is used as the modulus of the exponentiation, resulting in a [Modular exponentiation](https://en.wikipedia.org/wiki/Modular_exponentiation) operation. In other words, `pow(x, y, z)` is equivalent to `(x ** y) % z`, but accordingly to Pyt...
You're not actually timing the computation with `**` and `%`, because the result gets constant-folded by the bytecode compiler. Avoid that: ``` timeit.timeit('(a**b) % c', setup='a=65537; b=767587; c=14971787') ``` and the `pow` version will win hands down.
Python and OpenSSL version reference issue on OS X
37,690,054
8
2016-06-07T21:54:04Z
37,712,029
14
2016-06-08T20:11:08Z
[ "python", "osx", "ssl", "openssl", "version" ]
Trying to resolve an OpenSSL version issue I'm having. It seems that I have three different versions of OpenSSL on my Mac. 1. Python 2.7.11 has version 0.9.7m: ``` python -c "import ssl; print ssl.OPENSSL_VERSION" OpenSSL 0.9.7m 23 Feb 2007 ``` 2. At the Terminal: ``` openssl version OpenSSL 1....
Use this as a workaround: ``` export CRYPTOGRAPHY_ALLOW_OPENSSL_098=1 ``` This appears to be a recent check of the hazmat cryptography library. You can see the source code at: <https://github.com/pyca/cryptography/blob/master/src/cryptography/hazmat/bindings/openssl/binding.py#L221> The `CRYPTOGRAPHY_ALLOW_OPENSSL_...
How to create a dictionary from a list with a list of keys only and key-value pairs (Python)?
37,705,101
3
2016-06-08T14:18:22Z
37,705,455
9
2016-06-08T14:31:52Z
[ "python", "string", "list", "dictionary" ]
This is an extension of this question: [How to split a string within a list to create key-value pairs in Python](http://stackoverflow.com/questions/12739911/how-to-separate-string-and-create-a-key-value-pairs-python) The difference from the above question is the items in my list are not all key-value pairs; some items...
For each split "pair", you can append `[1]` and extract the first 2 elements. This way, 1 will be used when there isn't a value: ``` print dict((s.split('=')+[1])[:2] for s in l) ```
pip error while installing Python: "Ignoring ensurepip failure: pip 8.1.1 requires SSL/TLS"
37,723,236
6
2016-06-09T10:21:07Z
37,723,517
11
2016-06-09T10:34:26Z
[ "python", "install" ]
I downloaded the Python 3.5 source code and ran the following: ``` $ tar -xf Python-3.5.2.tar.xz $ ./configure --with-ensurepip=upgrade $ make $ sudo make altinstall ``` It proceeded well until `make`. When `sudo make altinstall` ran, it printed: `Ignoring ensurepip failure: pip 8.1.1 requires SSL/TLS` What went wr...
You are most likely not compiling Python with SSL/TLS support - this is likely because you don't have the SSL development libraries installed on your system. Install the following dependency, and then re-configure and re-compile Python 3.5. **Ubuntu** ``` apt-get install libssl-dev ``` In addition it is recommended...
Find 3 letter words
37,728,006
4
2016-06-09T13:55:51Z
37,728,157
8
2016-06-09T14:01:56Z
[ "python" ]
I have the following code in Python: ``` import re string = "what are you doing you i just said hello guys" regexValue = re.compile(r'(\s\w\w\w\s)') mo = regexValue.findall(string) ``` My goal is to find any 3 letter word, but for some reason I seem to only be getting the "are" and not the "you" in my list. I figured...
It's not regex, but you could do this: ``` words = [word for word in string.split() if len(word) == 3] ```
Python nosetests with coverage no longer shows missing lines
37,733,194
7
2016-06-09T18:05:02Z
37,746,141
10
2016-06-10T10:39:45Z
[ "python", "nose", "coverage.py" ]
I've been using the following command to run tests and evaluate code coverage for a Python project for over a year now. ``` nosetests -v --with-coverage --cover-package=genhub genhub/*.py ``` The coverage report used to include a column on the far right showing the lines missing coverage. ``` Name St...
In coverage.py 4.1, I fixed a problem with the coverage.py API defaulting two parameters to non-None values. One of them was `show_missing`. The best way to fix this in your project is to set `show_missing` in your .coveragerc file: ``` # .coveragerc [report] show_missing = True ```
How to use SyntaxNet output to operate an executive command ,for example save a file in a folder, on Linux system
37,753,980
2
2016-06-10T17:24:03Z
38,444,785
8
2016-07-18T19:43:09Z
[ "python", "xml", "terminal", "semantics", "syntaxnet" ]
having downloaded and trained [SyntaxNet](https://github.com/tensorflow/models/tree/master/syntaxnet), I am trying to write a program that can open new/existed files, for example AutoCAD files, and save the files in an specific directory by analyzing the text: **open LibreOffice file X** . considering the output of Syn...
I am a beginner in Computer Science World and SyntaxNet. I wrote a simple SyntaxNet-Python algorithm which used SyntaxNet to analyze a text command a user inserts,"open the file book which I have written with laboratory writer with LibreOffice writer", and then analyzes SyntaxNet output with a python algorithm in order...
What does CPython actually do when "=" is performed on primitive type variables?
37,764,401
4
2016-06-11T13:39:27Z
37,764,949
7
2016-06-11T14:38:23Z
[ "python", "cpython", "reference-counting" ]
For instance: ``` a = some_process_that_generates_integer_result() b = a ``` Someone told me that *b* and *a* will point to same chunk of integer object, thus *b* would modify the reference count of that object. The code is executed in function `PyObject* ast2obj_expr(void* _o)` in *Python-ast.c*: ``` static PyObjec...
First of all, there are no “primitive objects” in Python. Everything is an object, of the same kind, and they are all handled in the same way on the language level. As such, the following assignments work the same way regardless of the values which are assigned: ``` a = some_process_that_generates_integer_result()...
mac - pip install pymssql error
37,771,434
3
2016-06-12T06:38:34Z
38,002,724
8
2016-06-23T22:10:13Z
[ "python", "osx", "python-2.7", "pymssql" ]
I use mac(Ver. 10.11.5). I want to install module pymssql for python. In terminal, I input `sudo -H pip install pymssql`, `pip install pymssql`, `sudo pip install pymssql` . But error occur. The directory '/Users/janghyunsoo/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cach...
I was able to work around this by reverting to an older version of FreeTDS through Homebrew before running the pip install. ``` brew unlink freetds; brew install homebrew/versions/freetds091 ``` The solution was found by andrewmwhite at: <https://github.com/pymssql/pymssql/issues/432>
Fast Numpy Loops
37,793,370
11
2016-06-13T15:14:11Z
37,793,744
7
2016-06-13T15:31:42Z
[ "python", "numpy", "vectorization", "cython" ]
How do you optimize this code (***without*** vectorizing, as this leads up to using the semantics of the calculation, which is quite often far from being non-trivial): ``` slow_lib.py: import numpy as np def foo(): size = 200 np.random.seed(1000031212) bar = np.random.rand(size, size) moo = np.zeros((...
Memory permitting, you can use [`np.einsum`](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.einsum.html) to perform those heavy calculations in a vectorized manner, like so - ``` moo = size*np.einsum('ij,ik->jk',bar,bar) ``` One can also use [`np.tensordot`](http://docs.scipy.org/doc/numpy-1.10.1/re...
Fast Numpy Loops
37,793,370
11
2016-06-13T15:14:11Z
37,794,513
12
2016-06-13T16:11:37Z
[ "python", "numpy", "vectorization", "cython" ]
How do you optimize this code (***without*** vectorizing, as this leads up to using the semantics of the calculation, which is quite often far from being non-trivial): ``` slow_lib.py: import numpy as np def foo(): size = 200 np.random.seed(1000031212) bar = np.random.rand(size, size) moo = np.zeros((...
Here's the code for `outer`: ``` def outer(a, b, out=None): a = asarray(a) b = asarray(b) return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis,:], out) ``` So each call to `outer` involves a number of python calls. Those eventually call compiled code to perform the multiplication. But each incurs ...
Regex - Python matching between string and first occurence
37,797,979
2
2016-06-13T19:46:30Z
37,798,006
7
2016-06-13T19:48:45Z
[ "python", "regex" ]
I'm having a hard time grasping regex no matter how much documentation I read up on. I'm trying to match everything between a a string and the first occurrence of `&` this is what I have ``` link = "group.do?sys_id=69adb887157e450051e85118b6ff533c&amp;&" rex = re.compile("group\.do\?sys_id=(.?)&") sysid = rex.search(...
You don't necessarily need regular expressions here. Use [`urlparse`](https://docs.python.org/2/library/urlparse.html) instead: ``` >>> from urlparse import urlparse, parse_qs >>> parse_qs(urlparse(link).query)['sys_id'][0] '69adb887157e450051e85118b6ff533c' ``` In case of [Python 3](https://docs.python.org/3/librar...
Variable step in a for loop
37,845,872
17
2016-06-15T21:14:00Z
37,846,018
19
2016-06-15T21:23:21Z
[ "python", "for-loop" ]
I am trying to loop between 0.01 and 10, but between 0.01 and 0.1 use 0.01 as the step, then between 0.1 and 1.0 use 0.1 as step, and between 1.0 and 10.0 use 1.0 as step. I have the while loop code written, but want to make it more pythonic. ``` i = 0.01 while i < 10: # do something print i if i < 0.1: ...
A special-purse generator function might be the right way to go. This would effectively separate the boring part (getting the list of numbers right) from the interesting part (the `# do something` in your example). ``` def my_range(): for j in .01, .1, 1.: for i in range(1, 10, 1): yield i * j ...
Why is Django returning stale cache data?
37,849,236
9
2016-06-16T03:08:58Z
37,904,144
9
2016-06-19T05:11:48Z
[ "python", "django", "django-cache", "django-cache-machine" ]
I have two Django models as shown below, `MyModel1` & `MyModel2`: ``` class MyModel1(CachingMixin, MPTTModel): name = models.CharField(null=False, blank=False, max_length=255) objects = CachingManager() def __str__(self): return "; ".join(["ID: %s" % self.pk, "name: %s" % self.name, ] ) class MyM...
## Is django-cache-machine really needed? ``` MyModel1.objects.all()[0] ``` Roughly translates to ``` SELECT * FROM app_mymodel LIMIT 1 ``` Queries like this are always fast. There would not be a significant difference in speeds whether you fetch it from the cache or from the database. When you use cache manager y...
How can I perform two-dimensional interpolation using scipy?
37,872,171
29
2016-06-17T02:27:48Z
37,872,172
35
2016-06-17T02:27:48Z
[ "python", "scipy", "interpolation" ]
> **This Q&A is intended as a canonical(-ish) concerning two-dimensional (and multi-dimensional) interpolation using scipy. There are often questions concerning the basic syntax of various multidimensional interpolation methods, I hope to set these straight too.** I have a set of scattered two-dimensional data points,...
Disclaimer: I'm mostly writing this post with syntactical considerations and general behaviour in mind. I'm not familiar with the memory and CPU aspect of the methods described, and I aim this answer at those who have reasonably small sets of data, such that the quality of the interpolation can be the main aspect to co...
How to round a number to a chosen integer
37,877,895
16
2016-06-17T09:26:29Z
37,878,425
21
2016-06-17T09:49:45Z
[ "python", "rounding" ]
In Denmark we have an odd grading system that goes as follows. [-3,00,02,4,7,10,12] Our assignment is to take a vector with different decimal numbers, and round it to the nearest valid grade. Here is our code so far. ``` import numpy as np def roundGrade(grades): if (-5<grades<-1.5): gradesRounded = -...
You are getting that error because when you print, you are using incorrect syntax: ``` print(roundGrade(np.array[-2.1,6.3,8.9,9])) ``` needs to be ``` print(roundGrade(np.array([-2.1,6.3,8.9,9]))) ``` Notice the extra parentheses: `np.array(<whatever>)` However, this won't work, since your function expects a singl...
How to round a number to a chosen integer
37,877,895
16
2016-06-17T09:26:29Z
37,878,529
17
2016-06-17T09:55:08Z
[ "python", "rounding" ]
In Denmark we have an odd grading system that goes as follows. [-3,00,02,4,7,10,12] Our assignment is to take a vector with different decimal numbers, and round it to the nearest valid grade. Here is our code so far. ``` import numpy as np def roundGrade(grades): if (-5<grades<-1.5): gradesRounded = -...
You could simply take the minimum distance from each grade to each grade group, like so. This assumes you actually want to round to the nearest grade from your grade group, which your current code doesn't do exactly. ``` grade_groups = [-3,0,2,4,7,10,12] sample_grades = [-2.1,6.3,8.9,9] grouped = [min(grade_groups,key...
Indexing one array by another in numpy
37,878,946
4
2016-06-17T10:15:22Z
37,879,017
7
2016-06-17T10:18:54Z
[ "python", "numpy" ]
Suppose I have a matrix **A** with some arbitrary values: ``` array([[ 2, 4, 5, 3], [ 1, 6, 8, 9], [ 8, 7, 0, 2]]) ``` And a matrix **B** which contains indices of elements in A: ``` array([[0, 0, 1, 2], [0, 3, 2, 1], [3, 2, 1, 0]]) ``` How do I select values from **A** pointed by **B**,...
You can use [`NumPy's advanced indexing`](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing) - ``` A[np.arange(A.shape[0])[:,None],B] ``` One can also use `linear indexing` - ``` m,n = A.shape out = np.take(A,B + n*np.arange(m)[:,None]) ``` Sample run - ``` In [40]: A Out[40]: array...
using decorators to persist python objects
37,883,015
8
2016-06-17T13:35:20Z
37,914,677
10
2016-06-20T04:34:07Z
[ "python", "ipython-notebook", "jupyter-notebook" ]
Code that I got from below link, can persist data to the disk. <http://tohyongcheng.github.io/python/2016/06/07/persisting-a-cache-in-python-to-disk.html> I tried it but the file does not get generated. ``` import atexit import pickle # or import cPickle as pickle def persist_cache_to_disk(filename): def decora...
The problem is the example employs `atexit` which runs the dump routine only when python exits. This modified version will dump each time the cache is updated: ``` import atexit import functools import pickle # or import cPickle as pickle def persist_cache_to_disk(filename): def decorator(original_func): ...
Meaning of '>>' in Python byte code
37,900,782
11
2016-06-18T19:19:45Z
37,900,805
12
2016-06-18T19:21:46Z
[ "python", "virtual-machine", "bytecode" ]
I have disassembled the following python code ``` def factorial(n): if n <= 1: return 1 elif n == 2: return 2 elif n ==4: print('hi') return n * 2 ``` and the resulting bytecode ``` 2 0 LOAD_FAST 0 (n) 3 LOAD_CONST 1 (1) ...
They are jump targets; positions earlier `*JUMP*` bytecode jumps to when the condition is met. The first jump: ``` 9 POP_JUMP_IF_FALSE 16 ``` jumps to offset 16, so at offset 16 the output has a target `>>`: ``` 4 >> 16 LOAD_FAST 0 (n) ``` From the [`dis.disassemble()` function do...
Is there a Python constant for Unicode whitespace?
37,903,317
15
2016-06-19T02:05:25Z
37,903,645
9
2016-06-19T03:20:37Z
[ "python", "c", "string", "unicode", "whitespace" ]
The `string` module contains a `whitespace` attribute, which is a string consisting of all the ASCII characters that are considered whitespace. Is there a corresponding constant that includes Unicode spaces too, such as the [no-break space (U+00A0)](http://www.fileformat.info/info/unicode/char/00a0/index.htm)? We can s...
> # Is there a Python constant for Unicode whitespace? Short answer: **No.** I have personally grepped for these characters (specifically, the numeric code points) in the Python code base, and such a constant is not there. The sections below explains why it is not necessary, and how it is implemented without this inf...
How to obtain the right alpha value to perfectly blend two images?
37,911,062
9
2016-06-19T19:34:00Z
37,918,596
8
2016-06-20T09:10:55Z
[ "python", "opencv", "image-processing", "computer-vision", "alphablending" ]
I've been trying to blend two images. The current approach I'm taking is, I obtain the coordinates of the overlapping region of the two images, and only for the overlapping regions, I blend with a hardcoded alpha of 0.5, before adding it. SO basically I'm just taking half the value of each pixel from overlapping region...
Here is the way I would do it in general: ``` int main(int argc, char* argv[]) { cv::Mat input1 = cv::imread("C:/StackOverflow/Input/pano1.jpg"); cv::Mat input2 = cv::imread("C:/StackOverflow/Input/pano2.jpg"); // compute the vignetting masks. This is much easier before warping, but I will try... // i...
Cut within a pattern using Python regex
37,928,771
12
2016-06-20T17:50:25Z
37,929,012
7
2016-06-20T18:04:32Z
[ "python", "regex", "string", "split", "protein-database" ]
**Objective:** I am trying to perform a cut in Python RegEx where split doesn't quite do what I want. I need to cut within a pattern, but between characters. **What I am looking for:** I need to recognize the pattern below in a string, and split the string at the location of the pipe. The pipe isn't actually in the s...
A non regex way would be to [replace](https://docs.python.org/2/library/stdtypes.html#str.replace) the pattern with the piped value and then [split](https://docs.python.org/2/library/stdtypes.html#str.split). ``` >>> pattern = 'CDE|FG' >>> s = 'ABCDEFGHIJKLMNOCDEFGZYPE' >>> s.replace('CDEFG',pattern).split('|') ['ABCD...
Identifying consecutive occurrences of a value
37,934,399
9
2016-06-21T01:56:07Z
37,934,721
8
2016-06-21T02:39:32Z
[ "python", "pandas", "dataframe", "itertools" ]
I have a df like so: ``` Count 1 0 1 1 0 0 1 1 1 0 ``` and I want to return a `1` in a new column if there are two or more consecutive occurrences of `1` in `Count` and a `0` if there is not. So in the new column each row would get a `1` based on this criteria being met in the column `Count`. My desired output would ...
You could: ``` df['consecutive'] = df.Count.groupby((df.Count != df.Count.shift()).cumsum()).transform('size') * df.Count ``` to get: ``` Count consecutive 0 1 1 1 0 0 2 1 2 3 1 2 4 0 0 5 0 0 6 1 3 7 ...
'WSGIRequest' object has no attribute 'user' Django admin
37,949,198
5
2016-06-21T15:55:52Z
37,950,161
27
2016-06-21T16:45:28Z
[ "python", "django", "admin", "panel", "wsgi" ]
When I trying to access the admin page it gives me the following error: ``` System check identified no issues (0 silenced). June 21, 2016 - 15:26:14 Django version 1.9.7, using settings 'librato_chart_sender_web.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Se...
I found the answer. The variable name on: ``` MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.Authenticat...
'WSGIRequest' object has no attribute 'user' Django admin
37,949,198
5
2016-06-21T15:55:52Z
39,519,162
10
2016-09-15T19:44:03Z
[ "python", "django", "admin", "panel", "wsgi" ]
When I trying to access the admin page it gives me the following error: ``` System check identified no issues (0 silenced). June 21, 2016 - 15:26:14 Django version 1.9.7, using settings 'librato_chart_sender_web.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Se...
To resolve this go to settings.py where there MIDDLEWARE Change that to MIDDLEWARE\_CLASSES <https://docs.djangoproject.com/ja/1.9/topics/http/middleware/>
Flask app get "IOError: [Errno 32] Broken pipe"
37,962,925
6
2016-06-22T08:46:48Z
38,628,780
7
2016-07-28T06:38:31Z
[ "python", "web", "flask", "webserver" ]
Now I use flask to develop web app. But at first it works well,after operating web page for a while,the flask back-end shows error like these: ``` File "/usr/lib64/python2.6/BaseHTTPServer.py", line 329, in handle self.handle_one_request() File "/usr/lib/python2.6/site-packages/werkzeug/serving.py", line 251...
The built-in werkzeug server is not capable of handling the remote end closing the connection while the server is still churing its content out. instead of `app.run(debug=True,port=5000)` try ``` from gevent.wsgi import WSGIServer http_server = WSGIServer(('', 5000), app) http_server.serve_forever() ``` or if you a...
What is the pythonic way of instantiating a class, calling one of its methods, and returning it from a lambda function?
37,970,032
2
2016-06-22T13:47:53Z
37,970,134
9
2016-06-22T13:52:10Z
[ "python", "lambda" ]
I am dealing widgets and signals and I want to bind a signal to a certain callback. Since I don't really need to create a named callback function in the case of interest, I am defining it as a lambda function. However, the way it integrates with other classes is best described by the following minimal working example: ...
The most pythonic solution is to not use a lambda: ``` def foo(): x = Foo() x.parse("All set") return x print(foo().bar) ``` Lambdas in python are a syntactic convenience and are strictly less powerful than named functions.
Split complicated strings in Python dynamically
37,975,964
4
2016-06-22T18:43:09Z
37,976,086
8
2016-06-22T18:50:50Z
[ "python", "regex", "string", "split" ]
I have been having difficulty with organizing a function that will handle strings in the manner I want. I have looked into a handful previous questions [1](http://stackoverflow.com/questions/4982531/how-do-i-split-a-comma-delimited-string-in-python-except-for-the-commas-that-are), [2](http://stackoverflow.com/questions...
Use [`ast`'s `literal_eval`](https://docs.python.org/2/library/ast.html#ast.literal_eval)! ``` from ast import literal_eval s = """('Vdfbr76','gsdf','gsfd','',NULL), ('Vkdfb23l','gsfd','gsfg','[email protected]',NULL), ('4asg0124e','Lead Actor/SFX MUA/Prop designer','John Smith','[email protected]',NULL), ('asdguIux','Directo...
Empty class size in python
37,990,752
12
2016-06-23T11:48:13Z
37,990,980
12
2016-06-23T11:58:20Z
[ "python" ]
I just trying to know the rationale behind the empty class size in python, In C++ as everyone knows the size of empty class will always shows 1 byte(as far as i have seen) this let the run time to create unique object,and i trying to find out what size of empty class in python: ``` class Empty:pass # i hope this will ...
I assume you are running a 64 bit version of Python 3. On 32 bit Python 3.6 (on Linux), your code prints `show 508`. However, that's the size of the class object itself, which inherits quite a lot of things from the base `object` class. If you instead get the size of an *instance* of your class the result is much smal...
type(4) == type(int) is False in Python?
38,006,826
2
2016-06-24T06:23:33Z
38,006,843
10
2016-06-24T06:25:00Z
[ "python", "python-2.7", "types", "integer" ]
I tried `type(4) == type(int)`, which returns `False`, but `print type(4)` returns `<type 'int'>`, so 4 is obviously `int`. Confused why the first statement returns `False` and not `True`?
The `type` of `int` is *type itself*: ``` >>> type(int) <type 'type'> ``` You'd compare with `int` **directly**; `int` is, after all, a type, as we established above: ``` >>> type(4) == int True ``` or even, since `int` is a singleton, like all types should be: ``` >>> type(4) is int True ``` However, the proper ...
How to tell if tensorflow is using gpu acceleration from inside python shell?
38,009,682
4
2016-06-24T09:14:23Z
38,019,608
7
2016-06-24T18:07:13Z
[ "python", "ubuntu", "tensorflow" ]
I have installed tensorflow in my ubuntu 16.04 using the second answer [here](https://devtalk.nvidia.com/default/topic/936429/-solved-tensorflow-with-gpu-in-anaconda-env-ubuntu-16-04-cuda-7-5-cudnn-/) with ubuntu's builtin apt cuda installation. Now my question is how can I test if tensorflow is really using gpu? I ha...
No, I don't think "open CUDA library" is enough to tell, because different nodes of the graph may be on different devices. To find out which device is used, you can enable log device placement like this: ``` sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) ```
Implementing an asynchronous iterator
38,031,066
11
2016-06-25T17:24:14Z
38,031,740
14
2016-06-25T18:36:26Z
[ "python", "python-3.x", "asynchronous", "python-asyncio" ]
Per [PEP-492](https://www.python.org/dev/peps/pep-0492/#asynchronous-iterators-and-async-for) I am trying to implement an asynchronous iterator, such that I can do e.g. ``` async for foo in bar: ... ``` Here is a trivial example, similar to the one in the docs, with a very basic test of instantiation and async it...
If you read [a little further down the documentation](https://www.python.org/dev/peps/pep-0492/#why-aiter-does-not-return-an-awaitable) it mentions that (emphasis mine): > PEP 492 was accepted in CPython 3.5.0 with `__aiter__` defined as a > method, that was expected to return **an awaitable resolving to an > asynchro...
Looping through an interval in either direction
38,036,637
4
2016-06-26T08:32:09Z
38,036,694
7
2016-06-26T08:38:13Z
[ "python", "loops", "intervals" ]
Suppose you want to loop through all integers between two bounds `a` and `b` (inclusive), but don't know in advance how `a` compares to `b`. Expected behavior: ``` def run(a, b): if a < b: for i in range(a, b + 1): print i, elif a > b: for i in range(a, b - 1, -1): print...
This will work for all cases: ``` def run(a, b): """Iterate from a to b (inclusive).""" step = -1 if b < a else 1 for x in xrange(a, b + step, step): yield x ``` The insight that led me to this formulation was that `step` and the adjustment to `b` were the same in both of your cases; once you have...
Python return several value to add in the middle of a list
38,038,123
2
2016-06-26T11:36:25Z
38,038,151
9
2016-06-26T11:39:23Z
[ "python" ]
Is it possible to make a function that returns several elements like this: ``` def foo(): return 'b', 'c', 'd' print ['a', foo(), 'e'] # ['a', 'b', 'c', 'd', 'e'] ``` I tried this but it doesn't work
You can insert a sequence into a list with a slice assignment: ``` bar = ['a', 'e'] bar[1:1] = foo() print bar ``` Note that the slice is essentially empty; `bar[1:1]` is an empty list between `'a'` and `'e'` here. To do this on one line in Python 2 requires concatenation: ``` ['a'] + list(foo()) + ['e'] ``` If yo...
Django Left Outer Join
38,060,232
13
2016-06-27T17:52:43Z
38,108,285
12
2016-06-29T19:16:34Z
[ "python", "django", "django-models", "orm" ]
I have a website where users can see a list of movies, and create reviews for them. The user should be able to see the list of all the movies. Additionally, IF they have reviewed the movie, they should be able to see the score that they gave it. If not, the movie is just displayed without the score. They do not care ...
First of all, there is not a way (atm Django 1.9.7) to have a representation **with Django's ORM** of the raw query you posted, ***exactly** as you want*; although, you can get the same desired result with something like: ``` >>> Topic.objects.annotate(f=Case(When(record__user=johnny, then=F('record__value')), output_...
How to fix Selenium WebDriverException: "The browser appears to have exited"
38,074,031
4
2016-06-28T10:44:26Z
38,617,777
7
2016-07-27T15:49:04Z
[ "python", "selenium", "selenium-webdriver", "selenium-firefoxdriver" ]
I got this exception when I want to use `FireFox webdriver` > raise WebDriverException "The browser appears to have exited " > WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log\_file in the > FirefoxBinary constructor, check it for details. I read [this qu...
If you're running Selenium on Firefox 47.0, you need to update to Firefox 47.0.1 which is not released in Ubuntu's main repos.. so you have to add this PPA: <https://launchpad.net/~ubuntu-mozilla-security/+archive/ubuntu/ppa> Release notes: <https://www.mozilla.org/en-US/firefox/47.0.1/releasenotes/> "Selenium WebDri...
How can I disable ExtDeprecationWarning for external libs in flask
38,079,200
5
2016-06-28T14:37:18Z
38,080,580
9
2016-06-28T15:37:53Z
[ "python", "flask" ]
When I run my script, I get this output: ``` /app/venv/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.sqlalchemy is deprecated, use flask_sqlalchemy instead. .format(x=modname), ExtDeprecationWarning /app/venv/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecatio...
First, you *should* care about this because the packages you're using aren't up to date. Report a bug that they should switch to using direct import names, such as `flask_sqlalchemy`, rather than the `flask.ext` import hook. Add a [`warnings.simplefilter`](https://docs.python.org/3.5/library/warnings.html) line to fil...
Finding an array elements location in a pandas frame column (a.k.a pd.series)
38,083,227
9
2016-06-28T18:01:33Z
38,083,374
9
2016-06-28T18:08:47Z
[ "python", "arrays", "numpy", "pandas", "indexing" ]
I have a pandas frame similar to this one: ``` import pandas as pd import numpy as np data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']} df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4']) Col1 Col2 Col3 Col4 R1 4 10 100 AAA ...
This should do it: ``` df.loc[df.Col4.isin(target_array)].index ``` --- EDIT: I ran three options: from selected answers. Mine, Bruce Pucci, and Divakar [![enter image description here](http://i.stack.imgur.com/GdHMa.png)](http://i.stack.imgur.com/GdHMa.png) Divakars was faster by a large amount. I'd pick his.
Finding an array elements location in a pandas frame column (a.k.a pd.series)
38,083,227
9
2016-06-28T18:01:33Z
38,083,418
10
2016-06-28T18:11:40Z
[ "python", "arrays", "numpy", "pandas", "indexing" ]
I have a pandas frame similar to this one: ``` import pandas as pd import numpy as np data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']} df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4']) Col1 Col2 Col3 Col4 R1 4 10 100 AAA ...
You can use [`NumPy's in1d`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html) - ``` df.index[np.in1d(df['Col4'],target_array)] ``` **Explanation** 1) Create a `1D` mask corresponding to each row telling us whether there is a match between `col4's` element and any element in `target_array` : ``` ...
Finding an array elements location in a pandas frame column (a.k.a pd.series)
38,083,227
9
2016-06-28T18:01:33Z
38,084,031
7
2016-06-28T18:48:20Z
[ "python", "arrays", "numpy", "pandas", "indexing" ]
I have a pandas frame similar to this one: ``` import pandas as pd import numpy as np data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']} df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4']) Col1 Col2 Col3 Col4 R1 4 10 100 AAA ...
For the sake of completeness I've added two (`.query()` variants) - my timings against 400K rows df: ``` In [63]: df.shape Out[63]: (400000, 4) In [64]: %timeit df.index[np.in1d(df['Col4'],target_array)] 10 loops, best of 3: 35.1 ms per loop In [65]: %timeit df.index[df.Col4.isin(target_array)] 10 loops, best of 3:...
How to remove Python tools for Visual Studio (June 2016) uodate notification? It's already installed
38,085,253
7
2016-06-28T19:59:08Z
38,085,524
13
2016-06-28T20:16:16Z
[ "python", "visual-studio-2015", "installation" ]
I have updated VS 2015 Community to Update 3. According to the installer, this includes Python tools 2.2.4. However, Visual Studio still reports that update is available (from 2.2.3 to 2.2.4) and when I choose to do that, VS Setup starts, but Update button is disabled. It enables if I uncheck Python tools (due the fa...
I ran into the same issue. [Downloading the stand-alone installer and running it fixes the issue](https://ptvs.azureedge.net/download/PTVS%202.2.4%20VS%202015.msi).
Assign external function to class variable in Python
38,097,638
5
2016-06-29T10:59:43Z
38,097,916
8
2016-06-29T11:12:23Z
[ "python", "oop", "python-2.x" ]
I am trying to assign a function defined elsewhere to a class variable so I can later call it in one of the methods of the instance, like this: ``` from module import my_func class Bar(object): func = my_func def run(self): self.func() # Runs my function ``` The problem is that this fails because wh...
Python functions are [*descriptor* objects](https://docs.python.org/2/howto/descriptor.html), and when attributes on a class accessing them an instance causes them to be bound as methods. If you want to prevent this, use the [`staticmethod` function](https://docs.python.org/2/library/functions.html#staticmethod) to wr...
Why PyPi doesn't show download stats anymore?
38,102,317
3
2016-06-29T14:15:16Z
38,102,521
7
2016-06-29T14:24:42Z
[ "python", "pypi" ]
It was so handy to get an idea if the package is popular or not (even if its popularity is the reason of some "import" case in another popular package). But now I don't see this info for some reason. An example: <https://pypi.python.org/pypi/blist> Why did they turn off this useful thing?
As can be seen in [this mail.python.org article](https://mail.python.org/pipermail/distutils-sig/2013-May/020855.html), download stats were removed because they weren't updating and would be too difficult to fix. Donald Stufft, the author of the article, listed these reasons: > There are numerous reasons for their re...
Is there any legitimate use of list[True], list[False] in Python?
38,117,555
37
2016-06-30T08:17:05Z
38,117,588
58
2016-06-30T08:18:59Z
[ "python", "boolean" ]
Since `True` and `False` are instances of `int`, the following is valid in Python: ``` >>> l = [0, 1, 2] >>> l[False] 0 >>> l[True] 1 ``` I understand why this happens. However, I find this behaviour a bit unexpected and can lead to hard-to-debug bugs. It has certainly bitten me a couple of times. Can anyone think o...
In the past, some people have used this behaviour to produce a poor-man's [conditional expression](http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator): ``` ['foo', 'bar'][eggs > 5] # produces 'bar' when eggs is 6 or higher, 'foo' otherwise ``` However, with a [proper conditiona...
Is there any legitimate use of list[True], list[False] in Python?
38,117,555
37
2016-06-30T08:17:05Z
38,123,068
34
2016-06-30T12:27:00Z
[ "python", "boolean" ]
Since `True` and `False` are instances of `int`, the following is valid in Python: ``` >>> l = [0, 1, 2] >>> l[False] 0 >>> l[True] 1 ``` I understand why this happens. However, I find this behaviour a bit unexpected and can lead to hard-to-debug bugs. It has certainly bitten me a couple of times. Can anyone think o...
If you are puzzled why `bool` is a valid index argument: this is simply for **consistency** with the fact that `bool` is a subclass of `int` and in Python it **is** a numerical type. If you are asking why `bool` is a numerical type in the first place then you have to understand that `bool` wasn't present in old releas...
Dividing two columns of a different DataFrames
38,128,014
2
2016-06-30T15:51:49Z
38,130,693
13
2016-06-30T18:26:40Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
I am using Spark to do exploratory data analysis on a user log file. One of the analysis that I am doing is average requests on daily basis per host. So in order to figure out the average, I need to divide the total request column of the DataFrame by number unique Request column of the DataFrame. ``` total_req_per_day...
It is not possible to reference column from another table. If you want to combine data you'll have to `join` first using something similar to this: ``` from pyspark.sql.functions import col (total_req_per_day_df.alias("total") .join(daily_hosts_df.alias("host"), ["day"]) .select(col("day"), (col("total.count"...
Groupby in python pandas: Fast Way
38,143,717
6
2016-07-01T11:00:16Z
38,145,104
7
2016-07-01T12:10:26Z
[ "python", "numpy", "pandas", "group" ]
I want to improve the time of a `groupby` in python pandas. I have this code: ``` df["Nbcontrats"] = df.groupby(['Client', 'Month'])['Contrat'].transform(len) ``` The objective is to count how many contracts a client has in a month and add this information in a new column (`Nbcontrats`). * `Client`: client code * `M...
Here's one way to proceed : * Slice out the relevant columns (`['Client', 'Month']`) from the input dataframe into a NumPy array. This is mostly a performance-focused idea as we would be using NumPy functions later on, which are optimized to work with NumPy arrays. * Convert the two columns data from `['Client', 'Mont...
How to work with surrogate pairs in Python?
38,147,259
5
2016-07-01T13:55:31Z
38,147,966
10
2016-07-01T14:28:45Z
[ "python", "python-3.x", "unicode", "surrogate-pairs" ]
This is a follow-up to [Converting to Emoji](http://stackoverflow.com/questions/38106422/converting-to-emoji). In that question, the OP had a `json.dumps()`-encoded file with an emoji represented as a surrogate pair - `\ud83d\ude4f`. S/he was having problems reading the file and translating the emoji correctly, and the...
You've mixed a literal string `\ud83d` in a json file on disk (six characters: `\ u d 8 3 d`) and a *single* character `u'\ud83d'` (specified using a string literal in Python source code) in memory. It is the difference between `len(r'\ud83d') == 6` and `len('\ud83d') == 1` on Python 3. If you see `'\ud83d\ude4f'` Pyt...
Mixing datetime.strptime() arguments
38,147,923
8
2016-07-01T14:26:51Z
38,215,307
17
2016-07-06T01:51:30Z
[ "python", "datetime", "pycharm", "pylint", "static-code-analysis" ]
It is quite a common mistake to mix up the [`datetime.strptime()`](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime) format string and date string arguments using: ``` datetime.strptime("%B %d, %Y", "January 8, 2014") ``` instead of the other way around: ``` datetime.strptime("January 8, 20...
I claim that this cannot be checked statically *in the general case*. Consider the following snippet: ``` d = datetime.strptime(read_date_from_network(), read_format_from_file()) ``` This code may be completely valid, where both `read_date_from_network` and `read_format_from_file` really do return strings of the pro...
How do I reliably split a string in Python?
38,149,470
69
2016-07-01T15:50:23Z
38,149,500
100
2016-07-01T15:52:02Z
[ "python", "string", "python-3.x", "split" ]
In Perl I can do: ``` my ($x, $y) = split /:/, $str; ``` And it will work whether or not the string contains the pattern. In Python, however this won't work: ``` a, b = "foo".split(":") # ValueError: not enough values to unpack ``` What's the canonical way to prevent errors in such cases?
If you're splitting into just two parts (like in your example) you can use [`str.partition()`](https://docs.python.org/3.5/library/stdtypes.html#str.partition) to get a guaranteed argument unpacking size of 3: ``` >>> a, sep, b = "foo".partition(":") >>> a, sep, b ('foo', '', '') ``` `str.partition()` always returns ...
How do I reliably split a string in Python?
38,149,470
69
2016-07-01T15:50:23Z
38,149,677
56
2016-07-01T16:01:42Z
[ "python", "string", "python-3.x", "split" ]
In Perl I can do: ``` my ($x, $y) = split /:/, $str; ``` And it will work whether or not the string contains the pattern. In Python, however this won't work: ``` a, b = "foo".split(":") # ValueError: not enough values to unpack ``` What's the canonical way to prevent errors in such cases?
Since you are on Python 3, it is easy. PEP 3132 introduced a welcome simplification of the syntax when assigning to tuples - *Extended iterable unpacking*. In the past, if assigning to variables in a tuple, the number of items on the left of the assignment must be exactly equal to that on the right. In Python 3 we can...
How do I reliably split a string in Python?
38,149,470
69
2016-07-01T15:50:23Z
38,149,856
15
2016-07-01T16:12:12Z
[ "python", "string", "python-3.x", "split" ]
In Perl I can do: ``` my ($x, $y) = split /:/, $str; ``` And it will work whether or not the string contains the pattern. In Python, however this won't work: ``` a, b = "foo".split(":") # ValueError: not enough values to unpack ``` What's the canonical way to prevent errors in such cases?
`split` will always return a list. `a, b = ...` will always expect list length to be two. You can use something like `l = string.split(':'); a = l[0]; ...`. Here is a one liner: `a, b = (string.split(':') + [None]*2)[:2]`
How do I reliably split a string in Python?
38,149,470
69
2016-07-01T15:50:23Z
38,150,707
21
2016-07-01T17:09:00Z
[ "python", "string", "python-3.x", "split" ]
In Perl I can do: ``` my ($x, $y) = split /:/, $str; ``` And it will work whether or not the string contains the pattern. In Python, however this won't work: ``` a, b = "foo".split(":") # ValueError: not enough values to unpack ``` What's the canonical way to prevent errors in such cases?
You are always free to catch the exception. For example: ``` some_string = "foo" try: a, b = some_string.split(":") except ValueError: a = some_string b = "" ``` If assigning the whole original string to `a` and an empty string to `b` is the desired behaviour, I would probably use `str.partition()` as e...
What is a good explanation of how to read the histogram feature of TensorBoard?
38,149,622
13
2016-07-01T15:58:16Z
38,173,831
9
2016-07-03T19:58:09Z
[ "python", "machine-learning", "statistics", "tensorflow" ]
Question is simple, **how do you read those graphs**? I read their explanation and it doesn't make sense to me. I was reading TensorFlow's [newly updated readme file for TensorBoard](https://github.com/tensorflow/tensorflow/blob/r0.9/tensorflow/tensorboard/README.md) and in it it tries to explain what a "histogram" is...
The lines that they are talking about are described below: [![enter image description here](http://i.stack.imgur.com/ENhlR.png)](http://i.stack.imgur.com/ENhlR.png) as for the meaning of percentile, check out the [wikipedia article](https://en.wikipedia.org/wiki/Percentile), basically, the 93rd percentile means that 9...
Digit separators in Python code
38,155,177
12
2016-07-01T23:58:08Z
38,155,210
10
2016-07-02T00:03:10Z
[ "python", "literals" ]
Is there any way to group digits in a Python code to increase code legibility? I've tried `'` and `_` which are [*digit separators*](https://en.wikipedia.org/wiki/Integer_literal#Digit_separators) of some other languages, but no avail. A weird operator which concatenates its left hand side with its right hand side cou...
This is not implemented in python at the present time. You can look at the lexical analysis for strict definitions [python2.7](https://docs.python.org/2/reference/lexical_analysis.html#numeric-literals), [python3.5](https://docs.python.org/3.5/reference/lexical_analysis.html#numeric-literals) ... Supposedly it [will b...
How to know when to use numpy.linalg instead of scipy.linalg?
38,168,016
6
2016-07-03T08:15:01Z
38,168,215
8
2016-07-03T08:41:20Z
[ "python", "arrays", "numpy", "scipy" ]
Received wisdom is to prefer `scipy.linalg` over `numpy.linalg` functions. For doing linear algebra, ideally (and conveniently) I would like to combine the functionalities of `numpy.array` and `scipy.linalg` without ever looking towards `numpy.linalg`. This is not always possible and may become too frustrating. Is the...
So, the normal rule is to just use `scipy.linalg` as it generally supports all of the `numpy.linalg` functionality and more. The [documentation](https://docs.scipy.org/doc/scipy/reference/linalg.html) says this: > **See also** > > `numpy.linalg` for more linear algebra functions. Note that although `scipy.linalg` impo...
What is faster, `if x` or `if x != 0`?
38,172,499
3
2016-07-03T17:25:06Z
38,172,713
13
2016-07-03T17:48:55Z
[ "python" ]
I was wondering, what code runs faster? For example, we have variable x: ``` if x!=0 : return ``` or ``` if x: return ``` I tried to check with timeit, and here are results: ``` >>> def a(): ... if 0 == 0: return ... >>> def b(): ... if 0: return ...>>> timeit(a) 0.18059834650234943 >>> timeit(b) 0.131150...
This is too hard to show in a comment: there's more (or less ;-) ) going on here than any of the comments so far noted. With `a()` and `b()` defined as you showed, let's go on: ``` >>> from dis import dis >>> dis(b) 2 0 LOAD_CONST 0 (None) 3 RETURN_VALUE ``` What happens is tha...
graph.write_pdf("iris.pdf") AttributeError: 'list' object has no attribute 'write_pdf'
38,176,472
6
2016-07-04T03:13:34Z
38,177,223
12
2016-07-04T04:59:49Z
[ "python", "machine-learning", "graphviz", "pydot" ]
My code is follow the class of machine learning of google.The two code are same.I don't know why it show error.May be the type of variable is error.But google's code is same to me.Who has ever had this problem? This is error ``` [0 1 2] [0 1 2] Traceback (most recent call last): File "/media/joyce/oreo/python/machi...
I think you are using newer version of python. Please try with pydotplus. ``` import pydotplus ... graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_pdf("iris.pdf") ``` This should do it.
Simulate if-in statement in Java
38,182,463
4
2016-07-04T10:28:15Z
38,182,484
12
2016-07-04T10:29:21Z
[ "java", "python", "if-statement" ]
I've coded for several months in Python, and now i have to switch to Java for work's related reasons. My question is, there is a way to simulate this kind of statement ``` if var_name in list_name: # do something ``` without defining an additional `isIn()`-like boolean function that scans `list_name` in order to ...
You're looking for [`List#contains`](https://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)) which is inherited from [`Collection#contains`](https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#contains(java.lang.Object)) (so you can use it with `Set` objects also) ``` ...
Find unique pairs in list of pairs
38,187,286
12
2016-07-04T14:38:41Z
38,187,443
13
2016-07-04T14:48:59Z
[ "python", "list" ]
I have a (large) list of lists of integers, e.g., ``` a = [ [1, 2], [3, 6], [2, 1], [3, 5], [3, 6] ] ``` Most of the pairs will appear twice, where the order of the integers doesn't matter (i.e., `[1, 2]` is equivalent to `[2, 1]`). I'd now like to find the pairs that appear only *once*, and g...
``` ctr = Counter(frozenset(x) for x in a) b = [ctr[frozenset(x)] == 1 for x in a] ``` We can use Counter to get counts of each list (turn list to frozenset to ignore order) and then for each list check if it only appears once.
Two variables in Python have same id, but not lists or tuples
38,189,660
26
2016-07-04T17:21:10Z
38,189,759
30
2016-07-04T17:30:08Z
[ "python", "python-3.x", "tuples", "identity", "python-internals" ]
Two variables in Python have the same `id`: ``` a = 10 b = 10 a is b >>> True ``` If I take two `list`s: ``` a = [1, 2, 3] b = [1, 2, 3] a is b >>> False ``` according to [this link](http://stackoverflow.com/questions/27460234/two-variables-with-the-same-list-have-different-ids-why-is-that?answertab=votes#tab-top) ...
Immutable objects don't have the same `id`, and as a mater of fact this is not true for any type of objects that you define separately. Every time you define an object in Python, you'll create a new object with a new identity. But there are some exceptions for small integers (between -5 and 256) and small strings (int...
Two variables in Python have same id, but not lists or tuples
38,189,660
26
2016-07-04T17:21:10Z
38,189,766
17
2016-07-04T17:30:50Z
[ "python", "python-3.x", "tuples", "identity", "python-internals" ]
Two variables in Python have the same `id`: ``` a = 10 b = 10 a is b >>> True ``` If I take two `list`s: ``` a = [1, 2, 3] b = [1, 2, 3] a is b >>> False ``` according to [this link](http://stackoverflow.com/questions/27460234/two-variables-with-the-same-list-have-different-ids-why-is-that?answertab=votes#tab-top) ...
**Immutable `!=` same object.**\* [An immutable object is simply an object whose state cannot be altered;](https://docs.python.org/3.5/reference/datamodel.html#data-model) and that is all. *When a new object is created, **a new address will be assigned to it**.* As such, checking if the addresses are equal with `is` w...
Two variables in Python have same id, but not lists or tuples
38,189,660
26
2016-07-04T17:21:10Z
38,189,778
12
2016-07-04T17:31:49Z
[ "python", "python-3.x", "tuples", "identity", "python-internals" ]
Two variables in Python have the same `id`: ``` a = 10 b = 10 a is b >>> True ``` If I take two `list`s: ``` a = [1, 2, 3] b = [1, 2, 3] a is b >>> False ``` according to [this link](http://stackoverflow.com/questions/27460234/two-variables-with-the-same-list-have-different-ids-why-is-that?answertab=votes#tab-top) ...
Take a look at this code: ``` >>> a = (1, 2, 3) >>> b = (1, 2, 3) >>> c = a >>> id(a) 178153080L >>> id(b) 178098040L >>> id(c) 178153080L ``` In order to figure out why `a is c` is evaluated as `True` whereas `a is b` yields `False` I strongly recommend you to run step-by-step the snippet above in the [Online Python...
ValueError time data 'Fri Mar 11 15:59:57 EST 2016' does not match format '%a %b %d %H:%M:%S %Z %Y'
38,189,867
4
2016-07-04T17:38:42Z
38,189,982
7
2016-07-04T17:48:22Z
[ "python", "datetime", "strptime" ]
I am trying to simply create a datetime object from the following date: 'Fri Mar 11 15:59:57 EST 2016' using the format: '%a %b %d %H:%M:%S %Z %Y'. Here's the code. ``` from datetime import datetime date = datetime.strptime('Fri Mar 11 15:59:57 EST 2016', '%a %b %d %H:%M:%S %Z %Y') ``` However, this results in a Val...
For the %Z specifier, `strptime` only recognises "UTC", "GMT" and whatever is in `time.tzname` (so whether it recognises "EST" will depend on the time zone of your computer). This is [issue 22377](http://bugs.python.org/issue22377). See: [Python strptime() and timezones?](http://stackoverflow.com/questions/3305413/pyt...
Is there an one-line python code to replace this nested loop?
38,225,181
2
2016-07-06T13:23:54Z
38,225,216
9
2016-07-06T13:25:57Z
[ "python", "for-loop", "dictionary" ]
variables: ``` rs = { 'results': [ {'addresses': [{'State': 'NY'}, {'State': 'IL'}]}, {'addresses': [{'State': 'NJ'}, {'State': 'IL'}]} ] } ``` I want to get a list of states for each member of results. Currently I used the following code: ``` for y in rs['results']: for x in y['addresses...
You almost got it, you just got it the other way around: ``` phy_states = [x['State'] for y in rs['results'] for x in y['addresses']] ```
Django Rest framework: passing request object around makes it lose POST data in newer version
38,227,476
3
2016-07-06T15:10:13Z
38,339,312
8
2016-07-12T21:39:43Z
[ "python", "django", "django-rest-framework" ]
I'm upgrading a site from Django 1.4 to Django 1.9 I have a view passing control to another view like this: ``` @csrf_protect @api_view(['POST']) @authentication_classes((SessionAuthentication,)) def preview(request, project_id, channel_type, format=None): return build(request, project_id, channel_type, p...
You could just separate out the logic you're storing in the `build` view into a common function used by both endpoints without any decorators e.g. `_build` – this way whatever is happening within the decorators shouldn't occur in the case of the call within `preview`. ``` @csrf_protect @api_view(['POST']) @authentic...
Understanding this line: list_of_tuples = [(x,y) for x, y, label in data_one]
38,229,059
10
2016-07-06T16:29:11Z
38,229,389
8
2016-07-06T16:47:46Z
[ "python", "numpy", "list-comprehension" ]
As you've already understood I'm a beginner and am trying to understand what the "Pythonic way" of writing this function is built on. I know that other threads might include a partial answer to this, but I don't know what to look for since I don't understand what is happening here. This line is a code that my friend s...
Both ways are correct and work. You could probably relate the first way with the way things are done in C and other languages. This is, you basically run a for loop to go through all of the values and then append it to your list of tuples. The second way is more pythonic but does the same. If you take a look at `[(x,y...
Understanding this line: list_of_tuples = [(x,y) for x, y, label in data_one]
38,229,059
10
2016-07-06T16:29:11Z
38,229,435
13
2016-07-06T16:50:54Z
[ "python", "numpy", "list-comprehension" ]
As you've already understood I'm a beginner and am trying to understand what the "Pythonic way" of writing this function is built on. I know that other threads might include a partial answer to this, but I don't know what to look for since I don't understand what is happening here. This line is a code that my friend s...
``` list_of_tuples = [(x,y) for x, y, label in data_one] ``` `(x, y)` is a [`tuple`](http://www.tutorialspoint.com/python/python_tuples.htm) <-- linked tutorial. This is a list [comprehension](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) ``` [(x,y) for x, y, label in data_one] # ^ ...
copying strings to the list in Python
38,231,261
3
2016-07-06T18:30:51Z
38,231,326
7
2016-07-06T18:34:09Z
[ "python", "string", "list", "copy", "append" ]
I have a list `data`, and I am reading lines from it. ``` item = user = channel = time = [] with open('train_likes.csv') as f: data = csv.reader(f) readlines = f.readlines() ``` I want to split each line into single string elements and append each element to a one of 2 other lists: `user`, `items` ``` fo...
When you write `item=user=channel=time=[]`, you are creating only one object, with 4 aliases. So appending to `item` is the same as appending to `user`. Instead you should write ``` item, user, channel, time = [], [], [], [] ``` or simply ``` item = [] user = [] channel = [] time = [] ```
Numpy: Replace every value in the array with the mean of its adjacent elements
38,232,497
4
2016-07-06T19:44:03Z
38,232,755
8
2016-07-06T20:00:42Z
[ "python", "arrays", "numpy", "numpy-broadcasting" ]
I have an ndarray, and I want to replace every value in the array with the mean of its adjacent elements. The code below can do the job, but it is super slow when I have 700 arrays all with shape (7000, 7000) , so I wonder if there are better ways to do it. Thanks! ``` a = np.array(([1,2,3,4,5,6,7,8,9],[4,5,6,7,8,9,10...
Well, that's a [`smoothing operation in image processing`](https://en.wikipedia.org/wiki/Smoothing), which can be achieved with `2D` convolution. You are working a bit differently on the near-boundary elements. So, if the boundary elements are let off for precision, you can use [`scipy's convolve2d`](http://docs.scipy....
list comprehension where list itself is None
38,234,951
3
2016-07-06T22:40:45Z
38,234,988
8
2016-07-06T22:44:06Z
[ "python", "list-comprehension" ]
Is there a way for me to deal with the case where the list my\_list itself can be None in the list comprehension: ``` [x for x in my_list] ``` I tried this: ``` [x for x in my_list if my_list is not None else ['1']] ``` However, it doesn't seem to work.
I think this does what you want: ``` >>> my_list = None >>> [x for x in my_list] if my_list is not None else ['1'] ['1'] ``` The change here is moving the ternary statement outside of the list comprehension. Alternatively, if we add some parens, we can keep the ternary statement inside the list comprehension: ``` >...
Exception during list comprehension. Are intermediate results kept anywhere?
38,239,281
18
2016-07-07T06:59:15Z
38,239,480
26
2016-07-07T07:10:30Z
[ "python", "list-comprehension" ]
When using try-except in a for loop context, the commands executed so far are obviously done with ``` a = [1, 2, 3, 'text', 5] b = [] try: for k in range(len(a)): b.append(a[k] + 4) except: print('Error!') print(b) ``` results with ``` Error! [5, 6, 7] ``` However the same is not true for list comp...
The list comprehension intermediate results are kept on an internal CPython stack, and are not accessible from the Python expressions that are part of the list comprehension. Note that Python executes the `[.....]` **first**, which produces a list object, and only **then** assigns that result to the name `c`. If an ex...
Exception during list comprehension. Are intermediate results kept anywhere?
38,239,281
18
2016-07-07T06:59:15Z
38,240,321
11
2016-07-07T07:59:14Z
[ "python", "list-comprehension" ]
When using try-except in a for loop context, the commands executed so far are obviously done with ``` a = [1, 2, 3, 'text', 5] b = [] try: for k in range(len(a)): b.append(a[k] + 4) except: print('Error!') print(b) ``` results with ``` Error! [5, 6, 7] ``` However the same is not true for list comp...
Let's look at the bytecode: ``` >>> def example(): ... c=[] ... try: ... c = [a[k] + 4 for k in range(len(a))] ... except: ... print('Error!') ... print(c) ... >>> import dis >>> dis.dis(example) --- removed some instructions 27 GET_ITER >> 2...
falied to install flask under virutalenv on windows -- [Error 2] The system cannot find the file specified
38,243,633
6
2016-07-07T10:53:00Z
38,413,695
15
2016-07-16T17:21:32Z
[ "python", "windows", "flask", "virtualenv" ]
I'm using python 2.7 on a windows box.I'm able to install flask using pip install, as you can see below: ![cool](http://i.stack.imgur.com/2gEWO.png) However, after I created a virtualenv, I got below error when trying to do the same thing. scripts: ``` $pip install virtualenv $cd /d d: $mkdir test $cd test $virtua...
This issue seems to be related with the setuptools version installed in your virtualenv. Downgrading to an older version fixed it for me. From your virtualenv: ``` pip install setuptools==21.2.1 pip install flask ```