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 |
|---|---|---|---|---|---|---|---|---|---|
Cumulative Ranking of Values in Pandas with Ties | 38,246,058 | 3 | 2016-07-07T12:55:06Z | 38,246,382 | 7 | 2016-07-07T13:10:00Z | [
"python",
"pandas",
"dataframe",
"cumulative-sum"
] | I am trying to find a way to do a cumulative total that accounts for ties in Pandas.
Lets take hypothetical data from a track meet, where I have people, races, heats, and time.
Each person's placement is according to the following:
For a given race/heat combination:
* The person person with the lowest time placed f... | You could use:
```
grouped = df.groupby(['Race','Heat'])
df['Place'] = grouped['Time'].transform(lambda x: pd.factorize(x, sort=True)[0]+1)
```
---
```
import pandas as pd
df = pd.DataFrame({'Heat': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1], 'Person': ['RUNNER1', 'RUNNER2', 'RUNNER3', 'RUNNER4', 'RUNNER5'... |
How to split data into 3 sets (train, validation and test)? | 38,250,710 | 11 | 2016-07-07T16:26:26Z | 38,251,063 | 7 | 2016-07-07T16:47:10Z | [
"python",
"pandas",
"dataframe",
"machine-learning",
"scikit-learn"
] | I have a pandas dataframe and I wish to divide it to 3 seprate sets. I know that using [train\_test\_split](http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html) from `sklearn.cross_validation`, one can divide the data in two sets (train and test). However, I couldn't find any... | ### Note:
Function was written to handle seeding of randomized set creation. You should not rely on set splitting that doesn't randomize the sets.
```
import numpy as np
import pandas as pd
def train_validate_test_split(df, train_percent=.6, validate_percent=.2, seed=None):
np.random.seed(seed)
perm = np.ran... |
How to split data into 3 sets (train, validation and test)? | 38,250,710 | 11 | 2016-07-07T16:26:26Z | 38,251,213 | 10 | 2016-07-07T16:56:12Z | [
"python",
"pandas",
"dataframe",
"machine-learning",
"scikit-learn"
] | I have a pandas dataframe and I wish to divide it to 3 seprate sets. I know that using [train\_test\_split](http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html) from `sklearn.cross_validation`, one can divide the data in two sets (train and test). However, I couldn't find any... | Numpy solution (thanks to [root](http://stackoverflow.com/questions/38250710/how-to-split-data-into-3-sets-train-development-and-test/38251213?noredirect=1#comment63923795_38251213) for the randomizing hint) - we will split our data set into the following parts: (60% - train set, 20% - validation set, 20% - test set):
... |
Create a list of tuples with adjacent list elements if a condition is true | 38,251,245 | 26 | 2016-07-07T16:57:49Z | 38,251,312 | 37 | 2016-07-07T17:01:19Z | [
"python",
"list",
"python-3.x",
"tuples",
"list-comprehension"
] | I am trying to create a list of tuples where the tuple contents are the number `9` and the number before it in the list.
**Input List:**
```
myList = [1, 8, 9, 2, 4, 9, 6, 7, 9, 8]
```
**Desired Output:**
```
sets = [(8, 9), (4, 9), (7, 9)]
```
**Code:**
```
sets = [list(zip(myList[i:i], myList[-1:])) for i in my... | Cleaner Pythonic approach:
```
>>> [(x,y) for x,y in zip(myList, myList[1:]) if y == 9]
[(8, 9), (4, 9), (7, 9)]
```
---
What is the code above doing:
* `zip(some_list, some_list[1:])` would generate a list of pairs of adjacent elements.
* Now with that tuple, filter on the condition that the second element is equa... |
Create a list of tuples with adjacent list elements if a condition is true | 38,251,245 | 26 | 2016-07-07T16:57:49Z | 38,251,318 | 7 | 2016-07-07T17:01:45Z | [
"python",
"list",
"python-3.x",
"tuples",
"list-comprehension"
] | I am trying to create a list of tuples where the tuple contents are the number `9` and the number before it in the list.
**Input List:**
```
myList = [1, 8, 9, 2, 4, 9, 6, 7, 9, 8]
```
**Desired Output:**
```
sets = [(8, 9), (4, 9), (7, 9)]
```
**Code:**
```
sets = [list(zip(myList[i:i], myList[-1:])) for i in my... | You were pretty close, I'll show you an alternative way that might be more intuitive if you're just starting out:
```
sets = [(myList[i-1], myList[i]) for i in range(len(myList)) if myList[i] == 9]
```
Get the index in the range of the list lenght, and if the value at the position `i` is equal to `9`, grab the adjace... |
Create a list of tuples with adjacent list elements if a condition is true | 38,251,245 | 26 | 2016-07-07T16:57:49Z | 38,251,331 | 17 | 2016-07-07T17:02:14Z | [
"python",
"list",
"python-3.x",
"tuples",
"list-comprehension"
] | I am trying to create a list of tuples where the tuple contents are the number `9` and the number before it in the list.
**Input List:**
```
myList = [1, 8, 9, 2, 4, 9, 6, 7, 9, 8]
```
**Desired Output:**
```
sets = [(8, 9), (4, 9), (7, 9)]
```
**Code:**
```
sets = [list(zip(myList[i:i], myList[-1:])) for i in my... | Part of your issue is that `myList[i:i]` will always return an empty list. The end of a slice is exclusive, so when you do `a_list[0:0]` you're trying to take the elements of `a_list` that exist **between** index 0 and index 0.
You're on the right track, but you want to zip the list with itself.
```
[(x, y) for x, y ... |
Comparison of Pandas lookup times | 38,254,067 | 15 | 2016-07-07T19:46:24Z | 38,258,390 | 8 | 2016-07-08T03:13:17Z | [
"python",
"performance",
"pandas"
] | After experimenting with timing various types of lookups on a Pandas DataFrame I am left with a few questions.
Here is the set up...
```
import pandas as pd
import numpy as np
import itertools
letters = [chr(x) for x in range(ord('a'), ord('z'))]
letter_combinations = [''.join(x) for x in itertools.combinations(lett... | The disparity in these %timeit results
```
In [273]: %timeit df1[df1['letter'] == 'ben']
10 loops, best of 3: 36.1 ms per loop
In [274]: %timeit df2[df2['letter'] == 'ben']
10 loops, best of 3: 108 ms per loop
```
also shows up in the *pure NumPy* equality comparisons:
```
In [275]: %timeit df1['letter'].values == ... |
Can generators be recursive? | 38,254,304 | 16 | 2016-07-07T20:01:20Z | 38,254,338 | 23 | 2016-07-07T20:04:29Z | [
"python",
"recursion",
"generator"
] | I naively tried to create a recursive generator. Didn't work. This is what I did:
```
def recursive_generator(lis):
yield lis[0]
recursive_generator(lis[1:])
for k in recursive_generator([6,3,9,1]):
print(k)
```
All I got was the first item `6`.
Is there a way to make such code work? Essentially transfe... | Try this:
```
def recursive_generator(lis):
yield lis[0]
yield from recursive_generator(lis[1:])
for k in recursive_generator([6,3,9,1]):
print(k)
```
I should point out this doesn't work because of a bug in your function. It should probably include a check that `lis` isn't empty, as shown below:
```
de... |
Max recursion is not exactly what sys.getrecursionlimit() claims. How come? | 38,265,839 | 27 | 2016-07-08T11:47:43Z | 38,265,931 | 35 | 2016-07-08T11:52:47Z | [
"python",
"recursion"
] | I've made a small function that will actually measure the max recursion limit:
```
def f(x):
r = x
try:
r = f(x+1)
except Exception as e:
print(e)
finally:
return r
```
To know what to expect I've checked:
```
In [28]: import sys
In [29]: sys.getrecursionlimit()
Out[29]: 1000... | The recursion limit is not the limit on recursion but the maximum depth of the python interpreter stack.There is something on the stack before your function gets executed. Spyder executes some python stuff before it calls your script, as do other interpreters like ipython.
You can inspect the stack via methods in the ... |
Max recursion is not exactly what sys.getrecursionlimit() claims. How come? | 38,265,839 | 27 | 2016-07-08T11:47:43Z | 38,266,011 | 8 | 2016-07-08T11:56:28Z | [
"python",
"recursion"
] | I've made a small function that will actually measure the max recursion limit:
```
def f(x):
r = x
try:
r = f(x+1)
except Exception as e:
print(e)
finally:
return r
```
To know what to expect I've checked:
```
In [28]: import sys
In [29]: sys.getrecursionlimit()
Out[29]: 1000... | This limit is for stack, not for the function you define. There are other internal things which might push something to stack.
And of course it could depend on env in which it was executed. Some can pollute stack more, some less. |
Is extending a Python list (e.g. l += [1]) guaranteed to be thread-safe? | 38,266,186 | 21 | 2016-07-08T12:04:03Z | 38,266,364 | 9 | 2016-07-08T12:13:54Z | [
"python",
"multithreading",
"thread-safety",
"python-multithreading"
] | If I have an integer `i`, it is not safe to do `i += 1` on multiple threads:
```
>>> i = 0
>>> def increment_i():
... global i
... for j in range(1000): i += 1
...
>>> threads = [threading.Thread(target=increment_i) for j in range(10)]
>>> for thread in threads: thread.start()
...
>>> for thread in threads: th... | From <http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm> :
> Operations that replace other objects may invoke those other objectsâ `__del__` method when their reference count reaches zero, and that can affect things. This is especially true for the mass updates to dictionaries and lists... |
Is extending a Python list (e.g. l += [1]) guaranteed to be thread-safe? | 38,266,186 | 21 | 2016-07-08T12:04:03Z | 38,320,815 | 14 | 2016-07-12T05:42:11Z | [
"python",
"multithreading",
"thread-safety",
"python-multithreading"
] | If I have an integer `i`, it is not safe to do `i += 1` on multiple threads:
```
>>> i = 0
>>> def increment_i():
... global i
... for j in range(1000): i += 1
...
>>> threads = [threading.Thread(target=increment_i) for j in range(10)]
>>> for thread in threads: thread.start()
...
>>> for thread in threads: th... | There isn't a happy ;-) answer to this. There's nothing guaranteed about any of it, which you can confirm simply by noting that the Python reference manual makes no guarantees about atomicity.
In CPython it's a matter of pragmatics. As a snipped part of effbot's article says,
> In theory, this means an exact accounti... |
Applications of '~' (tilde) operator in Python | 38,271,945 | 13 | 2016-07-08T16:54:50Z | 38,272,045 | 11 | 2016-07-08T17:02:41Z | [
"python",
"python-3.x",
"operator-overloading",
"bit-manipulation",
"tilde"
] | I just discovered the [bitwise complement unary operation](https://en.wikipedia.org/wiki/Bitwise_operation#NOT) in Python via [this question](https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python) and have been trying to come up with an actual application for it, and if not, to determine if it's gene... | The standard use cases for the bitwise NOT operator are bitwise operations, just like the bitwise AND `&`, the bitwise OR `|`, the bitwise XOR `^`, and bitwise shifting `<<` and `>>`. Although they are rarely used in higher level applications, there are still some times where you need to do bitwise manipulations, so th... |
How to repeat individual characters in strings in Python | 38,273,353 | 4 | 2016-07-08T18:36:47Z | 38,273,369 | 15 | 2016-07-08T18:37:59Z | [
"python",
"string"
] | I know that
```
"123abc" * 2
```
evaluates as `"123abc123abc"`, but is there an easy way to repeat individual letters N times, e.g. convert `"123abc"` to `"112233aabbcc"` or `"111222333aaabbbccc"`? | What about:
```
>>> s = '123abc'
>>> n = 3
>>> ''.join(char*n for char in s)
'111222333aaabbbccc'
>>>
``` |
How to count multiple unique occurrences of unique occurrences in Python list? | 38,273,531 | 3 | 2016-07-08T18:50:29Z | 38,273,595 | 11 | 2016-07-08T18:54:47Z | [
"python"
] | Let's say I have a 2D list in Python:
```
mylist = [["A", "X"],["A", "X"],["A", "Y"],["B", "X"],["B", "X"],["A", "Y"]]
```
In this case my "keys" would be the first element of each array ("A" or "B") and my "values" would be the second element ("X" or "Y"). At the end of my consolidation the output should consolidate... | I think the easiest way to do this would be with Counter and defaultdict:
```
from collections import defaultdict, Counter
output = defaultdict(Counter)
for a, b in mylist:
output[a][b] += 1
``` |
Unpack a Python tuple from left to right? | 38,276,068 | 18 | 2016-07-08T22:10:02Z | 38,276,095 | 45 | 2016-07-08T22:12:42Z | [
"python",
"python-3.x",
"tuples",
"iterable-unpacking"
] | Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right?
For example for
```
j = 1,2,3,4,5,6,7
(1,2,3,4,5,6,7)
v,b,n = j[4:7]
```
Can I modify the slice notation so that `v = j[6], b=j[5], n=j[4]` ?
I realise I can just order the left side to get the desired element but ther... | This should do:
```
v,b,n = j[6:3:-1]
```
A step value of `-1` starting at `6` |
Unpack a Python tuple from left to right? | 38,276,068 | 18 | 2016-07-08T22:10:02Z | 38,276,235 | 10 | 2016-07-08T22:28:51Z | [
"python",
"python-3.x",
"tuples",
"iterable-unpacking"
] | Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right?
For example for
```
j = 1,2,3,4,5,6,7
(1,2,3,4,5,6,7)
v,b,n = j[4:7]
```
Can I modify the slice notation so that `v = j[6], b=j[5], n=j[4]` ?
I realise I can just order the left side to get the desired element but ther... | ```
n,b,v=j[4:7]
```
will also work. You can just change the order or the returned unpacked values |
Unpack a Python tuple from left to right? | 38,276,068 | 18 | 2016-07-08T22:10:02Z | 38,276,396 | 9 | 2016-07-08T22:46:47Z | [
"python",
"python-3.x",
"tuples",
"iterable-unpacking"
] | Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right?
For example for
```
j = 1,2,3,4,5,6,7
(1,2,3,4,5,6,7)
v,b,n = j[4:7]
```
Can I modify the slice notation so that `v = j[6], b=j[5], n=j[4]` ?
I realise I can just order the left side to get the desired element but ther... | You could ignore the first after reversing and use [extended iterable unpacking](https://www.python.org/dev/peps/pep-3132/):
```
j = 1, 2, 3, 4, 5, 6, 7
_, v, b, n, *_ = reversed(j)
print(v, b, n)
```
Which would give you:
```
6 5 4
```
Or if you want to get arbitrary elements you could use `operator.itemgetter`... |
Unpack a Python tuple from left to right? | 38,276,068 | 18 | 2016-07-08T22:10:02Z | 38,276,534 | 11 | 2016-07-08T23:04:10Z | [
"python",
"python-3.x",
"tuples",
"iterable-unpacking"
] | Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right?
For example for
```
j = 1,2,3,4,5,6,7
(1,2,3,4,5,6,7)
v,b,n = j[4:7]
```
Can I modify the slice notation so that `v = j[6], b=j[5], n=j[4]` ?
I realise I can just order the left side to get the desired element but ther... | In case you want to keep the original indices (i.e. don't want to bother with changing 4 and 7 to 6 and 3) you can also use:
```
v, b, n = (j[4:7][::-1])
``` |
Use groupby in Pandas to count things in one column in comparison to another | 38,278,603 | 4 | 2016-07-09T05:12:58Z | 38,279,370 | 7 | 2016-07-09T07:16:08Z | [
"python",
"pandas",
"dataframe"
] | Maybe groupby is the wrong approach. Seems like it should work but I'm not seeing it...
I want to group an event by it's outcome. Here is my DataFrame (df):
```
Status Event
SUCCESS Run
SUCCESS Walk
SUCCESS Run
FAILED Walk
```
Here is my desired result:
```
Event SUCCESS FAILED
Run 2 1
Walk 0 ... | An alternative solution, using [pivot\_table()](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html) method:
```
In [5]: df.pivot_table(index='Event', columns='Status', aggfunc=len, fill_value=0)
Out[5]:
Status FAILED SUCCESS
Event
Run 0 2
Walk 1 1
```
Timing... |
Why is str.strip() so much faster than str.strip(' ')? | 38,285,654 | 30 | 2016-07-09T19:38:30Z | 38,285,655 | 32 | 2016-07-09T19:38:30Z | [
"python",
"string",
"performance",
"python-3.x",
"python-internals"
] | Splitting on white-space can be done in two ways with **[`str.strip`](https://docs.python.org/3/library/stdtypes.html#str.strip)**. You can either issue a call with no arguments, `str.strip()`, which defaults to using a white-space delimiter or explicitly supply the argument yourself with `str.strip(' ')`.
But, why is... | ### In a tl;dr fashion:
This is because two functions exist for the two different cases, as can be seen in [`unicode_strip`](https://github.com/python/cpython/blob/master/Objects/unicodeobject.c#L12260); `do_strip` and `_PyUnicodeXStrip` the first executing much faster than the second.
Function **[`do_strip`](https:/... |
Why is str.strip() so much faster than str.strip(' ')? | 38,285,654 | 30 | 2016-07-09T19:38:30Z | 38,286,494 | 7 | 2016-07-09T21:24:51Z | [
"python",
"string",
"performance",
"python-3.x",
"python-internals"
] | Splitting on white-space can be done in two ways with **[`str.strip`](https://docs.python.org/3/library/stdtypes.html#str.strip)**. You can either issue a call with no arguments, `str.strip()`, which defaults to using a white-space delimiter or explicitly supply the argument yourself with `str.strip(' ')`.
But, why is... | For the reasons explained in @Jims answer the same behavior is found in `bytes` objects:
```
b = bytes(" " * 100 + "a" + " " * 100, encoding='ascii')
b.strip() # takes 427ns
b.strip(b' ') # takes 1.2μs
```
For `bytearray` objects this doesn't happen, the functions performing the `split` in this case are simil... |
Insert element to list based on previous and next elements | 38,285,679 | 9 | 2016-07-09T19:41:19Z | 38,285,773 | 8 | 2016-07-09T19:51:09Z | [
"python",
"list"
] | I'm trying to add a new tuple to a list of tuples (sorted by first element in tuple), where the new tuple contains elements from both the previous and the next element in the list.
Example:
```
oldList = [(3, 10), (4, 7), (5,5)]
newList = [(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)]
```
(4,10) was constructed from and... | ```
oldList = [(3, 10), (4, 7), (5,5)]
def pair(lst):
# create two iterators
it1, it2 = iter(lst), iter(lst)
# move second to the second tuple
next(it2)
for ele in it1:
# yield original
yield ele
# yield first ele from next and first from current
yield (next(it2)[0],... |
frozenset at least x elements | 38,292,379 | 3 | 2016-07-10T13:26:58Z | 38,292,424 | 7 | 2016-07-10T13:31:59Z | [
"python",
"frozenset"
] | I currently have this code, it checks if all elements in the array are the same. If this is the case, return true
```
def all_equal(lst):
"""
>>> all_equal([1,1,1,1,1,1,1])
True
>>> all_equal([1,2,3,1])
False
"""
return len(frozenset(lst)) == 1
```
But what I do want to check is if there are atleast 5 e... | Instead of using a set, use a [*bag* or *multiset* type](https://en.wikipedia.org/wiki/Multiset). A multiset counts how many times unique values occur.
In Python that's the [`collections.Counter()` object](https://docs.python.org/2/library/collections.html#collections.Counter):
```
from collections import Counter
de... |
frozenset at least x elements | 38,292,379 | 3 | 2016-07-10T13:26:58Z | 38,292,432 | 8 | 2016-07-10T13:33:04Z | [
"python",
"frozenset"
] | I currently have this code, it checks if all elements in the array are the same. If this is the case, return true
```
def all_equal(lst):
"""
>>> all_equal([1,1,1,1,1,1,1])
True
>>> all_equal([1,2,3,1])
False
"""
return len(frozenset(lst)) == 1
```
But what I do want to check is if there are atleast 5 e... | Use [`collections.Counter()`](https://docs.python.org/3/library/collections.html#collections.Counter):
```
from collections import Counter
def all_equal(lst, count):
return any(v >= count for v in Counter(lst).values())
``` |
Is there special significance to 16331239353195370.0? | 38,295,501 | 82 | 2016-07-10T19:02:56Z | 38,295,695 | 109 | 2016-07-10T19:25:02Z | [
"python",
"numpy",
"numerical-methods"
] | Using `import numpy as np` I've noticed that
```
np.tan(np.pi/2)
```
gives the number in the title and not `np.inf`
```
16331239353195370.0
```
I'm curious about this number. Is it related to some system machine precision parameter? Could I have calculated it from something? (I'm thinking along the lines of somethi... | `pi` isn't exactly representable as Python float (same as the platform C's `double` type). The closest representable approximation is used.
Here's the exact approximation in use on my box (probably the same as on your box):
```
>>> import math
>>> (math.pi / 2).as_integer_ratio()
(884279719003555, 562949953421312)
``... |
Django CSRF cookie not set correctly | 38,302,058 | 16 | 2016-07-11T08:10:02Z | 38,436,440 | 14 | 2016-07-18T12:13:45Z | [
"python",
"django",
"cookies",
"csrf"
] | Update 7-18:
Here is my nginx config for the proxy server:
```
server {
listen 80;
server_name blah.com; # the blah is intentional
access_log /home/cheng/logs/access.log;
error_log /home/cheng/logs/error.log;
location / {
proxy_pass http://127.0.0.1:8001;
}
... | Here is the issue: **You cannot have a cookie which key contains either the character '[' or ']'**
I discovered the solution following @Todor's [link](https://mail.python.org/pipermail/python-dev/2015-May/140135.html), then I found out about this [SO post](http://stackoverflow.com/a/33012793/1478290). Basically there ... |
elegant way to reduce a list of dictionaries? | 38,308,519 | 4 | 2016-07-11T13:41:54Z | 38,308,814 | 7 | 2016-07-11T13:56:42Z | [
"python",
"python-3.x",
"dictionary",
"reduce"
] | I have a list of dictionaries and each dictionary contains exactly the same keys. I want to find the average value for each key and I would like to know how to do it using reduce (or if not possible with another more elegant way than using nested `for`s).
Here is the list:
```
[
{
"accuracy": 0.78,
"f_measu... | As an alternative, if you're going to be doing such calculations on data, then you may wish to use [pandas](http://pandas.pydata.org/) (which will be overkill for a one off, but will greatly simplify such tasks...)
```
import pandas as pd
data = [
{
"accuracy": 0.78,
"f_measure": 0.8169374016795885,
"pr... |
grouping rows python pandas | 38,311,120 | 2 | 2016-07-11T15:46:30Z | 38,311,271 | 7 | 2016-07-11T15:55:04Z | [
"python",
"pandas",
"dataframe"
] | say I have the following dataframe and, the index represents ages, the column names is some category, and the values in the frame are frequencies...
Now I would like to group ages in various ways (2 year bins, 5 year bins and 10 year bins)
```
>>> table_w
1 2 3 4
20 1000 80 40 100
21 2000 40 ... | Use `pd.cut()` to create the age bins and group your dataframe with them.
```
import io
import numpy as np
import pandas as pd
data = io.StringIO("""\
1 2 3 4
20 1000 80 40 100
21 2000 40 100 100
22 3000 70 70 200
23 3000 100 90 100
24 2000 90 90 200
25 2000 100 80 20... |
Why does a Python script to read files cause my computer to emit beeping sounds? | 38,313,445 | 10 | 2016-07-11T18:07:40Z | 38,313,491 | 18 | 2016-07-11T18:10:57Z | [
"python"
] | I wrote a little module that will search files in a directory and all of its sub-directories for the occurrence of some input string. It's been handy a few times, mostly to find old scripts if I remember some function/variable name that I used.
So, I was completely baffled the other day when I used the functions and s... | This line:
```
print count,line,dir_element
```
is probably printing the [BEL character](https://en.wikipedia.org/wiki/Bell_character) if you feed your program binary files.
To test, here's a little code I wrote. Python will try and play it note-for-note. Don't worry. Be happy :)
```
def bel(): return chr(... |
how to convert items of array into array themselves Python | 38,314,820 | 3 | 2016-07-11T19:35:42Z | 38,314,856 | 7 | 2016-07-11T19:37:27Z | [
"python",
"python-3.x",
"numpy"
] | My problem is that I've got this array:
```
np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
```
and I want to convert the elements to array like this:
```
np.array([[0.0], [0.0], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
```
So is there a loop or a numpy function that I could use to do this task? | You can use a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions):
```
>>> a1 = np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
>>> np.array([[x] for x in a1])
array([[ 0. ],
[ 0. ],
[-1.2],
[-1.2],
[-3.4],
[-3.4],
[-4.5],
... |
how to convert items of array into array themselves Python | 38,314,820 | 3 | 2016-07-11T19:35:42Z | 38,314,864 | 13 | 2016-07-11T19:38:13Z | [
"python",
"python-3.x",
"numpy"
] | My problem is that I've got this array:
```
np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
```
and I want to convert the elements to array like this:
```
np.array([[0.0], [0.0], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
```
So is there a loop or a numpy function that I could use to do this task? | Or simply:
```
arr[:,None]
# array([[ 0. ],
# [ 0. ],
# [-1.2],
# [-1.2],
# [-3.4],
# [-3.4],
# [-4.5],
# [-4.5]])
``` |
What is the reason for _secret_backdoor_key variable in Python HMAC library source code? | 38,324,441 | 9 | 2016-07-12T09:07:13Z | 38,324,561 | 8 | 2016-07-12T09:11:57Z | [
"python",
"hash",
"python-internals"
] | When I was browsing Python HMAC module source code today I found out that it contains global variable `_secret_backdoor_key`. This variable is then checked to interrupt object initialization.
The code looks like this
```
# A unique object passed by HMAC.copy() to the HMAC constructor, in order
# that the latter retur... | To create a copy of the HMAC instance, you need to create an *empty* instance first.
The `_secret_backdoor_key` object is used as a sentinel to exit `__init__` early and not run through the rest of the `__init__` functionality. The `copy` method then sets the instance attributes directly:
```
def copy(self):
"""R... |
Why does '() is ()' return True when '[] is []' and '{} is {}' return False? | 38,328,857 | 44 | 2016-07-12T12:25:48Z | 38,328,858 | 48 | 2016-07-12T12:25:48Z | [
"python",
"python-3.x",
"tuples",
"identity",
"python-internals"
] | From what I've been aware of, using `[], {}, ()` to instantiate objects returns a new instance of `list, dict, tuple` respectively; a new instance object with ***a new identity***\*.
This was pretty clear to me until I actually tested it where I noticed that `() is ()` actually returns `False` instead of the expected ... | ### In short:
Python internally creates a `C` list of tuple objects whose first element contains the empty tuple. Every time `tuple()` or `()` is used, Python will return the existing object contained in the aforementioned `C` list and not create a new one.
Such mechanism does not exist for `dict` or `list` objects w... |
Catching the same expection in every method of a class | 38,332,356 | 4 | 2016-07-12T14:54:40Z | 38,332,482 | 7 | 2016-07-12T14:59:06Z | [
"python",
"python-3.x",
"exception",
"exception-handling"
] | I, a beginner, am working on a simple card-based GUI. written in Python. There is a base class that, among other things, consists a vocabulary of all the cards, like `_cards = {'card1_ID': card1, 'card2_ID': card2}`. The cards on the GUI are referenced by their unique IDs.
As I plan to make the code avabile for other ... | Extract the actual getting of the card from the id into a separate method, with a try/except there, and call that method from everywhere else.
```
def get_card(self, card_id):
try:
return self._cards[card_ID]
except KeyError:
raise ValueError("Invaild card ID")
def invert(self, card_id):
r... |
How to replace a function call in an existing method | 38,336,814 | 3 | 2016-07-12T18:53:12Z | 38,336,854 | 7 | 2016-07-12T18:55:33Z | [
"python",
"monkeypatching"
] | given a module with a class Foo with a method that calls a function `bar` defined in the module scope, is there a way to substitute `bar` for a different function without modification to the module?
```
class Foo(object):
def run(self):
bar()
def bar():
return True
```
I then have a an instance of `F... | Let's assume your module is called `deadbeef`, and you're using it like this
```
import deadbeef
â¦
foo_instance = deadbeef.Foo()
```
Then you could do
```
import deadbeef
deadbeef.bar = baz
â¦
``` |
Is there a comprehensive table of Python's "magic constants"? | 38,344,848 | 8 | 2016-07-13T07:08:28Z | 38,345,345 | 11 | 2016-07-13T07:34:35Z | [
"python",
"python-3.x"
] | Where are `__file__`, `__main__`, etc. defined, and what are they officially called? `__eq__` and `__ge__` are "magic methods", so right now I'm just referring to them as "magic constants" but I don't even know if that's right.
Google search really isn't turning up anything and even Python's own documentation doesn't ... | Short answer: **no**. For the longer answer, which got badly out of hand, keep reading...
---
There is no comprehensive table of those `__dunder_names__` (also not their official title!), as far as I'm aware. There are a couple of sources:
* The only real *"magic constant"* is `__debug__`: it's a `SyntaxError` to at... |
Why does `str.format()` ignore additional/unused arguments? | 38,349,822 | 11 | 2016-07-13T11:02:07Z | 38,350,141 | 10 | 2016-07-13T11:15:41Z | [
"python",
"string",
"python-3.x",
"string-formatting"
] | I saw ["Why doesn't join() automatically convert its arguments to strings?"](http://stackoverflow.com/a/22152693/2505645) and [the accepted answer](http://stackoverflow.com/a/22152693/2505645) made me think: since
> Explicit is better than implicit.
and
> Errors should never pass silently.
why does `str.format()` i... | Ignoring un-used arguments makes it possible to create arbitrary format strings for arbitrary-sized dictionaries or objects.
Say you wanted to give your program the feature to let the end-user change the output. You document what *fields* are available, and tell users to put those fields in `{...}` slots in a string. ... |
Split pandas dataframe column based on number of digits | 38,357,130 | 5 | 2016-07-13T16:30:06Z | 38,357,443 | 8 | 2016-07-13T16:46:37Z | [
"python",
"pandas",
"dataframe",
"data-manipulation"
] | I have a pandas dataframe which has two columns key and value, and the value always consists of a 8 digit number something like
```
>df1
key value
10 10000100
20 10000000
30 10100000
40 11110000
```
Now I need to take the value column and split it on the digits present, such that my result is a new data frame
``... | This should work:
```
df.value.astype(str).apply(list).apply(pd.Series).astype(int)
```
[](http://i.stack.imgur.com/ZTDqX.png) |
Pythonic way to check if integer fits in 64 bits | 38,359,202 | 3 | 2016-07-13T18:26:58Z | 38,359,221 | 8 | 2016-07-13T18:28:12Z | [
"python",
"integer",
"64bit"
] | What is the Pythonic way (without using any external libraries) to check if an integer is small enough to fit in a 64 bit signed quantity?
Sorry if this question has been asked before! | Just check the size with the [`int.bit_length()` method](https://docs.python.org/2/library/stdtypes.html#int.bit_length):
```
if integer_value.bit_length() <= 63:
```
The method takes the absolute value, so you want to leave a bit for the sign:
```
>>> (-2 ** 63).bit_length()
64
>>> (2 ** 63).bit_length()
64
``` |
Perl's __DATA__ equivalent in Python | 38,368,956 | 7 | 2016-07-14T08:17:37Z | 38,369,018 | 8 | 2016-07-14T08:20:38Z | [
"python",
"perl",
"filehandle"
] | When writing code in perl I often read data in from the filehandle `__DATA__` at the end of the script:
```
while (<DATA>) {
chomp;
say;
}
__DATA__
line1
line2
```
I find this quicker for testing code etc than reading in a file, as it means I can edit its contents on the fly.
From the [doc](http://perldoc.pe... | No, there is no direct equivalent in Python. Put your data in a multi-line variable:
```
DATA = '''\
line1
line2
'''
```
You can then use `DATA.splitlines()` if you must have access to separate lines. You can put this at the end of your Python file provided you only use the name `DATA` in a function that is not calle... |
Lambdas from a list comprehension are returning a lambda when called | 38,369,470 | 51 | 2016-07-14T08:43:46Z | 38,370,058 | 17 | 2016-07-14T09:09:30Z | [
"python",
"lambda"
] | I am trying to iterate the lambda func over a list as in `test.py`, and I want to get the call result of the lambda, not the function object itself. However, the following output really confused me.
```
------test.py---------
#!/bin/env python
#coding: utf-8
a = [lambda: i for i in range(5)]
for i in a:
print i()... | Closures in Python are [late-binding](http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures), meaning that each lambda function in the list will only evaluate the variable `i` when invoked, and *not* when defined. That's why all functions return the same value, i.e. the last value of `ì` (which... |
Lambdas from a list comprehension are returning a lambda when called | 38,369,470 | 51 | 2016-07-14T08:43:46Z | 38,370,271 | 46 | 2016-07-14T09:18:35Z | [
"python",
"lambda"
] | I am trying to iterate the lambda func over a list as in `test.py`, and I want to get the call result of the lambda, not the function object itself. However, the following output really confused me.
```
------test.py---------
#!/bin/env python
#coding: utf-8
a = [lambda: i for i in range(5)]
for i in a:
print i()... | In Python 2 list comprehension 'leaks' the variables to outer scope:
```
>>> [i for i in xrange(3)]
[0, 1, 2]
>>> i
2
```
Note that the behavior is different on Python 3:
```
>>> [i for i in range(3)]
[0, 1, 2]
>>> i
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'i' is not ... |
How to check whether for loop ends completely in python? | 38,381,850 | 3 | 2016-07-14T18:40:49Z | 38,381,893 | 10 | 2016-07-14T18:43:15Z | [
"python",
"loops",
"for-loop",
"break"
] | This is a ceased for loop :
```
for i in [1,2,3]:
print(i)
if i==3:
break
```
How can I check its difference with this :
```
for i in [1,2,3]:
print(i)
```
This is an idea :
```
IsBroken=False
for i in [1,2,3]:
print(i)
if i==3:
IsBroken=True
break
if IsBroken==True:
... | `for` loops can take an `else` block which can serve this purpose:
```
for i in [1,2,3]:
print(i)
if i==3:
break
else:
print("for loop was not broken")
``` |
what does on_delete does on Django models? | 38,388,423 | 3 | 2016-07-15T05:26:57Z | 38,389,488 | 8 | 2016-07-15T06:44:00Z | [
"python",
"django",
"django-models"
] | I'm quite familiar with Django, but recently noticed there exists a `on_delete=models.CASCADE` option with the models, I have searched for the documentation for the same but couldn't find anything more than,
> **Changed in Django 1.9:**
>
> `on_delete` can now be used as the second positional argument (previously it w... | This is the behaviour to adopt when the referenced object is deleted. It is not specific to django, this is an SQL standard.
There are 6 possible actions to take when such event occurs:
* `CASCADE`: When the referenced object is deleted, also delete the objects that have references to it (When you remove a blog post ... |
Sort A list of Strings Based on certain field | 38,388,799 | 4 | 2016-07-15T05:57:44Z | 38,389,035 | 8 | 2016-07-15T06:15:18Z | [
"python",
"list",
"python-2.7",
"sorting"
] | Overview: I have data something like this (each row is a string):
> 81:0A:D7:19:25:7B, **2016-07-14 14:29:13**, 2016-07-14 14:29:15, -69, 22:22:22:22:22:23,null,^M
> 3B:3F:B9:0A:83:E6, **2016-07-14 01:28:59**, 2016-07-14 01:29:01, -36, 33:33:33:33:33:31,null,^M
> B3:C0:6E:77:E5:31, **2016-07-14 08:26:45**, 2016-07-14 ... | You can use the list method `list.sort` which sorts in-place or use the `sorted()` built-in function which returns a new list. the `key` argument takes a function which it applies to each element of the sequence before sorting. You can use a combination of `string.split(',')` and indexing to the second element, e.g. so... |
numpy: Why is there a difference between (x,1) and (x, ) dimensionality | 38,402,227 | 5 | 2016-07-15T17:41:57Z | 38,403,363 | 7 | 2016-07-15T18:59:24Z | [
"python",
"numpy"
] | I am wondering why in numpy there are one dimensional array of dimension (length, 1) and also one dimensional array of dimension (length, ) w/o a second value.
I am running into this quite frequently, e.g. when using `np.concatenate()` which then requires a `reshape` step beforehand (or I could directly use `hstack`/`... | The data of a `ndarray` is stored as a 1d buffer - just a block of memory. The multidimensional nature of the array is produced by the `shape` and `strides` attributes, and the code that uses them.
The `numpy` developers chose to allow for an arbitrary number of dimensions, so the shape and strides are represented as ... |
Is None really a built-in? | 38,404,151 | 2 | 2016-07-15T19:55:09Z | 38,404,298 | 9 | 2016-07-15T20:05:12Z | [
"python",
"built-in",
"nonetype"
] | I am trying to use Python's (2.7) `eval` in a (relatively) safe manner. Hence, I defined:
```
def safer_eval(string):
"""Safer version of eval() as globals and builtins are inaccessible"""
return eval(string, {'__builtins__': {}})
```
As expected, the following does not work any more:
```
print safer_eval("T... | `None` is a *constant* in Python, see the [*Keywords* documentation](https://docs.python.org/2/reference/lexical_analysis.html#keywords):
> Changed in version 2.4: `None` became a constant and is now recognized by the compiler as a name for the built-in object `None`. Although it is not a keyword, you cannot assign a ... |
A neat way to create an infinite cyclic generator? | 38,415,014 | 2 | 2016-07-16T19:51:41Z | 38,415,018 | 7 | 2016-07-16T19:52:34Z | [
"python",
"python-3.x"
] | I want a generator that cycle infinitely through a list of values.
Here is my solution, but I may be missing a more obvious one.
The ingredients: a generator function that flatten an infinitely nested list, and a list appendant to itself
```
def ge(x):
for it in x:
if isinstance(it, list):
yi... | You can use [`itertools.cycle`](https://docs.python.org/2.7/library/itertools.html#itertools.cycle) to achieve the same result
> Make an iterator returning elements from the iterable and saving a
> copy of each. When the iterable is exhausted, return elements from the
> **saved copy**.
*Emphasis mine*. Your only conc... |
What index should I use to convert a numpy array into a pandas dataframe? | 38,419,314 | 3 | 2016-07-17T08:30:29Z | 38,419,655 | 7 | 2016-07-17T09:13:49Z | [
"python",
"arrays",
"numpy",
"pandas",
"dataframe"
] | I am trying to convert a simple numpy array into a pandas dataframe.
`x` is my array, `nam` is the list of the columns names.
```
x = np.array([2,3,1,0])
nam = ['col1', 'col2', 'col3', 'col4']
```
I use `pd.DataFrame` to convert `x`
```
y = pd.DataFrame(x, columns=nam)
```
But I have this error message :
> ValueE... | Another simplier solution with `[]`:
```
x = np.array([2,3,1,0])
nam = ['col1', 'col2', 'col3', 'col4']
print (pd.DataFrame([x], columns=nam))
col1 col2 col3 col4
0 2 3 1 0
``` |
Proper type annotation of Python functions with yield | 38,419,654 | 8 | 2016-07-17T09:13:46Z | 38,423,388 | 7 | 2016-07-17T16:25:17Z | [
"python",
"generator",
"coroutine",
"static-typing",
"mypy"
] | After reading Eli Bendersky's article [on implementing state machines via Python coroutines](http://eli.thegreenplace.net/2009/08/29/co-routines-as-an-alternative-to-state-machines/) I wanted to...
* see his example run under Python3
* and also add the appropriate type annotations for the generators
I succeeded in do... | I figured out the answer on my own.
I searched, but found no documentation for the 3 type parameters of `Generator` in the [official typing documentation for Python 3.5.2](https://docs.python.org/3/library/typing.html) - beyond a truly cryptic mention of...
```
class typing.Generator(Iterator[T_co], Generic[T_co, T_c... |
Python: PEP 8 class name as variable | 38,433,503 | 19 | 2016-07-18T09:45:48Z | 38,434,962 | 10 | 2016-07-18T10:58:05Z | [
"python",
"pep8"
] | Which is the convention according to PEP 8 for writing variables that identify class names (not instances)?
That is, given two classes, `A` and `B`, which of the following statements would be the right one?
```
target_class = A if some_condition else B
instance = target_class()
```
or
```
TargetClass = A if some_co... | In lack of a specific covering of this case in PEP 8, one can make up an argument for both sides of the medal:
One side is: As `A` and `B` both are variables as well, but hold a reference to a class, use CamelCase (`TargetClass`) in this case.
Nothing prevents you from doing
```
class A: pass
class B: pass
x = A
A =... |
Pandas dataframe, split data by last column in last position but keep other columns | 38,441,831 | 3 | 2016-07-18T16:32:15Z | 38,442,043 | 7 | 2016-07-18T16:46:02Z | [
"python",
"pandas",
"dataframe"
] | Very new to pandas so any explanation with a solution is appreciated.
I have a dataframe such as
```
Company Zip State City
1 *CBRE San Diego, CA 92101
4 1908 Brands Boulder, CO 80301
7 1st Infantry Division Headquarters Fort... | you can use [extract()](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html) method:
```
In [110]: df
Out[110]:
Company Zip State City
1 *CBRE San Diego, CA 92101
4 1908 Br... |
Filling dict with NA values to allow conversion to pandas dataframe | 38,446,457 | 8 | 2016-07-18T21:43:09Z | 38,446,637 | 7 | 2016-07-18T21:58:24Z | [
"python",
"pandas"
] | I have a dict that holds computed values on different time lags, which means they start on different dates. For instance, the data I have may look like the following:
```
Date col1 col2 col3 col4 col5
01-01-15 5 12 1 -15 10
01-02-15 7 0 9 11 7
01-03-15 ... | Another option is to use `from_dict` with `orient='index'` and then take the tranpose:
```
my_dict = {'a' : [1, 2, 3, 4, 5], 'b': [1, 2, 3]}
df = pd.DataFrame.from_dict(my_dict, orient='index').T
```
Note that you could run into problems with `dtype` if your columns have different types, e.g. floats in one column, st... |
list of objects python | 38,448,914 | 9 | 2016-07-19T03:03:15Z | 38,449,719 | 10 | 2016-07-19T04:42:11Z | [
"python",
"python-object"
] | I am trying to print a list of python objects that contain a list as a property and i am having some unexpected results:
here is my code:
```
class video(object):
name = ''
url = ''
class topic(object):
topicName = ''
listOfVideo = []
def addVideo(self,videoToAdd):
self.listOfVideo.app... | You have created `class variables` instead of `instance variables`, which are different for each instance object. Define your class as follows:
```
class topic(object):
def __init__(self):
self.topicName = ''
self.listOfVideo = []
def addVideo(self,videoToAdd):
self.listOfVideo.append... |
Simple function that returns a number incremented by 1 on each call, without globals? | 38,455,353 | 8 | 2016-07-19T10:03:32Z | 38,455,715 | 11 | 2016-07-19T10:18:33Z | [
"python",
"increment"
] | I am trying to write a python function that on the first call, returns a 1. On the second call, returns a 2. On the third, a 3. Etc.
Currently, I have achieved this using a global variable:
```
index = 0
def foo():
global index
index += 1
return index
```
When calling the function three times:
```
prin... | Using a closure:
```
def make_inc():
val = [0]
def inc():
val[0] += 1
return val[0]
return inc
inc = make_inc()
print inc()
print inc()
print inc()
```
Using a class (the most obvious solution in an OOPL ):
```
class Inc(object):
def __init__(self):
self._val = 0
def __c... |
Merging multiple dataframes on column | 38,467,193 | 3 | 2016-07-19T19:44:12Z | 38,467,413 | 7 | 2016-07-19T19:57:14Z | [
"python",
"pandas",
"dataframe"
] | I am trying to merge/join multiple `Dataframe`s and so far I have no luck. I've found `merge` method, but it works only with two Dataframes. I also found this SO [answer](http://stackoverflow.com/a/23671390/1080517) suggesting to do something like that:
```
df1.merge(df2,on='name').merge(df3,on='name')
```
Unfortunat... | use `pd.concat`
```
dflist = [df1, df2]
keys = ["%d" % i for i in range(1, len(dflist) + 1)]
merged = pd.concat([df.set_index('name') for df in dflist], axis=1, keys=keys)
merged.columns = merged.swaplevel(0, 1, 1).columns.to_series().str.join('_')
merged
```
[ of a csv file where each key is a datetime object and each value is a list, containing two numbers (let's call them a and b, so the list is [a,b]) stored as strings:
```
import csv
import datetime as dt
with open(fileInput,'r') as inFile:... | ### Setup
```
dictData = {'2010': ['1', '2'],
'2011': ['4', '3'],
'2012': ['0', '45'],
'2013': ['8', '7'],
'2014': ['9', '0'],
'2015': ['22', '1'],
'2016': ['3', '4'],
'2017': ['0', '5'],
'2018': ['7', '8'],
'20... |
why is a sum of strings converted to floats | 38,470,550 | 14 | 2016-07-20T00:27:31Z | 38,470,963 | 15 | 2016-07-20T01:36:39Z | [
"python",
"pandas"
] | ### Setup
consider the following dataframe (note the strings):
```
df = pd.DataFrame([['3', '11'], ['0', '2']], columns=list('AB'))
df
```
[](http://i.stack.imgur.com/iEQcv.png)
```
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entr... | Went with the good old stack trace. Learned a bit about pdb through Pycharm as well. Turns out what happens is the following:
1)
```
cls.sum = _make_stat_function(
'sum', name, name2, axis_descr,
'Return the sum of the values for the requested axis',
nanops.nansum)
```
Let's have ... |
How to import a gzip file larger than RAM limit into a Pandas DataFrame? "Kill 9" Use HDF5? | 38,472,387 | 4 | 2016-07-20T04:34:18Z | 38,472,574 | 8 | 2016-07-20T04:52:59Z | [
"python",
"pandas",
"dataframe",
"gzip",
"hdf5"
] | I have a `gzip` which is approximately 90 GB. This is well within disk space, but far larger than RAM.
How can I import this into a pandas dataframe? I tried the following in the command line:
```
# start with Python 3.4.5
import pandas as pd
filename = 'filename.gzip' # size 90 GB
df = read_table(filename, compres... | I'd do it this way:
```
filename = 'filename.gzip' # size 90 GB
hdf_fn = 'result.h5'
hdf_key = 'my_huge_df'
cols = ['colA','colB','colC','ColZ'] # put here a list of all your columns
cols_to_index = ['colA','colZ'] # put here the list of YOUR columns, that you want to index
chunksize = 10**6 # you m... |
Pandas rolling computations for printing elements in the window | 38,473,205 | 8 | 2016-07-20T05:49:32Z | 38,473,356 | 9 | 2016-07-20T05:58:59Z | [
"python",
"pandas",
"dataframe"
] | I want to make a series out of the values in a column of pandas dataframe in a sliding window fashion. For instance, if this is my dataframe
```
state
0 1
1 1
2 1
3 1
4 0
5 0
6 0
7 1
8 4
9 1
```
for a window size of say 3, I want to get a list as [111, 111, 110, 100, 000...]
I am lo... | ```
a = np.array([100, 10, 1])
s.rolling(3).apply(a.dot).apply('{:03.0f}'.format)
0 nan
1 nan
2 111
3 111
4 110
5 100
6 000
7 001
8 014
9 141
Name: state, dtype: object
```
thx @Alex for reminding me to use `dot` |
django-debug-toolbar breaking on admin while getting sql stats | 38,479,063 | 19 | 2016-07-20T10:43:45Z | 38,479,670 | 34 | 2016-07-20T11:12:25Z | [
"python",
"django",
"django-admin",
"django-debug-toolbar"
] | Environment:django debug toolbar breaking while using to get sql stats else it's working fine on the other pages, breaking only on the pages which have sql queries.
```
Request Method: GET
Request URL: http://www.blog.local/admin/
Django Version: 1.9.7
Python Version: 2.7.6
Installed Applications:
[
....
'django.co... | sqlparse latest version was released today and it's not compatible with django-debug-toolbar version 1.4, Django version 1.9
workaround is force pip to install `sqlparse==0.1.19` |
How to natively increment a dictionary element's value? | 38,486,601 | 5 | 2016-07-20T17:02:31Z | 38,486,696 | 11 | 2016-07-20T17:07:32Z | [
"python",
"python-3.x",
"dictionary"
] | When working with Python 3 dictionaries, I keep having to do something like this:
```
d=dict()
if 'k' in d:
d['k']+=1
else:
d['k']=0
```
I seem to remember there being a native way to do this, but was looking through the documentation and couldn't find it. Do you know what this is? | This is the use case for [`collections.defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict), here simply using the `int` callable for the default factory.
```
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d
defaultdict(<class 'int'>, {})
>>> d['k'] +=1
>>> d
... |
Is there a pythonic way to process tree-structured dict keys? | 38,489,772 | 8 | 2016-07-20T19:59:45Z | 38,489,875 | 11 | 2016-07-20T20:05:45Z | [
"python",
"dictionary",
"tree"
] | I'm looking for a pythonic idiom to turn a list of keys and a value into a dict with those keys nested. For example:
```
dtree(["a", "b", "c"]) = 42
or
dtree("a/b/c".split(sep='/')) = 42
```
would return the nested dict:
```
{"a": {"b": {"c": 42}}}
```
This could be used to turn a set of values with hierarchica... | > I'm looking for a pythonic idiom to turn a list of keys and a value into a dict with those keys nested.
```
reduce(lambda v, k: {k: v}, reversed("a/b/c".split("/")), 42)
```
> This could be used to turn a set of values with hierarchical keys into a tree
```
def hdict(keys, value, sep="/"):
return reduce(lambda... |
Comparing rows of two pandas dataframes? | 38,493,795 | 4 | 2016-07-21T02:17:44Z | 38,494,149 | 7 | 2016-07-21T02:59:47Z | [
"python",
"pandas",
"numpy",
"dataframe"
] | This is a continuation of my question. [Fastest way to compare rows of two pandas dataframes?](http://stackoverflow.com/questions/38267763/fastest-way-to-compare-rows-of-two-pandas-dataframes/38270174#38270174)
I have two dataframes `A` and `B`:
`A` is 1000 rows x 500 columns, filled with binary values indicating eit... | I'll stick by my initial answer but maybe explain better.
You are asking to compare 2 pandas dataframes. Because of that, I'm going to build dataframes. I may use numpy, but my inputs and outputs will be dataframes.
### Setup
You said we have a a 1000 x 500 array of ones and zeros. Let's build that.
```
A_init = pd... |
Change the color of text within a pandas dataframe html table python using styles and css | 38,511,373 | 6 | 2016-07-21T18:06:19Z | 38,511,805 | 10 | 2016-07-21T18:28:57Z | [
"python",
"html",
"css",
"pandas",
"dataframe"
] | I have a pandas dataframe:
```
arrays = [['Midland','Midland','Hereford','Hereford','Hobbs','Hobbs','Childress','Childress','Reese','Reese',
'San Angelo','San Angelo'],['WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(t... | This takes a few steps:
First import `HTML` and `re`
```
from IPython.display import HTML
import re
```
You can get at the `html` pandas puts out via the `to_html` method.
```
df_html = df.to_html()
```
Next we are going to generate a random identifier for the html table and style we are going to create.
```
rand... |
Why does jupyter display "None not found"? | 38,517,887 | 10 | 2016-07-22T03:53:26Z | 39,225,574 | 12 | 2016-08-30T10:53:59Z | [
"python",
"kernel",
"anaconda",
"jupyter",
"jupyter-notebook"
] | I am trying to use jupyter to write and edit python code. I have a .ipynb file open, but I see "None not found" in the upper right hand corner and I can't execute any of the code that I write. What's so bizarre is that I'll open other .ipynb files and have no problem. Additionally, when I click on the red "None not fou... | I had the same problem here. The solution for me was:
1. in the menu in Kernel -> Change kernel -> choose Python [Root] (or
the kernel you want),
2. save the file,
3. close it,
4. reopen it. |
Why and how are Python functions hashable? | 38,518,849 | 38 | 2016-07-22T05:30:35Z | 38,518,893 | 37 | 2016-07-22T05:34:56Z | [
"python",
"hash"
] | I recently tried the following commands in Python:
```
>>> {lambda x: 1: 'a'}
{<function __main__.<lambda>>: 'a'}
>>> def p(x): return 1
>>> {p: 'a'}
{<function __main__.p>: 'a'}
```
The success of both `dict` creations indicates that both lambda and regular functions are hashable. (Something like `{[]: 'a'}` fails ... | It's nothing special. As you can see if you examine the unbound `__hash__` method of the function type:
```
>>> def f(): pass
...
>>> type(f).__hash__
<slot wrapper '__hash__' of 'object' objects>
```
it just inherits `__hash__` from `object`. Function `==` and `hash` work by identity. The difference between `id` and... |
Why and how are Python functions hashable? | 38,518,849 | 38 | 2016-07-22T05:30:35Z | 38,519,187 | 20 | 2016-07-22T05:58:09Z | [
"python",
"hash"
] | I recently tried the following commands in Python:
```
>>> {lambda x: 1: 'a'}
{<function __main__.<lambda>>: 'a'}
>>> def p(x): return 1
>>> {p: 'a'}
{<function __main__.p>: 'a'}
```
The success of both `dict` creations indicates that both lambda and regular functions are hashable. (Something like `{[]: 'a'}` fails ... | It can be useful, e.g., to create sets of function objects, or to index a dict by functions. Immutable objects *normally* support `__hash__`. In any case, there's no internal difference between a function defined by a `def` or by a `lambda` - that's purely syntactic.
The algorithm used depends on the version of Python... |
Declaring decorator inside a class | 38,524,332 | 2 | 2016-07-22T10:37:23Z | 38,524,579 | 7 | 2016-07-22T10:49:36Z | [
"python",
"python-2.7",
"wrapper",
"decorator",
"python-decorators"
] | I'm trying to use custom wrappers/decorators in Python, and I'd like to declare one **inside** a class, so that I could for instance print a snapshot of the attributes. I've tried things from [this question](http://stackoverflow.com/q/11740626/5018771) with no success.
---
Here is what I'd like to do (NB: this code d... | You will need to handle `self` explicitly.
```
class TestWrapper():
def __init__(self, a, b):
self.a = a
self.b = b
self.c = 0
def enter_exit_info(func):
def wrapper(self, *arg, **kw):
print '-- entering', func.__name__
print '-- ', self.__dict__
... |
How do I unit test a method that sets internal data, but doesn't return? | 38,529,807 | 7 | 2016-07-22T15:07:36Z | 38,531,286 | 7 | 2016-07-22T16:26:00Z | [
"python",
"unit-testing"
] | From what Iâve read, unit test should test only one function/method at a time. But Iâm not clear on how to test methods that only set internal object data with no return value to test off of, like the setvalue() method in the following Python class (and this is a simple representation of something more complicated)... | ## The misconception
The real problem you have here is that you are working on a false premise:
> If unit test law dictates that we should test every function, one at a time...
This is not at all what good unit testing is about.
Good unit testing is about decomposing your code into logical components, putting them ... |
How to assign member variables temporarily? | 38,531,851 | 12 | 2016-07-22T17:02:28Z | 38,532,086 | 20 | 2016-07-22T17:19:17Z | [
"python",
"python-2.7",
"python-decorators",
"python-descriptors"
] | I often find that I need to assign some member variables temporarily, *e.g.*
```
old_x = c.x
old_y = c.y
# keep c.z unchanged
c.x = new_x
c.y = new_y
do_something(c)
c.x = old_x
c.y = old_y
```
but I wish I could simply write
```
with c.x = new_x; c.y = new_y:
do_something(c)
```
or even
```
do_something(c ... | [Context managers](https://docs.python.org/2/reference/datamodel.html#context-managers) may be used for it easily.
Quoting official docs:
> Typical uses of context managers include saving and restoring various
> kinds of global state, locking and unlocking resources, closing opened
> files, etc.
It seems like saving... |
Invalid block tag. Did you forget to register or load this tag? | 38,537,464 | 2 | 2016-07-23T02:06:01Z | 38,537,520 | 7 | 2016-07-23T02:19:42Z | [
"python",
"html",
"django"
] | Getting an invalid block tag message `Invalid block tag on line 2: 'out'. Did you forget to register or load this tag?` but don't know why. Here's my setup:
graphs.html
```
{% out %}
```
views.py
```
out = 'something to say'
template = loader.get_template('viz_proj/graphs.html')
context = {
'out' : out
}
retur... | I think you want to try {{ out }} instead of {% out %}. |
Functionality of Python `in` vs. `__contains__` | 38,542,543 | 7 | 2016-07-23T13:54:30Z | 38,542,777 | 7 | 2016-07-23T14:19:30Z | [
"python",
"contains"
] | I implemented the `__contains__` method on a class for the first time the other day, and the behavior wasn't what I expected. I suspect there's some subtlety to the [`in`](https://docs.python.org/2/library/operator.html) operator that I don't understand and I was hoping someone could enlighten me.
It appears to me tha... | Use the source, Luke!
Let's trace down the `in` operator implementation
```
>>> import dis
>>> class test(object):
... def __contains__(self, other):
... return True
>>> def in_():
... return 1 in test()
>>> dis.dis(in_)
2 0 LOAD_CONST 1 (1)
3 LOAD_GLOBAL ... |
Removing duplicate edges from graph in Python list | 38,555,385 | 6 | 2016-07-24T18:30:45Z | 38,555,503 | 7 | 2016-07-24T18:41:32Z | [
"python"
] | My program returns a list of tuples, which represent the edges of a graph, in the form of:
```
[(i, (e, 130)), (e, (i, 130)), (g, (a, 65)), (g, (d, 15)), (a, (g, 65))]
```
So, (i, (e, 130)) means that 'i' is connected to 'e' and is 130 units away.
Similarly, (e, (i, 130)) means that 'e' is connected to 'i' and is 13... | If a tuple `(n1, (n2, distance))` represents a bidirectional connection, I would introduce a normalization property which constraints the ordering of the two nodes in the tuple. This way, each possible edge has exactly one unique representation.
Consequently, a normalization function would map a given, potentially unn... |
Subset of dictionary keys | 38,565,727 | 4 | 2016-07-25T10:48:00Z | 38,565,965 | 7 | 2016-07-25T10:59:44Z | [
"python",
"dictionary"
] | I've got a python dictionary of the form `{'ip1:port1' : <value>, 'ip1:port2' : <value>, 'ip2:port1' : <value>, ...}`. Dictionary keys are strings, consisting of ip:port pairs. Values are not important for this task.
I need a list of `ip:port` combinations with unique IP addresses, ports can be any of those that appea... | You can use [`itertools.groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby) to group by same IP addresses:
```
data = {'ip1:port1' : "value1", 'ip1:port2' : "value2", 'ip2:port1' : "value3", 'ip2:port2': "value4"}
by_ip = {k: list(g) for k, g in itertools.groupby(sorted(data), key=lambda s: s... |
Pycharm import RuntimeWarning after updating to 2016.2 | 38,569,992 | 28 | 2016-07-25T14:08:50Z | 38,724,508 | 29 | 2016-08-02T15:21:38Z | [
"python",
"import",
"pycharm"
] | After updating to new version 2016.2, I am getting
```
RuntimeWarning: Parent module 'tests' not found while handling absolute import
import unittest
RuntimeWarning: Parent module 'tests' not found while handling absolute import
import datetime as dt
```
'tests' is a package inside my main app package, and I rece... | This is a known issue with the 2016.2 release. Progress can be followed on the JetBrains website [here](https://youtrack.jetbrains.com/issue/PY-20171). According to this page it's due to be fixed in the 2016.3 release but you can follow the utrunner.py workaround that others have mentioned in the meantime (I downloaded... |
Should I use `__setattr__`, a property or...? | 38,574,070 | 4 | 2016-07-25T17:32:41Z | 38,574,167 | 9 | 2016-07-25T17:38:40Z | [
"python"
] | I have an object with two attributes, `file_path` and `save_path`. Unless `save_path` is explicitly set, I want it to have the same value as `file_path`.
I *think* the way to do this is with `__setattr__`, with something like the following:
```
class Class():
...
def __setattr__(self, name, value):
if nam... | First, the easiest way to do this would be with a property:
```
class Class(object):
def __init__(self, ...):
self._save_path = None
...
@property
def save_path(self):
if self._save_path is None:
return self.file_path
else:
return self._save_path
... |
Create child of str (or int or float or tuple) that accepts kwargs | 38,574,834 | 4 | 2016-07-25T18:18:18Z | 38,575,015 | 7 | 2016-07-25T18:29:26Z | [
"python",
"python-3.x",
"parent-child",
"subclass",
"kwargs"
] | I need a class that behaves like a string but also takes additional `kwargs`. Therefor I subclass `str`:
```
class Child(str):
def __init__(self, x, **kwargs):
# some code ...
pass
inst = Child('a', y=2)
print(inst)
```
This however raises:
```
Traceback (most recent call last):
File "/home/... | You need to override `__new__` in this case, not `__init__`:
```
>>> class Child(str):
... def __new__(cls, s, **kwargs):
... inst = str.__new__(cls, s)
... inst.__dict__.update(kwargs)
... return inst
...
>>> c = Child("foo")
>>> c.upper()
'FOO'
>>> c = Child("foo", y="banana")
>>> c.upper()
'FOO... |
Python- np.mean() giving wrong means? | 38,576,480 | 7 | 2016-07-25T20:04:34Z | 38,576,857 | 8 | 2016-07-25T20:27:08Z | [
"python",
"numpy",
"mean"
] | **The issue**
So I have 50 netCDF4 data files that contain decades of monthly temperature predictions on a global grid. I'm using np.mean() to make an ensemble average of all 50 data files together while preserving time length & spatial scale, but np.mean() gives me two different answers. The first time I run its bloc... | In the line
```
alltas[:,:,:,50] = np.mean(alltas,axis=3,dtype=np.float64)
```
the argument to `mean` should be `alltas[:,:,:,:50]`:
```
alltas[:,:,:,50] = np.mean(alltas[:,:,:,:50], axis=3, dtype=np.float64)
```
Otherwise you are including those final zeros in the calculation of the ensemble means. |
pandas equivalent of np.where | 38,579,532 | 6 | 2016-07-26T00:52:45Z | 38,579,700 | 7 | 2016-07-26T01:15:44Z | [
"python",
"numpy",
"pandas"
] | `np.where` has the semantics of a vectorized if/else (similar to Apache Spark's `when`/`otherwise` DataFrame method). I know that I can use `np.where` on pandas `Series`, but `pandas` often defines its own API to use instead of raw `numpy` functions, which is usually more convenient with `pd.Series`/`pd.DataFrame`.
Su... | Try:
```
(df['A'] + df['B']).where((df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])
```
The difference between the `numpy` `where` and `DataFrame` `where` is that the default values are supplied by the `DataFrame` that the `where` method is being called on ([docs](http://pandas.pydata.org/pandas-docs/stable/generate... |
rounding errors in Python floor division | 38,588,815 | 29 | 2016-07-26T11:35:11Z | 38,589,033 | 9 | 2016-07-26T11:45:40Z | [
"python",
"python-2.7",
"python-3.x",
"floating-point",
"rounding"
] | I know rounding errors happen in floating point arithmetic but can somebody explain the reason for this one:
```
>>> 8.0 / 0.4 # as expected
20.0
>>> floor(8.0 / 0.4) # int works too
20
>>> 8.0 // 0.4 # expecting 20.0
19.0
```
This happens on both Python 2 and 3 on x64.
As far as I see it this is either a bug or ... | That's because there is no 0.4 in python (floating-point finite representation) it's actually a float like `0.4000000000000001` which makes the floor of division to be 19.
```
>>> floor(8//0.4000000000000001)
19.0
```
But the true division (`/`) [returns a reasonable approximation of the division result if the argume... |
rounding errors in Python floor division | 38,588,815 | 29 | 2016-07-26T11:35:11Z | 38,589,356 | 10 | 2016-07-26T12:01:54Z | [
"python",
"python-2.7",
"python-3.x",
"floating-point",
"rounding"
] | I know rounding errors happen in floating point arithmetic but can somebody explain the reason for this one:
```
>>> 8.0 / 0.4 # as expected
20.0
>>> floor(8.0 / 0.4) # int works too
20
>>> 8.0 // 0.4 # expecting 20.0
19.0
```
This happens on both Python 2 and 3 on x64.
As far as I see it this is either a bug or ... | Ok after a little bit of research I have found this [issue](https://bugs.python.org/issue27463).
What seems to be happening is, that as @khelwood suggested `0.4` evaluates internally to `0.40000000000000002220`, which when dividing `8.0` yields something slightly smaller than `20.0`. The `/` operator then rounds to the... |
rounding errors in Python floor division | 38,588,815 | 29 | 2016-07-26T11:35:11Z | 38,589,543 | 10 | 2016-07-26T12:10:42Z | [
"python",
"python-2.7",
"python-3.x",
"floating-point",
"rounding"
] | I know rounding errors happen in floating point arithmetic but can somebody explain the reason for this one:
```
>>> 8.0 / 0.4 # as expected
20.0
>>> floor(8.0 / 0.4) # int works too
20
>>> 8.0 // 0.4 # expecting 20.0
19.0
```
This happens on both Python 2 and 3 on x64.
As far as I see it this is either a bug or ... | @jotasi explained the true reason behind it.
However if you want to prevent it, you can use `decimal` module which was basically designed to represent decimal floating point numbers exactly in contrast to binary floating point representation.
So in your case you could do something like:
```
>>> from decimal import *... |
rounding errors in Python floor division | 38,588,815 | 29 | 2016-07-26T11:35:11Z | 38,589,899 | 20 | 2016-07-26T12:26:58Z | [
"python",
"python-2.7",
"python-3.x",
"floating-point",
"rounding"
] | I know rounding errors happen in floating point arithmetic but can somebody explain the reason for this one:
```
>>> 8.0 / 0.4 # as expected
20.0
>>> floor(8.0 / 0.4) # int works too
20
>>> 8.0 // 0.4 # expecting 20.0
19.0
```
This happens on both Python 2 and 3 on x64.
As far as I see it this is either a bug or ... | As you and khelwood already noticed, `0.4` cannot be exactly represented as a float. Why? It is two fifth (`4/10 == 2/5`) which does not have a finite binary fraction representation.
Try this:
```
from fractions import Fraction
Fraction('8.0') // Fraction('0.4')
# or equivalently
# Fraction(8, 1) // Fract... |
drop elements of a level of a multi-level index pandas | 38,615,616 | 4 | 2016-07-27T14:18:54Z | 38,616,050 | 7 | 2016-07-27T14:35:51Z | [
"python",
"pandas",
"indexing",
"multi-index"
] | In the following DataFrame there are a 2-level MultiIndex, namely `city` and `date`:
```
temp
count
city date
SFO 2014-05-31 31
2014-06-30 30
2014-07-31 31
2014-08-31 31
2014-09-30 30
YYZ 2014-05-31 31
2014-06-30 30
2014-... | You can give [drop](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.drop.html) a specific `level`:
```
In[4]: df.drop([Timestamp('2014-05-31'),Timestamp('2014-09-30')],level=1)
Out[4]:
temp
count
city date
SFO 2014-06-30 30
2014-07-31 31... |
Convert Python sequence to NumPy array, filling missing values | 38,619,143 | 12 | 2016-07-27T17:01:10Z | 38,619,278 | 9 | 2016-07-27T17:10:13Z | [
"python",
"arrays",
"numpy",
"sequence",
"variable-length-array"
] | The implicit conversion of a Python sequence of *variable-length* lists into a NumPy array cause the array to be of type *object*.
```
v = [[1], [1, 2]]
np.array(v)
>>> array([[1], [1, 2]], dtype=object)
```
Trying to force another type will cause an exception:
```
np.array(v, dtype=np.int32)
ValueError: setting an ... | Pandas and its `DataFrame`-s deal beautifully with missing data.
```
import numpy as np
import pandas as pd
v = [[1], [1, 2]]
print(pd.DataFrame(v).fillna(0).values.astype(np.int32))
# array([[1, 0],
# [1, 2]], dtype=int32)
``` |
Convert Python sequence to NumPy array, filling missing values | 38,619,143 | 12 | 2016-07-27T17:01:10Z | 38,619,333 | 9 | 2016-07-27T17:12:47Z | [
"python",
"arrays",
"numpy",
"sequence",
"variable-length-array"
] | The implicit conversion of a Python sequence of *variable-length* lists into a NumPy array cause the array to be of type *object*.
```
v = [[1], [1, 2]]
np.array(v)
>>> array([[1], [1, 2]], dtype=object)
```
Trying to force another type will cause an exception:
```
np.array(v, dtype=np.int32)
ValueError: setting an ... | You can use [itertools.zip\_longest](https://docs.python.org/3.4/library/itertools.html#itertools.zip_longest):
```
import itertools
np.array(list(itertools.zip_longest(*v, fillvalue=0))).T
Out:
array([[1, 0],
[1, 2]])
```
Note: For Python 2, it is [itertools.izip\_longest](https://docs.python.org/2/library/i... |
Maximum recursion depth exceeded, but only when using a decorator | 38,624,852 | 6 | 2016-07-27T23:36:17Z | 38,624,949 | 7 | 2016-07-27T23:46:50Z | [
"python",
"python-3.x",
"recursion",
"decorator",
"memoization"
] | I'm writing a program to calculate Levenshtein distance in Python. I implemented memoization because I am running the algorithm recursively. My original function implemented the memoization in the function itself. Here's what it looks like:
```
# Memoization table mapping from a tuple of two strings to their Levenshte... | Consider the stack frames (function calls) that are happening in your original code. They will look something like:
```
lev(s, t)
-> lev(..., ...)
-> lev(..., ...)
-> lev(..., ...)
-> lev(..., ...)
```
In you memoized version they appear as:
```
wraps(s, t)
-> lev(..., ...)
-> wraps(s, t)
... |
Why is a generator produced by yield faster than a generator produced by xrange? | 38,626,308 | 10 | 2016-07-28T02:48:00Z | 38,626,519 | 9 | 2016-07-28T03:16:39Z | [
"python",
"python-2.7",
"python-3.x",
"yield"
] | I was investigating Python generators and decided to run a little experiment.
```
TOTAL = 100000000
def my_sequence():
i = 0
while i < TOTAL:
yield i
i += 1
def my_list():
return range(TOTAL)
def my_xrange():
return xrange(TOTAL)
```
Memory usage (using psutil to get process RSS memo... | I'm going to preface this answer by saying that timings on this scale are likely going to be hard to measure accurately (probably best to use `timeit`) and that these sorts of optimizations will almost never make any difference in your actual program's runtime ...
Ok, now the disclaimer is done ...
The first thing th... |
Inserting elements from array to the string | 38,635,199 | 2 | 2016-07-28T11:35:53Z | 38,635,274 | 7 | 2016-07-28T11:39:10Z | [
"python",
"arrays",
"string"
] | I have two variables:
```
query = "String: {} Number: {}"
param = ['text', 1]
```
I need to merge these two variables and keep the quote marks in case of string and numbers without quote marks.
result= `"String: 'text' Number: 1"`
I tried to use query.format(param), but it removes the quote marks around the 'text'.... | You can use `repr` on each item in `param` within a generator expression, then use `format` to add them to your string.
```
>>> query = "String: {} Number: {}"
>>> param = ['text', 1]
>>> query.format(*(repr(i) for i in param))
"String: 'text' Number: 1"
``` |
ValueError: too many values to unpack - Is it possible to ignore one value? | 38,636,765 | 2 | 2016-07-28T12:44:57Z | 38,636,821 | 7 | 2016-07-28T12:47:06Z | [
"python",
"unpack"
] | The following line returns an error:
```
self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash = readUserFileMatrixFromFile(x,True)
```
The function actually returns 6 values. But in this case, the last one is useless (its None). So i want to store only 5.
Is it possible to igno... | You can use `*rest` from Python 3.
```
>>> x, y, z, *rest = 1, 2, 3, 4, 5, 6, 7
>>> x
1
>>> y
2
>>> rest
[4, 5, 6, 7]
```
This way you can always be sure to not encounter unpacking issues. |
Python: How to delete rows ending in certain characters? | 38,644,696 | 9 | 2016-07-28T19:01:08Z | 38,644,862 | 7 | 2016-07-28T19:10:13Z | [
"python",
"python-3.x",
"pandas"
] | I have a large data file and I need to delete rows that end in certain letters.
Here is an example of the file I'm using:
```
User Name DN
MB212DA CN=MB212DA,CN=Users,DC=prod,DC=trovp,DC=net
MB423DA CN=MB423DA,OU=Generic Mailbox,DC=prod,DC=trovp,DC=net
MB424PL CN=MB424PL,CN=Users,DC=prod,DC=trov... | You could use this expression
```
df = df[~df['User Name'].str.contains('(?:DA|PL)$')]
```
It will return all rows that don't end in either DA or PL.
The `?:` is so that the brackets would not capture anything. Otherwise, you'd see pandas returning the following (harmless) warning:
```
UserWarning: This pattern has... |
count number of events in an array python | 38,651,692 | 4 | 2016-07-29T06:13:46Z | 38,651,757 | 11 | 2016-07-29T06:17:48Z | [
"python",
"arrays",
"time-series"
] | I have the following array:
```
a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0]
```
Each time I have a '1' or a series of them(consecutive), this is one event. I need to get, in Python, how many events my array has. So in this case we will have 5 events (that is 5 times 1 or sequences of it appears). ... | You could use [`itertools.groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby) (it does exactly what you want - groups consecutive elements) and count all groups which starts with `1`:
```
In [1]: from itertools import groupby
In [2]: a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0... |
Where is a Python built-in object's __enter__() and __exit__() defined? | 38,666,733 | 2 | 2016-07-29T20:09:03Z | 38,666,836 | 7 | 2016-07-29T20:16:49Z | [
"python",
"with-statement",
"contextmanager",
"code-inspection"
] | I've read that the object's \_\_ enter\_\_() and \_\_ exit\_\_() methods are called every time 'with' is used. I understand that for user-defined objects, you can define those methods yourself, but I don't understand how this works for built-in objects/functions like 'open' or even the testcases.
This code works as ex... | `open()` is a function. It *returns* something that has an `__enter__` and `__exit__` method. Look at something like this:
```
>>> class f:
... def __init__(self):
... print 'init'
... def __enter__(self):
... print 'enter'
... def __exit__(self, *a):
... print 'exit'
...
>>> with ... |
What is the inverse of the numpy cumsum function? | 38,666,924 | 10 | 2016-07-29T20:23:38Z | 38,666,977 | 10 | 2016-07-29T20:27:10Z | [
"python",
"numpy",
"cumsum"
] | If I have `z = cumsum( [ 0, 1, 2, 6, 9 ] )`, which gives me `z = [ 0, 1, 3, 9, 18 ]`, how can I get back to the original array `[ 0, 1, 2, 6, 9 ]` ? | ```
z[1:] -= z[:-1].copy()
```
Short and sweet, with no slow Python loops. We take views of all but the first element (`z[1:]`) and all but the last (`z[:-1]`), and subtract elementwise. The copy makes sure we subtract the original element values instead of the values we're computing. |
Fail to Launch Mozilla with selenium | 38,676,719 | 8 | 2016-07-30T17:38:13Z | 38,676,858 | 11 | 2016-07-30T17:53:02Z | [
"java",
"python",
"selenium",
"firefox",
"mozilla"
] | I am trying to launch `Mozilla` but still i am getting this error:
> Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see <https://github.com/mozilla/geckodriver>. The latest version can be dow... | *The `Selenium` client bindings will try to locate the `geckodriver` executable from the system `PATH`. You will need to add the directory containing the executable to the system path.*
* On **Unix** systems you can do the following to append it to your systemâs search path, if youâre using a bash-compatible shell... |
How (in what form) to share (deliver) a Python function? | 38,700,517 | 19 | 2016-08-01T13:46:07Z | 38,771,976 | 9 | 2016-08-04T15:48:25Z | [
"python",
"sockets",
"deployment",
"publish"
] | The final outcome of my work should be a Python function that takes a JSON object as the only input and return another JSON object as output. To keep it more specific, I am a data scientist, and the function that I am speaking about, is derived from data and it delivers predictions (in other words, it is a machine lear... | You have the right idea with using a socket but there are tons of frameworks doing exactly what you want. Like [hleggs](http://stackoverflow.com/users/6464893/hleggs), I suggest you checkout [Flask](http://flask.pocoo.org/) to build a microservice. This will let the other team post JSON objects in an HTTP request to yo... |
One-liner to save value of if statement? | 38,700,537 | 3 | 2016-08-01T13:46:58Z | 38,700,640 | 7 | 2016-08-01T13:51:00Z | [
"python",
"variables",
"if-statement"
] | Is there a smart way to write the following code in three or four lines?
```
a=l["artist"]
if a:
b=a["projects"]
if b:
c=b["project"]
if c:
print c
```
So I thought for something like pseudocode:
```
a = l["artist"] if True:
``` | How about:
```
try:
print l["artist"]["projects"]["project"]
except KeyError:
pass
except TypeError:
pass # None["key"] raises TypeError.
```
This will `try` to `print` the value, but if a `KeyError` is raised, the `except` block will be run. `pass` means to do nothing. This is known and EAFP: itâs **E*... |
Why is there an underscore following the "from" in the Twilio Rest API? | 38,708,834 | 5 | 2016-08-01T22:02:56Z | 38,708,867 | 11 | 2016-08-01T22:07:15Z | [
"python",
"twilio",
"twilio-api"
] | In the [twilio python library](https://www.twilio.com/docs/libraries/python#testing-your-installation), we have this feature to create messages:
`from twilio.rest import TwilioRestClient`
and we can write:
`msg = TwilioRestClient.messages.create(body=myMsgString, from_=myNumber, to=yourNumber)`
My question is simpl... | This is because `from` would be an invalid argument name, resulting in a `SyntaxError` - it's a python keyword.
Appending a trailing underscore is the recommended way to avoid such conflicts mentioned in the [PEP8 style guide](https://www.python.org/dev/peps/pep-0008/#function-and-method-arguments):
> If a function a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.