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
Strange output when writing to stdout in console
37,047,368
4
2016-05-05T09:46:28Z
37,047,458
7
2016-05-05T09:51:04Z
[ "python", "python-3.x", "stdout", "sys" ]
I was just playing around with `sys.stdout.write()` in a Python console when I noticed that this gives some strange output. For every `write()` call the number of characters written, passed to the function respectively gets append to the output. `>>> sys.stdout.write('foo bar')` for example results in `foo bar7` bein...
Apart from writing out the given string, `write` will also return the number of characters (actually, bytes, try `sys.stdout.write('へllö')`) As the python console prints the return value of each expression to stdout, the return value is appended to the actual printed value. Because `write` doesn't append any newlin...
What is the difference between a number n and (n) in python
37,047,988
2
2016-05-05T10:17:30Z
37,048,024
13
2016-05-05T10:19:45Z
[ "python", "python-3.x", "int" ]
``` print(type(1)) print(type((1))) ``` gives me ``` <class 'int'> ``` Also ``` print(id(1)) print(id((1))) ``` gives me ``` 1555424112 1555424112 ``` however `(1)` is recognized as an instance where as `1` is not? for e.g., on doing a `(1)`. in editor I get a lot of methods such as `bit_length`, `conjugate`, `_...
`(..)` merely *groups* an expression. For integers, it also has the side-effect that the `.` character for *floating point decimals* can be disambiguated from the `.` attribute access operator. So ``` 1.bit_length() ``` is a syntax error, because `bit_length` is not a valid non-integer portion for a real number. But...
Python 2.7.9 Print statement with list strange output
37,048,372
2
2016-05-05T10:37:05Z
37,048,433
8
2016-05-05T10:40:31Z
[ "python" ]
Why whole argument in print function along with paranthesis is printed when only the string should have been This is Python 2.7.9 ``` import os alist = [ 'A' ,'B'] print('Hello there') print('The first item is ',alist[0]) print('Good Evening') root@justin:/python# python hello.py Hello there ('The first item is ',...
In python 2 `print` isn't a function it's a statement. When you write ``` print('The first item is ',alist[0]) ``` it's actually means "print me a tuple of 2 elements: `'The first item is '` and `alist[0]`" it's equivalent to ``` a = ('The first item is ',alist[0]) print a ``` if you want to print only strings you...
Times two faster than bit shift?
37,053,379
120
2016-05-05T14:35:16Z
37,054,723
124
2016-05-05T15:42:39Z
[ "python", "performance", "python-3.x", "bit-shift" ]
I was looking at the source of [sorted\_containers](https://github.com/grantjenks/sorted_containers/blob/master/sortedcontainers/sortedlist.py) and was surprised to see [this line](https://github.com/grantjenks/sorted_containers/blob/master/sortedcontainers/sortedlist.py#L72): ``` self._load, self._twice, self._half =...
This seems to be because multiplication of small numbers is optimized in CPython 3.5, in a way that left shifts by small numbers are not. Positive left shifts always create a larger integer object to store the result, as part of the calculation, while for multiplications of the sort you used in your test, a special opt...
Is slicing really slower in Python 3.4?
37,056,654
11
2016-05-05T17:26:04Z
37,056,826
10
2016-05-05T17:34:50Z
[ "python", "performance", "python-2.7", "python-3.4" ]
This [question](http://stackoverflow.com/q/37052139/6292850) and my [answer](http://stackoverflow.com/a/37055026/6292850) got me thinking about this peculiar difference between Python 2.7 and Python 3.4. Take the simple example code: ``` import timeit import dis c = 1000000 r = range(c) def slow(): for pos in ran...
On Python 2.7, you're iterating over a list and slicing a list. On Python 3.4, you're iterating over a `range` and **slicing a `range`**. When I run a test with a list on both Python versions: ``` from __future__ import print_function import timeit print(timeit.timeit('x[5:8]', setup='x = list(range(10))')) ``` I ge...
Stop at exception in my, not library code
37,069,323
8
2016-05-06T09:51:07Z
37,398,488
7
2016-05-23T18:56:23Z
[ "python", "exception", "exception-handling", "ipython" ]
I'm developing an app using a Python library `urllib` and it is sometimes rising exceptions due to not being able to access an URL. However, the exception is raised almost 6 levels into the standard library stack: ``` /home/user/Workspace/application/main.py in call(path) 11 head...
I would go with modifying the code: ``` try: resp = urllib.request.urlopen(req) except Exception as e: raise RuntimeError(e) ``` That way: * %pdb moves you to your code, * the original exception is preserved as argument of the "secondary" exception. You may also monkeypatch `urllib.request.urlopen()` funct...
Programmatically searching google in Python using custom search
37,083,058
4
2016-05-07T00:04:53Z
37,084,643
10
2016-05-07T04:55:24Z
[ "python", "google-custom-search" ]
I have a snippet of code using the pygoogle python module that allows me to programmatically search for some term in google succintly: ``` g = pygoogle(search_term) g.pages = 1 results = g.get_urls()[0:10] ``` I just found out that this has been discontinued unfortunately and replaced by something called the googl...
It is possible to do this. The setup is... not very straightforward, but the end result is that you can search the entire web from python with few lines of code. There are 3 main steps in total. # 1st step: get Google API key The [pygoogle](http://pygoogle.sourceforge.net/)'s page states: > Unfortunately, Google no...
tf.shape() get wrong shape in tensorflow
37,085,430
6
2016-05-07T06:47:17Z
37,085,824
12
2016-05-07T07:33:11Z
[ "python", "tensorflow" ]
I define a tensor like this: `x = tf.get_variable("x", [100])` But when I try to print shape of tensor : `print( tf.shape(x) )` I get **Tensor("Shape:0", shape=(1,), dtype=int32)**, why the result of output should not be shape=(100)
[tf.shape(input, name=None)](https://www.tensorflow.org/versions/r0.8/api_docs/python/array_ops.html#shape) returns a 1-D integer tensor representing the shape of input. You're looking for: `x.get_shape()` that returns the `TensorShape` of the `x` variable.
The difference between np.random.seed(int) and np.random.seed(array_like)?
37,085,669
7
2016-05-07T07:15:30Z
37,086,802
8
2016-05-07T09:27:43Z
[ "python", "numpy", "random" ]
In python's numpy library, the `np.random.seed` method can accept two different type of parameter: `int` and `array_like[int]`, what's the difference between them? Such as: `np.random.seed(2)` and `np.random.seed([2013, 1, 4])`.
The state of the underlying [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister) PRNG is very large, 624 32-bit integers, to be exact. If given an integer seed, the initialization routine will run a smaller PRNG to expand that single 32-bit integer out to the full 624-element state. This does mean that yo...
Difference between defining typing.Dict and dict?
37,087,457
9
2016-05-07T10:36:37Z
37,087,556
12
2016-05-07T10:45:42Z
[ "python", "dictionary", "type-hinting" ]
I am practicing using type hints in Python 3.5. One of my colleague uses `typing.Dict`: ``` import typing def change_bandwidths(new_bandwidths: typing.Dict, user_id: int, user_name: str) -> bool: print(new_bandwidths, user_id, user_name) return False def my_chang...
There is no real difference between using a plain `typing.Dict` and `dict`, no. However, `typing.Dict` is a [*Generic type*](https://docs.python.org/3/library/typing.html#generics) that lets you specify the type of the keys and values *too*, making it more flexible: ``` def change_bandwidths(new_bandwidths: typing.Di...
Difference between Variable and get_variable in TensorFlow
37,098,546
7
2016-05-08T09:57:28Z
37,102,908
7
2016-05-08T17:44:49Z
[ "python", "tensorflow" ]
As far as I know, `Variable` is the default operation for making a variable, and `get_variable` is mainly used for weight sharing. On the one hand, there are some people suggesting using `get_variable` instead of the primitive `Variable` operation whenever you need a variable. On the other hand, I merely see any use o...
I'd recommend to always use `tf.get_variable(...)` -- it will make it way easier to refactor your code if you need to share variables at any time, e.g. in a multi-gpu setting (see the multi-gpu CIFAR example). There is no downside to it. Pure `tf.Variable` is lower-level; at some point `tf.get_variable()` did not exis...
Nested for in Python
37,102,022
2
2016-05-08T16:17:01Z
37,102,053
7
2016-05-08T16:20:22Z
[ "python", "python-2.7", "nested" ]
I have a list and I want to **iterate** over it, and then iterate in a nested `for` insde the first one over the same list from the next position that the first one I've read. In a language like Java would be: ``` int[10] array; for (int i=0; i < array.length(); i++) for (int j=i+1; j < array.length(); j ++) ...
``` for i in range(0,len(array)): for j in range(i+1,len(array)): #do something with array[i] and array[j] ```
Detect the first unique rows in multiple numpy 2-d arrays
37,104,013
4
2016-05-08T19:33:13Z
37,104,973
7
2016-05-08T21:24:34Z
[ "python", "arrays", "numpy", "scipy" ]
I have multiple numpy 2-d arrays which I want to compare rowwise. The output of my function should be a numpy 2-d array representing all rows of the three inputs arrays. I want to be able to detect the first time that a row occurs, every second or third duplicate row should be flagged as False in the output. It is not ...
Here's a fast vectorized approach: ``` def find_dupe_rows(*arrays): A = np.vstack(arrays) rtype = np.dtype((np.void, A.dtype.itemsize*A.shape[1])) _, first_idx = np.unique(A.view(rtype), return_index=True) out = np.zeros(A.shape[0], np.bool) out[first_idx] = True return out.reshape(len(arrays...
How to add regularizations in TensorFlow?
37,107,223
11
2016-05-09T03:04:56Z
37,143,333
8
2016-05-10T15:47:09Z
[ "python", "neural-network", "tensorflow", "deep-learning" ]
I found in many available neural network code implemented using TensorFlow that regularization terms are often implemented by manually adding an additional term to loss value. My questions are: 1. Is there a more elegant or recommended way of regularization than doing it manually? 2. I also find that `get_variable` h...
As you say in the second point, using the `regularizer` argument is the recommended way. You can use it in `get_variable`, or set it once in your `variable_scope` and have all your variables regularized. The losses are collected in the graph, and you need to manually add them to your cost function like this. ``` re...
Return tuple with smallest y value from list of tuples
37,110,652
10
2016-05-09T08:10:03Z
37,110,813
15
2016-05-09T08:19:07Z
[ "python", "list", "tuples", "min" ]
I am trying to return a tuple the smallest second index value (y value) from a list of tuples. If there are two tuples with the lowest y value, then select the tuple with the largest x value (i.e first index). For example, suppose I have the tuple: ``` x = [(2, 3), (4, 3), (6, 9)] ``` The the value returned should b...
Include the `x` value in a tuple returned from the key; this second element in the key will be then used when there is a tie for the `y` value. To inverse the comparison (from smallest to largest), just negate that value: ``` min(x, key=lambda t: (t[1], -t[0])) ``` After all, `-4` is smaller than `-2`. Demo: ``` >>...
Where does Anaconda Python install on Windows?
37,117,571
5
2016-05-09T13:52:44Z
37,117,572
17
2016-05-09T13:52:44Z
[ "python", "pydev", "anaconda" ]
I installed Anaconda for Python 2.7 on my Windows machine and wanted to add the Anaconda interpreter to PyDev, but quick googling couldn't find the default place where Anaconda installed, and searching SO didn't turn up anything useful, so. Where does Anaconda 4.0 install on Windows 7? ***Suggestions this is a duplic...
To find where Anaconda was installed I used the "where" command on the command line in Windows. ``` C:\>where anaconda ``` which for me returned: > C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\Scripts\anaconda.exe Which allowed me to find the Anaconda Python interpreter at > C:\Users\User-Name\AppData\Loca...
installing cPickle with python 3.5
37,132,899
3
2016-05-10T08:20:38Z
37,138,791
8
2016-05-10T12:37:19Z
[ "python", "docker", "pickle", "python-3.5" ]
This might be silly but I am unable to install `cPickle` with python 3.5 docker image **Dockerfile** ``` FROM python:3.5-onbuild ``` **requirements.txt** ``` cpickle ``` When I try to build the image ``` $ docker build -t sample . Sending build context to Docker daemon 3.072 kB Step 1 : FROM python:3.5-onbuild # ...
`cPickle` comes with the standard library… in python 2.x. You are on python 3.x, so if you want `cPikcle`, you can do this: ``` >>> import _pickle as cPickle ``` However, in 3.x, it's easier just to use `pickle`. No need to install anything. If something requires `cPickle` in python 3.x, then that's probably a bug...
What is the correct way to report an error in a Python unittest in the setUp method?
37,134,320
8
2016-05-10T09:24:47Z
37,374,945
8
2016-05-22T13:23:33Z
[ "python", "unit-testing", "testing", "assert", "arrange-act-assert" ]
I've read some conflicting advice on the use of `assert` in the `setUp` method of a Python unit test. I can't see the harm in failing a test if a precondition that test relies on fails. For example: ``` import unittest class MyProcessor(): """ This is the class under test """ def __init__(self): ...
The purpose of `setUp` is to reduce [Boilerplate code](https://en.wikipedia.org/wiki/Boilerplate_code) which creates between the tests in the test class during the Arrange phase. In the Arrange phase you: setup everything needed for the running the tested code. This includes any initialization of dependencies, mocks a...
List unhashable, but tuple hashable?
37,136,878
3
2016-05-10T11:12:22Z
37,136,961
8
2016-05-10T11:16:15Z
[ "python", "list", "python-2.7", "hash", "tuples" ]
In [How to hash lists?](https://stackoverflow.com/questions/37125539/how-to-hash-lists) I was told that I should convert to a tuple first, e.g. `[1,2,3,4,5]` to `(1,2,3,4,5)`. So the first cannot be hashed, but the second can. Why\*? --- \*I am not really looking for a detailed technical explanation, but rather for ...
Mainly, because tuples are immutable. Assume the following works: ``` >>> l = [1, 2, 3] >>> t = (1, 2, 3) >>> x = {l: 'a list', t: 'a tuple'} ``` Now, what happens when you do `l.append(4)`? You've modified the key in your dictionary! From afar! If you're familiar with how hashing algorithms work, this should frighte...
Custom chained comparisons
37,140,933
15
2016-05-10T14:07:17Z
37,141,205
8
2016-05-10T14:18:33Z
[ "python" ]
Python allows expressions like `x > y > z`, which, according to the docs, is equivalent to `(x > y) and (y > z)` except `y` is only evaluated once. (<https://docs.python.org/3/reference/expressions.html>) However, this seems to break if I customize comparison functions. E.g. suppose I have the following class: (Apolog...
> Python allows expressions like `x > y > z`, which, according to the docs, is equivalent to `(x > y) and (y > z)` except `y` is only evaluated once. According to this, `low > high > low` will be equivalent to `(low > high) and (high > low)`. ``` >>> x = low > high # CompareList([False]) >>> y = high > low # Comp...
Mocking boto3 S3 client method Python
37,143,597
4
2016-05-10T15:59:35Z
37,144,161
8
2016-05-10T16:29:30Z
[ "python", "mocking", "boto", "boto3", "botocore" ]
I'm trying to mock a singluar method from the boto3 s3 client object to throw and exception. But I need all other methods for this class to work as normal. This is so I can test a singular Exception test when and error occurs performing a [upload\_part\_copy](http://boto3.readthedocs.io/en/latest/reference/services/s3...
Botocore has a client stubber you can use for just this purpose: [docs](http://botocore.readthedocs.io/en/latest/reference/stubber.html). Here's an example of putting an error in: ``` import boto3 from botocore.stub import Stubber client = boto3.client('s3') stubber = Stubber(client) stubber.add_client_error('upload...
Why is it faster to break rather than to raise an exception?
37,154,381
19
2016-05-11T06:12:57Z
37,155,232
26
2016-05-11T06:57:08Z
[ "python", "python-3.x" ]
After checking a few simple tests, it seems as if it might be faster to break from a loop to end a generator rather than to raise a StopIteration exception. Why is this the case if the standard and accepted method of stopping a generator is using the exception. [source](https://wiki.python.org/moin/Generators) ``` In ...
> Why is this the case if the standard and accepted method of stopping a generator is using the exception. The exception `StopIteration` is raised only when the generator has nothing to produce any more. And, it is not a standard way of stopping a generator midway. Here are two statements from the documentation on ge...
Why does a generator using `()` need a lot of memory?
37,156,574
27
2016-05-11T08:06:40Z
37,156,765
48
2016-05-11T08:14:56Z
[ "python", "python-2.7", "generator" ]
## Problem Let's assume that I want to find `n**2` for all numbers smaller than `20000000`. ### General setup for all three variants that I test: ``` import time, psutil, gc gc.collect() mem_before = psutil.virtual_memory()[3] time1 = time.time() # (comprehension, generator, function)-code come...
1. As others have pointed out in the comments, `range` creates a `list` in Python 2. Hence, it is not the generator per se that uses up the memory, but the `range` that the generator uses: ``` x = (i**2 for i in range(20000000)) # builds a 2*10**7 element list, not for the squares , but for the bases >>...
Python: converting iterable to list: 'list(x)' vs. full slice 'x[:]'
37,158,448
3
2016-05-11T09:30:04Z
37,158,481
9
2016-05-11T09:31:28Z
[ "python", "list", "slice" ]
I wonder if there is any difference in these two ways to convert an iterable to a list in Python: * using the `list()` constructor: ``` my_list = list(my_iterable) ``` * using a full slice: ``` my_list = my_iterable[:] ``` Are there differences in the implementation? If so, what about performance? Any c...
`list(thing)` gives you a list. `thing[:]` could give you any type it wants. In other words, the second option only works with specific types (and you haven't mentioned which types you're actually working with). Edit: A useful feature of `thing[:]` is that when it is supported it usually results in a reference to "a...
Python: converting iterable to list: 'list(x)' vs. full slice 'x[:]'
37,158,448
3
2016-05-11T09:30:04Z
37,158,494
11
2016-05-11T09:32:01Z
[ "python", "list", "slice" ]
I wonder if there is any difference in these two ways to convert an iterable to a list in Python: * using the `list()` constructor: ``` my_list = list(my_iterable) ``` * using a full slice: ``` my_list = my_iterable[:] ``` Are there differences in the implementation? If so, what about performance? Any c...
Not everything supports slicing, e.g. generators: ``` (x for x in range(5))[:] # raises an error ``` So `list` is more general. `[:]` is a mostly just a way to copy a list. The main reason `[:]` is possible is because it's what you get when you combine leaving out the index before the colon (e.g. `[:3]`) and leavi...
Choice made by Python 3.5 to choose the keys when comparing them in a dictionary
37,164,127
60
2016-05-11T13:26:35Z
37,164,377
21
2016-05-11T13:37:02Z
[ "python", "dictionary" ]
When constructing a dictionary as follows: ``` dict = { True: 'yes', 1: 'No'} ``` When I run it in the interactive Python interpreter the dict is represented this way: ``` dict = {True: 'No'} ``` I understand that the values `True` and `1` are equal due to the type coercion because when comparing numeric types, the...
`True` and `1` are different objects, but they both have the same value: ``` >>> True is 1 False >>> True == 1 True ``` This is similar to two strings that may have the same value, but are stored in different memory locations: ``` >>> x = str(12345) >>> y = str(12345) >>> x == y True >>> x is y False ``` First one...
Choice made by Python 3.5 to choose the keys when comparing them in a dictionary
37,164,127
60
2016-05-11T13:26:35Z
37,164,422
41
2016-05-11T13:38:39Z
[ "python", "dictionary" ]
When constructing a dictionary as follows: ``` dict = { True: 'yes', 1: 'No'} ``` When I run it in the interactive Python interpreter the dict is represented this way: ``` dict = {True: 'No'} ``` I understand that the values `True` and `1` are equal due to the type coercion because when comparing numeric types, the...
Dictionaries are implemented as hash tables and there are two important concepts when adding keys/values here: *hashing* and *equality*. To insert a particular key/value, Python first computes the *hash* value of the key. This hash value is used to determine the row of the table where Python should first attempt to pu...
Choice made by Python 3.5 to choose the keys when comparing them in a dictionary
37,164,127
60
2016-05-11T13:26:35Z
37,164,428
8
2016-05-11T13:38:53Z
[ "python", "dictionary" ]
When constructing a dictionary as follows: ``` dict = { True: 'yes', 1: 'No'} ``` When I run it in the interactive Python interpreter the dict is represented this way: ``` dict = {True: 'No'} ``` I understand that the values `True` and `1` are equal due to the type coercion because when comparing numeric types, the...
If the key is already present in the dictionary, it does not override the key only the value associated. I believe that writing `x = {True:"a", 1:"b"}` is along the lines of: ``` x = {} x[True] = "a" x[1] = "b" ``` and by the time it reaches `x[1] = "b"` the key `True` is already in the dict so why change it? why no...
Choice made by Python 3.5 to choose the keys when comparing them in a dictionary
37,164,127
60
2016-05-11T13:26:35Z
37,164,447
31
2016-05-11T13:39:34Z
[ "python", "dictionary" ]
When constructing a dictionary as follows: ``` dict = { True: 'yes', 1: 'No'} ``` When I run it in the interactive Python interpreter the dict is represented this way: ``` dict = {True: 'No'} ``` I understand that the values `True` and `1` are equal due to the type coercion because when comparing numeric types, the...
Basic premise is - `True` and `1` have same hashes and are equal to each other - that's why they cannot be separate keys in hash table (technically inequal object with same hashes may - but hash collisions decreases performance). ``` >>> True == 1 True >>> hash(1) 1 >>> hash(True) 1 ``` Now, let's consider a bytecode...
Why does date + timedelta become date, not datetime?
37,165,952
17
2016-05-11T14:38:58Z
37,166,707
7
2016-05-11T15:08:50Z
[ "python", "datetime" ]
In Python, in an operation of numbers of mixed type, the narrower type is [widened to that of the other](https://docs.python.org/3.5/library/stdtypes.html#numeric-types-int-float-complex), such as `int` + `float` → `float`: ``` In [57]: 3 + 0.1 Out[57]: 3.1 ``` But for `datetime.date`, we have `datetime.date` + `da...
The behaviour is [documented](https://docs.python.org/3/library/datetime.html): > *date2* is moved forward in time if `timedelta.days > 0`, or backward if `timedelta.days < 0`. Afterward `date2 - date1 == timedelta.days`. **`timedelta.seconds` and `timedelta.microseconds` are ignored.** (My emphasis. This behaviour h...
tflearn / tensorflow does not learn xor
37,166,268
8
2016-05-11T14:52:32Z
37,167,223
8
2016-05-11T15:33:39Z
[ "python", "machine-learning", "tensorflow", "deep-learning" ]
Following code was written to learn the XOR function, but about half of the time the network does not learn and the loss after each epoch stays the same. ``` train_f = [[0, 0], [0, 1], [1, 0], [1, 1]] train_c = [[0], [1], [1], [0]] test_f = train_f test_c = train_c import tensorflow as tf import tflearn X = [[0., 0....
The network with `relu`s (as it is written in the code snippet) is expected to often fail to train. The reason for that is that if the input to relu is less than zero, the output is zero, and therefore the gradient going back is also zero. Since you have two layers, each having only two relu units, with random initial...
Optimization of arithmetic expressions - what is this technique called?
37,179,184
13
2016-05-12T06:45:28Z
37,179,266
17
2016-05-12T06:49:46Z
[ "python", "optimization", "arithmetic-expressions" ]
A discussion with a friend led to the following realization: ``` >>> import dis >>> i = lambda n: n*24*60*60 >>> dis.dis(i) 1 0 LOAD_FAST 0 (n) 3 LOAD_CONST 1 (24) 6 BINARY_MULTIPLY 7 LOAD_CONST 2 (60) 10 BINA...
This optimization technique is called [constant folding](https://en.wikipedia.org/wiki/Constant_folding). The reason for constant folding occurring in the latter code but not in the former is that Python has dynamic typing, and while in mathematics a product of real numbers is *commutative* and freely *associative*, i...
Using Deep Learning to Predict Subsequence from Sequence
37,179,916
17
2016-05-12T07:20:48Z
37,243,949
10
2016-05-15T21:40:54Z
[ "python", "theano", "deep-learning", "keras" ]
I have a data that looks like this: [![enter image description here](http://i.stack.imgur.com/CNK0K.jpg)](http://i.stack.imgur.com/CNK0K.jpg) It can be viewed [here](http://dpaste.com/2PZ9WH6) and has been included in the code below. In actuality I have ~7000 samples (row), [downloadable too](http://www.filedropper.c...
1. *Can RNN, LSTM or GRU used to predict subsequence as posed above?* Yes, you can use any of these. LSTMs and GRUs are types of RNNs; if by RNN you mean a [fully-connected RNN](http://keras.io/layers/recurrent/#simplernn), these have fallen out of favor because of the vanishing gradients problem ([1](http://www.dsi.u...
How to have list() consume __iter__ without calling __len__?
37,189,968
13
2016-05-12T14:29:29Z
37,192,530
10
2016-05-12T16:25:08Z
[ "python" ]
I have a class with both an `__iter__` and a `__len__` methods. The latter uses the former to count all elements. It works like the following: ``` class A: def __iter__(self): print("iter") for _ in range(5): yield "something" def __len__(self): print("len") n = 0 ...
It's a safe bet that the `list()` constructor is detecting that `len()` is available and calling it in order to pre-allocate storage for the list. Your implementation is pretty much completely backwards. You are implementing `__len__()` by using `__iter__()`, which is not what Python expects. The expectation is that `...
FFT in numpy vs FFT in MATLAB do not have the same results
37,190,596
5
2016-05-12T14:55:42Z
37,191,173
7
2016-05-12T15:19:05Z
[ "python", "matlab", "numpy", "fft" ]
I have a vector with complex numbers (can be found [here](https://www.dropbox.com/s/ve0de4ebk41s8y2/data.txt?dl=1)), both in Python and in MATLAB. I am calculating the `ifft`-transformation with ``` ifft(<vector>) ``` in MATLAB and with ``` np.fft.ifft(<vector>) ``` in Python. My problem is that I get two completel...
Actually, they are the same but Python is showing the imaginary part with extremely high precision. The imaginary components are being shown with values with a magnitude of around `10^{-12}`. Here's what I wrote to reconstruct your problem in MATLAB: ``` format long g; data = importdata('data.txt'); out = ifft(data);...
How to enable a virtualenv in a systemd service unit?
37,211,115
4
2016-05-13T13:18:13Z
37,211,676
11
2016-05-13T13:46:21Z
[ "python", "environment-variables", "virtualenv" ]
I want to "activate" a virtualenv in a systemd service file. I would like avoid to have a shell process between the systemd process and the python interpreter. My current solution looks like this: ``` [Unit] Description=fooservice After=syslog.target network.target [Service] Type=simple User=fooservice WorkingDirec...
The virtualenv is "baked into the Python interpreter in the virtualenv". This means you can launch `python` or [`console_scripts`](https://pythonhosted.org/setuptools/setuptools.html#automatic-script-creation) directly in that virtualenv and don't need to manage `PATH` etc yourself.: ``` ExecStart={{ venv_home }}/bin/...
How to generate random sequence of numbers in python?
37,212,700
3
2016-05-13T14:31:01Z
37,212,767
7
2016-05-13T14:34:18Z
[ "python", "random" ]
How to generate random sequence of 1, 2, 3 provided that 80 % of numbers will 1, 15 % will 2 and 5 % will 3?
Use `random` to get a random number in [0,1) and map your outputs to that interval. ``` from random import random result = [] # Return 100 results (for instance) for i in range(100): res = random() if res < 0.8: result.append(1) elif res < 0.95: result.append(2) else: result...
pandas .at versus .loc
37,216,485
4
2016-05-13T17:57:21Z
37,216,587
8
2016-05-13T18:04:00Z
[ "python", "pandas" ]
I've been exploring how to optimize my code and ran across `pandas` `.at` method. Per the [documentation](http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.at.html#pandas.DataFrame.at) > Fast label-based scalar accessor > > Similarly to loc, at provides label based scalar lookups. You can ...
`df.at` can only access a single value at a time. `df.loc` can select multiple rows and/or columns. Note that there is also [`df.get_value`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.get_value.html), which may be even quicker at accessing single values: ``` In [25]: %timeit df.loc[('a', ...
IPython console can't locate "backports.shutil_get_terminal_size" and won't load
37,232,446
9
2016-05-14T22:13:53Z
37,665,563
10
2016-06-06T19:38:55Z
[ "python", "python-2.7", "terminal", "ipython", "anaconda" ]
I'm running Python2.7 on windows 10 doing env and most pkg management with Anaconda. After upgrading a number of packages, my ipython console now fails to start in any IDE or at the console. When I attempt to run it at the console I get this error: ``` Traceback (most recent call last): File "C:\Anaconda3\Scripts\ipyt...
Try this ``` conda config --add channels conda-forge conda install backports.shutil_get_terminal_size ```
In Python: How to remove an object from a list if it is only referenced in that list?
37,232,884
16
2016-05-14T23:21:08Z
37,233,282
7
2016-05-15T00:38:49Z
[ "python", "list", "object", "reference", "garbage-collection" ]
I want to keep track of objects of a certain type that are currently in use. For example: Keep track of all instances of a class or all classes that have been created by a metaclass. It is easy to keep track of instances like this: ``` class A(): instances = [] def __init__(self): self.instances.appen...
This answer is the same as Kevin's but I was working up an example implementation with weak references and am posting it here. Using weak references solves the problem where an object is referenced by the `self.instance` list, so it will never be deleted. One of the things about creating a weak reference for an object...
Difficult Dataframe Reshape in Python Pandas
37,233,840
3
2016-05-15T02:13:30Z
37,233,930
7
2016-05-15T02:29:37Z
[ "python", "pandas" ]
If I have a dataframe that looks like this: ``` DATE1 DATE2 DATE3 AMOUNT1 AMOUNT2 AMOUNT3 1 1/1/15 5/22/14 7/12/13 5 6 3 .. .. .. .. .. .. .. ``` and I want to get it in the form: ``` DATE AMOUNT 1 1/1/15 5 2 5/22/14 6 3 ...
You could use `pd.lreshape`: ``` import pandas as pd df = pd.DataFrame([['1/1/15', '5/22/14', '7/12/13', 5, 6, 3]], columns=['DATE1', 'DATE2', 'DATE3', 'AMOUNT1', 'AMOUNT2', 'AMOUNT3']) result = pd.lreshape(df, {'AMOUNT': ['AMOUNT1', 'AMOUNT2', 'AMOUNT3'], 'DATE': ['DATE1...
What is the x = [m]*n syntax in Python?
37,234,887
9
2016-05-15T05:28:14Z
37,234,914
17
2016-05-15T05:32:17Z
[ "python", "terminology" ]
I stumbled on the 'x = [m]\*n' and running it in the interpreter I can see that the code allocates an n element array initialized with m. But I can't find a description of this type of code online. What is this called? ``` >>> x = [0]*7 >>> x [0, 0, 0, 0, 0, 0, 0] ```
`*` is just a multiplication - as `+` for lists is an intuitive thing, meaning concatenate both operands, the next step is multiplication by a scalar - with `[0] * N` meaning "concatenate this list with itself N times"! In other words: `*` is an operator defined in Python for its primitive sequence types and an intege...
What is the x = [m]*n syntax in Python?
37,234,887
9
2016-05-15T05:28:14Z
37,234,928
11
2016-05-15T05:35:19Z
[ "python", "terminology" ]
I stumbled on the 'x = [m]\*n' and running it in the interpreter I can see that the code allocates an n element array initialized with m. But I can't find a description of this type of code online. What is this called? ``` >>> x = [0]*7 >>> x [0, 0, 0, 0, 0, 0, 0] ```
From [the Python docs' description](https://docs.python.org/3/reference/expressions.html#binary-arithmetic-operations), the multiplication operator `*` used between an integer `n` and a primitive sequence type performs sequence repetition of the items in the sequence `n` times. So I suppose the term you are looking for...
Extract using Beautiful Soup
37,234,995
4
2016-05-15T05:46:40Z
37,235,213
7
2016-05-15T06:22:26Z
[ "python", "beautifulsoup" ]
I want to fetch the stock price from web site: <http://www.bseindia.com/> For example stock price appears as "S&P BSE :25,489.57".I want to fetch the numeric part of it as "25489.57" This is the code i have written as of now.It is fetching the entire div in which this amount appears but not the amount. Below is the c...
I had a look around in what is going on when that page loads the information and I was able to simulate what the javascript is doing in python. I found out it is referencing a page called `IndexMovers.aspx?ln=en` [check it out here](http://www.bseindia.com/Msource/IndexMovers.aspx?ln=en) [![enter image description her...
Special Matrix in Numpy
37,241,995
3
2016-05-15T18:17:52Z
37,242,171
9
2016-05-15T18:35:08Z
[ "python", "numpy" ]
I want to make a numpy array that looks like this: ``` m = [1, 1, 1, 0, 0, 0, 0, 0, 0 0, 0, 0, 1, 1, 1, 0, 0, 0 0, 0, 0, 0, 0, 0, 1, 1, 1] ``` I have seen this answer [Make special diagonal matrix in Numpy](https://stackoverflow.com/questions/18026541/make-special-diagonal-matrix-in-numpy) and I have this:...
One way is to simply stretch an identity array horizontally; ``` > np.repeat(np.identity(3, dtype=int), 3, axis=1) array([[1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1]]) ```
ImportError: cannot import name NUMPY_MKL
37,267,399
11
2016-05-17T04:52:01Z
37,281,256
25
2016-05-17T16:03:27Z
[ "python", "windows", "python-2.7", "numpy", "scipy" ]
I am trying to run the following simple code ``` import scipy scipy.test() ``` But I am getting the following error ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 586, in runfile execfile(f...
If you look at the line which is causing the error, you'll see this: ``` from numpy._distributor_init import NUMPY_MKL # requires numpy+mkl ``` This line comment states the dependency as `numpy+mkl` (`numpy` with [**Intel Math Kernel Library**](http://www.intel.com/software/products/mkl/)). This means that you've in...
getting Forbidden by robots.txt: scrapy
37,274,835
6
2016-05-17T11:28:33Z
37,278,895
12
2016-05-17T14:24:08Z
[ "python", "scrapy", "web-crawler" ]
while crawling website like <https://www.netflix.com>, getting Forbidden by robots.txt: https://www.netflix.com/> ERROR: No response downloaded for: <https://www.netflix.com/>
In the new version (scrapy 1.1) launched 2016-05-11 the crawl first downloads robots.txt before crawling. To change this behavior change in your `settings.py` with [ROBOTSTXT\_OBEY](http://doc.scrapy.org/en/1.1/topics/settings.html#robotstxt-obey) ``` ROBOTSTXT_OBEY=False ``` Here are the [release notes](http://doc.s...
"Fire and forget" python async/await
37,278,647
18
2016-05-17T14:13:00Z
37,345,564
14
2016-05-20T11:30:16Z
[ "python", "python-3.5", "python-asyncio" ]
Sometimes there is some non-critical asynchronous operation that needs to happen but I don't want to wait for it to complete. In Tornado's coroutine implementation you can "fire & forget" an asynchronous function by simply ommitting the `yield` key-word. I've been trying to figure out how to "fire & forget" with the n...
## asyncio.Task to “fire and forget” `asyncio.Task` [is a way](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task) to start some coroutine to executing "in background". Task created by `asyncio.ensure_future` [function](https://docs.python.org/3/library/asyncio-task.html#asyncio.ensure_future) wouldn...
ScrapyRT vs Scrapyd
37,283,531
15
2016-05-17T18:16:06Z
37,285,578
9
2016-05-17T20:22:07Z
[ "python", "web-scraping", "scrapy", "scrapyd" ]
We've been using [`Scrapyd` service](https://github.com/scrapy/scrapyd) for a while up until now. It provides a nice wrapper around a scrapy project and its spiders letting to control the spiders via an HTTP API: > Scrapyd is a service for running Scrapy spiders. > > It allows you to deploy your Scrapy projects and co...
They don't have thaaat much in common. As you have already seen you have to deploy your spiders to scrapyd and then schedule crawls. scrapyd is a standalone service running on a server where you can deploy and run every project/spider you like. With ScrapyRT you choose one of your projects and you `cd` to that directo...
How to tell Keras stop training based on loss value?
37,293,642
7
2016-05-18T08:02:26Z
37,296,168
11
2016-05-18T09:56:36Z
[ "python", "machine-learning", "neural-network", "conv-neural-network", "keras" ]
Currently I use the following code: ``` callbacks = [ EarlyStopping(monitor='val_loss', patience=2, verbose=0), ModelCheckpoint(kfold_weights_path, monitor='val_loss', save_best_only=True, verbose=0), ] model.fit(X_train.astype('float32'), Y_train, batch_size=batch_size, nb_epoch=nb_epoch, shuffle=True, ...
I found the answer. I looked into Keras sources and find out code for EarlyStopping. I made my own callback, based on it: ``` class EarlyStoppingByLossVal(Callback): def __init__(self, monitor='val_loss', value=0.00001, verbose=0): super(Callback, self).__init__() self.monitor = monitor sel...
How to iterate few elements in Python arrays?
37,298,611
2
2016-05-18T11:43:48Z
37,298,672
7
2016-05-18T11:46:41Z
[ "python", "python-2.7" ]
For example I have a list of objects like this: ``` [[{1},{2},{3}],[{4},{5}],[{6},{7},{8}]] ``` I need to iterate through them all to get on each iteration objects like: ``` 1,4,6 1,4,7 1,4,8 1,5,6 1,5,7 1,5,8 2,4,6 2,4,7 2,4,8 2,5,6 2,5,7 2,5,8 ``` Basically each result is like a sub array of the input...
You can easily use [`itertools.product`](https://docs.python.org/2/library/itertools.html#itertools.product) ``` >>> import itertools >>> x = list(itertools.product([1,2,3],[4,5],[6,7,8])) [(1, 4, 6), (1, 4, 7), (1, 4, 8), (1, 5, 6), (1, 5, 7), (1, 5, 8), (2, 4, 6), (2, 4, 7), (2, 4, 8), (2, 5, 6), (2, 5, 7), (2, 5, 8...
Attributes of Python module `this`
37,301,273
16
2016-05-18T13:35:19Z
37,301,341
28
2016-05-18T13:37:31Z
[ "python" ]
Typing `import this` returns Tim Peters' Zen of Python. But I noticed that there are 4 properties on the module: ``` this.i this.c this.d this.s ``` I can see that the statement ``` print(''.join(this.d.get(el, el) for el in this.s)) ``` uses `this.d` to decode `this.s` to print the Zen. But can someone tell me w...
`i` and `c` are simply *loop variables*, used to build the `d` dictionary. From [the module source code](https://hg.python.org/cpython/file/3.5/Lib/this.py): ``` d = {} for c in (65, 97): for i in range(26): d[chr(i+c)] = chr((i+13) % 26 + c) ``` This builds a [ROT-13 mapping](https://en.wikipedia.org/wik...
Show hidden option using argparse
37,303,960
7
2016-05-18T15:25:44Z
37,304,287
7
2016-05-18T15:39:37Z
[ "python", "argparse" ]
I'm using argprase to create an option, and it's a very specific option to do one specific job. The script currently has roughly 30 knobs, and most aren't used regularly. I'm creating an option: ``` opt.add_argument('-opt',help="Some Help", help=argparse.SUPPRESS) ``` But i want there to be two ways to show the help...
I don't think there's a builtin way to support this. You can probably hack around it by checking `sys.argv` directly and using that to modify how you build the parser: ``` import sys show_hidden_args = '--help-long' in sys.argv opt = argparse.ArgumentParser() opt.add_argument('--hidden-arg', help='...' if show_hidden...
Python3: zip in range
37,308,000
3
2016-05-18T18:57:02Z
37,308,050
8
2016-05-18T18:59:54Z
[ "python", "python-3.x" ]
I'm new to Python and I'm trying to zip 2 lists together into 1, which I was already able to do. I've got 2 lists with several things in them, but I'm asking the user to input a number, which should determine the range. So i've got List1: A1, A2, A3, A4, A5, A6 and List2: B1,B2,B3,B4,B5,B6 I know how to display the 2 c...
You can slice the result of `zip()` with [`itertools.islice()`](https://docs.python.org/3/library/itertools.html#itertools.islice): ``` >>> from itertools import islice >>> list(islice(c, number)) [('A1', 'B1'), ('A2', 'B2'), ('A3', 'B3')] ```
Merge two or more lists with given order of merging
37,309,556
8
2016-05-18T20:30:42Z
37,309,683
11
2016-05-18T20:38:11Z
[ "python", "python-2.7" ]
On start I have 2 lists and 1 list that says in what order I should merge those two lists. For example I have first list equal to `[a, b, c]` and second list equal to `[d, e]` and 'merging' list equal to `[0, 1, 0, 0, 1]`. That means: to make merged list first I need to take element from first list, then second, then ...
You could create 2 iterators from those lists, loop through the ordering list, and call [`next`](https://docs.python.org/3/library/functions.html#next) on one of the 2 iterators: ``` i1 = iter(['a', 'b', 'c']) i2 = iter(['d', 'e']) # Select the iterator to advance: `i2` if `x` == 1, `i1` otherwise print([next(i2 if x ...
Mutually exclusive option groups in python Click
37,310,718
5
2016-05-18T21:52:56Z
37,491,504
7
2016-05-27T20:07:45Z
[ "python", "python-click" ]
How can I create a mutually exclusive option group in Click? I want to either accept the flag "--all" or take an option with a parameter like "--color red".
I ran into this same use case recently; this is what I came up with. For each option, you can give a list of conflicting options. ``` from click import command, option, Option, UsageError class MutuallyExclusiveOption(Option): def __init__(self, *args, **kwargs): self.mutually_exclusive = set(kwargs.pop(...
What's the meaning of "(1,) == 1," in Python?
37,313,471
106
2016-05-19T03:29:25Z
37,313,506
137
2016-05-19T03:32:47Z
[ "python", "tuples", "equals-operator" ]
I'm testing the tuple structure, and I found it's strange when I use the `==` operator like: ``` >>> (1,) == 1, Out: (False,) ``` When I assign these two expressions to a variable, the result is true: ``` >>> a = (1,) >>> b = 1, >>> a==b Out: True ``` This questions is different from [Python tuple trailing comma s...
This is just operator precedence. Your first ``` (1,) == 1, ``` groups like so: ``` ((1,) == 1), ``` so builds a tuple with a single element from the result of comparing the one-element tuple `1,` to the integer `1` for equality They're not equal, so you get the 1-tuple `False,` for a result.
What's the meaning of "(1,) == 1," in Python?
37,313,471
106
2016-05-19T03:29:25Z
37,313,562
11
2016-05-19T03:39:37Z
[ "python", "tuples", "equals-operator" ]
I'm testing the tuple structure, and I found it's strange when I use the `==` operator like: ``` >>> (1,) == 1, Out: (False,) ``` When I assign these two expressions to a variable, the result is true: ``` >>> a = (1,) >>> b = 1, >>> a==b Out: True ``` This questions is different from [Python tuple trailing comma s...
When you do ``` >>> (1,) == 1, ``` it builds a tuple with the result from comparing the *tuple* `(1,)` with an *integer* and thus returning `False`. Instead when you assign to variables, the two *equal tuples* are compared with each other. You can try: ``` >>> x = 1, >>> x (1,) ```
What's the meaning of "(1,) == 1," in Python?
37,313,471
106
2016-05-19T03:29:25Z
37,313,614
79
2016-05-19T03:45:03Z
[ "python", "tuples", "equals-operator" ]
I'm testing the tuple structure, and I found it's strange when I use the `==` operator like: ``` >>> (1,) == 1, Out: (False,) ``` When I assign these two expressions to a variable, the result is true: ``` >>> a = (1,) >>> b = 1, >>> a==b Out: True ``` This questions is different from [Python tuple trailing comma s...
Other answers have already shown you that the behaviour is due to operator precedence, as documented [here](https://docs.python.org/3/reference/expressions.html#operator-precedence). I'm going to show you how to find the answer yourself next time you have a question similar to this. You can deconstruct how the express...
Transforming Dataframe columns into Dataframe of rows
37,333,614
5
2016-05-19T20:40:03Z
37,333,712
8
2016-05-19T20:46:07Z
[ "python", "pandas", "dataframe" ]
I have following DataFrame: ``` data = {'year': [2010, 2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012, 2013], 'store_number': ['1944', '1945', '1946', '1947', '1948', '1949', '1947', '1948', '1949', '1947'], 'retailer_name': ['Walmart','Walmart', 'CRV', 'CRV', 'CRV', 'Walmart', 'Walmart', 'CRV', 'CRV',...
Please see below for solution. Thanks to EdChum for corrections to original post. **Without reset\_index()** ``` stores.groupby(level=[0, 1, 2, 3]).sum().unstack().fillna(0) amount product a b c retailer_name store_number year CRV ...
Transforming Dataframe columns into Dataframe of rows
37,333,614
5
2016-05-19T20:40:03Z
37,333,857
7
2016-05-19T20:56:45Z
[ "python", "pandas", "dataframe" ]
I have following DataFrame: ``` data = {'year': [2010, 2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012, 2013], 'store_number': ['1944', '1945', '1946', '1947', '1948', '1949', '1947', '1948', '1949', '1947'], 'retailer_name': ['Walmart','Walmart', 'CRV', 'CRV', 'CRV', 'Walmart', 'Walmart', 'CRV', 'CRV',...
Unstack `product` from the index and fill `NaN` values with zero. ``` df = stores.groupby(level=[0, 1, 2, 3]).sum().unstack('product') mask = pd.IndexSlice['amount', :] df.loc[:, mask] = df.loc[:, mask].fillna(0) >>> df amount product a b c reta...
Pythonic way to iterate and/or enumerate with a binary 'switch'
37,342,396
2
2016-05-20T09:00:28Z
37,342,506
7
2016-05-20T09:05:42Z
[ "python", "loops", "iterator" ]
I'm working with a few things at the moment where there will be 2n possible outcomes that I need to iterate over in a binary manner. I'd like some kind of binary [enumeration](https://docs.python.org/3/library/functions.html#enumerate) or similar that I could use to switch on and off operators and/or functions in each...
Just produce the product of binary flags; if you need to switch 3 different things, generate the product of `(False, True)` three times: ``` from itertools import product for first, second, third in product((False, True), repeat=3): ``` You can also produce the product of operators; your sample could use [`operator`...
ImportError : cannot import name '_win32stdio'
37,342,603
5
2016-05-20T09:10:15Z
37,357,863
10
2016-05-21T01:00:26Z
[ "python", "visual-studio", "scrapy" ]
I am working with Scrapy framework to scrap out data from website, but getting the following error in command prompt: > ImportError: cannot import name '\_win32stdio' Traceback is attached as a screenshot. Kindly revert if require directory structure of my program's directory. ![Error in CMD](http://i.stack.imgur.c...
Scrapy can work with Python 3 on windows if you make some minor adjustments: 1. Copy the \_win32stdio and \_pollingfile to the appropriate directory under site-packages. Namely, twisted-dir\internet. Download these from <https://github.com/twisted/twisted/tree/trunk/twisted/internet> 2. `pip install pypiwin32` Grante...
How to correctly supply argument to the following Python script
37,355,964
2
2016-05-20T21:15:26Z
37,355,990
7
2016-05-20T21:17:17Z
[ "python", "linux", "command-line", "arguments" ]
I'm new to Python and would really like to run some files through the following Python script. <https://github.com/ashutoshkpandey/Variants_call/blob/master/Filter_Pindel_del_vcf.py> I'm running on Linux server and Python is installed. I saved the script in a directory with the two required files (Del.vcf and Output\...
Just remove commas: ``` python Filter_Pindel_del_vcf.py Del.vcf Output_D Outputfile ```
How to check if all items in list are string
37,357,798
2
2016-05-21T00:49:00Z
37,357,810
8
2016-05-21T00:50:57Z
[ "python", "python-3.x" ]
If I have a list in python, is there a function to tell me if all the items in the list are strings? For Example: `["one", "two", 3]` would return `False`, and `["one", "two", "three"]` would return `True`.
Just use `all()` and check for types with `isinstance()`. ``` >>> l = ["one", "two", 3] >>> all(isinstance(item, str) for item in l) False >>> l = ["one", "two", '3'] >>> all(isinstance(item, str) for item in l) True ```
Why are literal formatted strings so slow in Python 3.6 alpha?
37,365,311
19
2016-05-21T16:15:09Z
37,365,521
19
2016-05-21T16:34:30Z
[ "python", "performance", "string-formatting", "python-internals", "python-3.6" ]
I've downloaded a Python 3.6 alpha build from the Python Github repository, and one of my favourite new features is literal string formatting. It can be used like so: ``` >>> x = 2 >>> f"x is {x}" "x is 2" ``` This appears to do the same thing as using the `format` function on a `str` instance. However, one thing tha...
The `f"..."` syntax is effectively converted to a `str.join()` operation on the literal string parts around the `{...}` expressions, and the results of the expressions themselves passed through the `object.__format__()` method (passing any `:..` format specification in). You can see this when disassembling: ``` >>> im...
Cleanest way to filter a Pandas dataframe?
37,375,158
2
2016-05-22T13:46:13Z
37,375,226
8
2016-05-22T13:52:16Z
[ "python", "pandas" ]
Python: ``` pd.read_csv("CME-datasets-codes.csv", header=None) ``` Produces: ``` 0 1 0 CME/OH2014 Oats Futures, March 2014, OH2014, CBOT 1 CME/HGG2004 Copper Futures, February 2004, HGG2004, COMEX 2 CME/BRH2014 Brazilian Real (BRL/USD) Futures, March 2014, ... 3 CME/F5H2014 ...
``` df[df[0].str.startswith('CME/C')] ```
Python - Check if multiple variables have the same value
37,376,516
3
2016-05-22T16:01:34Z
37,376,566
8
2016-05-22T16:07:37Z
[ "python", "python-3.x" ]
I have a set of three variables x, y, z and I want to check if they **all share the same value**. In my case, the value will either by 1 or 2, but I only need to know if they are all the same. Currently I'm using ``` if 1 == x and 1 == y and 1 == z: sameness = True ``` Looking for the answer I've found: ``` if...
If you have an arbitrary sequence, use the [`all()` function](https://docs.python.org/3/library/functions.html#all) with a [generator expression](https://docs.python.org/3/tutorial/classes.html#generator-expressions): ``` values = [x, y, z] # can contain any number of values if all(v == 1 for v in values): ``` other...
Extracting items from a list and assigning them to variables
37,376,776
3
2016-05-22T16:28:11Z
37,376,812
8
2016-05-22T16:31:15Z
[ "python", "list" ]
I'm trying to extract the first three items from `numbers`, and assign them to three different variables, as follows: ``` numbers = [1,2,3,4,5,7,8,9,10] [first_item, second_item, third_item] = numbers ``` Why am I getting this error? ``` Traceback (most recent call last): File "test.py", line 2, in <module> [f...
You don't assign to them in a list like that, and you need to handle the rest of the unpacking for your list - your error message is indicating that there are more values to unpack than you have variables to assign to. One way you can amend this is by assigning the remaining elements in your list to a `rest` variable w...
In Python Dictionaries, how does ( (j*5)+1 ) % 2**i cycle through all 2**i
37,378,874
17
2016-05-22T19:43:42Z
37,379,175
13
2016-05-22T20:13:13Z
[ "python", "algorithm", "dictionary", "linear-probing" ]
I am researching how python implements dictionaries. One of the equations in the python dictionary implementation relates the the pseudo random probing for an empty dictionary slot using the equation ``` j = ((j*5) + 1) % 2**i ``` which is explained [here](https://hg.python.org/cpython/file/52f68c95e025/Objects/dicto...
This is the same principle that pseudo-random number generators use, as Jasper hinted at, namely [linear congruential generators](https://en.wikipedia.org/wiki/Linear_congruential_generator). A linear congruential generator is a sequence that follows the relationship `X_(n+1) = (a * X_n + c) mod m`. From the wiki page,...
Spark ALS predictAll returns empty
37,379,751
4
2016-05-22T21:16:03Z
37,435,580
7
2016-05-25T11:21:12Z
[ "python", "apache-spark", "machine-learning", "pyspark", "rdd" ]
I have the following Python test code (the arguments to ALS.train are defined elsewhere): ``` r1 = (2, 1) r2 = (3, 1) test = sc.parallelize([r1, r2]) model = ALS.train(ratings, rank, numIter, lmbda) predictions = model.predictAll(test) print test.take(1) print predictions.count() print predictions ``` ...
There are two basic conditions under which `MatrixFactorizationMode.predictAll` may return a RDD with lower number of items than the input: * user is missing in the training set. * product is missing in the training set. You can easily reproduce this behavior and check that it is is not dependent on the way how RDD h...
Replacing repeated captures
37,381,249
24
2016-05-23T01:01:07Z
37,381,369
9
2016-05-23T01:21:00Z
[ "python", "regex" ]
This is sort of a follow-up to [Python regex - Replace single quotes and brackets](http://stackoverflow.com/questions/37375828/python-regex-replace-single-quotes-and-brackets) thread. **The task:** Sample input strings: ``` RSQ(name['BAKD DK'], name['A DKJ']) SMT(name['BAKD DK'], name['A DKJ'], name['S QRT']) ``` D...
You could do this. Though I don't think it's very readable. And doing it this way could get unruly if you start adding more patterns to replace. It takes advantage of the fact that the replacement string can also be a function. ``` s = "RSQ(name['BAKD DK'], name['A DKJ'])" re.sub(r"^(\w+)|name\['(.*?)'\]", lambda m: '...
Replacing repeated captures
37,381,249
24
2016-05-23T01:01:07Z
37,381,447
13
2016-05-23T01:33:33Z
[ "python", "regex" ]
This is sort of a follow-up to [Python regex - Replace single quotes and brackets](http://stackoverflow.com/questions/37375828/python-regex-replace-single-quotes-and-brackets) thread. **The task:** Sample input strings: ``` RSQ(name['BAKD DK'], name['A DKJ']) SMT(name['BAKD DK'], name['A DKJ'], name['S QRT']) ``` D...
You can indeed use the regex module and repeated captures. The main interest is that you can check the structure of the matched string: ``` import regex regO = regex.compile(r''' \w+ \( (?: name\['([^']*)'] (?: ,[ ] | (?=\)) ) )* \) ''', regex.VERBOSE); regO.sub(lambda m: 'XYZ(' + (', '.join(m.captures(1))) ...
Replacing repeated captures
37,381,249
24
2016-05-23T01:01:07Z
37,383,496
9
2016-05-23T05:56:52Z
[ "python", "regex" ]
This is sort of a follow-up to [Python regex - Replace single quotes and brackets](http://stackoverflow.com/questions/37375828/python-regex-replace-single-quotes-and-brackets) thread. **The task:** Sample input strings: ``` RSQ(name['BAKD DK'], name['A DKJ']) SMT(name['BAKD DK'], name['A DKJ'], name['S QRT']) ``` D...
Please do not do this in any code I have to maintain. You are trying to parse syntactically valid Python. Use [`ast`](https://docs.python.org/3/library/ast.html) for that. It's more readable, easier to extend to new syntax, and won't fall apart on some weird corner case. Working sample: ``` from ast import parse l ...
TensorFlow, "'module' object has no attribute 'placeholder'"
37,383,812
3
2016-05-23T06:20:20Z
37,386,150
7
2016-05-23T08:29:39Z
[ "python", "machine-learning", "tensorflow" ]
I've been trying to use tensorflow for two days now installing and reinstalling it over and over again in python2.7 and 3.4. No matter what I do, I get this error message when trying to use tensorflow.placeholder() It's very boilerplate code: ``` tf_in = tf.placeholder("float", [None, A]) # Features ``` No matter wh...
**Solution: Do not use "tensorflow" as your filename.** Notice that you use tensorflow.py as your filename. And I guess you write code like: ``` import tensorflow as tf ``` Then you are actually importing the script file "tensorflow.py" that is under your current working directory, rather than the "real" tensorflow ...
How can I create a type hint that my returned list contains strings?
37,386,499
16
2016-05-23T08:47:14Z
37,386,610
19
2016-05-23T08:53:08Z
[ "python", "python-3.5", "type-hinting" ]
I want to use Type Hints in my Python program. How can I create Type Hints for complex data structures like * lists with strings * a generator returning integers? **Example** ``` def names() -> list: # I would like to specify that the list contains strings? return ['Amelie', 'John', 'Carmen'] def numbers():...
Use the [`typing` module](https://docs.python.org/3/library/typing.html); it contains *generics*, type objects you can use to specify containers with constraints on their contents: ``` import typing def names() -> typing.List[str]: # list object with strings return ['Amelie', 'John', 'Carmen'] def numbers() -> ...
Spurious newlines added in Django management commands
37,400,807
13
2016-05-23T21:23:38Z
39,931,636
10
2016-10-08T11:08:05Z
[ "python", "django", "python-3.x", "stdout", "django-management-command" ]
Running Django v1.10 on Python 3.5.0: ``` from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): print('hello ', end='', file=self.stdout) print('world', file=self.stdout) ``` Expected output: ``` hello world ``` Actual output: ``` h...
As is mentioned in [Django 1.10's Custom Management Commands](https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/) document: > When you are using management commands and wish to provide console output, you should write to **self.stdout** and **self.stderr**, instead of printing to **stdout** and *...
Smoothing Edges of a Binary Image
37,409,811
6
2016-05-24T09:40:28Z
37,458,312
7
2016-05-26T10:34:15Z
[ "python", "opencv", "image-processing", "blur", "edge" ]
How to smooth the edges of this binary image of blood vessels obtained after thresholding. [![enter image description here](http://i.stack.imgur.com/YyNQV.png)](http://i.stack.imgur.com/YyNQV.png) I tried a method somewhat similar to [this method](http://stackoverflow.com/questions/21795643/image-edge-smoothing-with-...
Here is the result I obtained with your image: [![enter image description here](http://i.stack.imgur.com/frmkx.png)](http://i.stack.imgur.com/frmkx.png) My method is mostly based on several `cv::medianBlur`applied on a scaled-up image. Here is the code: ``` cv::Mat vesselImage = cv::imread(filename); //the original ...
Efficient Double Sum of Products
37,416,978
7
2016-05-24T14:48:51Z
37,417,313
8
2016-05-24T15:02:34Z
[ "python", "numpy" ]
Consider two `ndarrays` of length `n`, `arr1` and `arr2`. I'm computing the following sum of products, and doing it `num_runs` times to benchmark: ``` import numpy as np import time num_runs = 1000 n = 100 arr1 = np.random.rand(n) arr2 = np.random.rand(n) start_comp = time.clock() for r in xrange(num_runs): sum...
A vectorized way : `np.sum(np.triu(np.multiply.outer(arr1,arr2),1))`. for a 30x improvement: ``` In [9]: %timeit np.sum(np.triu(np.multiply.outer(arr1,arr2),1)) 1000 loops, best of 3: 272 µs per loop In [10]: %timeit np.sum( [arr1[i]*arr2[j] for i in range(n) for j in range(i+1, n)] 100 lo...
Efficient Double Sum of Products
37,416,978
7
2016-05-24T14:48:51Z
37,417,863
12
2016-05-24T15:26:41Z
[ "python", "numpy" ]
Consider two `ndarrays` of length `n`, `arr1` and `arr2`. I'm computing the following sum of products, and doing it `num_runs` times to benchmark: ``` import numpy as np import time num_runs = 1000 n = 100 arr1 = np.random.rand(n) arr2 = np.random.rand(n) start_comp = time.clock() for r in xrange(num_runs): sum...
Rearrange the operation into an O(n) runtime algorithm instead of O(n^2), *and* take advantage of NumPy for the products and sums: ``` # arr1_weights[i] is the sum of all terms arr1[i] gets multiplied by in the # original version arr1_weights = arr2[::-1].cumsum()[::-1] - arr2 sum_prods = arr1.dot(arr1_weights) ``` ...
How many items has been scraped per start_url
37,417,373
4
2016-05-24T15:05:19Z
37,420,626
7
2016-05-24T17:54:18Z
[ "python", "scrapy", "scrapy-spider" ]
I use scrapy to crawl 1000 urls and store scraped item in a mongodb. I'd to know how many items have been found for each url. From scrapy stats I can see `'item_scraped_count': 3500` However, I need this count for each start\_url separately. There is also `referer` field for each item that I might use to count each url...
challenge accepted! there isn't something on `scrapy` that directly supports this, but you could separate it from your spider code with a [`Spider Middleware`](http://doc.scrapy.org/en/latest/topics/spider-middleware.html): **middlewares.py** ``` from scrapy.http.request import Request class StartRequestsCountMiddl...
Does PyPy work with asyncio?
37,419,442
5
2016-05-24T16:43:45Z
37,421,658
9
2016-05-24T18:51:57Z
[ "python", "performance", "asynchronous", "python-asyncio", "pypy" ]
Does PyPy support the aio and Python 3.5? I need the performance of `PyPy` and asynchrous code of `asyncio`. Also I need to use `async/await` in my code. Is that possible? If so, what are the nuances?
Currently PyPy supports Python 3.3. This means that you can [install asyncio](https://pypi.python.org/pypi/asyncio) on PyPy3.3. Note that PyPy's 3.3 support is only alpha / beta quality in the moment. We are however actively working on increasing performance and compatibility with CPython. The `async` / `await` featur...
Comparing 2 dictionaries: same key, mismatching values
37,425,592
4
2016-05-24T23:35:30Z
37,425,724
9
2016-05-24T23:49:57Z
[ "python" ]
I am currently trying to compare 2 data sets: ``` dict1 = {'a':1, 'b':2, 'c':3} dict2 = {'a':1, 'b':2, 'c':4} ``` In this case I want the output to be something like: ``` set1 = set([('c', 4), ('c',3)]) ``` since their keys match but values do not. I've tried a variation of comprehensions using the intersection an...
If you are using Python 2: ``` dict1.viewitems() ^ dict2.viewitems() ``` If you are using Python 3: ``` dict1.items() ^ dict2.items() ``` `viewitems` (Python 2) and `items` (Python 3) return a set-like object, which we can use the caret operator to calculate the symetric difference.
Dummy variables when not all categories are present
37,425,961
6
2016-05-25T00:22:39Z
37,451,867
8
2016-05-26T04:53:38Z
[ "python", "pandas", "machine-learning", "dummy-variable" ]
I have a set of dataframes where one of the columns contains a categorical variable. I'd like to convert it to several dummy variables, in which case I'd normally use `get_dummies`. What happens is that `get_dummies` looks at the data available in each dataframe to find out how many categories there are, and thus crea...
> is there a way to pass to get\_dummies (or an equivalent function) the names of the categories, so that, for the categories that don't appear in a given dataframe, it'd just create a column of 0s? Yes, there is! Pandas has a special type of Series just for [categorical data](http://pandas.pydata.org/pandas-docs/stab...
Scrapy: AttributeError: 'list' object has no attribute 'iteritems'
37,442,907
5
2016-05-25T16:27:24Z
37,469,195
8
2016-05-26T19:10:14Z
[ "python", "scrapy-spider", "six" ]
This is my first question on stack overflow. Recently I want to use [linked-in-scraper](https://github.com/junks/linkedInScraper), so I downloaded and instruct "scrapy crawl linkedin.com" and get the below error message. For your information, I use anaconda 2.3.0 and python 2.7.11. All the related packages, including s...
This is caused by the linked-in scraper's [settings](https://github.com/junks/linkedInScraper/blob/master/linkedIn/linkedIn/settings.py#L23): ``` ITEM_PIPELINES = ['linkedIn.pipelines.LinkedinPipeline'] ``` However, `ITEM_PIPELINES` is supposed to be a link, [according to the doc](http://doc.scrapy.org/en/latest/topi...
Multiple exceptions and code coverage when unit testing python
37,463,561
8
2016-05-26T14:21:08Z
37,473,190
7
2016-05-27T00:53:05Z
[ "python", "unit-testing", "testing", "code-coverage", "coverage.py" ]
**The Problem:** Here is an artificial example of the code under test: ``` from datetime import datetime def f(s): try: date = s.split(":")[1] return datetime.strptime(date, "%Y%m%d") except (ValueError, IndexError) as e: # some code here raise ``` Here is a set of tests I cu...
Coverage.py can only measure which execution paths (statements or branches) were run. It has no means of tracking what values were used, including what exception types were raised. As I see it, your options are: 1. Separate the exception clauses. In the code you've shown, the two exceptions could be raised by separat...
Python find index of all array elements in another array
37,467,515
2
2016-05-26T17:30:49Z
37,467,583
9
2016-05-26T17:34:31Z
[ "python", "numpy" ]
I am trying to do the following: ``` import numpy as np A = np.array([1,5,2,7,1]) B = np.sort(A) print B >>> [1,1,2,5,7] ``` I want to find the location of all elements in B as in original array A. i.e. I want to create an array C such that ``` print C >>[0,4,2,1,3] ``` which refers to 1 in B being present in A at ...
``` import numpy as np A = np.array([1,5,2,7,1]) print np.argsort(A) #prints [0 4 2 1 3] ```
How to make statement `import datetime` bind the datetime type instead of the datetime module?
37,491,110
4
2016-05-27T19:40:21Z
37,491,209
7
2016-05-27T19:47:23Z
[ "python", "python-import", "python-module" ]
After one too many times having accidentally typed `import datetime` when what was really needed was `from datetime import datetime`, I wondered whether it was possible to hack around and make the former do the latter. That is, to recreate this behaviour (in a freshly opened interpreter session): ``` $ python -ic '' ...
Here we go: `datetime.py`: ``` import sys import imp import os path = [p for p in sys.path if p != os.path.dirname(__file__)] f, pathname, desc = imp.find_module('datetime', path) std_datetime = imp.load_module('datetime', f, pathname, desc) # if this^ is renamed to datetime, everything breaks! f.close() class Call...
Why is dict definition faster in Python 2.7 than in Python 3.x?
37,502,392
24
2016-05-28T18:17:18Z
37,502,529
31
2016-05-28T18:33:09Z
[ "python", "python-2.7", "python-3.x", "dictionary", "python-internals" ]
I have encountered a (not very unusual) situation in which I had to either use a `map()` or a list comprehension expression. And then I wondered which one is faster. [This](http://stackoverflow.com/a/1247490/3120525) StackOverflow answer provided me the solution, but then I started to test it myself. Basically the res...
**Because nobody cares** The differences you are citing are on the order of tens or hundreds of nanoseconds. A slight difference in how the C compiler optimizes register use could easily cause such changes (as could any number of other C-level optimization differences). That, in turn, could be caused by any number of ...
Why is dict definition faster in Python 2.7 than in Python 3.x?
37,502,392
24
2016-05-28T18:17:18Z
37,502,747
20
2016-05-28T18:55:41Z
[ "python", "python-2.7", "python-3.x", "dictionary", "python-internals" ]
I have encountered a (not very unusual) situation in which I had to either use a `map()` or a list comprehension expression. And then I wondered which one is faster. [This](http://stackoverflow.com/a/1247490/3120525) StackOverflow answer provided me the solution, but then I started to test it myself. Basically the res...
As @Kevin already stated: > CPython is not designed to be fast in an absolute sense. It is > designed to be scalable Try this instead: ``` $ python -mtimeit "dict([(2,3)]*10000000)" 10 loops, best of 3: 512 msec per loop $ $ python3 -mtimeit "dict([(2,3)]*10000000)" 10 loops, best of 3: 502 msec per loop ``` And ag...
Why is dict definition faster in Python 2.7 than in Python 3.x?
37,502,392
24
2016-05-28T18:17:18Z
37,503,256
17
2016-05-28T19:56:10Z
[ "python", "python-2.7", "python-3.x", "dictionary", "python-internals" ]
I have encountered a (not very unusual) situation in which I had to either use a `map()` or a list comprehension expression. And then I wondered which one is faster. [This](http://stackoverflow.com/a/1247490/3120525) StackOverflow answer provided me the solution, but then I started to test it myself. Basically the res...
Let's [disassemble](https://docs.python.org/3/library/dis.html#dis.dis) `{}`: ``` >>> from dis import dis >>> dis(lambda: {}) 1 0 BUILD_MAP 0 3 RETURN_VALUE ``` [Python 2.7 implementation of BUILD\_MAP](https://hg.python.org/cpython/file/2.7/Python/ceval.c#l2498) ``` TARGET(B...
How can I start and stop a Python script from shell
37,511,265
2
2016-05-29T14:47:05Z
37,511,354
8
2016-05-29T14:54:59Z
[ "python", "shell" ]
thanks for helping! I want to start and stop a Python script from a shell script. The start works fine, but I want to stop / terminate the Python script after 10 seconds. (it's a counter that keeps counting). bud is won't stop.... I think it is hanging on the first line. What is the right way to start wait for 10 sec...
You're right, the shell script "hangs" on the first line until the python script finishes. If it doesn't, the shell script won't continue. Therefore you have to use `&` at the end of the shell command to run it in the background. This way, the python script starts and the shell script continues. The `kill` command doe...
how to make arrow that loops in matplotlib?
37,512,502
9
2016-05-29T16:50:23Z
38,224,201
7
2016-07-06T12:37:08Z
[ "python", "matplotlib" ]
what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried: ``` plt.figure() plt.xlim([0, 1]) plt.ylim([0, 1]) plt.annotate("", xy=(0.6, 0.9), xycoords="figure fraction", xytext = (0.6, 0.8), textcoords="figure fraction", fon...
I find no way to make a loop using `plt.annotate` only once, but using it four times works : ``` import matplotlib.pyplot as plt fig,ax = plt.subplots() # coordinates of the center of the loop x_center = 0.5 y_center = 0.5 radius = 0.2 # linewidth of the arrow linewidth = 1 ax.annotate("", (x_center + radius, y_...
Python static typing does not work
37,526,876
2
2016-05-30T13:26:10Z
37,526,963
9
2016-05-30T13:30:47Z
[ "python", "python-3.x", "static-typing" ]
I found out that Python is intending to support static typing, but it still in beta phase. I tried the following code with python 3.4.3: ``` def somme(a: int, b: int) -> int: return a + b ``` the syntax is supported but I did not get the expected result. if I type `somme('1', '3')` I get 13, while I should get `T...
The function annotations there are *annotations*, nothing more. They're documentation about intended usage. Like it says in [PEP 3107](https://www.python.org/dev/peps/pep-3107/), the mechanism provides a single, standard way to specify function parameters and return values, replacing a variety of ad-hoc tools and libra...
What is the advantage of using a lambda:None function?
37,532,208
15
2016-05-30T19:02:38Z
37,532,492
11
2016-05-30T19:27:35Z
[ "python", "lambda", "namespaces", "names" ]
I saw the following [code](https://github.com/sunqm/pyscf/blob/master/mcscf/mc1step_uhf.py#L531): ``` eris = lambda:None eris.jkcpp = np.einsum('iipq->ipq', eriaa[:ncore[0],:ncore[0],:,:]) eris.jc_PP = np.einsum('iipq->pq', eriab[:ncore[0],:ncore[0],:,:]) ``` Can we define arbitrary attributes for a function defined ...
This looks like a trick to create a simple object to hold values in one line. Most built-in objects don't allow you to set arbitrary attributes on them: ``` >>> object().x = 0 Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'object' object has no attribute 'x' >>> ''.x = 0 Trac...
Why is statistics.mean() so slow?
37,533,666
42
2016-05-30T21:05:05Z
37,533,799
65
2016-05-30T21:22:30Z
[ "python", "performance", "mean" ]
I compared the performance of the `mean` function of the `statistics` module with the simple `sum(l)/len(l)` method and found the `mean` function to be very slow for some reason. I used `timeit` with the two code snippets below to compare them, does anyone know what causes the massive difference in execution speed? I'm...
Python's `statistics` module is not built for speed, but for precision In [the specs for this module](https://www.python.org/dev/peps/pep-0450/), it appears that > The built-in sum can lose accuracy when dealing with floats of wildly > differing magnitude. Consequently, the above naive mean fails this > "torture test...
addCleanUp vs tearDown
37,534,021
14
2016-05-30T21:50:18Z
37,534,051
15
2016-05-30T21:53:21Z
[ "python", "unit-testing", "python-unittest" ]
Recently, Ned Batchelder during [his talk at PyCon 2016](http://nedbatchelder.com/text/machete.html) noted: > If you are using `unittest` to write your tests, definitely use > `addCleanup`, it's much better than `tearDown`. Up until now, I've never used `addCleanUp()` and got used to `setUp()`/`tearDown()` pair of me...
Per the [`addCleanup` doc string](https://docs.python.org/3.5/library/unittest.html#unittest.TestCase.addCleanup): > Cleanup items are called even if setUp fails (unlike tearDown) `addCleanup` can be used to register multiple functions, so you could use separate functions for each resource you wish to clean up. That ...
How to map a function to every item in every sublist of a list
37,537,609
3
2016-05-31T05:39:53Z
37,537,652
11
2016-05-31T05:43:51Z
[ "python", "list", "python-2.7" ]
Is there a way to do this without using a regular for loop to iterate through the main list? ``` >>> map(lambda x: x*2, [[1,2,3],[4,5,6]]) [[1, 2, 3, 1, 2, 3], [4, 5, 6, 4, 5, 6]] # want [[2,4,6],[8,10,12]] ```
You have nested lists, and `x` represents just one of the lists. To process that, you need to actually map the multiplication function on to the individual elements of `x`, like this ``` >>> map(lambda x: map(lambda y: y * 2, x), [[1, 2, 3], [4, 5, 6]]) [[2, 4, 6], [8, 10, 12]] ``` But I would prefer list comprehensi...
Pandas: sum all rows
37,558,572
2
2016-06-01T02:45:11Z
37,558,643
7
2016-06-01T02:54:39Z
[ "python", "pandas", "dataframe" ]
I have a `DataFrame` that looks like this: ``` score num_participants 0 20 1 15 2 5 3 10 4 12 5 15 ``` I need to find the number of participants with `score` that is greater than or equal to the `score` in the current row: ``` score num_participants num_participants_with_score_greater_or_eq...
This is a reverse `cumsum`. Reverse the list, `cumsum`, then reverse back. ``` df.iloc[::-1].cumsum().iloc[::-1] score num_participants 0 15 77 1 15 57 2 14 42 3 12 37 4 9 27 5 5 15 ```
What do all the distributions available in scipy.stats look like?
37,559,470
4
2016-06-01T04:31:48Z
37,559,471
15
2016-06-01T04:31:48Z
[ "python", "matplotlib", "scipy", "statistics", "distribution" ]
# Visualizing [`scipy.stats`](http://docs.scipy.org/doc/scipy/reference/stats.html) distributions A histogram can be made of [the `scipy.stats` normal random variable](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html#scipy.stats.norm) to see what the distribution looks like. ``` % matplotlib ...
# Visualizing all [`scipy.stats` distributions](http://docs.scipy.org/doc/scipy/reference/stats.html) Based on the [list of `scipy.stats` distributions](http://docs.scipy.org/doc/scipy/reference/stats.html), plotted below are the [histogram](https://en.wikipedia.org/wiki/Histogram)s and [PDF](https://en.wikipedia.org/...