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 |
|---|---|---|---|---|---|---|---|---|---|
jupyter giving 404: Not Found error on WIndows 7 | 33,031,069 | 4 | 2015-10-09T06:11:42Z | 34,791,817 | 7 | 2016-01-14T14:18:08Z | [
"python",
"jupyter"
] | I installed anaconda PYTHON 2.7 64bit on Win 7 and then updated using
```
conda update conda
```
Later installed
```
conda install jupyter
```
When I tried to run from the same drive on windows using
```
jupyter notebook
```
it launches on Firefox and states
```
404: Not Found
```
On the command it says
```
Re... | I found a simple cause of this could be trying to run Jupyter from the root of a drive - running it from C:\ failed. Cricboy007's suggestion to create a folder (no particular name, I called mine notebook) and run Jupyter once you've used cd to make that the working directory worked for me. |
Add an empty column to spark DataFrame | 33,038,686 | 4 | 2015-10-09T12:45:43Z | 33,041,986 | 8 | 2015-10-09T15:24:05Z | [
"python",
"apache-spark",
"pyspark",
"pyspark-sql"
] | As mentioned in [many](http://stackoverflow.com/questions/29483498/append-a-column-to-data-frame-in-apache-spark-1-3) [other locations](http://apache-spark-user-list.1001560.n3.nabble.com/Append-column-to-Data-Frame-or-RDD-td22385.html) on the web, adding a new column to an existing DataFrame is not straightforward. Un... | All you need here is a literal and cast:
```
from pyspark.sql.functions import lit
new_df = old_df.withColumn('new_column', lit(None).cast(StringType()))
```
A full example:
```
df = sc.parallelize([row(1, "2"), row(2, "3")]).toDF()
df.printSchema()
## root
## |-- foo: long (nullable = true)
## |-- bar: string (... |
Why is the time complexity of python's list.append() method O(1)? | 33,044,883 | 6 | 2015-10-09T18:24:37Z | 33,044,923 | 7 | 2015-10-09T18:27:02Z | [
"python",
"python-2.7",
"time-complexity",
"amortized-analysis"
] | As seen in the documentation for [TimeComplexity](https://wiki.python.org/moin/TimeComplexity), Python's `list` type is implemented is using an array.
So if an array is being used and we do a few appends, eventually you will have to reallocate space and copy all the information to the new space.
After all that, how ... | If you look at the footnote in the document you linked, you can see that they include a caveat:
> These operations rely on the "Amortized" part of "Amortized Worst
> Case". Individual actions may take surprisingly long, depending on the
> history of the container.
Using [amortized analysis](https://en.wikipedia.org/w... |
How do you alias a type in python? | 33,045,222 | 3 | 2015-10-09T18:47:59Z | 33,045,252 | 7 | 2015-10-09T18:50:29Z | [
"python",
"alias"
] | In some (mostly functional) languages you can do something like this:
```
type row = list(datum)
```
or
```
type row = [datum]
```
So that we can build things like this:
```
type row = [datum]
type table = [row]
type database = [table]
```
Is there a way to do this in python? You could do it using classes, but py... | Since Python 3.5 you may use [typing](https://docs.python.org/3/library/typing.html) module.
Quoting docs,
A type alias is defined by assigning the type to the alias:
```
Vector = List[float]
```
To learn more about enforcing types in Python you may want to get familiar with PEPs: [PEP483](https://www.python.org/dev... |
NumPy exception when using MLlib even though Numpy is installed | 33,045,556 | 5 | 2015-10-09T19:12:48Z | 33,082,057 | 15 | 2015-10-12T13:12:27Z | [
"python",
"numpy",
"apache-spark",
"pyspark",
"apache-spark-mllib"
] | Here's the code I'm trying to execute:
```
from pyspark.mllib.recommendation import ALS
iterations=5
lambdaALS=0.1
seed=5L
rank=8
model=ALS.train(trainingRDD,rank,iterations, lambda_=lambdaALS, seed=seed)
```
When I run the `model=ALS.train(trainingRDD,rank,iterations, lambda_=lambdaALS, seed=seed)` command that depe... | It is a bug in Mllib init code
```
import numpy
if numpy.version.version < '1.4':
raise Exception("MLlib requires NumPy 1.4+")
```
'1.10' is < from '1.4'
You can use NumPy 1.9.2 .
If you have to use NumPy 1.10 and don't want to upgrade to spark 1.5.1 .
Do a manual update to the code.
[https://github.com/apache/s... |
Is there a better more readable way to coalese columns in pandas | 33,047,277 | 4 | 2015-10-09T21:16:47Z | 36,490,274 | 8 | 2016-04-08T02:01:36Z | [
"python",
"pandas"
] | I often need a new column that is the best I can achieve from other columns and I have a specific list of preference priorities. I am willing to take the first non null value.
```
def coalesce(values):
not_none = (el for el in values if el is not None)
return next(not_none, None)
df = pd.DataFrame([{'third':'... | The Pandas equivalent to `COALESCE` is the method `fillna()`:
```
result = column_a.fillna(column_b)
```
The result is a column where each value is taken from `column_a` if that column provides a non-null value, otherwise the value is taken from `column_b`. So your `combo1` can be produced with:
```
df['first'].fill... |
Python equivalent of Scala's exists() function? | 33,048,555 | 2 | 2015-10-09T23:29:58Z | 33,048,617 | 7 | 2015-10-09T23:37:52Z | [
"python",
"list",
"scala",
"exists"
] | Scala lists have an exists() function that returns a boolean if the list has an element that satisfies your predicate.
Is there a way to do this in python that's just as clean?
I've been using
```
if next(x for x in mylist if x > 10): return Something
```
Is there a better way? | Use [**`any`**](https://docs.python.org/2/library/functions.html#any):
```
if any(x > 10 for x in mylist):
return Something
```
You can complement this with [**`all`**](https://docs.python.org/2/library/functions.html#all), and use `not any` and `not all` to round it out.
Your way of using [**`next`**](https://d... |
Confusing about a Python min quiz | 33,049,388 | 15 | 2015-10-10T01:42:24Z | 33,049,433 | 9 | 2015-10-10T01:52:54Z | [
"python"
] | Just now I saw a quiz on [this page](https://github.com/cosmologicon/pywat/blob/master/quiz.md):
```
>>> x, y = ???
>>> min(x, y) == min(y, x)
False
```
The example answer is
```
x, y = {0}, {1}
```
From the documentation I know that:
> min(iterable[, key=func]) -> value
> min(a, b, c, ...[, key=func]) -> value
... | The comparison operators `<`, `<=`, `>=`, and `>` check whether one set is a strict subset, subset, superset, or strict superset of another, respectively.
`{0}` and `{1}` are `False` for all of these, so the result depends on the check order and operator. |
Confusing about a Python min quiz | 33,049,388 | 15 | 2015-10-10T01:42:24Z | 33,049,473 | 8 | 2015-10-10T01:59:26Z | [
"python"
] | Just now I saw a quiz on [this page](https://github.com/cosmologicon/pywat/blob/master/quiz.md):
```
>>> x, y = ???
>>> min(x, y) == min(y, x)
False
```
The example answer is
```
x, y = {0}, {1}
```
From the documentation I know that:
> min(iterable[, key=func]) -> value
> min(a, b, c, ...[, key=func]) -> value
... | The key point here is, the two sets are not subsets of each other, so both are `False` for `<` even though they are not equal:
```
>>> {0} < {1}
False
>>> {0} > {1}
False
>>> {0} == {1}
False
```
So which one is smaller? The fact that sets don't provide [**strict weak ordering**](https://en.wikipedia.org/wiki/Weak_or... |
Confusing about a Python min quiz | 33,049,388 | 15 | 2015-10-10T01:42:24Z | 33,049,550 | 7 | 2015-10-10T02:14:22Z | [
"python"
] | Just now I saw a quiz on [this page](https://github.com/cosmologicon/pywat/blob/master/quiz.md):
```
>>> x, y = ???
>>> min(x, y) == min(y, x)
False
```
The example answer is
```
x, y = {0}, {1}
```
From the documentation I know that:
> min(iterable[, key=func]) -> value
> min(a, b, c, ...[, key=func]) -> value
... | `min` is implemented roughly like this:
```
def min(*args):
least = args[0]
for arg in args:
if arg < least:
least = arg
return least
```
The way the comparison operators work for sets break one of the assumptions that this implicitly makes: that for every pair of objects, either they ... |
Accessing attributes on literals work on all types, but not `int`; why? | 33,054,229 | 43 | 2015-10-10T12:55:24Z | 10,955,711 | 39 | 2012-06-08T20:33:54Z | [
"python",
"python-2.7",
"python-3.x",
"language-lawyer"
] | I have read that everything in python is an object, and as such I started to experiment with different types and invoking *`__str__`* on them — at first I was feeling really excited, but then I got confused.
```
>>> "hello world".__str__()
'hello world'
>>> [].__str__()
'[]'
>>> 3.14.__str__()
'3.14'
>>> 3..__str__()
... | Add a space after the `4`:
```
4 .__str__()
```
Otherwise, the lexer will split this expression into the tokens `"4."`, `"__str__"`, `"("` and `")"`, i.e. the first token is interpreted as a floating point number. The lexer always tries to build the longest possible token. |
Accessing attributes on literals work on all types, but not `int`; why? | 33,054,229 | 43 | 2015-10-10T12:55:24Z | 10,955,713 | 84 | 2012-06-08T20:34:00Z | [
"python",
"python-2.7",
"python-3.x",
"language-lawyer"
] | I have read that everything in python is an object, and as such I started to experiment with different types and invoking *`__str__`* on them — at first I was feeling really excited, but then I got confused.
```
>>> "hello world".__str__()
'hello world'
>>> [].__str__()
'[]'
>>> 3.14.__str__()
'3.14'
>>> 3..__str__()
... | You need parens:
```
(4).__str__()
```
The problem is the lexer thinks "4." is going to be a floating-point number.
Also, this works:
```
x = 4
x.__str__()
``` |
Accessing attributes on literals work on all types, but not `int`; why? | 33,054,229 | 43 | 2015-10-10T12:55:24Z | 10,955,754 | 7 | 2012-06-08T20:38:16Z | [
"python",
"python-2.7",
"python-3.x",
"language-lawyer"
] | I have read that everything in python is an object, and as such I started to experiment with different types and invoking *`__str__`* on them — at first I was feeling really excited, but then I got confused.
```
>>> "hello world".__str__()
'hello world'
>>> [].__str__()
'[]'
>>> 3.14.__str__()
'3.14'
>>> 3..__str__()
... | actually (to increase unreadability...):
```
4..hex()
```
is valid, too. it gives `'0x1.0000000000000p+2'` -- but then it's a float, of course... |
Accessing attributes on literals work on all types, but not `int`; why? | 33,054,229 | 43 | 2015-10-10T12:55:24Z | 33,054,230 | 45 | 2015-10-10T12:55:24Z | [
"python",
"python-2.7",
"python-3.x",
"language-lawyer"
] | I have read that everything in python is an object, and as such I started to experiment with different types and invoking *`__str__`* on them — at first I was feeling really excited, but then I got confused.
```
>>> "hello world".__str__()
'hello world'
>>> [].__str__()
'[]'
>>> 3.14.__str__()
'3.14'
>>> 3..__str__()
... | ### So you think you can dance floating-point?
`123` is just as much of an object as `3.14`, the "problem" lies within the grammar rules of the language; the parser thinks we are about to define a *float* — not an *int* with a trailing method call.
We will get the expected behavior if we wrap the number in parenthe... |
python 3.5: TypeError: a bytes-like object is required, not 'str' | 33,054,527 | 42 | 2015-10-10T13:28:09Z | 33,054,552 | 45 | 2015-10-10T13:30:57Z | [
"python"
] | I've very recently migrated to Py 3.5.
This code was working properly in Python 2.7:
```
with open(fname, 'rb') as f:
lines = [x.strip() for x in f.readlines()]
for line in lines:
tmp = line.strip().lower()
if 'some-pattern' in tmp: continue
# ... code
```
After upgrading to 3.5, I'm getting the:
``... | You opened the file in binary mode:
```
with open(fname, 'rb') as f:
```
This means that all data read from the file is returned as `bytes` objects, not `str`. You cannot then use a string in a containment test:
```
if 'some-pattern' in tmp: continue
```
You'd have to use a `bytes` object to test against `tmp` inst... |
python function not working properly it doesn't return the values that user should be getting | 33,055,778 | 2 | 2015-10-10T15:43:50Z | 33,055,821 | 8 | 2015-10-10T15:49:09Z | [
"python"
] | ```
def divisors(n):
ans =0
for i in range(n):
i += 1
k=n%i
if k!=1:
ans=i
return ans
print(20)
```
I have a function that's not working properly when I run it prints the `n` value instead of printing out the divisors. | Three key issues are:
1. `k=n%i` returns the remainder - if the remainder != 1 it doesn't mean that `i` is a divisor!
2. in the for-loop you keep overriding `ans` and at the end of the function you return the value that was found on the last iteration that satisfied the `if` condition. What you want to do instead is t... |
Pandas Dataframe: Replacing NaN with row average | 33,058,590 | 3 | 2015-10-10T20:21:04Z | 33,058,777 | 7 | 2015-10-10T20:42:32Z | [
"python",
"pandas"
] | I am trying to learn pandas but i have been puzzled with the following please. I want to replace NaNs is a dataframe with the row average. Hence something like `df.fillna(df.mean(axis=1))` should work but for some reason it fails for me. Am I missing anything please, something I'm doing wrong? Is is because its not imp... | As commented the axis argument to fillna is [NotImplemented](https://github.com/pydata/pandas/issues/4514).
```
df.fillna(df.mean(axis=1), axis=1)
```
*Note: this would be critical here as you don't want to fill in your nth columns with the nth row average.*
For now you'll need to iterate through:
```
In [11]: m = ... |
How to execute a command in the terminal from a Python script? | 33,065,588 | 7 | 2015-10-11T13:34:12Z | 33,065,666 | 9 | 2015-10-11T13:41:49Z | [
"python",
"shell",
"python-2.7",
"terminal",
"ubuntu-14.04"
] | I want to execute a command in terminal from a Python script.
```
./driver.exe bondville.dat
```
This command is getting printed in the terminal, but it is failing to execute.
Here are my steps:
```
echo = "echo"
command="./driver.exe"+" "+"bondville.dat"
os.system(echo + " " + command)
```
It should execute the ... | The `echo` terminal command **echoes** its arguments, so printing the command to the terminal is the expected result.
Are you typing `echo driver.exe bondville.dat` and is it running your `driver.exe` program?
If not, then you need to get rid of the echo in the last line of your code:
```
os.system(command)
``` |
Cython speedup isn't as large as expected | 33,067,867 | 4 | 2015-10-11T17:19:22Z | 33,068,834 | 10 | 2015-10-11T18:52:59Z | [
"python",
"numpy",
"cython"
] | I have written a Python function that computes pairwise electromagnetic interactions between a largish number (N ~ 10^3) of particles and stores the results in an NxN complex128 ndarray. It runs, but it is the slowest part of a larger program, taking about 40 seconds when N=900 [corrected]. The original code looks like... | The real power of NumPy is in performing an operation across a huge number of elements in a vectorized manner instead of using that operation in chunks spread across loops. In your case, you are using two nested loops and one IF conditional statement. I would propose extending the dimensions of the intermediate arrays,... |
Boto3, python and how to handle errors | 33,068,055 | 19 | 2015-10-11T17:36:47Z | 33,663,484 | 41 | 2015-11-12T02:39:14Z | [
"python",
"amazon-web-services",
"boto",
"boto3"
] | I just picked up python as my go-to scripting language and I am trying to figure how to do proper error handling with boto3.
I am trying to create an IAM user:
```
def create_user(username, iam_conn):
try:
user = iam_conn.create_user(UserName=username)
return user
except Exception as e:
... | Use the response contained within the exception. Here is an example:
```
import boto3
import botocore
try:
iam = boto3.client('iam')
user = iam.create_user(UserName='fred')
print "Created user: %s" % user
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'EntityAlreadyExis... |
How to print a text without substring in Python | 33,069,128 | 3 | 2015-10-11T19:19:31Z | 33,069,141 | 9 | 2015-10-11T19:21:01Z | [
"python",
"text"
] | I want to search for a word in the text and then print the text without that word. For example, we have the text "I was with my friend", I want the text be "I with my friend". I have done the following so far:
```
text=re.compile("[^was]")
val = "I was with my friend"
if text.search(val):
print text.search(val... | ```
val = "I was with my friend"
print val.replace("was ", "")
```
Output:
```
I with my friend
``` |
Fast linear interpolation in Numpy / Scipy "along a path" | 33,069,366 | 18 | 2015-10-11T19:44:33Z | 33,333,070 | 10 | 2015-10-25T18:03:46Z | [
"python",
"numpy",
"scipy",
"interpolation"
] | Let's say that I have data from weather stations at 3 (known) altitudes on a mountain. Specifically, each station records a temperature measurement at its location every minute. I have two kinds of interpolation I'd like to perform. And I'd like to be able to perform each quickly.
So let's set up some data:
```
impor... | A linear interpolation between two values `y1`, `y2` at locations `x1` and `x2`, with respect to point `xi` is simply:
```
yi = y1 + (y2-y1) * (xi-x1) / (x2-x1)
```
With some vectorized Numpy expressions we can select the relevant points from the dataset and apply the above function:
```
I = np.searchsorted(altitude... |
How to map lambda expressions in Java | 33,070,704 | 5 | 2015-10-11T22:16:05Z | 33,070,807 | 7 | 2015-10-11T22:32:00Z | [
"java",
"python",
"lambda"
] | I'm coming from Python, and trying to understand how lambda expressions work differently in Java. In Python, you can do stuff like:
```
opdict = { "+":lambda a,b: a+b, "-": lambda a,b: a-b,
"*": lambda a,b: a*b, "/": lambda a,b: a/b }
sum = opdict["+"](5,4)
```
How can I accomplish something similar in Ja... | Easy enough to do with a [`BiFunction`](https://docs.oracle.com/javase/8/docs/api/java/util/function/BiFunction.html) in Java 8:
```
final Map<String, BiFunction<Integer, Integer, Integer>> opdict = new HashMap<>();
opdict.put("+", (x, y) -> x + y);
opdict.put("-", (x, y) -> x - y);
opdict.put("*", (x, y) -> x * y);
o... |
How does this Python 3 quine work? | 33,071,521 | 11 | 2015-10-12T00:12:41Z | 33,071,551 | 11 | 2015-10-12T00:19:46Z | [
"python",
"quine"
] | Found this example of quine:
```
s='s=%r;print(s%%s)';print(s%s)
```
I get that `%s` and `%r` do the `str` and `repr` functions, as pointed [here](http://stackoverflow.com/questions/2354329/whats-the-meaning-of-r-in-python), but what exactly means the `s%s` part and how the quine works? | `s` is set to:
```
's=%r;print(s%%s)'
```
so the `%r` gets replaced by exactly that (*keeping* the single quotes) in `s%s` and the final `%%` with a single `%`, giving:
```
s='s=%r;print(s%%s)';print(s%s)
```
and hence the quine. |
Regex matching except whitespace in Python | 33,071,878 | 3 | 2015-10-12T01:15:08Z | 33,071,908 | 7 | 2015-10-12T01:20:16Z | [
"python",
"regex"
] | I am looking to match on a white space followed by anything except whitespace [i.e. letters, punctuation] at the start of a line in Python. For example:
```
` a` = True
` .` = True
` a` = False [double whitespace]
`ab` = False [no whitespace]
```
The rule `re.match(" \w")` works except with punctuation... | Remember the following:
```
\s\S
```
* `\s` is whitespace
* `\S` is everything but whitespace |
python regex match single quote | 33,072,292 | 2 | 2015-10-12T02:16:26Z | 33,072,314 | 7 | 2015-10-12T02:20:14Z | [
"python",
"regex"
] | I try to match single quote in below:
```
s= "name:'abc','hello'"
```
but seems the behaviour of match/findall is different:
```
re.match("\B'\w+'\B", s) # ===> return None
re.findall("\B'\w+'\B", s) #===> RETURN ['abc', 'hello']
```
actually this is caused by single quotes in the string, anyone knows what's go... | See <https://docs.python.org/2/library/re.html#search-vs-match> -- "Python offers two different primitive operations based on regular expressions: `re.match()` checks for a match only at the beginning of the string, while `re.search()` checks for a match anywhere in the string (this is what Perl does by default)."
You... |
Django 1.8, makemigrations not detecting newly added app | 33,074,543 | 6 | 2015-10-12T06:30:02Z | 33,076,398 | 9 | 2015-10-12T08:23:03Z | [
"python",
"django"
] | I have an existing django project with a,b,c apps. All of them are included in installed apps in settings file. They have their own models with for which the migrations have already been ran. Now, if I add a new app d, add a model to it, include it in installed apps and try to run a blanket makemigrations using `python... | If you create a new app manually and add it to the INSTALLED\_APPS setting without adding a migrations module inside it, the system will not pick up changes as this is not considered a migrations configured app.
The startapp command automatically adds the migrations module inside of your new app.
**startapp structure... |
Losslessly compressing images on django | 33,077,804 | 12 | 2015-10-12T09:36:20Z | 33,989,023 | 9 | 2015-11-29T22:40:14Z | [
"python",
"django",
"lossless-compression"
] | I'm doing optimization and Google recommends Lossless compression to images, looking for a way to implement this in Django.
Here's the images they specified, I think for it to be done effectively it needs to implemented systemwide possibly using a middleware class wondering if anyone has done this before. Here's the l... | > Losslessly compressing <http://www.kenyabuzz.com/media/uploads/clients/kenya_buzz_2.jpg> could save 594.3KiB (92% reduction).
First of all, the information in the logs is rather misleading because it is impossible to compress images by 92% using a lossless format (except for some cases like single-colour images, bas... |
Mapping dictionary value to list | 33,078,554 | 14 | 2015-10-12T10:11:43Z | 33,078,575 | 7 | 2015-10-12T10:12:56Z | [
"python"
] | Given the following dictionary:
```
dct = {'a':3, 'b':3,'c':5,'d':3}
```
How can I apply these values to a list such as:
```
lst = ['c', 'd', 'a', 'b', 'd']
```
in order to get something like:
```
lstval = [5, 3, 3, 3, 3]
``` | You can iterate keys from your list using `map` function:
```
lstval = list(map(dct.get, lst))
```
Or if you prefer list comprehension:
```
lstval = [dct[key] for key in lst]
``` |
Mapping dictionary value to list | 33,078,554 | 14 | 2015-10-12T10:11:43Z | 33,078,598 | 13 | 2015-10-12T10:14:01Z | [
"python"
] | Given the following dictionary:
```
dct = {'a':3, 'b':3,'c':5,'d':3}
```
How can I apply these values to a list such as:
```
lst = ['c', 'd', 'a', 'b', 'd']
```
in order to get something like:
```
lstval = [5, 3, 3, 3, 3]
``` | You can use a list comprehension for this:
```
lstval = [ dct.get(k, your_fav_default) for k in lst ]
```
I personally propose using list comprehensions over built-in `map` because it looks familiar to all Python programmers, is easier to parse and extend in case a custom default value is required. |
Mapping dictionary value to list | 33,078,554 | 14 | 2015-10-12T10:11:43Z | 33,078,607 | 17 | 2015-10-12T10:14:42Z | [
"python"
] | Given the following dictionary:
```
dct = {'a':3, 'b':3,'c':5,'d':3}
```
How can I apply these values to a list such as:
```
lst = ['c', 'd', 'a', 'b', 'd']
```
in order to get something like:
```
lstval = [5, 3, 3, 3, 3]
``` | Using [`map`](https://docs.python.org/2/library/functions.html#map):
```
>>> map(dct.get, lst)
[5, 3, 3, 3, 3]
```
Using a [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions):
```
>>> [dct[k] for k in lst]
[5, 3, 3, 3, 3]
``` |
Dot product with dictionaries | 33,079,472 | 10 | 2015-10-12T11:01:51Z | 33,079,563 | 17 | 2015-10-12T11:06:43Z | [
"python"
] | I am trying to do a dot product of the values of two dictionary. For example.
```
dict_1={'a':2, 'b':3, 'c':5, 'd':2}
dict_2={'a':2. 'b':2, 'd':3, 'e':5 }
```
In list form, the above looks like this:
```
dict_1=[2,3,5,2,0]
dict_2=[2,2,0,3,5]
```
The dot product of the dictionary with same key would result in.
```
... | Use sum function on list produced through iterate dict\_1 keys in couple with get() function against dict\_2:
```
dot_product = sum(dict_1[key]*dict_2.get(key, 0) for key in dict_1)
``` |
Understanding iterable types in comparisons | 33,080,675 | 6 | 2015-10-12T12:04:14Z | 33,080,724 | 7 | 2015-10-12T12:06:39Z | [
"python",
"iterator"
] | Recently I ran into cosmologicon's [pywats](https://github.com/cosmologicon/pywat) and now try to understand part about fun with iterators:
```
>>> a = 2, 1, 3
>>> sorted(a) == sorted(a)
True
>>> reversed(a) == reversed(a)
False
```
Ok, `sorted(a)` returns a `list` and `sorted(a) == sorted(a)` becomes just a two list... | `sorted` returns a list, whereas `reversed` returns a `reversed` object and is a different object. If you were to cast the result of `reversed` to a list before comparison, they will be equal.
```
In [8]: reversed(a)
Out[8]: <reversed at 0x2c98d30>
In [9]: reversed(a)
Out[9]: <reversed at 0x2c989b0>
``` |
Understanding iterable types in comparisons | 33,080,675 | 6 | 2015-10-12T12:04:14Z | 33,080,837 | 10 | 2015-10-12T12:12:35Z | [
"python",
"iterator"
] | Recently I ran into cosmologicon's [pywats](https://github.com/cosmologicon/pywat) and now try to understand part about fun with iterators:
```
>>> a = 2, 1, 3
>>> sorted(a) == sorted(a)
True
>>> reversed(a) == reversed(a)
False
```
Ok, `sorted(a)` returns a `list` and `sorted(a) == sorted(a)` becomes just a two list... | The basic reason why `id(reversed(a) == id(reversed(a)` returns `True` , whereas `reversed(a) == reversed(a)` returns `False` , can be seen from the below example using custom classes -
```
>>> class CA:
... def __del__(self):
... print('deleted', self)
... def __init__(self):
... print... |
Actions before close python script | 33,084,356 | 7 | 2015-10-12T15:04:53Z | 33,084,414 | 7 | 2015-10-12T15:07:57Z | [
"python"
] | Hi i have an script in python that run in a infinite loop some actions, but sometimes i have to close the script and update it with a new version, make some works in the server, etc.
The question, is how can i do to stop the script and before close it, the script make some actions after the loop as close sqlite connec... | You can catch a signal an execute something other then `sys.exit`
```
import signal
import sys
def signal_handler(signal, frame):
print 'You pressed Ctrl+C - or killed me with -2'
#.... Put your logic here .....
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
``` |
Python - What is exactly sklearn.pipeline.Pipeline? | 33,091,376 | 10 | 2015-10-12T22:42:46Z | 33,094,099 | 17 | 2015-10-13T04:24:40Z | [
"python",
"machine-learning",
"scikit-learn"
] | I can't figure out how the `sklearn.pipeline.Pipeline` works exactly.
There are a few explanation in the [doc](http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html). For example what do they mean by:
> Pipeline of transforms with a final estimator.
To make my question clearer, what are `st... | **Transformer** in scikit-learn - some class that have fit and transform method, or fit\_transform method.
**Predictor** - some class that has fit and predict methods, or fit\_predict method.
**Pipeline** is just an abstract notion, it's not some existing ml algorithm. Often in ML tasks you need to perform sequence o... |
Get a dict from a python list | 33,092,558 | 3 | 2015-10-13T01:05:46Z | 33,092,608 | 7 | 2015-10-13T01:13:43Z | [
"python",
"list",
"python-2.7",
"dictionary"
] | I have a list `my_list = ['a', 'b', 'c', 'd']` and I need to create a dictionary which looks like
```
{ 'a': ['a', 'b', 'c', 'd'],
'b': ['b', 'a', 'c', 'd'],
'c': ['c', 'a', 'b', 'd'],
'd': ['d', 'a', 'b', 'c'] }
```
each element as its value being the list but the first element is itself.
Here is my code
... | ```
>>> seq
['a', 'b', 'c', 'd']
>>> {e: [e]+[i for i in seq if i != e] for e in seq}
{'a': ['a', 'b', 'c', 'd'],
'b': ['b', 'a', 'c', 'd'],
'c': ['c', 'a', 'b', 'd'],
'd': ['d', 'a', 'b', 'c']}
``` |
How to find the sum of a string in a list | 33,094,687 | 7 | 2015-10-13T05:20:19Z | 33,094,782 | 7 | 2015-10-13T05:28:57Z | [
"python",
"list",
"python-2.7"
] | I have a list like this
```
['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']
```
in python. I want to find the sum of the lists that are strings like this:
```
['MGM', '1'], ['MGD', '1'], ['V1', '3'], ['AuD', '1']
```
Should I convert them to lists within the lists first? If so how would I go a... | Given:
```
s = [['MGM', '1'], ['MGD', '1'], ['V1', '[0,2,0,1]'], ['AuD', '[0,0,0,1]']]
```
The following will convert the second items to Python objects:
```
import ast
for sublist in s:
sublist[1] = ast.literal_eval(sublist[1])
```
Result:
```
[['MGM', 1], ['MGD', 1], ['V1', [0, 2, 0, 1]], ['AuD', [0, 0, 0, 1... |
Nested List comprehension in Python | 33,095,393 | 8 | 2015-10-13T06:14:58Z | 33,095,457 | 8 | 2015-10-13T06:19:22Z | [
"python",
"list",
"for-loop",
"list-comprehension"
] | I have a List inside of a List in Python and i want to convert them into a single list using List comprehension:
```
>>> aa = [[1,2],[1,2]]
>>> bb = [num for num in numbers for numbers in aa]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'numbers' is not defined
>>>
```
What... | You have the `for` loops in your list comprehension in the opposite order -
```
bb = [num for numbers in aa for num in numbers]
```
Demo -
```
>>> aa = [[1,2],[1,2]]
>>> bb = [num for numbers in aa for num in numbers]
>>> bb
[1, 2, 1, 2]
``` |
What is the difference between !r and %r in Python? | 33,097,143 | 7 | 2015-10-13T07:56:51Z | 33,097,227 | 8 | 2015-10-13T08:00:48Z | [
"python",
"string",
"format",
"string-formatting"
] | As the title states, what is the difference between these two flags? It seems they both convert the value to a string using repr()?
Also, in this line of code:
```
"{0!r:20}".format("Hello")
```
What does the 0 in front of the !r do? | `%r` is not a valid placeholder in the `str.format()` formatting operations; it only works in [old-style `%` string formatting](https://docs.python.org/2/library/stdtypes.html#string-formatting). It indeed converts the object to a representation through the `repr()` function.
In `str.format()`, `!r` is the equivalent,... |
matplotlib example code not working on python virtual environment | 33,100,969 | 3 | 2015-10-13T11:01:50Z | 33,180,744 | 14 | 2015-10-16T22:58:14Z | [
"python",
"osx",
"matplotlib",
"virtualenv"
] | I am trying to display the x y z coordinate of an image in matplotlib. [the example code](http://matplotlib.org/examples/api/image_zcoord.html) work perfectly well on the global python installation: As I move the cursor the x,y,z values get updated instantaneously. However, when I run the example code on a python virtu... | This is likely to be a problem with the macosx backend for matplotlib. Switch to using an alternative backend for matplotlib (e.g. use qt4 instead of 'macosx'). For details of how to switch backend and what exactly that means - see [the docs here](http://matplotlib.org/faq/usage_faq.html#what-is-a-backend). Note that y... |
Pycharm and sys.argv arguments | 33,102,272 | 6 | 2015-10-13T12:05:19Z | 33,102,415 | 8 | 2015-10-13T12:13:12Z | [
"python",
"linux",
"pycharm"
] | I am trying to debug a script which takes command line arguments as an input. Arguments are text files in the same directory. Script gets file names from sys.argv list. My problem is I cannot launch the script with arguments in pycharm.
I have tried to enter arguments into "Script parameters" field in "Run" > "Edit co... | In PyCharm the parameters are added in the **`Script Parameters`** as you did but, *enclosed in double quotes* `"` and without specifying the Interpreter flags like `-s`, those are specified in the **`Interpreter options`** box.
Script Parameters box contents:
```
"file1.txt" "file2.txt"
```
Interpeter flags:
```
-... |
Using list comprehensions to make a funcion more pythonic | 33,105,863 | 2 | 2015-10-13T14:51:57Z | 33,105,991 | 11 | 2015-10-13T14:57:30Z | [
"python",
"python-2.7",
"list-comprehension"
] | I'm doing some [Google Python Class](https://developers.google.com/edu/python/exercises/basic) exercises and I'm trying to find a pythonic solution to the following problem.
> D. Given a list of numbers, return a list where all adjacent ==
> elements have been reduced to a single element, so [1, 2, 2, 3]
> returns [1,... | > Am I trying to do something which is impossible to do with list comprehensions?
Yep. A list comprehension can't refer to itself by name, because the variable doesn't get bound at all until the comprehension is completely done evaluating. That's why you get a `NameError` if you don't have `result = []` in your second... |
HTTPError: HTTP Error 503: Service Unavailable goslate language detection request : Python | 33,107,292 | 11 | 2015-10-13T15:56:17Z | 33,448,911 | 10 | 2015-10-31T06:52:11Z | [
"python",
"http-error",
"http-status-code-503",
"goslate"
] | I have just started using the goslate library in python to detect the language of the words in a text but after testing it for 7-8 inputs, I gave the input which had the words written in two languages arabic and english. After which, it started giving me the error.
```
Traceback (most recent call last):
File "<pyshe... | maybe looking for this: <https://pypi.python.org/pypi/textblob> it is better than goslate,
since textblob is blocked as of now, maybe py-translate could do the trick,
<https://pypi.python.org/pypi/py-translate/#downloads>
<http://pythonhosted.org/py-translate/devs/api.html>
```
from translate import translator
tran... |
What is the difference between skew and kurtosis functions in pandas vs. scipy? | 33,109,107 | 6 | 2015-10-13T17:37:27Z | 33,109,272 | 11 | 2015-10-13T17:46:05Z | [
"python",
"numpy",
"pandas",
"scipy"
] | I decided to compare skew and kurtosis functions in pandas and scipy.stats, and don't understand why I'm getting different results between libraries.
As far as I can tell from the documentation, both kurtosis functions compute using Fisher's definition, whereas for skew there doesn't seem to be enough of a description... | The difference is due to different normalizations. Scipy by default does not correct for bias, whereas pandas does.
You can tell scipy to correct for bias by passing the `bias=False` argument:
```
>>> x = pandas.Series(np.random.randn(10))
>>> stats.skew(x)
-0.17644348972413657
>>> x.skew()
-0.20923623968879457
>>> s... |
Why is it not possible to convert "1.7" to integer directly, without converting to float first? | 33,113,938 | 8 | 2015-10-13T22:52:15Z | 33,113,952 | 9 | 2015-10-13T22:54:04Z | [
"python",
"floating-point",
"integer",
"type-conversion",
"coercion"
] | When I type `int("1.7")` Python returns error (specifically, ValueError). I know that I can convert it to integer by `int(float("1.7"))`. I would like to know why the first method returns error. | From the [documentation](https://docs.python.org/2/library/functions.html#int):
> If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in radix base ...
Obviously, `"1.7"` does not represent an integer literal in radix base.
If you want to know *why* the... |
Caffe: Reading LMDB from Python | 33,117,607 | 9 | 2015-10-14T05:53:29Z | 33,123,313 | 17 | 2015-10-14T10:47:24Z | [
"python",
"caffe",
"lmdb"
] | I've extracted features using caffe, which generates a .mdb file.
Then I'm trying to read it using Python and display it as a readable number.
```
import lmdb
lmdb_env = lmdb.open('caffefeat')
lmdb_txn = lmdb_env.begin()
lmdb_cursor = lmdb_txn.cursor()
for key, value in lmdb_cursor:
print str(value)
```
This pr... | Here's the working code I figured out
```
import caffe
import lmdb
lmdb_env = lmdb.open('directory_containing_mdb')
lmdb_txn = lmdb_env.begin()
lmdb_cursor = lmdb_txn.cursor()
datum = caffe.proto.caffe_pb2.Datum()
for key, value in lmdb_cursor:
datum.ParseFromString(value)
label = datum.label
data = caff... |
Convert String back to List | 33,127,758 | 2 | 2015-10-14T14:13:51Z | 33,127,781 | 8 | 2015-10-14T14:15:00Z | [
"python",
"string",
"csv"
] | I messed up yesterday and saved a datframe to csv and in that dataframe I had a column which was a list of strings. Now that list of strings, is a string(of a list of strings) when I import it back into python from a csv. Is there a way I can, upon importing, change it back to a list of strings?
Example:
```
testList... | That's what [`ast.literal_eval`](https://docs.python.org/2/library/ast.html) is for :
```
>>> from ast import literal_eval
>>>
>>> literal_eval( "['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']")
['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']
``` |
How to set class attribute with await in __init__ | 33,128,325 | 13 | 2015-10-14T14:36:09Z | 33,134,213 | 14 | 2015-10-14T19:42:46Z | [
"python",
"python-3.x",
"python-asyncio"
] | How can I define a class with `await` in the constructor or class body?
For example what I want:
```
import asyncio
# some code
class Foo(object):
async def __init__(self, settings):
self.settings = settings
self.pool = await create_pool(dsn)
foo = Foo(settings)
# it raises:
# TypeError: __in... | Most magic methods aren't designed to work with `async def`/`await` - in general, you should only be using `await` inside the dedicated asynchronous magic methods - `__aiter__`, `__anext__`, `__aenter__`, and `__aexit__`. Using it inside other magic methods either won't work at all (as is the case with `__init__`), or ... |
How to set class attribute with await in __init__ | 33,128,325 | 13 | 2015-10-14T14:36:09Z | 33,140,788 | 9 | 2015-10-15T05:47:55Z | [
"python",
"python-3.x",
"python-asyncio"
] | How can I define a class with `await` in the constructor or class body?
For example what I want:
```
import asyncio
# some code
class Foo(object):
async def __init__(self, settings):
self.settings = settings
self.pool = await create_pool(dsn)
foo = Foo(settings)
# it raises:
# TypeError: __in... | I would recommend a separate factory method. It's safe and straightforward. However, if you insist on a `async` version of `__init__()`, here's an example:
```
def asyncinit(cls):
__new__ = cls.__new__
async def init(obj, *arg, **kwarg):
await obj.__init__(*arg, **kwarg)
return obj
def ne... |
Convert a list of strings to either int or float | 33,130,279 | 5 | 2015-10-14T16:05:40Z | 33,130,297 | 9 | 2015-10-14T16:06:38Z | [
"python",
"list"
] | I have a list which looks something like this:
```
['1', '2', '3.4', '5.6', '7.8']
```
How do I change the first two to `int` and the three last to `float`?
I want my list to look like this:
```
[1, 2, 3.4, 5.6, 7.8]
``` | Use a [conditional inside a list comprehension](http://stackoverflow.com/q/4406389/4099593)
```
>>> s = ['1', '2', '3.4', '5.6', '7.8']
>>> [float(i) if '.' in i else int(i) for i in s]
[1, 2, 3.4, 5.6, 7.8]
```
Interesting edge case of exponentials. You can add onto the conditional.
```
>>> s = ['1', '2', '3.4', '5... |
Evenly distribute within a list (Google Foobar: Maximum Equality) | 33,134,485 | 2 | 2015-10-14T19:57:27Z | 33,134,842 | 9 | 2015-10-14T20:20:16Z | [
"python",
"list",
"python-2.7"
] | This question comes from Google Foobar, and my code passes all but the last test, with the input/output hidden.
# The prompt
> In other words, choose two elements of the array, x[i] and x[j]
> (i distinct from j) and simultaneously increment x[i] by 1 and decrement
> x[j] by 1. Your goal is to get as many elements of... | Sorry, but your code doesn't work in my testing. I fed it [0, 0, 0, 0, 22] and got back a list of [5, 5, 4, 4, 4] for an answer of 3; the maximum would be 4 identical cars, with the original input being one such example. [4, 4, 4, 4, 6] would be another. I suspect that's your problem, and that there are quite a few oth... |
Can Golang multiply strings like Python can? | 33,139,020 | 8 | 2015-10-15T02:52:25Z | 33,139,049 | 15 | 2015-10-15T02:54:48Z | [
"python",
"string",
"python-3.x",
"go"
] | Python can multiply strings like so:
```
Python 3.4.3 (default, Mar 26 2015, 22:03:40)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 'my new text is this long'
>>> y = '#' * len(x)
>>> y
'########################'
>>>
```
Can Golang do the equivalent somehow? | It has a function instead of an operator, [Repeat](https://golang.org/pkg/strings/#Repeat). Here's a port of your Python example:
```
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
x := "my new text is this long"
y := strings.Repeat("#", utf8.RuneCountInString(x))
fmt.Pr... |
how to use python's any | 33,139,089 | 6 | 2015-10-15T02:58:38Z | 33,139,109 | 12 | 2015-10-15T03:01:02Z | [
"python",
"any"
] | I feel very confused about some code like this[not written by me]:
```
version = any(func1(), func2()) # wrong, should be any([func1(), func2()])
def func1():
if something:
return 1
else:
return None
def func2():
if something:
return 2
else:
return 3
```
`version` must be a... | You can simply use `or` here.
```
version = func1() or func2()
```
Make sure the functions are defined before trying to call them.
This works because `or` returns the first True-like value or the last value (if no value is True-like) . And 'None' is considered False-like in Boolean context. |
why does x -= x + 4 return -4 instead of 4 | 33,139,310 | 5 | 2015-10-15T03:24:14Z | 33,139,322 | 14 | 2015-10-15T03:25:46Z | [
"python",
"operators",
"assignment-operator"
] | new to python and trying to wrestle with the finer points of assignment operators. Here's my code and then the question.
```
x = 5
print(x)
x -= x + 4
print(x)
```
the above code, returns 5 the first time, but yet -4 upon the second print. In my head I feel that the number should actually be 4 as I am reading... | `x -= x + 4` can be written as:
```
x = x - (x + 4) = x - x - 4 = -4
``` |
How to feed caffe multi label data in HDF5 format? | 33,140,000 | 4 | 2015-10-15T04:38:41Z | 33,166,461 | 14 | 2015-10-16T09:05:52Z | [
"python",
"neural-network",
"deep-learning",
"caffe"
] | I want to use caffe with a vector label, not integer. I have checked some answers, and it seems HDF5 is a better way. But then I'm stucked with error like:
> accuracy\_layer.cpp:34] Check failed: `outer_num_ * inner_num_ == bottom[1]->count()` (50 vs. 200) Number of labels must match number of predictions; e.g., if la... | Answer to this question's title:
The HDF5 file should have two dataset in root, named "data" and "label", respectively. The shape is (`data amount`, `dimension`). I'm using only one-dimension data, so I'm not sure what's the order of `channel`, `width`, and `height`. Maybe it does not matter. `dtype` should be float o... |
TypeError: only integer arrays with one element can be converted to an index 3 | 33,144,039 | 6 | 2015-10-15T08:55:21Z | 33,144,798 | 9 | 2015-10-15T09:30:50Z | [
"python",
"arrays",
"list",
"numpy",
"append"
] | I'm having this error in the title, and don't know what's wrong. It's working when I use np.hstack instead of np.append, but I would like to make this faster, so use append.
> time\_list a list of floats
>
> heights is a 1d np.array of floats
```
j = 0
n = 30
time_interval = 1200
axe_x = []
while j < np.size(time_li... | The issue is just as the error indicates, `time_list` is a normal python list, and hence you cannot index it using another list (unless the other list is an array with single element). Example -
```
In [136]: time_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
In [137]: time_list[np.arange(5,6)]
Out[137]: 6
In [138]: tim... |
advance time artificially in pytest | 33,150,313 | 9 | 2015-10-15T13:48:21Z | 33,150,603 | 7 | 2015-10-15T14:01:52Z | [
"python",
"py.test"
] | I have code that depends on elapsed time (for instance: If 10 minutes has passed)
What is the best way to simulate this in pytest?
Monkey patching methods in module time?
Example code (the tested code - a bit schematic but conveys the message):
```
current_time = datetime.datetime.utcnow()
retry_time = current_time ... | [FreezeGun](https://github.com/spulec/freezegun/) is probably the easiest solution.
Sample code from its readme:
```
from freezegun import freeze_time
@freeze_time("2012-01-14")
def test():
assert datetime.datetime.now() == datetime.datetime(2012, 01, 14)
``` |
Addition of list and NumPy number | 33,151,072 | 11 | 2015-10-15T14:22:44Z | 33,151,321 | 12 | 2015-10-15T14:33:29Z | [
"python",
"list",
"numpy"
] | If you add an integer to a list, you get an error raised by the \_\_add\_\_ function of the list (I suppose):
```
>>> [1,2,3] + 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
```
If you add a list to a NumPy array, I assume that the ... | `list` does not know how to handle addition with NumPy arrays. Even in `[1,2,3] + np.array([3])`, it's NumPy arrays that handle the addition.
As [documented in the data model](https://docs.python.org/2/reference/datamodel.html#coercion-rules):
> * For objects x and y, first `x.__op__(y)` is tried. If this is not impl... |
Addition of list and NumPy number | 33,151,072 | 11 | 2015-10-15T14:22:44Z | 33,151,502 | 8 | 2015-10-15T14:41:12Z | [
"python",
"list",
"numpy"
] | If you add an integer to a list, you get an error raised by the \_\_add\_\_ function of the list (I suppose):
```
>>> [1,2,3] + 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
```
If you add a list to a NumPy array, I assume that the ... | It is because of the `__radd__` method of np.array, check out this link : <http://www.rafekettler.com/magicmethods.html#numeric> (paragraph Reflected arithmetic operators).
In facts, when you try `[1,2,3].__add__(np.array([3]))`, it raises an error, so `np.array([3]).__radd__([1,2,3])` is called. |
How do I use multiple conditions with pyspark.sql.funtions.when()? | 33,151,861 | 5 | 2015-10-15T14:56:35Z | 33,157,063 | 7 | 2015-10-15T19:37:07Z | [
"python",
"apache-spark"
] | I have a dataframe with a few columns. Now I want to derive a new column from 2 other columns:
```
from pyspark.sql import functions as F
new_df = df.withColumn("new_col", F.when(df["col-1"] > 0.0 & df["col-2"] > 0.0, 1).otherwise(0))
```
With this I only get an exception:
```
py4j.Py4JException: Method and([class j... | Use brackets to enforce the desired operator precedence:
```
F.when( (df["col-1"]>0.0) & (df["col-2"]>0.0), 1).otherwise(0)
``` |
Why wasn't the string at the top of this function printed? | 33,156,785 | 4 | 2015-10-15T19:21:41Z | 33,156,870 | 10 | 2015-10-15T19:25:52Z | [
"python",
"docstring"
] | I encountered the following function in a tutorial. When I call the function, `"This prints a passed string into this function"` isn't printed. Why does the function not print this piece of text when called?
```
def printme(str):
"This prints a passed string into this function"
print str
return
# Now you can... | What youâre seeing there is a document string, or *docstring* in short.
A docstring is a string that is supposed to document the thing it is attached to. In your case, it is attached to a function, and as such is supposed to document the function. You can also have docstrings for classes and modules.
You create doc... |
pandas v0.17.0: AttributeError: 'unicode' object has no attribute 'version' | 33,159,634 | 9 | 2015-10-15T22:32:23Z | 33,168,054 | 18 | 2015-10-16T10:20:10Z | [
"python",
"pandas"
] | I installed pandas v0.17.0 directly from the sources on my linux suse 13.2 64 bits. I had previously v0.14.1 installed using yast.
Now
```
>>> import pandas
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/site-packages/pandas-0.17.0-py2.7-linux-x86_64.egg/pandas/__... | ```
pip install -U matplotlib
```
worked for me.
Thanks joris! |
Getting only element from a single-element list in Python? | 33,161,448 | 21 | 2015-10-16T02:09:27Z | 33,161,467 | 32 | 2015-10-16T02:12:23Z | [
"python",
"list",
"python-2.7"
] | When a Python list is known to always contain a single item, is there way to access it other than:
```
mylist[0]
```
You may ask, 'Why would you want to?'. Curiosity alone. There seems to be an alternative way to do *everything* in Python. | Sequence unpacking:
```
singleitem, = mylist
# Identical in behavior (byte code produced is the same),
# but arguably more readable since a lone trailing comma could be missed:
[singleitem] = mylist
```
Explicit use of iterator protocol:
```
singleitem = next(iter(mylist))
```
Destructive pop:
```
singleitem = myl... |
How to create standalone executable file from python 3.5 scripts? | 33,168,229 | 4 | 2015-10-16T10:28:32Z | 33,174,611 | 13 | 2015-10-16T15:48:39Z | [
"python",
"exe",
"python-3.5"
] | Most of the programs available only support upto python version 3.4. | You can use [PyInstaller](http://www.pyinstaller.org) which support python 3.5.
To install it with pip execute in terminal:
`pip install pyinstaller`
To make the .exe file:
```
pyinstaller --onefile script.py
``` |
removing an backslash from a string | 33,169,772 | 3 | 2015-10-16T11:48:59Z | 33,169,823 | 7 | 2015-10-16T11:51:05Z | [
"python",
"nltk"
] | I have a string that is a sentence like `I don't want it, there'll be others`
So the text looks like this `I don\'t want it, there\'ll be other`
for some reason a `\` comes with the text next to the `'`. It was read in from another source. I want to remove it, but can't. I've tried.
`sentence.replace("\'","'")`
`sen... | The `\` is just there to [escape](https://docs.python.org/2/reference/lexical_analysis.html#string-literals) the `'` character. It is only visible in the representation (`repr`) of the string, it's not actually a character in the string. See the following demo
```
>>> repr("I don't want it, there'll be others")
'"I do... |
Reduce multiple list comprehesion into a single statement | 33,170,298 | 4 | 2015-10-16T12:15:56Z | 33,170,357 | 14 | 2015-10-16T12:18:52Z | [
"python",
"list-comprehension"
] | Looking for a reduced list comprehesion and less loops and memory usage, there is some way to reduce two loops to build the final paths, transforming it into a single list comprehesion?
```
def build_paths(domains):
http_paths = ["http://%s" % d for d in domains]
https_paths = ["https://%s" % d for d in do... | Add a second loop:
```
['%s://%s' % (scheme, domain) for scheme in ('http', 'https') for domain in domains]
```
This builds all the `http` urls first, then the `https` urls, just like your original code. |
Printing from list in Python | 33,172,827 | 3 | 2015-10-16T14:23:41Z | 33,172,924 | 15 | 2015-10-16T14:27:25Z | [
"python",
"list"
] | In the following code, I am trying to print each name with another name once:
```
myList = ['John', 'Adam', 'Nicole', 'Tom']
for i in range(len(myList)-1):
for j in range(len(myList)-1):
if (myList[i] <> myList[j+1]):
print myList[i] + ' and ' + myList[j+1] + ' are now friends'
```
The result ... | This is a good opportunity to use itertools.combinations:
```
In [9]: from itertools import combinations
In [10]: myList = ['John', 'Adam', 'Nicole', 'Tom']
In [11]: for n1, n2 in combinations(myList, 2):
....: print "{} and {} are now friends".format(n1, n2)
....:
John and Adam are now friends
John and Ni... |
Python Requests getting ('Connection aborted.', BadStatusLine("''",)) error | 33,174,804 | 4 | 2015-10-16T16:00:44Z | 33,226,080 | 9 | 2015-10-20T00:26:25Z | [
"python",
"python-3.x",
"python-requests"
] | ```
def download_torrent(url):
fname = os.getcwd() + '/' + url.split('title=')[-1] + '.torrent'
try:
schema = ('http:')
r = requests.get(schema + url, stream=True)
with open(fname, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
... | I took a closer look at your question today and I've got your code working on my end.
The error you get indicates the host isn't responding in the expected manner. In this case, it's because **it detects that you're trying to scrape it and deliberately disconnecting you**.
If you try your `requests` code with this UR... |
Programmatically convert pandas dataframe to markdown table | 33,181,846 | 3 | 2015-10-17T01:39:59Z | 33,869,154 | 8 | 2015-11-23T10:46:53Z | [
"python",
"pandas",
"markdown"
] | I have a Pandas Dataframe generated from a database, which has data with mixed encodings. For example:
```
+----+-------------------------+----------+------------+------------------------------------------------+--------------------------------------------------------+--------------+-----------------------+
| ID | pat... | Improving the answer further, for use in IPython Notebook:
```
def pandas_df_to_markdown_table(df):
from IPython.display import Markdown, display
fmt = ['---' for i in range(len(df.columns))]
df_fmt = pd.DataFrame([fmt], columns=df.columns)
df_formatted = pd.concat([df_fmt, df])
display(Markdown(df... |
Django rest framework serializing many to many field | 33,182,092 | 9 | 2015-10-17T02:24:27Z | 33,182,227 | 12 | 2015-10-17T02:53:21Z | [
"python",
"django",
"django-models",
"django-rest-framework",
"django-serializer"
] | How do I serialize a many-to-many field into list of something, and return them through rest framework? In my example below, I try to return the post together with a list of tags associated with it.
**models.py**
```
class post(models.Model):
tag = models.ManyToManyField(Tag)
text = models.CharField(max_lengt... | You will need a `TagSerializer`, whose `class Meta` has `model = Tag`. After `TagSerializer` is created, modify the `PostSerializer` with `many=True` for a `ManyToManyField` relation:
```
class PostSerializer(serializers.ModelSerializer):
tag = TagSerializer(read_only=True, many=True)
class Meta:
...
... |
Assigning to vs. from a slice | 33,182,333 | 11 | 2015-10-17T03:10:56Z | 33,182,355 | 9 | 2015-10-17T03:17:05Z | [
"python",
"slice",
"idioms"
] | When reading `profile.py` of python standard library I came across the assignment statement `sys.argv[:] = args`, which is used to modify `sys.argv` to make the program being profiled see the correct command line arguments. I understand that this is different from `sys.argv = args[:]` in the actual operations, but **in... | The difference is, when you use `a[:] = b` it means you will override whatever is already on `a`. If you have something else with a reference to `a` it will change as well, as it keeps referencing the same location.
In the other hand, `a = b[:]` creates a new reference and copy all the values from `b` to this new refe... |
Creating a program that prints true if three words are entered in dictionary order | 33,183,399 | 7 | 2015-10-17T06:06:17Z | 33,183,415 | 8 | 2015-10-17T06:09:02Z | [
"python",
"string",
"python-3.x",
"order",
"lexicographic"
] | I am trying to create a program that asks the user for three words and prints 'True' if the words are entered in dictionary order. E.G:
```
Enter first word: chicken
Enter second word: fish
Enter third word: zebra
True
```
Here is my code so far:
```
first = (input('Enter first word: '))
second = (input('Enter se... | If you work on a list of arbitrary length, I believe using [`sorted()`](https://docs.python.org/2/library/functions.html#sorted "sorted()") as other answers indicate is good for small lists (with small strings) , when it comes to larger lists and larger strings and cases (and cases where the list can be randomly ordere... |
On OS X El Capitan I can not upgrade a python package dependent on the six compatibility utilities NOR can I remove six | 33,185,147 | 12 | 2015-10-17T09:47:05Z | 33,599,105 | 21 | 2015-11-08T21:13:21Z | [
"python",
"osx",
"sudo",
"six"
] | I am trying to use scrape, but I have a problem.
> from six.moves import xmlrpc\_client as xmlrpclib
>
> ImportError: cannot import name xmlrpc\_client
Then, I tried `pip install --upgrade six scrape`, but:
```
Found existing installation: six 1.4.1
DEPRECATION: Uninstalling a distutils installed project (six)... | I just got around what I think was the same problem. You might consider trying this (sudo, if necessary):
`pip install scrape --upgrade --ignore-installed six`
[Github](https://github.com/pypa/pip/issues/3165) is ultimately where I got this answer (and there are a few more suggestions you may consider if this one doe... |
On OS X El Capitan I can not upgrade a python package dependent on the six compatibility utilities NOR can I remove six | 33,185,147 | 12 | 2015-10-17T09:47:05Z | 36,022,226 | 9 | 2016-03-15T21:11:05Z | [
"python",
"osx",
"sudo",
"six"
] | I am trying to use scrape, but I have a problem.
> from six.moves import xmlrpc\_client as xmlrpclib
>
> ImportError: cannot import name xmlrpc\_client
Then, I tried `pip install --upgrade six scrape`, but:
```
Found existing installation: six 1.4.1
DEPRECATION: Uninstalling a distutils installed project (six)... | I don't think this is a duplicate, but actually [this issue discussed here on the pip GitHub repository issues list](https://github.com/pypa/pip/issues/3165).
The core of the problem is tied to Apple's new SIP that they shipped with El Capitan. More [specifically](https://github.com/pypa/pip/issues/3165#issuecomment-1... |
django:django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet | 33,186,413 | 10 | 2015-10-17T12:04:53Z | 33,550,079 | 11 | 2015-11-05T16:39:54Z | [
"python",
"django"
] | I was stuck with the process when I wanted to deploy django project on server today. When I run `python manage.py runserver` on server, the terminal shows me this:
```
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/site-pac... | This could well be an issue with your Django settings. For example, I just had specified in `LOGGING` a filename in a non-existent directory. As soon as I changed it to an existing directory, the issue was resolved. |
Iterators for built-in containers | 33,186,651 | 4 | 2015-10-17T12:32:03Z | 33,186,713 | 9 | 2015-10-17T12:37:52Z | [
"python",
"python-3.x",
"iterator",
"containers"
] | From my understanding so far, you can easily create an iterator for a *user-defined* object by simply defining **both** the `__iter__` method and the `__next__` method for it. That's pretty intuitive to understand.
I also get it that you can manually build an iterator for any *built-in* container by simply calling the... | If the container was its own iterator (e.g. provided a `__next__` method), you could only iterate over it *in one place*. You could not have independent iterators. Each call to `__next__` would give the next value in the container and you'd not be able to go back to the first value; you have in effect a generator that ... |
Add numbers and exit with a sentinel | 33,187,609 | 8 | 2015-10-17T14:16:20Z | 33,187,743 | 7 | 2015-10-17T14:32:08Z | [
"python",
"loops",
"sentinel"
] | My assignment is to add up a series of numbers using a loop, and that loop requires the sentinel value of `0` for it to stop. It should then display the total numbers added. So far, my code is:
```
total = 0
print("Enter a number or 0 to quit: ")
while True:
number = int(input("Enter a number or 0 to quit: "))
... | The main reason your code is not working is because `break` ends the innermost loop (in this case your `while` loop) *immediately*, and thus your lines of code after the break will not be executed.
This can easily be fixed using the methods others have pointed out, but I'd like to suggest changing your `while` loop's s... |
Python: regex to make a python dictionary out of a sequence of words? | 33,207,089 | 5 | 2015-10-19T05:17:32Z | 33,207,190 | 10 | 2015-10-19T05:26:39Z | [
"python",
"regex"
] | I have a .txt file with the following contents:
```
norway sweden
bhargama bhargama
forbisganj forbesganj
canada usa
ankara turkey
```
I want to overwrite the file such that these are its new contents:
```
'norway' : 'sweden',
'bhargama': 'bhargama',
'forbisganj' : 'forbesganj',
'canada': 'usa',
'ankara': 'tu... | You don't need a regular expression for that.
File:
```
norway sweden
bhargama bhargama
forbisganj forbesganj
canada usa
ankara turkey
```
Code:
```
with open('myfile.txt') as f:
my_dictionary = dict(line.split() for line in f)
```
This goes through each line in your file and splits it on whitespace into ... |
Pandas warning when using map: A value is trying to be set on a copy of a slice from a DataFrame | 33,215,630 | 4 | 2015-10-19T13:24:27Z | 33,217,544 | 7 | 2015-10-19T14:51:35Z | [
"python",
"pandas"
] | I've got the following code and it works. This basically renames values in columns so that they can be later merged.
```
pop = pd.read_csv('population.csv')
pop_recent = pop[pop['Year'] == 2014]
mapping = {
'Korea, Rep.': 'South Korea',
'Taiwan, China': 'Taiwan'
}
f= lambda x: mapping.get(x, x)
pop_re... | The issue is with [chained indexing](http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy) , what you are actually trying to do is to set values to - `pop[pop['Year'] == 2014]['Country Name']` - this would not work most of the times (as explained very well in the linked documentation... |
Is there any way to check with Python unittest assert if an iterable is not empty? | 33,216,488 | 10 | 2015-10-19T14:02:49Z | 33,216,600 | 13 | 2015-10-19T14:08:02Z | [
"python",
"python-2.7",
"unit-testing",
"assertions",
"python-unittest"
] | After submitting queries to a service, I get a dictionary / a list back and I want to make sure it's not empty. I am on Python 2.7.
I am surprised I don't see any `assertEmpty` method for the `unittest.TestCase` class instance.
The existing alternatives such as:
```
self.assertTrue(bool(d))
```
and
```
self.assert... | Empty lists/dicts evaluate to False, so `self.assertTrue(d)` gets the job done. |
Installing OpenCV 3 for Python 3 on a mac using Homebrew and pyenv | 33,222,965 | 9 | 2015-10-19T20:05:43Z | 33,222,993 | 11 | 2015-10-19T20:07:25Z | [
"python",
"osx",
"opencv",
"python-3.x"
] | I am running Mac OS X 10.11 (El Capitan). I want to:
* Maintain my system version of Python as the default
* Install Python 3.5 alongside it
* Install OpenCV 3 and the Python bindings
I installed `pyenv` and Python 3.5 by following this SO answer: <http://stackoverflow.com/a/18671336/1410871>
I activated my Python 3... | Answering my own question: I have to manually create a symlink to the shared object file and place it in the pyenv Python 3 site-packages directory:
```
ln -s /usr/local/opt/opencv3/lib/python3.5/site-packages/cv2.cpython-35m-darwin.so ~/.pyenv/versions/3.5.0/lib/python3.5/site-packages/cv2.so
```
Now the line `impor... |
Generate a list of 6 random numbers between 1 and 6 in python | 33,224,944 | 3 | 2015-10-19T22:21:53Z | 33,224,964 | 9 | 2015-10-19T22:23:28Z | [
"python",
"random",
"numbers"
] | So this is for a practice problem for one of my classes. I want to generate a list of 6 random numbers between 1 and 6. For example,startTheGame() should return [1,4,2,5,4,6]
I think I am close to getting it but Im just not sure how to code it so that all 6 numbers are appended to the list and then returned. Any help ... | Use a [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions):
```
import random
def startTheGame():
mylist=[random.randint(1,6) for _ in range(6)]
return mylist
```
List comprehensions are among the most powerful tools offered by Python. They are considered very pyt... |
Can a website detect when you are using selenium with chromedriver? | 33,225,947 | 55 | 2015-10-20T00:08:57Z | 33,403,473 | 17 | 2015-10-28T23:39:33Z | [
"javascript",
"python",
"google-chrome",
"selenium",
"selenium-chromedriver"
] | I've been testing out Selenium with Chromedriver and I noticed that some pages can detect that you're using Selenium even though there's no automation at all. Even when I'm just browsing manually just using chrome through Selenium and Xephyr I often get a page saying that suspicious activity was detected. I've checked ... | As we've already figured out in the question and the posted answers, there is an anti Web-scraping and a Bot detection service called ["Distil Networks"](http://www.distilnetworks.com/) in play here. And, according to the company CEO's [interview](http://www.forbes.com/sites/timconneally/2013/01/28/theres-something-abo... |
Python for loop iterating 'i' | 33,226,223 | 2 | 2015-10-20T00:43:11Z | 33,226,245 | 7 | 2015-10-20T00:45:45Z | [
"python",
"list",
"for-loop",
"dictionary"
] | I am using the following script:
```
tagRequest = requests.get("https://api.instagram.com/v1/tags/" + tag + "/media/recent?client_id=" + clientId)
tagData = json.loads(tagRequest.text)
tagId = tagData["data"][0]["user"]["id"]
for i in tagData["data"]:
print tagData["data"][i]
```
My script is supposed to iterate... | You are iterating over the contents of `tagData['data']` not its indices, so:
```
for i in tagData["data"]:
print i
```
Or indices:
```
for i in xrange(len(tagData["data"])):
print tagData["data"][i]
``` |
Is it possible to have static type assertions in PyCharm? | 33,227,330 | 9 | 2015-10-20T03:11:15Z | 33,730,487 | 7 | 2015-11-16T07:42:33Z | [
"python",
"pycharm"
] | ```
def someproperty(self, value):
"""
:type value: int
"""
assert isinstance(value, int)
# other stuff
```
I'd like Pycharm to assert when the user sets the value to something other than an int. I'm already using a type hint. Is there another way to get this functionality? Thanks in advance for an... | Using pycharm you can get somewhat close to static type checking, using type declarations and increasing the severity of the "Type checker" inspection:
[](http://i.stack.imgur.com/PGUpm.png)
This will make type checks very prominent in your code:
[![... |
Spark: How to map Python with Scala or Java User Defined Functions? | 33,233,737 | 5 | 2015-10-20T10:06:08Z | 33,257,733 | 9 | 2015-10-21T11:07:01Z | [
"java",
"python",
"scala",
"apache-spark",
"pyspark"
] | Let's say for instance that my team has choosen Python as the reference language to develop with Spark. But later for performance reasons, we would like to develop specific Scala or Java specific librairies in order to map them with our Python code (something similar to Python stubs with Scala or Java skeletons).
Don'... | I wouldn't go so far as to say it is supported but it is certainly possible. All SQL functions available currently in PySpark are simply a wrappers around Scala API.
Lets assume I want to reuse `GroupConcat` UDAF I've created as an answer to [SPARK SQL replacement for mysql GROUP\_CONCAT aggregate function](http://sta... |
trouble with python manage.py migrate -> No module named psycopg2 | 33,237,274 | 2 | 2015-10-20T12:56:12Z | 33,237,669 | 7 | 2015-10-20T13:14:32Z | [
"python",
"django",
"postgresql",
"psycopg2",
"migrate"
] | I have some trouble with migrating Django using postgresql.
This is my first time with Django and I am just following the tutorial. Next to that I have looked on Google and Stackoverflow to see if I could find a solution.
I have created a virtualenv to run the Django project as suggested on the Django website.
Next I... | It must be because you are installing psycopg2 in your system level python installation not in your virtualenv.
```
sudo apt-get install python-psycopg2
```
will install it in your system level python installation.
You can install it in your virtualenv by
```
pip install psycopg2
```
after activating your virtuale... |
Trailing slash triggers 404 in Flask path rule | 33,241,050 | 8 | 2015-10-20T15:44:09Z | 33,285,603 | 12 | 2015-10-22T16:10:08Z | [
"python",
"flask"
] | I want to redirect any path under `/users` to a static app. The following view should capture these paths and serve the appropriate file (it just prints the path for this example). This works for `/users`, `/users/604511`, and `/users/604511/action`. Why does the path `/users/` cause a 404 error?
```
@bp.route('/users... | Your `/users` route is missing a trailing slash, which Werkzeug interprets as an explicit rule to not match a trailing slash. Either add the trailing slash, and Werkzeug will redirect if the url doesn't have it, or set [`strict_slashes=False`](http://werkzeug.pocoo.org/docs/0.10/routing/#rule-format) on the route and W... |
Stopword removal with NLTK and Pandas | 33,245,567 | 5 | 2015-10-20T19:47:28Z | 33,246,035 | 9 | 2015-10-20T20:15:58Z | [
"python",
"csv",
"pandas",
"nltk",
"stop-words"
] | I have some issues with Pandas and NLTK. I am new at programming, so excuse me if i ask questions that might be easy to solve. I have a csv file which has 3 columns(Id,Title,Body) and about 15.000 rows.
My goal is to remove the stopwords from this csv file. The operation for lowercase and split are working well. But i... | you are trying to do an inplace replace. you should do
```
df['Title'] = df['Title'].apply(lambda x: [item for item in x if item not in stop])
df['Body'] = df['Body'].apply(lambda x: [item for item in x if item not in stop])
``` |
installing libicu-dev on mac | 33,259,191 | 4 | 2015-10-21T12:21:22Z | 33,352,241 | 9 | 2015-10-26T17:44:53Z | [
"python",
"windows",
"osx",
"unicode",
"pip"
] | how do i install libicu-dev on mac. This is the instruction recommended on the documentation
```
sudo apt-get install python-numpy libicu-dev
```
<http://polyglot.readthedocs.org/en/latest/Installation.html>
I am using anaconda but it seems to always throw up an
```
In file included from _icu.cpp:27:
./common.h... | I just got PyICU to install on OSX, after it was failing due to that same error. Here is what I recommend:
1. Install [homebrew](http://brew.sh/) (package manager for OSX)
2. `brew install icu4c` # Install the library; may be already installed
3. Verify that the necessary include directory is present: `ls -l /usr/loca... |
Split Text in Python | 33,260,106 | 2 | 2015-10-21T13:03:31Z | 33,260,154 | 11 | 2015-10-21T13:05:30Z | [
"python",
"text",
"split"
] | Is there an easy way to split text into separate lines each time a specific type of font arises. For example, I have text that looks like this:
```
BILLY: The sky is blue. SALLY: It really is blue. SAM: I think it looks like this: terrible.
```
I'd like to split the text into lines for each speaker:
```
BILLY: The s... | ```
import re
a="BILLY: The sky is blue. SALLY: It really is blue. SAM: I think it looks like this: terrible."
print re.split(r"\s(?=[A-Z]+:)",a)
```
You can use `re.split` for this.
Output:`['BILLY: The sky is blue.', 'SALLY: It really is blue.', 'SAM: I think it looks like this: terrible.']` |
pandas replace zeros with previous non zero value | 33,261,359 | 5 | 2015-10-21T13:59:09Z | 33,261,465 | 8 | 2015-10-21T14:03:27Z | [
"python",
"pandas"
] | I have the following dataframe:
```
index = range(14)
data = [1, 0, 0, 2, 0, 4, 6, 8, 0, 0, 0, 0, 2, 1]
df = pd.DataFrame(data=data, index=index, columns = ['A'])
```
How can I fill the zeros with the previous non-zero value using pandas? Is there a fillna that is not just for "NaN"?.
The output should look like:
`... | You can use `replace` with `method='ffill'`
```
In [87]: df['A'].replace(to_replace=0, method='ffill')
Out[87]:
0 1
1 1
2 1
3 2
4 2
5 4
6 6
7 8
8 8
9 8
10 8
11 8
12 2
13 1
Name: A, dtype: int64
```
To get numpy array, work on `values`
```
In [88]: df['A'].replace(t... |
Why is "object.__dict__ is object.__dict__" False? | 33,262,578 | 8 | 2015-10-21T14:52:10Z | 33,262,645 | 7 | 2015-10-21T14:55:31Z | [
"python"
] | If I run the following code in a Python interpreter:
```
>>> object.__dict__ is object.__dict__
False
```
Why is the result `False`? | `object.__dict__`, unlike other `__dict__`s, returns a `mappingproxy` object (a `dict_proxy` in Python 2). These are created *on the fly* when `__dict__` is requested. So as a result, you get a new proxy every time you access `object.__dict__`. They all proxy the same underlying object, but the proxy is a fresh one all... |
Python/Django: Why does importing a module right before using it prevent a circular import? | 33,262,825 | 10 | 2015-10-21T15:04:08Z | 33,263,168 | 7 | 2015-10-21T15:21:22Z | [
"python",
"django",
"import",
"circular"
] | I've run into this problem a few times in different situations but my setup is the following:
I have two Django models files. One that contains User models and CouponCodes that a user can use to sign up for a Course. Those are both in the account/models.py file. Course and the related many-to-many field are in a diffe... | When a module is imported (well, the first time it's imported in a given process), all the top-level statements are executed (remember that `import` *is* an executable statement). So you cannot have module1 with an `import module2` statement at the top-level and module2 with an `import module1` at the top-level - it ca... |
Is there any way to clear django.db.connection.queries? | 33,265,144 | 5 | 2015-10-21T17:00:19Z | 33,265,391 | 7 | 2015-10-21T17:14:34Z | [
"python",
"django",
"django-models"
] | I want to monitor query time in my system(built with `Django models`).
Finally I found `django.db.connection.queries`.
It shows all queries and time taking for it.
Using this, I want to print the list of which I have done queries at regular interval and then I want to clear the list I printed after printing.
It see... | You can call `reset_queries()` from the django.db module. |
Python: get a frequency count based on two columns (variables) in pandas dataframe | 33,271,098 | 4 | 2015-10-21T23:41:23Z | 33,271,634 | 7 | 2015-10-22T00:44:50Z | [
"python",
"pandas",
"group-by",
"dataframe"
] | Hello I have the following dataframe.
```
Group Size
Short Small
Short Small
Moderate Medium
Moderate Small
Tall Large
```
I want to count the frequency of how many time the same row appears in the dataframe.
```
Group Size ... | You can use groupby's [`size`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html):
```
In [11]: df.groupby(["Group", "Size"]).size()
Out[11]:
Group Size
Moderate Medium 1
Small 1
Short Small 2
Tall Large 1
dtype: int64
In [12]: df.groupb... |
No module named BeautifulSoup (but it should be installed) | 33,286,790 | 3 | 2015-10-22T17:14:51Z | 33,286,853 | 7 | 2015-10-22T17:19:06Z | [
"python"
] | I downloaded BeautifulSoup.
Then I upgraded pip:
> pip install --upgrade pip
Then, installed BS:
> pip install beautifulsoup4
It seems like everything worked fine, but now when I run these three lines of code:
```
from BeautifulSoup import BeautifulSoup
import urllib2
import csv
```
I get this error.
> Traceba... | I think it should be `from bs4 import BeauitfulSoup` :) |
Replace empty strings with None/null values in DataFrame | 33,287,886 | 5 | 2015-10-22T18:14:52Z | 33,308,193 | 10 | 2015-10-23T17:27:25Z | [
"python",
"apache-spark",
"dataframe",
"apache-spark-sql",
"pyspark"
] | I have a [Spark 1.5.0 DataFrame](https://spark.apache.org/docs/1.5.0/api/python/pyspark.sql.html#pyspark.sql.DataFrame) with a mix of `null` and empty strings in the same column. I want to convert all empty strings in all columns to `null` (`None`, in Python). The DataFrame may have hundreds of columns, so I'm trying t... | It is as simple as this:
```
from pyspark.sql.functions import col, when
def blank_as_null(x):
return when(col(x) != "", col(x)).otherwise(None)
dfWithEmptyReplaced = testDF.withColumn("col1", blank_as_null("col1"))
dfWithEmptyReplaced.show()
## +----+----+
## |col1|col2|
## +----+----+
## | foo| 1|
## |null|... |
Noun phrases with spacy | 33,289,820 | 5 | 2015-10-22T20:12:04Z | 33,512,175 | 11 | 2015-11-04T01:26:34Z | [
"python",
"spacy"
] | How can I extract noun phrases from text using spacy?
I am not referring to part of speech tags.
In the documentation I cannot find anything about noun phrases or regular parse trees. | If you want base NPs, i.e. NPs without coordination, prepositional phrases or relative clauses, you can use the noun\_chunks iterator on the Doc and Span objects:
```
>>> from spacy.en import English
>>> nlp = English()
>>> doc = nlp(u'The cat and the dog sleep in the basket near the door.')
>>> for np in doc.noun_chu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.