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 |
|---|---|---|---|---|---|---|---|---|---|
Multiply high order matrices with numpy | 30,816,747 | 9 | 2015-06-13T08:43:49Z | 30,817,037 | 13 | 2015-06-13T09:22:53Z | [
"python",
"numpy",
"matrix",
"scipy",
"linear-algebra"
] | I created this toy problem that reflects my much bigger problem:
```
import numpy as np
ind = np.ones((3,2,4)) # shape=(3L, 2L, 4L)
dist = np.array([[0.1,0.3],[1,2],[0,1]]) # shape=(3L, 2L)
ans = np.array([np.dot(dist[i],ind[i]) for i in xrange(dist.shape[0])]) # shape=(3L, 4L)
print ans
""" prints:
[[ 0.4 0.4 ... | You could use `np.einsum` to do the operation since it allows for very careful control over which axes are multiplied and which are summed:
```
>>> np.einsum('ijk,ij->ik', ind, dist)
array([[ 0.4, 0.4, 0.4, 0.4],
[ 3. , 3. , 3. , 3. ],
[ 1. , 1. , 1. , 1. ]])
```
The function multiplies the ent... |
Multiply high order matrices with numpy | 30,816,747 | 9 | 2015-06-13T08:43:49Z | 30,819,011 | 13 | 2015-06-13T13:07:21Z | [
"python",
"numpy",
"matrix",
"scipy",
"linear-algebra"
] | I created this toy problem that reflects my much bigger problem:
```
import numpy as np
ind = np.ones((3,2,4)) # shape=(3L, 2L, 4L)
dist = np.array([[0.1,0.3],[1,2],[0,1]]) # shape=(3L, 2L)
ans = np.array([np.dot(dist[i],ind[i]) for i in xrange(dist.shape[0])]) # shape=(3L, 4L)
print ans
""" prints:
[[ 0.4 0.4 ... | Following [@ajcr's great answer](http://stackoverflow.com/a/30817037/3523490), I wanted to determine which method is the fastest, so I used `timeit` :
```
import timeit
setup_code = """
import numpy as np
i,j,k = (300,200,400)
ind = np.ones((i,j,k)) #shape=(3L, 2L, 4L)
dist = np.random.rand(i,j) #shape=(3L, 2L)
"""
... |
Python 2.7.9 Mac OS 10.10.3 Message "setCanCycle: is deprecated. Please use setCollectionBehavior instead" | 30,818,222 | 4 | 2015-06-13T11:37:51Z | 30,855,388 | 7 | 2015-06-15T21:37:45Z | [
"python",
"osx",
"tkinter",
"anaconda",
"spyder"
] | This is my first message and i hope can you help me to solve my problem.
When I launch a python script I have this message :
> 2015-06-10 23:15:44.146 python[1044:19431] setCanCycle: is deprecated.Please use setCollectionBehavior instead
>
> 2015-06-10 23:15:44.155 python[1044:19431] setCanCycle: is deprecated.Please... | The version of the Tkinter library which Anaconda has installed was compiled on an older version of OS X. The warnings your seeing aren't actually a problem and will go away once a version of the library compiled on a more recent version of OS X are added to the Anaconda repository.
<https://groups.google.com/a/continu... |
Test if dict contained in dict | 30,818,694 | 18 | 2015-06-13T12:30:35Z | 30,818,799 | 33 | 2015-06-13T12:41:49Z | [
"python",
"dictionary"
] | Testing for equality works fine like this for python dicts:
```
first = {"one":"un", "two":"deux", "three":"trois"}
second = {"one":"un", "two":"deux", "three":"trois"}
print(first == second) # Result: True
```
But now my second dict contains some additional keys I want to ignore:
```
first = {"one":"un", "two":"... | You can use a [dictionary view](https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects):
```
# Python 2
if first.viewitems() <= second.viewitems():
# true only if `first` is a subset of `second`
# Python 3
if first.items() <= second.items():
# true only if `first` is a subset of `second`
```
... |
How to label and change the scale of Seaborn kdeplot's axes | 30,819,056 | 6 | 2015-06-13T13:11:53Z | 30,846,758 | 7 | 2015-06-15T13:43:05Z | [
"python",
"matplotlib",
"seaborn"
] | Here's my code
```
import numpy as np
from numpy.random import randn
import pandas as pd
from scipy import stats
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
fig = sns.kdeplot(treze, shade=True, color=c1,cut =0, clip=(0,2000))
fig = sns.kdeplot(cjjardim, shade=True, color=c2,cut =0,... | 1) what you are looking for is most probably some combination of get\_yticks() and set\_yticks:
```
plt.yticks(fig.get_yticks(), fig.get_yticks() * 100)
plt.ylabel('Distribution [%]', fontsize=16)
```
Note: as mwaskom is commenting times 10000 and a % sign is mathematically incorrect.
2) you can specify where you wa... |
Convert string date into date format in python? | 30,819,423 | 3 | 2015-06-13T13:52:59Z | 30,819,460 | 8 | 2015-06-13T13:58:02Z | [
"python",
"date",
"datetime"
] | How to convert the below string date into date format in python.
```
input:
date='15-MARCH-2015'
expected output:
2015-03-15
```
I tried to use `datetime.strftime` and `datetime.strptime`. it is not accepting this format. | You can use `datetime.strptime` with a proper format :
```
>>> datetime.strptime('15-MARCH-2015','%d-%B-%Y')
datetime.datetime(2015, 3, 15, 0, 0)
```
Read more about `datetime.strptime` and date formatting: <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior> |
Dump a Python dictionary with array value inside to CSV | 30,819,738 | 2 | 2015-06-13T14:26:51Z | 30,819,788 | 8 | 2015-06-13T14:30:44Z | [
"python"
] | I got something like this:
```
dict = {}
dict["p1"] = [.1,.2,.3,.4]
dict["p2"] = [.4,.3,.2,.1]
dict["p3"] = [.5,.6,.7,.8]
```
How I can dump this dictionary into csv like this structure? :
```
.1 .4 .5
.2 .3 .6
.3 .2 .7
.4 .1 .8
```
Really appreciated ! | `dict`s have no order so you would need an [`OrderedDict`](https://docs.python.org/2/library/collections.html#collections.OrderedDict) and to transpose the values:
```
import csv
from collections import OrderedDict
d = OrderedDict()
d["p1"] = [.1,.2,.3,.4]
d["p2"] = [.4,.3,.2,.1]
d["p3"] = [.5,.6,.7,.8]
with open("ou... |
Python NLTK pos_tag not returning the correct part-of-speech tag | 30,821,188 | 7 | 2015-06-13T16:52:28Z | 30,823,202 | 27 | 2015-06-13T20:24:08Z | [
"python",
"machine-learning",
"nlp",
"nltk",
"pos-tagger"
] | Having this:
```
text = word_tokenize("The quick brown fox jumps over the lazy dog")
```
And running:
```
nltk.pos_tag(text)
```
I get:
```
[('The', 'DT'), ('quick', 'NN'), ('brown', 'NN'), ('fox', 'NN'), ('jumps', 'NNS'), ('over', 'IN'), ('the', 'DT'), ('lazy', 'NN'), ('dog', 'NN')]
```
This is incorrect. The ta... | **In short**:
> NLTK is not perfect. In fact, no model is perfect.
**Note:**
As of NLTK version 3.1, default `pos_tag` function is no longer the [old MaxEnt English pickle](http://stackoverflow.com/questions/31386224/what-created-maxent-treebank-pos-tagger-english-pickle).
It is now the **perceptron tagger** from [... |
What to set `SPARK_HOME` to? | 30,824,818 | 10 | 2015-06-14T00:12:30Z | 30,825,179 | 17 | 2015-06-14T01:29:26Z | [
"python",
"apache-spark",
"pythonpath",
"pyspark",
"apache-zeppelin"
] | Installed apache-maven-3.3.3, scala 2.11.6, then ran:
```
$ git clone git://github.com/apache/spark.git -b branch-1.4
$ cd spark
$ build/mvn -DskipTests clean package
```
Finally:
```
$ git clone https://github.com/apache/incubator-zeppelin
$ cd incubator-zeppelin/
$ mvn install -DskipTests
```
Then ran the server:... | Two environment variables are required:
```
SPARK_HOME=/spark
PYTHONPATH=$SPARK_HOME/python:$SPARK_HOME/python/lib/py4j-VERSION-src.zip:$PYTHONPATH
``` |
What does this: s[s[1:] == s[:-1]] do in numpy? | 30,831,084 | 17 | 2015-06-14T15:20:13Z | 30,831,133 | 19 | 2015-06-14T15:25:17Z | [
"python",
"numpy"
] | I've been looking for a way to efficiently check for duplicates in a numpy array and stumbled upon a question that contained an answer using this code.
What does this line mean in numpy?
```
s[s[1:] == s[:-1]]
```
Would like to understand the code before applying it. Looked in the Numpy doc but had trouble finding t... | The slices `[1:]` and `[:-1]` mean *all but the first* and *all but the last* elements of the array:
```
>>> import numpy as np
>>> s = np.array((1, 2, 2, 3)) # four element array
>>> s[1:]
array([2, 2, 3]) #Â last three elements
>>> s[:-1]
array([1, 2, 2]) # first three elements
```
therefore the comparison gener... |
Multiprocessing IOError: bad message length | 30,834,132 | 16 | 2015-06-14T20:23:15Z | 31,794,365 | 10 | 2015-08-03T18:33:08Z | [
"python",
"numpy",
"multiprocessing",
"pool",
"ioerror"
] | I get an `IOError: bad message length` when passing large arguments to the `map` function. How can I avoid this?
The error occurs when I set `N=1500` or bigger.
The code is:
```
import numpy as np
import multiprocessing
def func(args):
i=args[0]
images=args[1]
print i
return 0
N=1500 #N=1000 w... | You're creating a pool and sending all the images at once to func(). If you can get away with working on a single image at once, try something like this, which runs to completion with N=10000 in 35s with Python 2.7.10 for me:
```
import numpy as np
import multiprocessing
def func(args):
i = args[0]
img = args... |
AttributeError: FileInput instance has no attribute '__exit__' | 30,835,090 | 7 | 2015-06-14T22:13:03Z | 30,835,248 | 13 | 2015-06-14T22:32:43Z | [
"python"
] | I am trying to read from multiple input files and print the second row from each file next to each other as a table
```
import sys
import fileinput
with fileinput.input(files=('cutflow_TTJets_1l.txt ', 'cutflow_TTJets_1l.txt ')) as f:
for line in f:
proc(line)
def proc(line):
parts = line.split("&... | The problem is that as of python 2.7.10, the fileinput module does not support being used as a context manager, i.e. the `with` statement, so you have to handle closing the sequence yourself. The following should work:
```
f = fileinput.input(files=('cutflow_TTJets_1l.txt ', 'cutflow_TTJets_1l.txt '))
for line in f:
... |
How to get the index of an integer from a list if the list contains a boolean? | 30,843,103 | 14 | 2015-06-15T10:40:23Z | 30,843,199 | 13 | 2015-06-15T10:45:54Z | [
"python",
"list",
"indexing"
] | I am just starting with Python.
How to get index of integer `1` from a list if the list contains a boolean `True` object before the `1`?
```
>>> lst = [True, False, 1, 3]
>>> lst.index(1)
0
>>> lst.index(True)
0
>>> lst.index(0)
1
```
I think Python considers `0` as `False` and `1` as `True` in the argument of the `... | The [documentation](https://docs.python.org/3/library/stdtypes.html#lists) says that
> Lists are mutable sequences, typically used to store collections of
> homogeneous items (where the precise degree of similarity will vary by
> application).
You shouldn't store heterogeneous data in lists.
The implementation of `li... |
How to get the index of an integer from a list if the list contains a boolean? | 30,843,103 | 14 | 2015-06-15T10:40:23Z | 30,843,812 | 7 | 2015-06-15T11:17:58Z | [
"python",
"list",
"indexing"
] | I am just starting with Python.
How to get index of integer `1` from a list if the list contains a boolean `True` object before the `1`?
```
>>> lst = [True, False, 1, 3]
>>> lst.index(1)
0
>>> lst.index(True)
0
>>> lst.index(0)
1
```
I think Python considers `0` as `False` and `1` as `True` in the argument of the `... | Booleans **are** integers in Python, and this is why you can use them just like any integer:
```
>>> 1 + True
2
>>> [1][False]
1
```
[this doesn't mean you should :)]
This is due to the fact that `bool` is a subclass of `int`, and almost always a boolean will behave just like 0 or 1 (except when it is cast to string... |
Linear programming with scipy.optimize.linprog | 30,849,883 | 3 | 2015-06-15T16:06:24Z | 30,850,123 | 7 | 2015-06-15T16:20:13Z | [
"python",
"numpy",
"scipy"
] | I've just check the simple linear programming problem with scipy.optimize.linprog:
```
1*x[1] + 2x[2] -> max
1*x[1] + 0*x[2] <= 5
0*x[1] + 1*x[2] <= 5
1*x[1] + 0*x[2] >= 1
0*x[1] + 1*x[2] >= 1
1*x[1] + 1*x[2] <= 6
```
And got the very strange result, I expected that x[1] will be 1 and x[2] will be 5, but:
```
>>> p... | `optimize.linprog` always minimizes your target function. If you want to maximize instead, you can use that `max(f(x)) == -min(-f(x))`
```
from scipy import optimize
optimize.linprog(
c = [-1, -2],
A_ub=[[1, 1]],
b_ub=[6],
bounds=(1, 5),
method='simplex'
)
```
This will give you your expected r... |
Benefit of using os.mkdir vs os.system("mkdir") | 30,854,465 | 2 | 2015-06-15T20:31:57Z | 30,854,516 | 10 | 2015-06-15T20:35:13Z | [
"python",
"python-2.7"
] | Simple question that I can't find an answer to:
Is there a benefit of using `os.mkdir("somedir")` over `os.system("mkdir somedir")` or `subprocess.call()`, beyond code portability?
Answers should apply to Python 2.7.
Edit: the point was raised that a hard-coded directory versus a variable (possibly containing user-d... | ## Correctness
Think about what happens if your directory name contains spaces:
```
mkdir hello world
```
...creates *two* directories, `hello` and `world`. And if you just blindly substitute in quotes, that won't work if your filename contains that quoting type:
```
'mkdir "' + somedir + '"'
```
...does very litt... |
ensure_future not available in module asyncio | 30,854,576 | 7 | 2015-06-15T20:39:29Z | 30,854,677 | 9 | 2015-06-15T20:45:53Z | [
"python",
"python-asyncio"
] | I'm trying to run this example from the [python asyncio tasks & coroutines documentation](https://docs.python.org/3.4/library/asyncio-task.html#example-future-with-run-forever)
```
import asyncio
@asyncio.coroutine
def slow_operation(future):
yield from asyncio.sleep(1)
future.set_result('Future is done!')
d... | <https://docs.python.org/3.4/library/asyncio-task.html#asyncio.ensure_future>
> `asyncio.ensure_future(coro_or_future, *, loop=None)`
>
> Schedule the execution of a coroutine object: wrap it in a future. Return a Task object.
>
> If the argument is a `Future`, it is returned directly.
>
> **New in version 3.4.4.**
T... |
Docker-compose and pdb | 30,854,967 | 10 | 2015-06-15T21:05:27Z | 30,901,026 | 9 | 2015-06-17T19:47:31Z | [
"python",
"docker",
"pdb",
"docker-compose"
] | I see that I'm not the first one to ask the question but there was no clear answer to this:
How to use pdb with docker-composer in Python development?
When you ask uncle Google about `django docker` you get awesome docker-composer examples and tutorials and I have an environment working - I can run `docker-compose up... | Try running your web container with the --service-ports option: `docker-compose run --service-ports web` |
What is a reliable isnumeric() function for python 3? | 30,855,314 | 2 | 2015-06-15T21:32:34Z | 30,855,376 | 7 | 2015-06-15T21:36:59Z | [
"python",
"regex",
"validation",
"python-3.x",
"isnumeric"
] | I am attempting to do what should be very simple and check to see if a value in an `Entry` field is a valid and real number. The `str.isnumeric()` method does not account for "-" negative numbers, or "." decimal numbers.
I tried writing a function for this:
```
def IsNumeric(self, event):
w = event.widget
if ... | ```
try:
float(w.get())
except ValueError:
# wasn't numeric
``` |
Analytical solution for Linear Regression using Python vs. Julia | 30,855,655 | 10 | 2015-06-15T21:56:55Z | 30,856,430 | 9 | 2015-06-15T23:09:21Z | [
"python",
"matrix",
"julia-lang"
] | Using example from Andrew Ng's class (finding parameters for Linear Regression using normal equation):
With Python:
```
X = np.array([[1, 2104, 5, 1, 45], [1, 1416, 3, 2, 40], [1, 1534, 3, 2, 30], [1, 852, 2, 1, 36]])
y = np.array([[460], [232], [315], [178]])
θ = ((np.linalg.inv(X.T.dot(X))).dot(X.T)).dot(y)
print(... | ## Using X^-1 vs the pseudo inverse
**pinv**(X) which corresponds to [the pseudo inverse](https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse#Applications) is more broadly applicable than **inv**(X), which X^-1 equates to. Neither Julia nor Python do well using **inv**, but in this case apparently Julia ... |
Analytical solution for Linear Regression using Python vs. Julia | 30,855,655 | 10 | 2015-06-15T21:56:55Z | 30,856,590 | 9 | 2015-06-15T23:27:01Z | [
"python",
"matrix",
"julia-lang"
] | Using example from Andrew Ng's class (finding parameters for Linear Regression using normal equation):
With Python:
```
X = np.array([[1, 2104, 5, 1, 45], [1, 1416, 3, 2, 40], [1, 1534, 3, 2, 30], [1, 852, 2, 1, 36]])
y = np.array([[460], [232], [315], [178]])
θ = ((np.linalg.inv(X.T.dot(X))).dot(X.T)).dot(y)
print(... | A more numerically robust approach in Python, without having to do the matrix algebra yourself is to use [`numpy.linalg.lstsq`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html) to do the regression:
```
In [29]: np.linalg.lstsq(X, y)
Out[29]:
(array([[ 188.40031942],
[ 0.3866255 ... |
How to delete documents from Elasticsearch | 30,859,142 | 5 | 2015-06-16T05:00:03Z | 30,859,283 | 9 | 2015-06-16T05:11:42Z | [
"python",
"elasticsearch"
] | I can't find any example of deleting documents from `Elasticsearch` in Python. Whay I've seen by now - is definition of `delete` and `delete_by_query` functions. But for some reason [documentation](http://elasticsearch-py.readthedocs.org/en/master/api.html#elasticsearch.Elasticsearch.delete_by_query) does not provide e... | Since you are not giving a document id while indexing your document, you have to get the auto-generated document id from the return value and delete according to the id. Or you can define the id yourself, try the following:
```
db.index(index="reestr",doc_type="some_type",id=1919, body=doc)
db.delete(index="reestr"... |
How to fix Python ValueError:bad marshal data? | 30,861,493 | 8 | 2015-06-15T18:54:48Z | 30,861,494 | 13 | 2015-06-15T18:54:48Z | [
"python"
] | Running flexget Python script in Ubuntu, I get an error:
```
$ flexget series forget "Orange is the new black" s03e01
Traceback (most recent call last):
File "/usr/local/bin/flexget", line 7, in <module>
from flexget import main
File "/usr/local/lib/python2.7/dist-packages/flexget/__init__.py", line 11, in <module>
fr... | If you get that error, the compiled version of the Python module (the .pyc file) is corrupt probably. Gentoo Linux provides `python-updater`, but in Debian the easier way to fix: just delete the .pyc file. If you don't know the pyc, just delete all of them (as root):
```
find /usr -name '*.pyc' -delete
``` |
Installing new versions of Python on Cygwin does not install Pip? | 30,863,501 | 20 | 2015-06-16T09:19:10Z | 31,958,249 | 40 | 2015-08-12T07:07:19Z | [
"python",
"cygwin",
"pip"
] | While I am aware of the option of [installing Pip from source](https://pip.pypa.io/en/latest/installing.html), I'm trying to avoid going down that path so that updates to Pip will be managed by Cygwin's package management.
I've [recently learned](http://stackoverflow.com/a/12476379/2489598) that the latest versions of... | [cel](https://stackoverflow.com/users/2272172/cel) self-answered this question in a [comment above](https://stackoverflow.com/questions/30863501/installing-new-versions-of-python-on-cygwin-does-not-install-pip/31958249#comment49786910_30863501). For posterity, let's convert this helpfully working solution into a genuin... |
What's wrong with order for not() in python? | 30,863,866 | 3 | 2015-06-16T09:36:22Z | 30,863,932 | 8 | 2015-06-16T09:39:16Z | [
"python",
"operators",
"boolean-expression"
] | What's wrong with using not() in python?. I tried this
```
In [1]: not(1) + 1
Out[1]: False
```
And it worked fine. But after readjusting it,
```
In [2]: 1 + not(1)
Out[2]: SyntaxError: invalid syntax
```
It gives an error. How does the order matters? | `not` is a [*unary operator*](https://docs.python.org/2/reference/expressions.html#boolean-operations), not a function, so please don't use the `(..)` call notation on it. The parentheses are ignored when parsing the expression and `not(1) + 1` is the same thing as `not 1 + 1`.
Due to precedence rules Python tries to ... |
Peewee KeyError: 'i' | 30,866,058 | 3 | 2015-06-16T11:17:27Z | 30,866,375 | 8 | 2015-06-16T11:33:06Z | [
"python",
"flask",
"peewee"
] | I am getting an odd error from Python's peewee module that I am not able to resolve, any ideas? I basically want to have 'batches' that contain multiple companies within them. I am making a batch instance for each batch and assigning all of the companies within it to that batch's row ID.
**Traceback**
```
Traceback (... | The issue lies within the Metadata for your Batch class. See peewee's [example](https://peewee.readthedocs.org/en/latest/peewee/example.html) where order\_by is used:
```
class User(BaseModel):
username = CharField(unique=True)
password = CharField()
email = CharField()
join_date = DateTimeField()
... |
How to sort list of strings by count of a certain character? | 30,870,933 | 2 | 2015-06-16T14:45:45Z | 30,870,984 | 9 | 2015-06-16T14:47:41Z | [
"python",
"list",
"python-2.7",
"sorting"
] | I have a list of strings and I need to order it by the appearance of a certain character, let's say `"+"`.
So, for instance, if I have a list like this:
```
["blah+blah", "blah+++blah", "blah+bl+blah", "blah"]
```
I need to get:
```
["blah", "blah+blah", "blah+bl+blah", "blah+++blah"]
```
I've been studying the `so... | Yes, [`list.sort`](https://docs.python.org/3/library/stdtypes.html#list.sort) can do it, though you need to specify the `key` argument:
```
In [4]: l.sort(key=lambda x: x.count('+'))
In [5]: l
Out[5]: ['blah', 'blah+blah', 'blah+bl+blah', 'blah+++blah']
```
In this code `key` function accepts a single argument and u... |
How is a raw string useful in Python? | 30,871,384 | 3 | 2015-06-16T15:03:55Z | 30,871,458 | 7 | 2015-06-16T15:07:00Z | [
"python"
] | I know the raw string operator `r` or `R` suppresses the meaning of escape characters but in what situation would this really be helpful? | Raw strings are commonly used for regular expressions which need to include backslashes.
```
re.match(r'\b(\w)+', string) # instead of re.match('(\\w)+', string
```
They are also useful for DOS file paths, which would otherwise have to double up every path separator.
```
path = r'C:\some\dir' # instead of 'C:\\som... |
How to get selected option using Selenium WebDriver with Python? | 30,872,786 | 6 | 2015-06-16T16:07:27Z | 30,872,875 | 7 | 2015-06-16T16:11:52Z | [
"python",
"selenium",
"selenium-webdriver",
"selecteditem",
"selected"
] | How to get selected option using Selenium WebDriver with Python:
Someone have a solution for a `getFirstSelectedOption`?
I'm using this to get the select element:
```
try:
FCSelect = driver.find_element_by_id('FCenter')
self.TestEventLog = self.TestEventLog + "<br>Verify Form Elements: F Center Select found"... | This is something that `selenium` makes it easy to deal with - the [`Select`](https://selenium-python.readthedocs.org/api.html#selenium.webdriver.support.select.Select) class:
```
from selenium.webdriver.support.select import Select
select = Select(driver.find_element_by_id('FCenter'))
selected_option = select.first_... |
How to merge two lists of string in Python | 30,876,691 | 3 | 2015-06-16T19:40:49Z | 30,876,717 | 7 | 2015-06-16T19:42:25Z | [
"python",
"string",
"list",
"merge"
] | I have two lists of string:
```
a = ['a', 'b', 'c']
b = ['d', 'e', 'f']
```
I should result:
```
['ad', 'be', 'cf']
```
What is the most pythonic way to do this ? | Probably with [`zip`](https://docs.python.org/3/library/functions.html#zip):
```
c = [''.join(item) for item in zip(a,b)]
```
You can also put multiple sublists into one large iterable and use the `*` operator to unpack it, passing each sublist as a separate argument to `zip`:
```
big_list = (a,b)
c = [''.join(item)... |
Why does slice [:-0] return empty list in Python | 30,879,473 | 3 | 2015-06-16T22:39:55Z | 30,879,490 | 11 | 2015-06-16T22:41:36Z | [
"python",
"list",
"slice",
"negative-number"
] | Stumbled upon something slightly perplexing today while writing some unittests:
```
blah = ['a', 'b', 'c']
blah[:-3] # []
blah[:-2] # ['a']
blah[:-1] # ['a', 'b']
blah[:-0] # []
```
Can't for the life of me figure out why `blah[:-0] # []` should be the case, the pattern definitely seems to suggest that it should be `... | `-0` is `0`, and a slice that goes from the beginning of a `list` inclusive to index `0` non-inclusive is an empty `list`. |
PySpark add a column to a DataFrame from a TimeStampType column | 30,882,268 | 7 | 2015-06-17T04:20:17Z | 30,992,905 | 17 | 2015-06-23T02:29:00Z | [
"python",
"apache-spark",
"apache-spark-sql",
"pyspark"
] | I have a DataFrame that look something like that. I want to operate on the day of the `date_time` field.
```
root
|-- host: string (nullable = true)
|-- user_id: string (nullable = true)
|-- date_time: timestamp (nullable = true)
```
I tried to add a column to extract the day. So far my attempts have failed.
```
... | You can use simple `map`:
```
df.rdd.map(lambda row:
Row(row.__fields__ + ["day"])(row + (row.date_time.day, ))
)
```
Another option is to register a function and run SQL query:
```
sqlContext.registerFunction("day", lambda x: x.day)
sqlContext.registerDataFrameAsTable(df, "df")
sqlContext.sql("SELECT *, day(dat... |
Creating deb or rpm with setuptools - data_files | 30,885,731 | 11 | 2015-06-17T08:05:51Z | 30,938,202 | 9 | 2015-06-19T12:30:53Z | [
"python",
"python-3.x",
"rpm",
"setuptools",
"deb"
] | I have a Python 3 project.
```
MKC
âââ latex
â âââ macros.tex
â âââ main.tex
âââ mkc
â âââ cache.py
â âââ __init__.py
â âââ __main__.py
âââ README.md
âââ setup.py
âââ stdeb.cfg
```
On install, I would like to move my latex files to known ... | When creating a deb file (I guess the same counts for a rpm file), `./setup.py --command-packages=stdeb.command bdist_deb` first creates a source distribution and uses that archive for further processing. But your LaTeX files are not included there, so they're not found.
You need to add them to the source package. Suc... |
python nested list comprehension string concatenation | 30,887,004 | 3 | 2015-06-17T09:04:44Z | 30,887,067 | 7 | 2015-06-17T09:07:52Z | [
"python",
"list-comprehension",
"nested-lists"
] | I have a list of lists in python looking like this:
```
[['a', 'b'], ['c', 'd']]
```
I want to come up with a string like this:
```
a,b;c,d
```
So the lists should be separated with a `;` and the values of the same list should be separated with a `,`
So far I tried `','.join([y for x in test for y in x])` which re... | ```
";".join([','.join(x) for x in a])
``` |
How to show minor tick labels on log-scale with Matplotlib | 30,887,920 | 2 | 2015-06-17T09:42:27Z | 30,890,025 | 7 | 2015-06-17T11:18:42Z | [
"python",
"matplotlib"
] | Does anyone know how to show the labels of the minor ticks on a logarithmic scale with Python/Matplotlib?
Thanks! | You can use `plt.tick_params(axis='y', which='minor')` to set the minor ticks on and format them with the `matplotlib.ticker` `FormatStrFormatter`. For example,
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
x = np.linspace(0,4,1000)
y = np.exp(x)
plt.plot(x, y)... |
I want to create a script for unzip (.tar.gz) file via (Python) | 30,887,979 | 5 | 2015-06-17T09:45:41Z | 30,888,321 | 8 | 2015-06-17T10:01:29Z | [
"python",
"tar",
"unzip",
"gz"
] | I am trying to make a script for unzipping all the .tar.gz files from folders in one directory. For example, I will have a file which it calls ( testing.tar.gz). Then if I do manually, I can press to "extract here" then the .tar.gz file will create a new file, and it calls testing.tar. Finally, if I repeat the process ... | Why do you want to "press" twice to extract a .tar.gz, when you can easily do it once? Here is a simple code to extract both .tar and .tar.gz in one go:
```
import tarfile
if (fname.endswith("tar.gz")):
tar = tarfile.open(fname, "r:gz")
tar.extractall()
tar.close()
elif (fname.endswith("tar")):
tar = t... |
How to print a tree in Python? | 30,893,895 | 7 | 2015-06-17T14:03:08Z | 30,893,896 | 7 | 2015-06-17T14:03:08Z | [
"python",
"tree",
"pretty-print"
] | I have the following class which represents a node of a tree:
```
class Node:
def __init__(self, name, parent=None):
self.name = name
self.parent = parent
self.children = []
# ...
if parent:
self.parent.children.append(self)
```
How to print such a tree? | This is my solution:
```
def print_tree(current_node, indent="", last='updown'):
nb_children = lambda node: sum(nb_children(child) for child in node.children) + 1
size_branch = {child: nb_children(child) for child in current_node.children}
""" Creation of balanced lists for "up" branch and "down" branch.... |
Type hint for 'other' in magic methods? | 30,898,998 | 5 | 2015-06-17T18:01:33Z | 30,899,060 | 8 | 2015-06-17T18:04:28Z | [
"python",
"type-hinting"
] | ```
class Interval(object):
def __sub__(self, other: Interval):
pass
```
The way it is I get a 'NameError: name 'Interval' is not defined'. Can someone tell me which type would be correct here? | The class doesn't exist until after Python finishes executing all the code inside the class block, including your method definitions.
Just use a string literal instead, as suggested in [PEP 484](https://www.python.org/dev/peps/pep-0484/#forward-references):
```
class Interval(object):
def __sub__(self, other: 'In... |
What happens to exceptions raised in a with statement expression? | 30,909,463 | 8 | 2015-06-18T07:49:00Z | 30,909,636 | 7 | 2015-06-18T07:58:47Z | [
"python",
"with-statement",
"contextmanager"
] | My understanding of Python's `with` statement is as follows:
`with` statement = `with` + *expression* + `as` + *target* + `:` + *suit*
1. *expression* is executed and returns a context manager
2. context manager's `__enter__` returns a value to *target*
3. The *suite* is executed.
4. context manager's `__exit__` meth... | The `with` statement only manages exceptions in *step 3*. If an exception is raised in step 1 (executing *expression*) or in step 2 (executing the context manager `__enter__` method), you *do not have a (valid and working) context manager* to hand the exception to.
So if the file does not exist, an exception is raised... |
Subsetting a 2D numpy array | 30,917,753 | 10 | 2015-06-18T14:10:44Z | 30,917,921 | 7 | 2015-06-18T14:17:11Z | [
"python",
"numpy",
"multidimensional-array",
"subset"
] | I have looked into documentations and also other questions here, but it seems I
have not got the hang of subsetting in numpy arrays yet.
I have a numpy array,
and for the sake of argument, let it be defined as follows:
```
import numpy as np
a = np.arange(100)
a.shape = (10,10)
# array([[ 0, 1, 2, 3, 4, 5, 6, ... | Another quick way to build the desired index is to use the [`np.ix_`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ix_.html) function:
```
>>> a[np.ix_(n1, n2)]
array([[ 0, 1, 2, 3, 4],
[10, 11, 12, 13, 14],
[20, 21, 22, 23, 24],
[30, 31, 32, 33, 34],
[40, 41, 42, 43, 44]])... |
Subsetting a 2D numpy array | 30,917,753 | 10 | 2015-06-18T14:10:44Z | 30,918,530 | 7 | 2015-06-18T14:42:09Z | [
"python",
"numpy",
"multidimensional-array",
"subset"
] | I have looked into documentations and also other questions here, but it seems I
have not got the hang of subsetting in numpy arrays yet.
I have a numpy array,
and for the sake of argument, let it be defined as follows:
```
import numpy as np
a = np.arange(100)
a.shape = (10,10)
# array([[ 0, 1, 2, 3, 4, 5, 6, ... | You've gotten a handful of nice examples of how to do what you want. However, it's also useful to understand the what's happening and why things work the way they do. There are a few simple rules that will help you in the future.
There's a big difference between "fancy" indexing (i.e. using a list/sequence) and "norma... |
Python is returning false to "1"=="1". Any ideas why? | 30,923,049 | 3 | 2015-06-18T18:30:05Z | 30,923,219 | 7 | 2015-06-18T18:39:37Z | [
"python",
"string",
"file",
"integer",
"logic"
] | I've written a scout system for my A Level computing task. The program is designed to store information on scouts at a scout hut, including badges, have a leaderboard system, and a management system for adding/finding/deleting scouts from the list. The scout information MUST be stored in a file.
File handling process ... | By conversion to string, you hide the error.
Always try repr(value) instead of str(value) for debugging purposes. You should also know, that it is better to compare integers instead of strings -- e.g. " 1" != "1".
> Edit: From your output, it is clear that you have an extra '\n'
> (Newline) in the sctID. Because you ... |
Why loop variable is not updated in python | 30,923,241 | 2 | 2015-06-18T18:40:33Z | 30,923,278 | 9 | 2015-06-18T18:42:24Z | [
"python"
] | This code is only printing 1 2 4 5..My question is that why p is not updated with the new array at 3rd iteration
```
p = [1, 2, [1, 2, 3], 4, 5]
for each in p:
if type(each) == int:
print each
else:
p = each
```
Actually to be precise when debugged the code I saw that it actually updating the value of p b... | Because of `if type(each) == int:` line. Your third element is a list (`[1, 2, 3]`) and not an int, so it doesn't print anything.
Now what comes to changing the `p` variable: `p` is just a name for an object, not the object itself. If you do `p = each` inside the for loop, it doesn't affect the original object you're ... |
pandas dataframe drop columns by number of nan | 30,923,324 | 4 | 2015-06-18T18:45:05Z | 30,925,185 | 7 | 2015-06-18T20:26:02Z | [
"python",
"pandas"
] | I have a dataframe with some columns containing nan. I'd like to drop those columns with certain number of nan. For example, in the following code, I'd like to drop any column with 2 or more nan. In this case, column 'C' will be dropped and only 'A' and 'B' will be kept. How can I implement it?
```
import pandas as pd... | There is a `thresh` param for [`dropna`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html#pandas.DataFrame.dropna), you just need to pass the length of your df - the number of `NaN` values you want as your threshold:
```
In [13]:
dff.dropna(thresh=len(dff) - 2, axis=1)
Out[13]:
... |
What is the difference between Python's __add__ and __concat__? | 30,924,533 | 8 | 2015-06-18T19:51:31Z | 30,924,612 | 7 | 2015-06-18T19:55:34Z | [
"python",
"operators"
] | The list of Python's standard operators includes both `__add__(a, b)` and `__concat__(a, b)`. Both of them are usually invoked by `a + b`. My question is, what is the difference between them? Is there a scenario where one would be used rather than the other? Is there any reason you would define both on a single object?... | If you check the source for the `operator` module ([add](https://hg.python.org/cpython/file/af793c7580f1/Lib/operator.py#l75), [concat](https://hg.python.org/cpython/file/af793c7580f1/Lib/operator.py#l146)), you will find these definitions for those functions:
```
def add(a, b):
"Same as a + b."
return a + b
... |
Get a list of N items with K selections for each element? | 30,924,997 | 3 | 2015-06-18T20:15:51Z | 30,925,060 | 7 | 2015-06-18T20:18:59Z | [
"python",
"list",
"list-comprehension"
] | For example if I have a selection set K
```
K = ['a','b','c']
```
and a length N
```
N = 4
```
I want to return all possible:
```
['a','a','a','a']
['a','a','a','b']
['a','a','a','c']
['a','a','b','a']
...
['c','c','c','c']
```
I can do it with recursion but it is not interesting. Is there a more Pythonic way? | That can be done with [`itertools`](https://docs.python.org/2/library/itertools.html).
```
>>> K = ['a','b','c']
>>> import itertools
>>> N = 4
>>> i = itertools.product(K,repeat = N)
>>> l = [a for a in i]
>>> l[:3]
[('a', 'a', 'a', 'a'), ('a', 'a', 'a', 'b'), ('a', 'a', 'a', 'c')]
```
EDIT: I realized you actually ... |
Pandas: Add multiple empty columns to DataFrame | 30,926,670 | 12 | 2015-06-18T22:09:43Z | 30,926,717 | 13 | 2015-06-18T22:13:41Z | [
"python",
"pandas"
] | This may be a stupid question, but how do I add multiple empty columns to a DataFrame from a list?
I can do:
```
df["B"] = None
df["C"] = None
df["D"] = None
```
But I can't do:
```
df[["B", "C", "D"]] = None
KeyError: "['B' 'C' 'D'] not in index"
``` | I'd [`concat`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html#pandas.concat) using a DataFrame ctor:
```
In [23]:
df = pd.DataFrame(columns=['A'])
df
Out[23]:
Empty DataFrame
Columns: [A]
Index: []
In [24]:
pd.concat([df,pd.DataFrame(columns=list('BCD'))])
Out[24]:
Empty DataFrame
Colu... |
Pandas: Add multiple empty columns to DataFrame | 30,926,670 | 12 | 2015-06-18T22:09:43Z | 30,943,503 | 15 | 2015-06-19T17:00:52Z | [
"python",
"pandas"
] | This may be a stupid question, but how do I add multiple empty columns to a DataFrame from a list?
I can do:
```
df["B"] = None
df["C"] = None
df["D"] = None
```
But I can't do:
```
df[["B", "C", "D"]] = None
KeyError: "['B' 'C' 'D'] not in index"
``` | You could use [`df.reindex`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.reindex.html) to add new columns:
```
In [18]: df = pd.DataFrame(np.random.randint(10, size=(5,1)), columns=['A'])
In [19]: df
Out[19]:
A
0 4
1 7
2 0
3 7
4 6
In [20]: df.reindex(columns=list('ABCD'))
Out[20]:
... |
A python script that activates the virtualenv and then runs another python script? | 30,927,567 | 8 | 2015-06-18T23:32:57Z | 30,927,921 | 7 | 2015-06-19T00:10:15Z | [
"python",
"windows",
"shell",
"command",
"virtualenv"
] | On windows vista, I need a script that starts the `activate` (to activate the virtualenv) script in
```
C:\Users\Admin\Desktop\venv\Scripts\
```
And later, in the virtual environment, starts to the `manage.py runserver`
in the folder :
```
C:\Users\Admin\Desktop\helloworld\
```
how should I do? What modules should ... | You can activate your virtualenv and then start server using a bat file.
Copy this script in to a file and save it with .bat extension (eg. runserver.bat)
```
@echo off
cmd /k "cd /d C:\Users\Admin\Desktop\venv\Scripts & activate & cd /d C:\Users\Admin\Desktop\helloworld & python manage.py runserver"
```
Then you ... |
Cache busting in Django 1.8? | 30,936,151 | 3 | 2015-06-19T10:42:18Z | 30,940,958 | 7 | 2015-06-19T14:41:10Z | [
"python",
"django"
] | I'm using Django 1.8 and I want to add a parameter to my static files to cache bust.
This is what I'm doing right now, setting a manual parameter:
```
<link href="{% static 'css/openprescribing.css' %}?q=0.1.1" rel="stylesheet">
```
But I feel there must be a better way to update the parameter.
I guess it would be ... | Yes this can be done automatically with `contrib.staticfiles`. There are two additional provided storage classes which will rename files using a hash. These
are documented here: [ManifestStaticFilesStorage](https://docs.djangoproject.com/en/1.8/ref/contrib/staticfiles/#manifeststaticfilesstorage) and [CachedStaticFiles... |
How to properly write coss-references to external documentation with intersphinx? | 30,939,867 | 8 | 2015-06-19T13:50:26Z | 30,981,554 | 12 | 2015-06-22T13:43:34Z | [
"python",
"opencv",
"documentation",
"python-sphinx",
"autodoc"
] | I'm trying to add cross-references to external API into my documentation but I'm facing three different behaviors.
I am using sphinx(1.3.1) with Python(2.3.7) and my intersphinx mapping is configured as:
```
{
'python': ('https://docs.python.org/2.7', None),
'numpy': ('http://docs.scipy.org/doc/numpy/', None),
'cv2' ... | I gave another try on trying to understand the content of an `objects.inv` file and hopefully this time I inspected numpy and h5py instead of only OpenCV's one.
## How to read an intersphinx inventory file
Despite the fact that I couldn't find anything useful about reading the content of an `object.inv` file, it is a... |
psycopg2: AttributeError: 'module' object has no attribute 'extras' | 30,940,167 | 17 | 2015-06-19T14:04:22Z | 30,940,250 | 26 | 2015-06-19T14:08:17Z | [
"python",
"psycopg2",
"importerror"
] | In my code I use the [`DictCursor`](http://initd.org/psycopg/docs/extras.html#dictionary-like-cursor) from `psycopg2.extras` like this
```
dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
```
However, all of the sudden I get the following error when I load the cursor:
```
AttributeError: 'module' ob... | You need to explicitly import `psycopg2.extras`:
```
import psycopg2.extras
``` |
Python capture all printed output | 30,942,622 | 10 | 2015-06-19T16:08:15Z | 30,942,680 | 9 | 2015-06-19T16:11:20Z | [
"python",
"piping"
] | I am looking to write console based programs in python that can execute functions to perform generic tasks, pretty generic. Is it possible to capture everything written to the console by print calls in a function without needing to return a string, similar to how bash and the windows shell allow piping the output of a ... | You can do this by setting `sys.stdout` to be a file of your choice
```
import sys
sys.stdout = open('out.dat', 'w')
print "Hello"
sys.stdout.close()
```
Will not display any output but will create a file called `out.dat` with the printed text.
Note that this doesn't need to be an actual file but could be a [Strin... |
multiprocessing.Pool with maxtasksperchild produces equal PIDs | 30,943,161 | 6 | 2015-06-19T16:40:40Z | 30,943,203 | 7 | 2015-06-19T16:43:41Z | [
"python",
"python-3.x",
"multiprocessing",
"pid"
] | I need to run a function in a process, which is completely isolated from all other memory, several times. I would like to use `multiprocessing` for that (since I need to serialize a complex output coming from the functions). I set the `start_method` to `'spawn'` and use a pool with `maxtasksperchild=1`. I would expect ... | You need to also specify `chunksize=1` in the call to `pool.map`. Otherwise, multiple items in your iterable get bundled together into one "task" from the perception of the worker processes:
```
import multiprocessing
import time
import os
def f(x):
print("PID: %d" % os.getpid())
time.sleep(x)
complex_obj... |
Why is single int 24 bytes, but in list it tends to 8 bytes | 30,946,955 | 5 | 2015-06-19T20:42:11Z | 30,947,014 | 8 | 2015-06-19T20:46:30Z | [
"python"
] | Here is what I am looking at:
```
In [1]: import sys
In [2]: sys.getsizeof(45)
Out[2]: 24
In [3]: sys.getsizeof([])
Out[3]: 72
In [4]: sys.getsizeof(range(1000))
Out[4]: 8072
```
I know that `int` in Python is growable (can get bigger that 24 bytes) objects that live on the heap, and I see why that object can be q... | This is the size of the object - [excluding the objects it contains](https://docs.python.org/3/library/sys.html#sys.getsizeof):
```
>>> d = range(10)
>>> sys.getsizeof(d)
152
>>> d[0] = 'text'
>>> sys.getsizeof(d)
152
>>> d
['text', 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
The size of the list with 1000 elements, in your case,... |
Why is single int 24 bytes, but in list it tends to 8 bytes | 30,946,955 | 5 | 2015-06-19T20:42:11Z | 30,947,030 | 7 | 2015-06-19T20:47:29Z | [
"python"
] | Here is what I am looking at:
```
In [1]: import sys
In [2]: sys.getsizeof(45)
Out[2]: 24
In [3]: sys.getsizeof([])
Out[3]: 72
In [4]: sys.getsizeof(range(1000))
Out[4]: 8072
```
I know that `int` in Python is growable (can get bigger that 24 bytes) objects that live on the heap, and I see why that object can be q... | The list doesn't contain any integers; it contains pointers to various objects, which happen to be integers and which are stored elsewhere. `getsizeof()` tells you the size only of the object you pass to it, not of any additional objects it points to. |
Why does '12345'.count('') return 6 and not 5? | 30,948,282 | 34 | 2015-06-19T22:38:48Z | 30,948,301 | 28 | 2015-06-19T22:41:04Z | [
"python",
"python-3.x",
"count"
] | ```
>>> '12345'.count('')
6
```
Why does this happen? If there are only 5 characters in that string, why is the count function returning one more?
Also, is there a more effective way of counting characters in a string? | That is because there are six different substrings that are the empty string: Before the 1, between the numbers, and after the 5.
If you want to count characters use `len` instead:
```
>>> len("12345")
5
``` |
Why does '12345'.count('') return 6 and not 5? | 30,948,282 | 34 | 2015-06-19T22:38:48Z | 30,948,311 | 25 | 2015-06-19T22:41:35Z | [
"python",
"python-3.x",
"count"
] | ```
>>> '12345'.count('')
6
```
Why does this happen? If there are only 5 characters in that string, why is the count function returning one more?
Also, is there a more effective way of counting characters in a string? | How many pieces do you get if you cut a string five times?
```
---|---|---|---|---|--- -> 6 pieces
```
The same thing is happening here. It counts the empty string after the `5` also.
`len('12345')` is what you should use. |
Why does '12345'.count('') return 6 and not 5? | 30,948,282 | 34 | 2015-06-19T22:38:48Z | 30,948,336 | 107 | 2015-06-19T22:43:39Z | [
"python",
"python-3.x",
"count"
] | ```
>>> '12345'.count('')
6
```
Why does this happen? If there are only 5 characters in that string, why is the count function returning one more?
Also, is there a more effective way of counting characters in a string? | `count` returns how many times an object occurs in a list, so if you count occurrences of `''` you get 6 because the empty string is at the beginning, end, and in between each letter.
Use the `len` function to find the length of a string. |
Django populate() isn't reentrant | 30,954,398 | 6 | 2015-06-20T13:11:37Z | 30,968,197 | 10 | 2015-06-21T18:58:31Z | [
"python",
"django",
"apache"
] | I keep getting this when I try to load my Django application on production . I tried all the stackoverflow answers but nothing has fixed it. Any other ideas. (I'm using Django 1.5.2 and Apache)
```
Traceback (most recent call last):
File "/var/www/thehomeboard/wwwhome/wsgi.py", line 37, in <module>
... | This RuntimeError first occured for me after upgrading to Django 1.7 (and still is present with Django 1.8). It is usually caused by an Django application which raises an error, but that error is swallowed somehow.
Here's a workaround which works for me. Add it to your wsgi.py and the *real* error should be logged:
`... |
Why is globals() a function in Python? | 30,958,904 | 13 | 2015-06-20T21:08:25Z | 30,958,981 | 17 | 2015-06-20T21:16:38Z | [
"python",
"global"
] | Python offers the function `globals()` to access a dictionary of all global variables. Why is that a function and not a variable? The following works:
```
g = globals()
g["foo"] = "bar"
print foo # Works and outputs "bar"
```
What is the rationale behind hiding globals in a function? And is it better to call it only ... | Because it may depend on the *Python implementation* how much work it is to build that dictionary.
In CPython, globals are kept in just another mapping, and calling the `globals()` function returns a reference to that mapping. But other Python implementations are free to create a separate dictionary for the object, as... |
Scrapy throws ImportError: cannot import name xmlrpc_client | 30,964,836 | 28 | 2015-06-21T13:06:56Z | 31,095,959 | 68 | 2015-06-28T03:47:37Z | [
"python",
"python-2.7",
"scrapy"
] | After install Scrapy via pip, and having `Python 2.7.10`:
```
scrapy
Traceback (most recent call last):
File "/usr/local/bin/scrapy", line 7, in <module>
from scrapy.cmdline import execute
File "/Library/Python/2.7/site-packages/scrapy/__init__.py", line 48,
in <module>
from scrapy.spiders import Spider
File "/Libra... | I've just fixed this issue on my OS X.
**Please backup your files first.**
```
sudo rm -rf /Library/Python/2.7/site-packages/six*
sudo rm -rf /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six*
sudo pip install six
```
Scrapy 1.0.0 is ready to go. |
Scrapy throws ImportError: cannot import name xmlrpc_client | 30,964,836 | 28 | 2015-06-21T13:06:56Z | 31,578,089 | 27 | 2015-07-23T04:19:43Z | [
"python",
"python-2.7",
"scrapy"
] | After install Scrapy via pip, and having `Python 2.7.10`:
```
scrapy
Traceback (most recent call last):
File "/usr/local/bin/scrapy", line 7, in <module>
from scrapy.cmdline import execute
File "/Library/Python/2.7/site-packages/scrapy/__init__.py", line 48,
in <module>
from scrapy.spiders import Spider
File "/Libra... | This is a known issue on Mac OSX for Scrapy. You can refer to [this link](https://github.com/scrapy/scrapy/commit/e645d6a01e53af35e27b47ed80cfd6f9282f50b2).
Basically the issue is with the PYTHONPATH in your system. To solve the issue change the current PYTHONPATH to point to the newer or none Mac OSX version of Pytho... |
Scrapy throws ImportError: cannot import name xmlrpc_client | 30,964,836 | 28 | 2015-06-21T13:06:56Z | 31,635,775 | 18 | 2015-07-26T10:12:26Z | [
"python",
"python-2.7",
"scrapy"
] | After install Scrapy via pip, and having `Python 2.7.10`:
```
scrapy
Traceback (most recent call last):
File "/usr/local/bin/scrapy", line 7, in <module>
from scrapy.cmdline import execute
File "/Library/Python/2.7/site-packages/scrapy/__init__.py", line 48,
in <module>
from scrapy.spiders import Spider
File "/Libra... | I had the same exact problem when upgrading to Scrapy 1.0. After numerous work arounds the solution that worked for me was uninstalling six with pip:
> sudo pip uninstall six
then re-installing six via easy\_install
> easy\_install six
Hope that works! |
Trivial functors | 30,964,994 | 7 | 2015-06-21T13:23:14Z | 30,965,000 | 11 | 2015-06-21T13:23:57Z | [
"python",
"python-3.x",
"functor"
] | I very often write code like:
```
sorted(some_dict.items(), key=lambda x: x[1])
sorted(list_of_dicts, key=lambda x: x['age'])
map(lambda x: x.name, rows)
```
where I would like to write:
```
sorted(some_dict.items(), key=idx_f(1))
sorted(list_of_dicts, key=idx_f('name'))
map(attr_f('name'), rows)
```
using:
```
de... | The `operator` module has [`operator.attrgetter()`](https://docs.python.org/3/library/operator.html#operator.attrgetter) and [`operator.itemgetter()`](https://docs.python.org/3/library/operator.html#operator.attrgetter) that do just that:
```
from operator import attrgetter, itemgetter
sorted(some_dict.items(), key=i... |
Fraction object doesn't have __int__ but int(Fraction(...)) still works | 30,966,227 | 4 | 2015-06-21T15:32:08Z | 30,966,278 | 8 | 2015-06-21T15:38:23Z | [
"python",
"int",
"fractions",
"python-internals"
] | In Python, when you have an object you can convert it to an integer using the `int` function.
For example `int(1.3)` will return `1`. This works internally by using the `__int__` magic method of the object, in this particular case `float.__int__`.
In Python `Fraction` objects can be used to construct exact fractions.... | The `__trunc__` method is used.
```
>>> class X(object):
def __trunc__(self):
return 2.
>>> int(X())
2
```
`__float__` does not work
```
>>> class X(object):
def __float__(self):
return 2.
>>> int(X())
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
int(X()... |
Eclipse, PyDev "Project interpreter not specifiedâ | 30,970,697 | 6 | 2015-06-22T00:30:59Z | 34,992,568 | 11 | 2016-01-25T12:24:13Z | [
"python",
"eclipse",
"pydev",
"interpreter"
] | I have installed PyDev in eclipse Luna. After successful installation of PyDev, when I want to create a new project I get the error:
Project interpreter not specified
How can I fix it? There is no option for interpreter to choose from.
eclipse version Luna,
Mac OSX Yosemite,
PyDev latest version (installed according ... | In my case it has worked with following steps
Prerequisite: Python should be installed
1. Go to Window -> Preferences -> PyDev -> Interpreters and click on "Python Interpreter".
2. Then click on new button and add python executable location.
> Example for windows:
>
> ```
> c:\python2.7\python.exe
> ```
>
> example ... |
How does the class_weight parameter in scikit-learn work? | 30,972,029 | 13 | 2015-06-22T04:11:59Z | 30,982,811 | 10 | 2015-06-22T14:39:31Z | [
"python",
"scikit-learn"
] | I am having a lot of trouble understanding how the `class_weight` parameter in scikit-learn's Logistic Regression operates.
**The Situation**
I want to use logistic regression to do binary classification on a very unbalanced data set. The classes are labelled 0 (negative) and 1 (positive) and the observed data is in ... | First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class.
I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.
For h... |
Why is using a generator function twice as fast in this case? | 30,973,746 | 10 | 2015-06-22T06:58:59Z | 30,974,243 | 8 | 2015-06-22T07:30:19Z | [
"python",
"performance",
"generator"
] | # The code which is common for both the implementations:
```
from math import sqrt
def factors(x):
num = 2
sq = int(sqrt(x))
for i in range(2, sq):
if (x % i) == 0:
num += 2
return num + ((1 if sq == sqrt(x) else 2) if x % sq == 0 else 0)
```
# 1. Implementation which doesn't make... | In the explicit case you're not taking the `int` of the expression before calling `factors` and therefore the value passed will be a floating-point number.
In the generator case you're instead yielding `int(...)`, calling `factors` passing an integer number. |
Why is using a generator function twice as fast in this case? | 30,973,746 | 10 | 2015-06-22T06:58:59Z | 30,974,391 | 10 | 2015-06-22T07:38:58Z | [
"python",
"performance",
"generator"
] | # The code which is common for both the implementations:
```
from math import sqrt
def factors(x):
num = 2
sq = int(sqrt(x))
for i in range(2, sq):
if (x % i) == 0:
num += 2
return num + ((1 if sq == sqrt(x) else 2) if x % sq == 0 else 0)
```
# 1. Implementation which doesn't make... | temp1():
```
def temp1():
i = 1
while True:
if factors(i * (i+1) * 0.5) > 500:
print(int(i * (i+1) * 0.5))
break
i += 1
```
temp2():
```
def temp2():
def triangle():
i = 1
while True:
yield int(0.5 * i * (i + 1))
... |
How to use JDBC source to write and read data in (Py)Spark? | 30,983,982 | 8 | 2015-06-22T15:30:15Z | 30,983,983 | 21 | 2015-06-22T15:30:15Z | [
"python",
"scala",
"apache-spark",
"apache-spark-sql",
"pyspark"
] | The goal of this question is to document:
* steps required to read and write data using JDBC connections in PySpark
* possible issues with JDBC sources and know solutions
With small changes these methods should work with other supported languages including Scala and R. | ## Writing data
1. Include applicable JDBC driver when you submit the application or start shell. You can use for example `--packages`:
```
bin/pyspark --packages group:name:version
```
or combining `driver-class-path` and `jars`
```
bin/pyspark --driver-class-path $PATH_TO_DRIVER_JAR --jars $PATH... |
Convert Rust vector of tuples to a C compatible structure | 30,984,688 | 16 | 2015-06-22T16:03:57Z | 30,992,210 | 16 | 2015-06-23T00:57:23Z | [
"python",
"rust",
"ctypes"
] | Following [these](http://stackoverflow.com/questions/30312885/pass-python-list-to-embedded-rust-function?lq=1) [answers](http://stackoverflow.com/questions/29182843/pass-a-c-array-to-a-rust-function), I've currently defined a Rust 1.0 function as follows, in order to be callable from Python using `ctypes`:
```
use std... | The most important thing to note is that there is **no such thing** as a tuple in C. C is the *lingua franca* of library interoperability, and you will be required to restrict yourself to abilities of this language. It doesn't matter if you are talking between Rust and another high-level language; you have to speak C.
... |
Python regular expression, matching the last word | 30,986,345 | 4 | 2015-06-22T17:36:17Z | 30,986,390 | 7 | 2015-06-22T17:39:00Z | [
"python",
"regex",
"list"
] | I've the following problem. I'm looking to find all words in a string that typically looks like so
`HelloWorldToYou`
Notice, each word is capitalized as a start followed by the next word and so on.
I'm looking to create a list of words from it. So the final expected output is a list that looks like
```
['Hello','World... | Use the alternation with `$`:
```
import re
mystr = 'HelloWorldToYou'
pat = re.compile(r'([A-Z][a-z]*)')
# or your version with `.*?`: pat = re.compile(r'([A-Z].*?)(?=[A-Z]+|$)')
print pat.findall(mystr)
```
See [IDEONE demo](https://ideone.com/Qf5mpx)
Output:
```
['Hello', 'World', 'To', 'You']
```
**Regex explan... |
Double Asterisk | 30,987,462 | 2 | 2015-06-22T18:42:58Z | 30,988,340 | 9 | 2015-06-22T19:34:56Z | [
"python"
] | I'm new to Python and really stumped on this. I'm reading from a book and the code works fine; I just don't get it!
```
T[i+1] = m*v[i+1]Ë**/L
```
What's with the double asterisk part of this code? It's even followed by a forward slash. The variable L is initialized with the value 1.0 However, it looks like someone ... | This code is from the book "Elementary Mechanics Using Python: A Modern Course Combining Analytical and Numerical Techniques".
According to the formula on the page 255:

So the Python line should be:
```
T[i+1] = m*v[i+1]**2/L + m*g*cos(s[i+1]/L)
``... |
Support vector machine in Python using libsvm example of features | 30,991,592 | 5 | 2015-06-22T23:34:10Z | 31,093,946 | 10 | 2015-06-27T22:00:00Z | [
"python",
"machine-learning",
"svm",
"libsvm"
] | I have scraped a lot of ebay titles like this one:
```
Apple iPhone 5 White 16GB Dual-Core
```
and I have manually tagged all of them in this way
```
B M C S NA
```
where B=Brand (Apple) M=Model (iPhone 5) C=Color (White) S=Size (Size) NA=Not Assigned (Dual Core)
Now I need to train a SVM classifier using the libs... | Here's a step-by-step guide for how to train an SVM using your data and then evaluate using the same dataset. It's also available at <http://nbviewer.ipython.org/gist/anonymous/2cf3b993aab10bf26d5f>. At the url you can also see the output of the intermediate data and the resulting accuracy (it's an [iPython notebook](h... |
Weird numpy.sum behavior when adding zeros | 30,998,305 | 21 | 2015-06-23T09:00:24Z | 31,072,639 | 7 | 2015-06-26T11:57:47Z | [
"python",
"numpy",
"sum",
"numerical-stability"
] | I understand how mathematically-equivalent arithmentic operations can result in different results due to numerical errors (e.g. summing floats in different orders).
However, it surprises me that adding zeros to `sum` can change the result. I thought that this always holds for floats, no matter what: `x + 0. == x`.
He... | **Short answer:** You are seeing the difference between
```
a + b + c + d
```
and
```
(a + b) + (c + d)
```
which because of floating point inaccuracies is not the same.
**Long answer:** Numpy implements pair-wise summation as an optimization of both speed (it allows for easier vectorization) and rounding error.
... |
Check if a list is a rotation of another list that works with duplicates | 31,000,591 | 17 | 2015-06-23T10:41:22Z | 31,000,688 | 7 | 2015-06-23T10:46:13Z | [
"python",
"arrays",
"algorithm",
"time-complexity"
] | I have this function for determining if a list is a rotation of another list:
```
def isRotation(a,b):
if len(a) != len(b):
return False
c=b*2
i=0
while a[0] != c[i]:
i+=1
for x in a:
if x!= c[i]:
return False
i+=1
return True
```
e.g.
```
>>> a = [1,2,3]
>>> b = [2,3,1]
>>> isR... | I think you could use something like this:
```
a1 = [3,4,5,1,2,4,2]
a2 = [4,5,1,2,4,2,3]
# Array a2 is rotation of array a1 if it's sublist of a1+a1
def is_rotation(a1, a2):
if len(a1) != len(a2):
return False
double_array = a1 + a1
return check_sublist(double_array, a2)
def check_sublist(a1, a2):
... |
Check if a list is a rotation of another list that works with duplicates | 31,000,591 | 17 | 2015-06-23T10:41:22Z | 31,000,695 | 28 | 2015-06-23T10:46:36Z | [
"python",
"arrays",
"algorithm",
"time-complexity"
] | I have this function for determining if a list is a rotation of another list:
```
def isRotation(a,b):
if len(a) != len(b):
return False
c=b*2
i=0
while a[0] != c[i]:
i+=1
for x in a:
if x!= c[i]:
return False
i+=1
return True
```
e.g.
```
>>> a = [1,2,3]
>>> b = [2,3,1]
>>> isR... | The following meta-algorithm will solve it.
* Build a concatenation of `a`, e.g., `a = [3,1,2,3,4]` => `aa = [3,1,2,3,4,3,1,2,3,4]`.
* Run any string adaptation of a string-matching algorithm, e.g., [Boyer Moore](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm) to find `b` in `aa`.
---
One ... |
Check if a list is a rotation of another list that works with duplicates | 31,000,591 | 17 | 2015-06-23T10:41:22Z | 31,001,317 | 13 | 2015-06-23T11:16:35Z | [
"python",
"arrays",
"algorithm",
"time-complexity"
] | I have this function for determining if a list is a rotation of another list:
```
def isRotation(a,b):
if len(a) != len(b):
return False
c=b*2
i=0
while a[0] != c[i]:
i+=1
for x in a:
if x!= c[i]:
return False
i+=1
return True
```
e.g.
```
>>> a = [1,2,3]
>>> b = [2,3,1]
>>> isR... | You can do it in `0(n)` time and `0(1)` space using a modified version of a maximal suffixes algorithm:
From [Jewels of Stringology](https://books.google.ie/books?id=9NdohJXtIyYC&lpg=PA139&ots=ln6d-CM3Gb&dq=Equivalence%20of%20cyclic%20two%20words&pg=PA139#v=onepage&q=Equivalence%20of%20cyclic%20two%20words&f=false):
*... |
Reddit search API not giving all results | 31,000,892 | 4 | 2015-06-23T10:56:22Z | 31,093,573 | 7 | 2015-06-27T21:12:29Z | [
"python",
"python-2.7",
"praw"
] | ```
import praw
def get_data_reddit(search):
username=""
password=""
r = praw.Reddit(user_agent='')
r.login(username,password,disable_warning=True)
posts=r.search(search, subreddit=None,sort=None, syntax=None,period=None,limit=None)
title=[]
for post in posts:
title.append(post.titl... | Limiting results on a search or list is a common tactic for reducing load on servers. The reddit API is clear that this is what it does (as you have already flagged). However it doesn't stop there...
The API also supports a variation of paged results for listings. Since it is a constantly changing database, they don't... |
What is python-dev package used for | 31,002,091 | 9 | 2015-06-23T11:54:12Z | 31,002,176 | 7 | 2015-06-23T11:58:34Z | [
"python",
"cpython"
] | I recently installed `lxml`.
Before that I had to install all the dependencies for that.
So I tried to install `liblxml2-dev`, `liblxslt1-dev` and `python-dev`
(google searched for what packages are required for `lxml`)
but even after that I could not able to install `lxml` by using the command
`pip install lxml`.
H... | python-dev contains the header files you need to build Python extensions. lxml is a Python C-API extension that is compiled when you do `pip install lxml`. The lxml sources have at least something like `#include <Python.h>` in the code. The compiler looks for the Python.h file during compilation, hence those files need... |
Stopping list selection in Python 2.7 | 31,003,486 | 11 | 2015-06-23T12:59:20Z | 31,003,579 | 23 | 2015-06-23T13:03:41Z | [
"python",
"list",
"python-2.7"
] | Imagine that I have an order list of tuples:
```
s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)]
```
Given a parameter `X`, I want to select all the tuples that have a first element equal or greater than `X` up to but not including the first tuple that has -1 as the second element.
For example, if `... | You can simply filter the tuples from the list as a generator expression and then you can stop taking the values from the generator expression when you get the first tuple whose second element is `-1`, like this
```
>>> s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)]
>>> from itertools import takewhil... |
My Django installs in virtual env are missing admin templates folder | 31,009,216 | 10 | 2015-06-23T17:12:21Z | 34,532,454 | 9 | 2015-12-30T15:36:01Z | [
"python",
"django"
] | When I Install a venv and install Django in it for example "DjangoUpgrade" then I am missing at this path the templates folder
```
:~/.venvs/DjangoUpgrade/local/lib/python2.7/site-packages/django/contrib/admin
```
Just to be clear this is the ls from that folder.
`actions.py exceptions.py filters.py forms.py helpers... | To solve this issue you should use "--no-binary" while installing django.
```
pip install --no-binary django -r requirements.txt
```
or
```
pip install --no-binary django django==1.4.21
```
Remember to upgrade your PIP installation to have the "--no-binary" option.
You can get further information in this link:
<ht... |
Iterate over list of values dictionary | 31,018,651 | 3 | 2015-06-24T05:55:54Z | 31,018,728 | 13 | 2015-06-24T06:00:54Z | [
"python",
"dictionary"
] | I have a dict like this
```
data = {
'a': [95, 93, 90],
'b': [643, 611, 610]
}
```
I want to iterate over the dict and fetch key and value from list of values for each item, something like this
```
{'a': 95, 'b': 643}
{'a': 93, 'b': 611}
{'a': 90, 'b': 610}
```
I have implemented the logic for this and it w... | Try something like this -
```
>>> data = {
... 'a': [95, 93, 90],
... 'b': [643, 611, 610]
... }
>>> lst = list(data.items())
>>> lst1 = list(zip(*[i[1] for i in lst]))
>>> lst1
[(95, 643), (93, 611), (90, 610)]
>>> newlist = []
>>> for aval, bval in lst1:
... newlist.append({lst[0][0]:aval , lst[1][0]:bva... |
Python: issue when using vars() dictionary | 31,020,065 | 12 | 2015-06-24T07:13:46Z | 31,020,173 | 9 | 2015-06-24T07:19:04Z | [
"python",
"dictionary"
] | I have the following snippet:
```
a, b = 1, 2
params = ['a', 'b']
res = {p: vars()[p] for p in params}
```
Which gives me `KeyError: 'a'` whereas the following code works fine:
```
a, b = 1, 2
params = ['a', 'b']
res = {}
for p in params:
res[p] = vars()[p]
```
What's the difference here? | [`vars()`](https://docs.python.org/2/library/functions.html#vars) without any argument acts like `locals()` and since a dictionary comprehension has its own scope it has no variable named `a` or `b`.
You can use [`eval()`](https://docs.python.org/2/library/functions.html#eval) here. Without any argument it will execut... |
Python if not == vs if != | 31,026,754 | 125 | 2015-06-24T12:35:39Z | 31,026,976 | 168 | 2015-06-24T12:45:34Z | [
"python",
"if-statement",
"equality"
] | What is the difference between these two lines of code:
```
if not x == 'val':
```
and
```
if x != 'val':
```
Is one more efficient than the other?
Would it be better to use
```
if x == 'val':
pass
else:
``` | Using [`dis`](https://docs.python.org/2/library/dis.html) to look at the bytecode generated for the two versions:
**`not ==`**
```
4 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 2 (==)
9 UNARY_NOT
... |
Python if not == vs if != | 31,026,754 | 125 | 2015-06-24T12:35:39Z | 31,027,250 | 22 | 2015-06-24T12:58:09Z | [
"python",
"if-statement",
"equality"
] | What is the difference between these two lines of code:
```
if not x == 'val':
```
and
```
if x != 'val':
```
Is one more efficient than the other?
Would it be better to use
```
if x == 'val':
pass
else:
``` | @jonrsharpe has an excellent explanation of what's going on. I thought I'd just show the difference in time when running each of the 3 options 10,000,000 times (enough for a slight difference to show).
Code used:
```
def a(x):
if x != 'val':
pass
def b(x):
if not x == 'val':
pass
def c(x):... |
What's the difference between type hinting in 3.3 and 3.5? | 31,029,343 | 6 | 2015-06-24T14:27:46Z | 31,029,363 | 8 | 2015-06-24T14:28:37Z | [
"python",
"python-3.x",
"type-hinting",
"python-3.5"
] | I keep hearing how type hinting will be a new feature in 3.5, but that makes me wonder what the arrow indicator (->) was in 3.3?
You can see it in the [3.3 grammar spec here,](https://docs.python.org/3.3/reference/grammar.html) which I found from [this question asked 2 years ago.](http://stackoverflow.com/questions/14... | The `->` is used for *annotations*. [One of the use cases for annotations](https://www.python.org/dev/peps/pep-3107/#use-cases) is type hinting.
Python 3.0 added annotations, Python 3.5 builds on that feature by introducing type hinting, standardising the feature.
The relevant PEP (Python Enhancement Proposals) are:
... |
Plotting categorical data with pandas and matplotlib | 31,029,560 | 12 | 2015-06-24T14:37:16Z | 31,029,857 | 17 | 2015-06-24T14:50:53Z | [
"python",
"pandas"
] | I have a data frame with categorical data:
```
colour direction
1 red up
2 blue up
3 green down
4 red left
5 red right
6 yellow down
7 blue down
```
and now I want to generate some graphs, like pie charts and histograns based on the categories. Is it possible without cr... | You can simply use `value_counts` on the series:
```
df.colour.value_counts().plot(kind='bar')
```
[](http://i.stack.imgur.com/ouoSE.png) |
Why is PyMongo 3 giving ServerSelectionTimeoutError? | 31,030,307 | 10 | 2015-06-24T15:11:20Z | 31,194,981 | 14 | 2015-07-02T21:31:45Z | [
"python",
"mongodb",
"uwsgi",
"mongolab",
"pymongo-3.x"
] | I'm using:
* Python 3.4.2
* PyMongo 3.0.2
* mongolab running mongod 2.6.9
* uWSGI 2.0.10
* CherryPy 3.7.0
* nginx 1.6.2
uWSGI start params:
```
--socket 127.0.0.1:8081 --daemonize --enable-threads --threads 2 --processes 2
```
I setup my MongoClient ONE time:
```
self.mongo_client = MongoClient('mongodb://user:pw@... | We're investigating this problem, tracked in [PYTHON-961](https://jira.mongodb.org/browse/PYTHON-961). You may be able to work around the issue by passing ***connect=False*** when creating instances of MongoClient. That defers background connection until the first database operation is attempted, avoiding what I suspec... |
get the index of the last negative value in a 2d array per column | 31,031,355 | 21 | 2015-06-24T15:57:18Z | 31,085,940 | 8 | 2015-06-27T06:35:40Z | [
"python",
"arrays",
"numpy"
] | I'm trying to get the index of the last negative value of an array per column (in order to slice it after).
a simple working example on a 1d vector is :
```
import numpy as np
A = np.arange(10) - 5
A[2] = 2
print A # [-5 -4 2 -2 -1 0 1 2 3 4]
idx = np.max(np.where(A <= 0)[0])
print idx # 5
A[:idx] = 0
print A... | Assuming that you are looking to set all elements for each row until the last negative element to be set to zero (as per the expected output listed in the question for a sample case), two approaches could be suggested here.
**Approach #1**
This one is based on [`np.cumsum`](http://docs.scipy.org/doc/numpy/reference/g... |
get the index of the last negative value in a 2d array per column | 31,031,355 | 21 | 2015-06-24T15:57:18Z | 31,088,753 | 12 | 2015-06-27T12:27:29Z | [
"python",
"arrays",
"numpy"
] | I'm trying to get the index of the last negative value of an array per column (in order to slice it after).
a simple working example on a 1d vector is :
```
import numpy as np
A = np.arange(10) - 5
A[2] = 2
print A # [-5 -4 2 -2 -1 0 1 2 3 4]
idx = np.max(np.where(A <= 0)[0])
print idx # 5
A[:idx] = 0
print A... | You already have good answers, but I wanted to propose a potentially quicker variation using the function `np.maximum.accumulate`. Since your method for a 1D array uses `max`/`where`, you may also find this approach quite intuitive. (*Edit: quicker Cython implementation added below*).
The overall approach is very simi... |
Can you upload to S3 using a stream rather than a local file? | 31,031,463 | 9 | 2015-06-24T16:02:29Z | 31,054,669 | 7 | 2015-06-25T15:30:21Z | [
"python",
"csv",
"amazon-s3",
"boto",
"buffering"
] | I need to create a CSV and upload it to an S3 bucket. Since I'm creating the file on the fly, it would be better if I could write it directly to S3 bucket as it is being created rather than writing the whole file locally, and then uploading the file at the end.
Is there a way to do this? My project is in Python and I'... | I did find a solution to my question, which I will post here in case anyone else is interested. I decided to do this as parts in a multipart upload. You can't stream to S3. There is also a package available that changes your streaming file over to a multipart upload which I used: [Smart Open](https://github.com/piskvor... |
Pandas: Find max value in each row of a column and identify corresponding values in another column | 31,032,896 | 3 | 2015-06-24T17:12:44Z | 31,032,989 | 7 | 2015-06-24T17:17:42Z | [
"python",
"pandas"
] | I have a two pandas data frame columns, for which the values are lists of tuples such as:
```
df[âAâ].values
(1.55, 2.07, 2.20, 2.23)
(0.67, 1.10, 1.73, 1.35)
(2.92, 1.98, 2.30, 2.66)
```
and
```
df[âBâ].values
(1.55, 0.0086, 0.078, 0.12)
(0.672, 0.142, 0.0166, 0.0173)
(1.97, 0.0094, 0.1648, 0.016)
```
I wo... | ```
import pandas as pd
import numpy as np
df_dict = dict(A=[(1.55, 2.07, 2.20, 2.23), (0.67, 1.10, 1.73, 1.35), (2.92, 1.98, 2.30, 2.66)],
B=[(1.55, 0.0086, 0.078, 0.12), (0.672, 0.142, 0.0166, 0.0173), (1.97, 0.0094, 0.1648, 0.016)])
df = pd.DataFrame(df_dict)
Out[180]:
A ... |
pandas get column average | 31,037,298 | 5 | 2015-06-24T21:22:11Z | 31,037,360 | 15 | 2015-06-24T21:26:16Z | [
"python",
"pandas"
] | I can't get the average or mean of a column in pandas. A have a dataframe. Neither of things I tried below gives me the average of the column `weight`
```
>>> allDF
ID birthyear weight
0 619040 1962 0.1231231
1 600161 1963 0.981742
2 25602033 1963 ... | If you only want the mean of the `weight` column, select the column (which is a Series) and call `.mean()`:
```
In [479]: df
Out[479]:
ID birthyear weight
0 619040 1962 0.123123
1 600161 1963 0.981742
2 25602033 1963 1.312312
3 624870 1987 0.942120
In [480]: df["wei... |
Why is "1.real" a syntax error but "1 .real" valid in Python? | 31,037,609 | 21 | 2015-06-24T21:42:18Z | 31,037,690 | 11 | 2015-06-24T21:48:13Z | [
"python"
] | So I saw [these two](https://twitter.com/bmispelon/status/613816239622909953) [questions on twitter](https://twitter.com/bmispelon/status/613818391967715329). How is `1.real` a syntax error but `1 .real` is not?
```
>>> 1.real
File "<stdin>", line 1
1.real
^
SyntaxError: invalid syntax
>>> 1 .real
1
>>>... | With `1.real` Python is looking for a floating-point numeric literal like `1.0` and you can't have an `r` in a float. With `1 .real` Python has taken `1` as an integer and is doing the attribute lookup on that.
It's important to note that the floating-point syntax error handling happens before the `.` attribute lookup... |
Why is "1.real" a syntax error but "1 .real" valid in Python? | 31,037,609 | 21 | 2015-06-24T21:42:18Z | 31,037,917 | 42 | 2015-06-24T22:02:42Z | [
"python"
] | So I saw [these two](https://twitter.com/bmispelon/status/613816239622909953) [questions on twitter](https://twitter.com/bmispelon/status/613818391967715329). How is `1.real` a syntax error but `1 .real` is not?
```
>>> 1.real
File "<stdin>", line 1
1.real
^
SyntaxError: invalid syntax
>>> 1 .real
1
>>>... | I guess that the `.` is greedily parsed as part of a number, if possible, making it the `float` `1.`, instead of being part of the method call.
Spaces are not allowed around the decimal point, but you can have spaces before and after the `.` in a method call. If the number is followed by a space, the parse of the numb... |
Error with simple Python code | 31,038,208 | 3 | 2015-06-24T22:27:09Z | 31,038,288 | 7 | 2015-06-24T22:33:13Z | [
"python"
] | I have a simple python (version 2.7.3) code that has an output that I can't figure out. The code prompts the user for a score (and will continue to do so if the input is anything other than a number from 0 to 1), determines the letter grade, and then exits. The code is as follows:
```
def calc_grade():
try:
... | On any error that occurs, you call `calc_grade` recursively again, so if you entered an invalid input, you'd have several calls. Instead, you should handle faulty errors iteratively:
```
def calc_grade():
score = None
while score is None:
try:
score = float(raw_input("Enter a score: ")... |
Python multi-line with statement | 31,039,022 | 11 | 2015-06-24T23:49:35Z | 31,039,332 | 10 | 2015-06-25T00:29:57Z | [
"python",
"python-3.x",
"multiline",
"with-statement"
] | What is a clean way to create a multi-line `with` in python? I want to open up several files inside a single `with`, but it's far enough to the right that I want it on multiple lines. Like this:
```
class Dummy:
def __enter__(self): pass
def __exit__(self, type, value, traceback): pass
with Dummy() as a, Dumm... | Given that you've tagged this Python 3, if you need to intersperse comments with your context managers, I would use a [`contextlib.ExitStack`](https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack):
```
with ExitStack() as stack:
a = stack.enter_context(Dummy()) # Relevant comment
b = stack.en... |
Insert element in Python list after every nth element | 31,040,525 | 11 | 2015-06-25T03:05:20Z | 31,040,944 | 7 | 2015-06-25T03:56:38Z | [
"python",
"list",
"indexing",
"insert",
"slice"
] | Say I have a Python list like this:
```
letters = ['a','b','c','d','e','f','g','h','i','j']
```
I want to insert an 'x' after every nth element, let's say three characters in that list. The result should be:
```
letters = ['a','b','c','x','d','e','f','x','g','h','i','x','j']
```
I understand that I can do that with... | I've got two one liners.
Given:
```
>>> letters = ['a','b','c','d','e','f','g','h','i','j']
```
1. Use `enumerate` to get index, add `'x'` every 3rd letter, *eg*: `mod(n, 3) == 2`, then concatenate into string and `list()` it.
```
>>> list(''.join(l + 'x' * (n % 3 == 2) for n, l in enumerate(letters)))
['... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.