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 |
|---|---|---|---|---|---|---|---|---|---|
Why isn't < working to read in a file from the command line (simple Python code)? | 21,692,784 | 2 | 2014-02-11T03:56:02Z | 21,692,804 | 8 | 2014-02-11T03:57:30Z | [
"python",
"file",
"input",
"command-line"
] | I have a simple program that reads in numbers and returns them sorted:
```
import sys
myset = set()
arguments = sys.argv[1:]
for x in arguments:
myset.add(int(x.rstrip()))
newset = sorted(myset)
print ("sorted")
for x in newset:
print x
```
It works perfectly when I type "python pysortints.py 1 5 6 7 2 6... | When you do
```
pysortints.py < testfile
```
the contents of `testfile` becomes available in the standard input, not as the command line parameters.
So, you need to read the data with `raw_input` (if you are using Python 2.x) or `input` (if your are using Python 3.x) functions.
Or alternatively, you can read direct... |
Is it possible to compute an inverse of sparse matrix in Python as fast as in Matlab? | 21,693,613 | 8 | 2014-02-11T05:09:13Z | 21,742,506 | 8 | 2014-02-12T23:52:23Z | [
"python",
"performance",
"matlab",
"numpy",
"sparse-matrix"
] | It takes 0.02 seconds for Matlab to compute the inverse of a diagonal matrix using the sparse command.
```
P = diag(1:10000);
P = sparse(P);
tic;
A = inv(P);
toc
```
However, for the Python code it takes forever - several minutes.
```
import numpy as np
import time
startTime = time.time()
P = np.diag(range(1,10000)... | Here is the answer. When you run inv in matlab for a sparse matrix, matlab check different properties of the matrix to optimize the calculation. For a sparse diagonal matrix, you can run the followin code to see what is matlab doing
```
n = 10000;
a = diag(1:n);
a = sparse(a);
I = speye(n,n);
spparms('spumoni',1);
ain... |
Difference between Python self and Java this | 21,694,901 | 8 | 2014-02-11T06:40:15Z | 21,695,075 | 7 | 2014-02-11T06:51:38Z | [
"java",
"python",
"this",
"self"
] | I had done a bit of Python long back. I am however moving over to Java now. I wanted to know if there were any differences between the Python "self" method and Java "this".
I know that "self" is not a keyword while "this" is. And that is pretty much what I could figure out. Am I missing anything else? | **Python self (here is the source: [Python self explanation](http://stackoverflow.com/questions/2709821/python-self-explained)):**
The reason you need to use *self*. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the m... |
Difference between Python self and Java this | 21,694,901 | 8 | 2014-02-11T06:40:15Z | 21,695,159 | 19 | 2014-02-11T06:56:21Z | [
"java",
"python",
"this",
"self"
] | I had done a bit of Python long back. I am however moving over to Java now. I wanted to know if there were any differences between the Python "self" method and Java "this".
I know that "self" is not a keyword while "this" is. And that is pretty much what I could figure out. Am I missing anything else? | First of all, let me correct you - `self` is not a method. Moving further:
Technically both `self` and `this` are used for the same thing. They are used to access the variable associated with the current instance. Only difference is, you have to include `self` explicitly as first parameter to an instance method in Pyt... |
Why is this iterative Collatz method 30% slower than its recursive version in Python? | 21,695,695 | 15 | 2014-02-11T07:30:10Z | 21,707,098 | 9 | 2014-02-11T16:13:21Z | [
"python",
"performance",
"recursion",
"iteration"
] | ### Prelude
I have two implementations for a particular problem, one recursive and one iterative, and I want to know what causes the iterative solution to be ~30% slower than the recursive one.
Given the recursive solution, I write an iterative solution making the stack explicit.
Clearly, I simply mimic what the re... | Here's my shot at a (partial) explanation after running some benchmarks, which confirm your figures.
While recursive function calls are expensive in CPython, they aren't nearly as expensive as emulating a call stack using lists. The stack for a recursive call is a compact structure implemented in C (see [Eli Bendersky... |
Scapy error: no module names pcapy | 21,698,894 | 10 | 2014-02-11T10:14:10Z | 21,699,024 | 10 | 2014-02-11T10:19:08Z | [
"python",
"scapy"
] | The code given below is for sniffing a packet from the IP address provided.
```
from scapy.all import *
sniff(filter="tcp and host 192.168.0.90", count=10)
```
On running this code the error I am getting is:
```
Traceback (most recent call last): File ".\sample.py", line 1, in <module>
from scapy.all import *... | try this to import For **Ubuntu**
```
$ sudo apt-get install python-pcapy
```
You can also build it from source:
```
$ sudo pip install "http://corelabs.coresecurity.com/index.php?module=Wiki&action=attachment&type=tool&page=Pcapy&file=pcapy-0.10.8.tar.gz"
```
And here is good documentation of Scapy. <http://www.se... |
ImportError: No module named flask.ext.login | 21,701,174 | 8 | 2014-02-11T11:57:35Z | 27,995,874 | 12 | 2015-01-17T03:32:00Z | [
"python",
"flask",
"flask-login"
] | I have a problem with flask\_login module.
i have installed flask\_login module successfully. Also from the command prompt i can run this script easily with no error:
```
Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more inform... | Install pip and then use the following command:
`C:\Python27\scripts>pip install Flask-Login` |
Why python set displays in "same" order if sets are unordered? | 21,701,618 | 3 | 2014-02-11T12:16:41Z | 21,701,640 | 11 | 2014-02-11T12:17:52Z | [
"python",
"set",
"order",
"python-internals"
] | I'm taking a first look at the python language from [Python wikibook](http://en.wikibooks.org/wiki/Python_Programming).
For sets the following is mentioned - `We can also have a loop move over each of the items in a set. However, since sets are unordered, it is undefined which order the iteration will follow.`
and th... | They are not randomly ordered, they are arbitrarily ordered. It means you should not count on the order of insertions being maintained as the actual internal implementation details determine the order instead.
The order depends on the insertion and deletion history of the set.
In CPython, sets use a hash table, where... |
Simulating the Knight Sequence Tour | 21,701,830 | 23 | 2014-02-11T12:26:33Z | 21,704,049 | 11 | 2014-02-11T14:04:01Z | [
"python",
"multithreading"
] | I am currently trying to write a simple multi-threading program using Python. However I have run on to a bug I think I am missing. I am trying to simply write a program that uses a brute force approach the problem below:

As can be seen from the image ... | There are several issues with your current code.
The first issue I see is that your checker never determines any potential move to be invalid. You have a bug in the conditional in this block:
```
if not to_be_removed:
for index in to_be_removed:
possible_moves.remove(index)
```
The loop only runs the loo... |
Simulating the Knight Sequence Tour | 21,701,830 | 23 | 2014-02-11T12:26:33Z | 21,833,334 | 30 | 2014-02-17T15:44:33Z | [
"python",
"multithreading"
] | I am currently trying to write a simple multi-threading program using Python. However I have run on to a bug I think I am missing. I am trying to simply write a program that uses a brute force approach the problem below:

As can be seen from the image ... | Your so-called *Quest of the [Knights Who Say Ni](https://en.wikipedia.org/wiki/Knights_who_say_Ni)* problem, while a clever rephrasing for asking a Python question, is more widely known as the [*Knights Tour*](https://en.wikipedia.org/wiki/Knights_tour "https://en.wikipedia.org/wiki/Knights_tour") mathematical problem... |
Creating a new column based on if-elif-else condition | 21,702,342 | 2 | 2014-02-11T12:49:58Z | 21,711,869 | 14 | 2014-02-11T20:04:43Z | [
"python",
"pandas",
"conditional"
] | I have a DataFrame `df`:
```
A B
a 2 2
b 3 1
c 1 3
```
I want to create a new column based on the following criteria:
if row `A == B: 0`
if row`A > B: 1`
if row `A < B: -1`
so given the above table, it should be:
```
A B C
a 2 2 0
b 3 1 1
c 1 3 -1
```
For ... | To formalize some of the approaches laid out above:
Create a function that operates on the rows of your dataframe like so:
```
def f(row):
if row['A'] == row['B']:
val = 0
elif row['A'] > row['B']:
val = 1
else:
val = -1
return val
```
Then apply it to your dataframe passing i... |
How to parse mjpeg http stream from ip camera? | 21,702,477 | 7 | 2014-02-11T12:57:13Z | 21,844,162 | 36 | 2014-02-18T04:08:05Z | [
"python",
"opencv",
"live-streaming",
"ip-camera",
"mjpeg"
] | Given below is the code written for getting live stream from an IP Camera.
```
from cv2 import *
from cv2 import cv
import urllib
import numpy as np
k=0
capture=cv.CaptureFromFile("http://IPADDRESS of the camera/axis-cgi/mjpg/video.cgi")
namedWindow("Display",1)
while True:
frame=cv.QueryFrame(capture)
if fra... | ```
import cv2
import urllib
import numpy as np
stream=urllib.urlopen('http://localhost:8080/frame.mjpg')
bytes=''
while True:
bytes+=stream.read(1024)
a = bytes.find('\xff\xd8')
b = bytes.find('\xff\xd9')
if a!=-1 and b!=-1:
jpg = bytes[a:b+2]
bytes= bytes[b+2:]
i = cv2.imdeco... |
How to parse mjpeg http stream from ip camera? | 21,702,477 | 7 | 2014-02-11T12:57:13Z | 36,675,148 | 7 | 2016-04-17T10:05:46Z | [
"python",
"opencv",
"live-streaming",
"ip-camera",
"mjpeg"
] | Given below is the code written for getting live stream from an IP Camera.
```
from cv2 import *
from cv2 import cv
import urllib
import numpy as np
k=0
capture=cv.CaptureFromFile("http://IPADDRESS of the camera/axis-cgi/mjpg/video.cgi")
namedWindow("Display",1)
while True:
frame=cv.QueryFrame(capture)
if fra... | First of all, please be aware that you should *first try* simply using OpenCV's video capture functions *directly*, e.g. `cv2.VideoCapture('http://localhost:8080/frame.mjpg')`!
This works just fine for me:
```
import cv2
cap = cv2.VideoCapture('http://localhost:8080/frame.mjpg')
while True:
ret, frame = cap.read()... |
AttributeError: 'module' object has no attribute | 21,702,945 | 3 | 2014-02-11T13:17:17Z | 21,704,320 | 8 | 2014-02-11T14:16:22Z | [
"python",
"opencv",
"ubuntu",
"stereo-3d"
] | I am trying to get the depth map of two stereo images. I have taken the code from <http://docs.opencv.org/trunk/doc/py_tutorials/py_calib3d/py_depthmap/py_depthmap.html>
I get the following error:
```
Traceback (most recent call last):
File "depth.py", line 9, in <module>
stereo = cv2.createStereoBM(numDisparit... | Use this function instead
```
stereo = cv2.StereoBM(cv2.STEREO_BM_BASIC_PRESET,ndisparities=16, SADWindowSize=15)
```
You can find documentation for this function [here](http://docs.opencv.org/2.4.1/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#stereobm-stereobm) |
Making a nested list from a list in Python | 21,706,274 | 2 | 2014-02-11T15:39:45Z | 21,706,309 | 7 | 2014-02-11T15:41:13Z | [
"python"
] | How do I make the following list:
```
nested_list = [['dave','dave'],['ian','ian'],['james','james']]
```
from:
```
list = ['dave', 'ian', 'james']
``` | ```
nested_list = [[x, x] for x in list]
```
or, if you don't mind tuples,
```
nested_list = zip(list, list)
``` |
Where is the NoneType located in Python 3.x? | 21,706,609 | 3 | 2014-02-11T15:52:52Z | 21,706,626 | 11 | 2014-02-11T15:53:51Z | [
"python",
"python-3.x",
"types",
"nonetype"
] | In Python 3, I would like to check whether `value` is either string or `None`.
One way to do this is
```
assert type(value) in { str, NoneType }
```
But where is `NoneType` located in Python?
Without any import, using `NoneType` produces `NameError: name 'NoneType' is not defined`. | You can use `type(None)` to get the type object, but you want to use `isinstance()` here, not `type() in {...}`:
```
assert isinstance(value, (str, type(None)))
```
The `NoneType` object is not otherwise exposed anywhere.
I'd not use type checking for that at all really, I'd use:
```
assert value is None or isinsta... |
How do I use the 'json' module to read in one JSON object at a time? | 21,708,192 | 12 | 2014-02-11T17:01:14Z | 21,709,058 | 12 | 2014-02-11T17:38:45Z | [
"python",
"json"
] | I have a multi-gigabyte JSON file. The file is made up of JSON objects that are no more than a few thousand characters each, but there are no line breaks between the records.
Using Python 3 and the `json` module, how can I read one JSON object at a time from the file into memory?
The data is in a plain text file. Her... | You can parse data in chunks using the [`JSONDecoder.raw_decode()` method](http://docs.python.org/2/library/json.html#json.JSONDecoder.raw_decode).
The following will yield complete objects as the parser finds them:
```
from json import JSONDecoder
from functools import partial
def json_parse(fileobj, decoder=JSOND... |
Python convention for variable naming to indicate units | 21,708,753 | 8 | 2014-02-11T17:26:02Z | 21,708,974 | 9 | 2014-02-11T17:34:31Z | [
"python",
"naming-conventions",
"pep8"
] | First, when I ask about units I mean units of measurement like inches, feet, pixels, cells. I am not referring to data types like int and float.
[Wikipedia](https://en.wikipedia.org/wiki/Hungarian_notation) refers to this as **logical data type** rather than **physical data type**.
I'd like to know the best way to na... | While you could come up with a naming convention, you might be better served by building an object representing "distance" with properties to read/write in different units. For instance:
```
class Distance(object):
def __init__(self):
self._inches = 0
@property
def inches(self):
return se... |
Least unofficial enum support in python2.7 - flufl.enum or enum34? | 21,709,300 | 5 | 2014-02-11T17:50:16Z | 21,715,170 | 7 | 2014-02-11T23:10:33Z | [
"python",
"enums"
] | Never thought I'd need to do this, but here I am intending to use enums in python 2.7.
There is Barry's [flufl.enum](http://packages.python.org/flufl.enum/docs/using.html) which PEP 435 says "...was the reference implementation upon which this PEP was originally based".
But there is also a backport [enum34](https://p... | `enum34` matches what is in Python3.4, so that's the one to use.
The one big difference between the backport and 3.4's:
* In Python 2 you cannot get definition order (because `__prepare__` doesn't exist yet), but there is a work-around -- define `__order__` and it will be the "definition order" in Python 2 (it's simp... |
How to return data from a MySQL query in a Flask app? | 21,709,992 | 2 | 2014-02-11T18:23:36Z | 21,717,690 | 8 | 2014-02-12T02:58:44Z | [
"python",
"mysql",
"flask"
] | I have the following code:
```
import flask as fk
import MySQLdb
import JSONEncoder
class SpecializedJSONEncoder(JSONEncoder):
def default(o):
if isinstance(o, date):
return date.strftime("%Y-%m-%d")
else:
super(SpecializedJSONEncoder, self).default(o)
app = fk.Flask(__na... | Use Flask's built-in [`jsonify`](http://flask.pocoo.org/docs/api/#flask.json.jsonify) function, as it is [already extended to work with dates](http://flask.pocoo.org/docs/api/#flask.json.JSONEncoder):
```
from Flask import jsonify
@app.route('/temp')
def temp():
# Load database results
# and then ...
retu... |
python converting set to list strange list behavior | 21,711,588 | 2 | 2014-02-11T19:49:27Z | 21,711,623 | 10 | 2014-02-11T19:51:33Z | [
"python"
] | I must be missing something because this is strange...
```
a = ['a', 'b', 'c']
a1 = ['b', 'a']
foo = list( set(a) - set(a1))
```
\*\* returning \*\*
```
foo == ['c']
type(foo) == <type 'list'>
foo[0] == 'c'
```
\*\* now the strange part \*\*
```
foo = foo.insert(0, 'z')
foo == None
```
why do list operations like... | `foo.insert()` *returns* `None`, but does change `foo` in the way you'd expect:
```
>>> foo = ['c']
>>> foo.insert(0, 'z')
>>> foo
['z', 'c']
```
If you wish to assign the result to a different variable, here is one way to do it:
```
>>> foo = ['c']
>>> bar = ['z'] + foo
>>> bar
['z', 'c']
``` |
Matplotlib imshow/matshow display values on plot | 21,712,047 | 4 | 2014-02-11T20:13:08Z | 21,712,361 | 11 | 2014-02-11T20:29:35Z | [
"python",
"numpy",
"matplotlib",
"visualization"
] | I am trying to create a 10x10 grid using either `imshow` or `matshow` in Matplotlib. The function below takes a numpy array as input, and plots the grid. However, I'd like to have values from the array also displayed inside the cells defined by the grid. So far I could not find a proper way to do it. I can use `plt.tex... | Can you do something like:
```
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
min_val, max_val = 0, 10
ind_array = np.arange(min_val + 0.5, max_val + 0.5, 1.0)
x, y = np.meshgrid(ind_array, ind_array)
for i, (x_val, y_val) in enumerate(zip(x.flatten(), y.flatten())):
c = 'x' if i%2 ... |
psycopg2, pymc, theano and DYLD_FALLBACK_LIBRARY_PATH | 21,713,148 | 3 | 2014-02-11T21:13:55Z | 21,714,067 | 7 | 2014-02-11T22:04:06Z | [
"python",
"osx",
"pymc",
"theano",
"psycopg"
] | I am unable to use `pymc` along with `psycopg2`. The following simple snippet from the tutorial:
```
import pymc as pm
with pm.Model() as model:
x = pm.Normal('x', mu=0., sd=1)
```
results in the following error:
> Exception: The environment variable 'DYLD\_FALLBACK\_LIBRARY\_PATH' does
> not contain the '/Users... | The development version of Theano don't need changes to DYLD\_FALLBACK\_LIBRARY\_PATH. So undo the change to it and update your Theano version. From:
<http://www.deeplearning.net/software/theano/install.html#bleeding-edge-install-instructions>
Run one of those 2 command depending of your need:
```
pip install --upgr... |
Need a fast way to count and sum an iterable in a single pass | 21,716,589 | 42 | 2014-02-12T01:04:50Z | 21,716,730 | 47 | 2014-02-12T01:18:54Z | [
"python",
"python-3.x"
] | Can any one help me? I'm trying to come up with a way to compute
```
>>> sum_widths = sum(col.width for col in cols if not col.hide)
```
and also count the number of items in this sum, without having to make two passes over `cols`.
It seems unbelievable but after scanning the std-lib (built-in functions, itertools, ... | I don't know about speed, but this is kind of pretty:
```
>>> from itertools import accumulate
>>> it = range(10)
>>> max(enumerate(accumulate(it), 1))
(10, 45)
``` |
Need a fast way to count and sum an iterable in a single pass | 21,716,589 | 42 | 2014-02-12T01:04:50Z | 21,716,742 | 23 | 2014-02-12T01:20:05Z | [
"python",
"python-3.x"
] | Can any one help me? I'm trying to come up with a way to compute
```
>>> sum_widths = sum(col.width for col in cols if not col.hide)
```
and also count the number of items in this sum, without having to make two passes over `cols`.
It seems unbelievable but after scanning the std-lib (built-in functions, itertools, ... | Here's some timing data that might be of interest:
```
import timeit
setup = '''
import random, functools, itertools, collections
x = [random.randint(0, 10) for _ in range(10**5)]
def count_and_sum(it):
c, s = 0, 0
for i in it:
c += 1
s += i
return c, s
def two_pass(it):
return sum(... |
Need a fast way to count and sum an iterable in a single pass | 21,716,589 | 42 | 2014-02-12T01:04:50Z | 21,716,754 | 93 | 2014-02-12T01:21:06Z | [
"python",
"python-3.x"
] | Can any one help me? I'm trying to come up with a way to compute
```
>>> sum_widths = sum(col.width for col in cols if not col.hide)
```
and also count the number of items in this sum, without having to make two passes over `cols`.
It seems unbelievable but after scanning the std-lib (built-in functions, itertools, ... | Using complex numbers
```
z = [1, 2, 4, 5, 6]
y = sum(x + 1j for x in z)
sum_z, count_z = y.real, int(y.imag)
print sum_z, count_z
18.0 5
``` |
Need a fast way to count and sum an iterable in a single pass | 21,716,589 | 42 | 2014-02-12T01:04:50Z | 21,717,164 | 26 | 2014-02-12T02:03:39Z | [
"python",
"python-3.x"
] | Can any one help me? I'm trying to come up with a way to compute
```
>>> sum_widths = sum(col.width for col in cols if not col.hide)
```
and also count the number of items in this sum, without having to make two passes over `cols`.
It seems unbelievable but after scanning the std-lib (built-in functions, itertools, ... | Adaption of DSM's answer. using `deque(... maxlen=1)` to save memory use.
```
import itertools
from collections import deque
deque(enumerate(itertools.accumulate(x), 1), maxlen=1)
```
timing code in ipython:
```
import itertools , random
from collections import deque
def count_and_sum(iter):
count = sum = 0... |
Need a fast way to count and sum an iterable in a single pass | 21,716,589 | 42 | 2014-02-12T01:04:50Z | 21,729,046 | 19 | 2014-02-12T13:16:30Z | [
"python",
"python-3.x"
] | Can any one help me? I'm trying to come up with a way to compute
```
>>> sum_widths = sum(col.width for col in cols if not col.hide)
```
and also count the number of items in this sum, without having to make two passes over `cols`.
It seems unbelievable but after scanning the std-lib (built-in functions, itertools, ... | As a follow-up to `senshin`'s answer, it's worth noting that the performance differences are largely due to quirks in CPython's implementation, that make some methods slower than others (for example, `for` loops are relatively slow in CPython). I thought it would be interesting to try the exact same test in PyPy (using... |
Python: how to determine if a list of words exist in a string | 21,718,345 | 9 | 2014-02-12T04:00:36Z | 21,718,896 | 8 | 2014-02-12T04:46:25Z | [
"python",
"regex"
] | Given a list `["one", "two", "three"]`, how to determine if each word exist in a specified string?
The word list is pretty short (in my case less than 20 words), but the strings to be searched is pretty huge (400,000 strings for each run)
My current implementation uses `re` to look for matches but I'm not sure if it'... | This function was found by Peter Gibson (below) to be the most performant of the answers here. It is good for datasets one may hold in memory (because it creates a list of words from the string to be searched and then a set of those words):
```
def words_in_string(word_list, a_string):
return set(word_list).inters... |
python flask-restful blueprint and factory pattern work together? | 21,718,603 | 6 | 2014-02-12T04:23:29Z | 21,719,288 | 13 | 2014-02-12T05:18:00Z | [
"python",
"rest",
"flask",
"blueprint",
"flask-restful"
] | I am working on a restful service using flask-restful, and i want to leverage both factory pattern and blueprint in my project.
in `app/__init__.py` i have a `create_app` function to create a flask app and return it to outside caller, so the caller can start the app.
```
def create_app():
app = Flask(__name__)
... | Flask-Restful, like all properly implemented Flask extensions, supports two methods of registering itself:
1. With the app at instantiation (as you are trying to do with `Api(current_app)`)
2. At a later point using [`api.init_app(app)`](http://flask-restful.readthedocs.org/en/latest/api.html#flask.ext.restful.Api.ini... |
Copying a key/value from one dictionary into another | 21,719,842 | 3 | 2014-02-12T05:57:59Z | 21,719,883 | 9 | 2014-02-12T06:00:08Z | [
"python",
"dictionary"
] | I have a dict with main data (roughly) as such: `{'UID': 'A12B4', 'name': 'John', 'email': '[email protected]}`
and I have another dict like: `{'UID': 'A12B4', 'other_thing: 'cats'}`
I'm unclear how to "join" the two dicts to then put "other\_thing" to the main dict. What I need is: `{'UID': 'A12B4', 'name': 'John', 'em... | you want to use the `dict.update` method:
```
d1 = {'UID': 'A12B4', 'name': 'John', 'email': '[email protected]'}
d2 = {'UID': 'A12B4', 'other_thing': 'cats'}
d1.update(d2)
```
Outputs:
```
{'email': '[email protected]', 'other_thing': 'cats', 'UID': 'A12B4', 'name': 'John'}
```
From the [Docs](http://docs.python.org/2/l... |
Find all columns of dataframe in Pandas whose type is float, or a particular type? | 21,720,022 | 11 | 2014-02-12T06:09:00Z | 21,720,133 | 7 | 2014-02-12T06:17:25Z | [
"python",
"pandas",
"dataframe",
"data-cleansing"
] | I have a dataframe, df, that has some columns of type float64, while the others are of object. Due to the mixed nature, I cannot use
```
df.fillna('unknown') #getting error "ValueError: could not convert string to float:"
```
as the error happened with the columns whose type is float64 (what a misleading error messag... | You can see what the dtype is for all the columns using the dtypes attribute:
```
In [11]: df = pd.DataFrame([[1, 'a', 2.]])
In [12]: df
Out[12]:
0 1 2
0 1 a 2
In [13]: df.dtypes
Out[13]:
0 int64
1 object
2 float64
dtype: object
In [14]: df.dtypes == object
Out[14]:
0 False
1 True
2 ... |
Find all columns of dataframe in Pandas whose type is float, or a particular type? | 21,720,022 | 11 | 2014-02-12T06:09:00Z | 30,740,087 | 9 | 2015-06-09T18:34:13Z | [
"python",
"pandas",
"dataframe",
"data-cleansing"
] | I have a dataframe, df, that has some columns of type float64, while the others are of object. Due to the mixed nature, I cannot use
```
df.fillna('unknown') #getting error "ValueError: could not convert string to float:"
```
as the error happened with the columns whose type is float64 (what a misleading error messag... | This is conciser:
```
# select the float columns
df_num = df.select_dtypes(include=[np.float])
# select non-numeric columns
df_num = df.select_dtypes(exclude=[np.number])
``` |
Cython & C++: passing by reference | 21,720,982 | 9 | 2014-02-12T07:07:48Z | 21,721,727 | 11 | 2014-02-12T07:49:59Z | [
"python",
"c++",
"reference",
"pass-by-reference",
"cython"
] | I am a noob with Cython and C++, so I have a question on argument passing. I want to avoid passing a copy of an argument in the following scenario:
```
# somefile.pyx
#distutils: language = c++
from libcpp.vector cimport vector
def add_one(vector[int] vect):
cdef int i
n = vect.size()
for i in range(n):
... | Found the naswer to my own question. Apparently, you can pass by reference, but the function MUST be `cdef`'ed, not `def`'ed. i.e.
```
# somefile.pyx
#distutils: language = c++
from libcpp.vector cimport vector
cdef void add_one(vector[int]& vect):
cdef int i
n = vect.size()
for i in range(<int>n):
... |
Counting 2d lists in python | 21,723,295 | 3 | 2014-02-12T09:11:39Z | 21,723,331 | 11 | 2014-02-12T09:12:47Z | [
"python",
"list",
"loops",
"multidimensional-array"
] | How can I count the number of items that are 'hit' in this 2d list??
```
grid = [['hit','miss','miss','hit','miss'],
['miss','miss','hit','hit','miss'],
['miss','miss','miss','hit','hit'],
['miss','miss','miss','hit','miss'],
['hit','miss','miss','miss','miss']]
battleships = 0
for i in grid:
... | Use [`list.count`](http://docs.python.org/2/library/stdtypes#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange):
```
>>> ['hit','miss','miss','hit','miss'].count('hit')
2
>>> grid = [['hit','miss','miss','hit','miss'],
... ['miss','miss','hit','hit','miss'],
... ['miss','miss','miss','hit','hit'... |
How to make a field non-editable in Flask Admin view of a model class | 21,727,129 | 3 | 2014-02-12T11:48:55Z | 22,596,795 | 12 | 2014-03-23T20:42:10Z | [
"python",
"flask",
"flask-admin"
] | I have a `User` model class and `password` is one attribute among many. I am using Flask web framework and Flask-Admin extension to create the admin view of my model classes. I want to make certain fields in the admin view like `password` non editable or not show them at all. How do I do it?
I can make the fields not ... | You should extend your view from ModelView and overwrite the necessary fields.
In my class it looks like this:
```
class UserView(ModelView):
column_list = ('first_name', 'last_name', 'username', 'email')
searchable_columns = ('username', 'email')
# this is to exclude the password field from list_view:
e... |
Python convex hull with scipy.spatial.Delaunay, how to eleminate points inside the hull? | 21,727,199 | 3 | 2014-02-12T11:52:42Z | 21,727,488 | 10 | 2014-02-12T12:05:41Z | [
"python",
"numpy",
"scipy",
"convex-hull",
"delaunay"
] | I have a list of 3D points in a np.array called `pointsList`, values are `float` :
```
[[1., 2., 10.],
[2., 0., 1.],
[3., 6., 9.],
[1., 1., 1.],
[2., 2., 2.],
[10., 0., 10.],
[0., 10., 5.],
... etc.
```
This code makes a Delaunay triangulation of the cloud of points:
```
import numpy as np
import scipy.spatial... | The convex hull is a subgraph of the Delaunay triangulation.
So you might just use [`scipy.spatial.ConvexHull()`](http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.spatial.ConvexHull.html), e. g.
```
from scipy.spatial import ConvexHull
cv = ConvexHull(pointList)
hull_points = cv.vertices
# the vertices ... |
Use of input/raw_input in python 2 and 3 | 21,731,043 | 17 | 2014-02-12T14:40:58Z | 21,731,110 | 19 | 2014-02-12T14:43:49Z | [
"python",
"python-3.x",
"input",
"python-2.x",
"raw-input"
] | I would like to set a user prompt with the following question:
```
save_flag is not set to 1; data will not be saved. Press enter to continue.
```
`input()` works in python3 but not python2. `raw_input()` works in python2 but not python3. Is there a way to do this so that the code is compatible with both python 2 and... | Bind `raw_input` to `input` in Python 2:
```
try:
input = raw_input
except NameError:
pass
```
Now `input` will return a string in Python 2 as well. |
Convert True/False value read from file to boolean | 21,732,123 | 23 | 2014-02-12T15:26:16Z | 21,732,183 | 29 | 2014-02-12T15:28:28Z | [
"python",
"string",
"boolean"
] | I'm reading a `True - False` value from a file and I need to convert it to boolean. Currently it always converts it to `True` even if the value is set to `False`.
Here's a `MWE` of what I'm trying to do:
```
with open('file.dat', mode="r") as f:
for line in f:
reader = line.split()
# Convert to bo... | `bool('True')` and `bool('False')` always return `True` because strings 'True' and 'False' are not empty.
To quote a a great man (and Python [documentation](http://docs.python.org/2/library/stdtypes.html#truth-value-testing)):
> ### [5.1. Truth Value Testing](https://docs.python.org/2/library/stdtypes.html#truth-valu... |
Convert True/False value read from file to boolean | 21,732,123 | 23 | 2014-02-12T15:26:16Z | 21,732,186 | 23 | 2014-02-12T15:28:42Z | [
"python",
"string",
"boolean"
] | I'm reading a `True - False` value from a file and I need to convert it to boolean. Currently it always converts it to `True` even if the value is set to `False`.
Here's a `MWE` of what I'm trying to do:
```
with open('file.dat', mode="r") as f:
for line in f:
reader = line.split()
# Convert to bo... | Use [`ast.literal_eval`](https://docs.python.org/2/library/ast.html#ast.literal_eval):
```
>>> import ast
>>> ast.literal_eval('True')
True
>>> ast.literal_eval('False')
False
```
> Why is flag always converting to True?
Non-empty strings are always True in Python.
Related: [Truth Value Testing](http://docs.python.... |
Convert True/False value read from file to boolean | 21,732,123 | 23 | 2014-02-12T15:26:16Z | 35,412,300 | 8 | 2016-02-15T14:46:57Z | [
"python",
"string",
"boolean"
] | I'm reading a `True - False` value from a file and I need to convert it to boolean. Currently it always converts it to `True` even if the value is set to `False`.
Here's a `MWE` of what I'm trying to do:
```
with open('file.dat', mode="r") as f:
for line in f:
reader = line.split()
# Convert to bo... | you can use [`distutils.util.strtobool`](https://docs.python.org/2/distutils/apiref.html#distutils.util.strtobool)
```
>>> from distutils.util import strtobool
>>> strtobool('True')
1
>>> strtobool('False')
0
```
`True` values are `y`, `yes`, `t`, `true`, `on` and `1`; `False` values are `n`, `no`, `f`, `false`, `of... |
Pandas dataframe add a field based on multiple if statements | 21,733,893 | 9 | 2014-02-12T16:35:48Z | 21,734,254 | 18 | 2014-02-12T16:49:27Z | [
"python",
"lambda"
] | I'm quite new to Python and Pandas so this might be an obvious question.
I have a dataframe with ages listed in it. I want to create a new field with an age banding. I can use the lambda statement to capture a single if / else statement but I want to use multiple if's e.g. `if age < 18 then 'under 18' elif age < 40 th... | The pandas DataFrame provides a nice querying ability.
What you are trying to do can be done simply with:
```
# Set a default value
df['Age_Group'] = '<40'
# Set Age_Group value for all row indexes which Age are greater than 40
df['Age_Group'][df['Age'] > 40] = '>40'
# Set Age_Group value for all row indexes which Ag... |
Using requests module, how to handle 'set-cookie' in request response? | 21,736,970 | 9 | 2014-02-12T18:50:53Z | 21,737,100 | 26 | 2014-02-12T18:56:58Z | [
"python",
"python-2.7",
"cookies",
"python-requests"
] | I'm attempting to open a login page (GET), fetch the cookies provided by the webserver, then submit a username and password pair to log into the site (POST).
Looking at [this Stackoverflow question/answer](http://stackoverflow.com/questions/6878418/putting-a-cookie-in-a-cookiejar), I would think that I would just do t... | Ignore the cookie-jar, let `requests` handle cookies for you. Use a [session object](http://docs.python-requests.org/en/latest/user/advanced/#session-objects) instead, it'll persist cookies and send them back to the server:
```
with requests.Session() as s:
r = s.get(URL1)
r = s.post(URL2, data="username and p... |
Python difference between randn and normal | 21,738,383 | 9 | 2014-02-12T20:01:37Z | 21,738,637 | 7 | 2014-02-12T20:13:40Z | [
"python",
"numpy"
] | I'm using the `randn` and `normal` functions from Python's `numpy.random` module. The functions are pretty similar from what I've read in the <http://docs.scipy.org> manual (they both concern the Gaussian distribution), but are there any subtler differences that I should be aware of? If so, in what situations would I b... | `randn` seems to give a distribution from some standardized normal distribution (mean 0 and variance 1). `normal` takes more parameters for more control. So `rand` seems to simply be a convenience function |
Python difference between randn and normal | 21,738,383 | 9 | 2014-02-12T20:01:37Z | 24,542,083 | 15 | 2014-07-02T22:26:18Z | [
"python",
"numpy"
] | I'm using the `randn` and `normal` functions from Python's `numpy.random` module. The functions are pretty similar from what I've read in the <http://docs.scipy.org> manual (they both concern the Gaussian distribution), but are there any subtler differences that I should be aware of? If so, in what situations would I b... | I'm a statistician who sometimes codes, not vice-versa, so this is something I can answer with some accuracy.
Looking at the docs that you linked in your question, I'll highlight some of the key differences:
normal:
```
numpy.random.normal(loc=0.0, scale=1.0, size=None)
# Draw random samples from a normal (Gaussian)... |
How to set a variable to be "Today's" date in Python/Pandas | 21,738,566 | 7 | 2014-02-12T20:10:39Z | 21,738,682 | 20 | 2014-02-12T20:16:42Z | [
"python",
"date",
"datetime",
"formatting",
"pandas"
] | I am trying to set a variable to equal today's date.
I looked this up and found a related article:
[Set today date as default value in the model](http://stackoverflow.com/questions/5023788/set-today-date-as-default-value-in-the-model)
However, this didn't particularly answer my question.
I used the suggested:
```
... | If you want a string `mm/dd/yyyy` instead of the `datetime` object, you can use `strftime` (string format time):
```
>>> dt.datetime.today().strftime("%m/%d/%Y")
# ^ note parentheses
'02/12/2014'
``` |
How to set a variable to be "Today's" date in Python/Pandas | 21,738,566 | 7 | 2014-02-12T20:10:39Z | 33,133,356 | 16 | 2015-10-14T18:51:45Z | [
"python",
"date",
"datetime",
"formatting",
"pandas"
] | I am trying to set a variable to equal today's date.
I looked this up and found a related article:
[Set today date as default value in the model](http://stackoverflow.com/questions/5023788/set-today-date-as-default-value-in-the-model)
However, this didn't particularly answer my question.
I used the suggested:
```
... | You mention you are using Pandas (in your title). If so, there is no need to use an external library, you can just use `to_datetime`
```
>>> pandas.to_datetime('today')
Timestamp('2015-10-14 00:00:00')
```
This will always return today's date at midnight, irrespective of the actual time (but guess what the argument `... |
Fast pandas filtering | 21,738,882 | 3 | 2014-02-12T20:28:02Z | 21,738,946 | 7 | 2014-02-12T20:31:54Z | [
"python",
"pandas"
] | I want to filter a pandas dataframe, if the name column entry has an item in a given list.
Here we have a DataFrame
```
x = DataFrame([['sam',328],['ruby',3213],['jon',121]], columns = ['name', 'score'])
```
Now lets say we have a list, ['sam', 'ruby'] and we want to find all rows where the name is in the list, then... | Try using [isin](http://pandas.pydata.org/pandas-docs/dev/indexing.html#indexing-with-isin) (thanks to DSM for suggesting `loc` over `ix` here):
```
In [78]: x = pd.DataFrame([['sam',328],['ruby',3213],['jon',121]], columns = ['name', 'score'])
In [79]: names = ['sam', 'ruby']
In [80]: x['name'].isin(names)
Out[80]:... |
How to close a SQLAlchemy session? | 21,738,944 | 15 | 2014-02-12T20:31:49Z | 21,742,461 | 25 | 2014-02-12T23:49:46Z | [
"python",
"session",
"sqlalchemy"
] | Following what we commented in [How to close sqlalchemy connection in MySQL](http://stackoverflow.com/questions/8645250/how-to-close-sqlalchemy-connection-in-mysql/8705750?noredirect=1#comment32872652_8705750), I am checking the connections that SQLAlchemy creates into my database and I cannot manage to close them with... | There's a central confusion here over the word "session". I'm not sure here, but it appears like you may be confusing the [SQLAlchemy Session](http://docs.sqlalchemy.org/en/latest/orm/session.html) with a [MySQL @@session](https://dev.mysql.com/doc/refman/5.1/en/set-statement.html), which refers to the scope of when yo... |
How to close a SQLAlchemy session? | 21,738,944 | 15 | 2014-02-12T20:31:49Z | 32,394,501 | 12 | 2015-09-04T09:23:58Z | [
"python",
"session",
"sqlalchemy"
] | Following what we commented in [How to close sqlalchemy connection in MySQL](http://stackoverflow.com/questions/8645250/how-to-close-sqlalchemy-connection-in-mysql/8705750?noredirect=1#comment32872652_8705750), I am checking the connections that SQLAlchemy creates into my database and I cannot manage to close them with... | `session.close()` will give the connection back to the connection pool of Engine and doesn't close the connection.
`engine.dispose()` will close all connections of the connection pool.
Engine will not use connection pool if you set `poolclass=NullPool`. So the connection (SQLAlchemy session) will close directly after... |
Python MySQLdb TypeError: not all arguments converted during string formatting | 21,740,359 | 14 | 2014-02-12T21:43:35Z | 21,740,476 | 30 | 2014-02-12T21:49:36Z | [
"python",
"python-2.7"
] | So I think I'm going crazy but upon running this script:
```
#! /usr/bin/env python
import MySQLdb as mdb
import sys
class Test:
def check(self, search):
try:
con = mdb.connect('localhost', 'root', 'password', 'recordsdb');
cur = con.cursor()
cur.execute( "SELECT *... | Instead of this:
```
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
```
Try this:
```
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", [search] )
```
See the MySQLdb [documentation](http://mysql-python.sourceforge.net/MySQLdb.html#some-examples). The reasoning is that `execute`'s se... |
Python MySQLdb TypeError: not all arguments converted during string formatting | 21,740,359 | 14 | 2014-02-12T21:43:35Z | 21,740,489 | 8 | 2014-02-12T21:50:13Z | [
"python",
"python-2.7"
] | So I think I'm going crazy but upon running this script:
```
#! /usr/bin/env python
import MySQLdb as mdb
import sys
class Test:
def check(self, search):
try:
con = mdb.connect('localhost', 'root', 'password', 'recordsdb');
cur = con.cursor()
cur.execute( "SELECT *... | You can try this code:
```
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", (search,) )
```
You can see the documentation : <http://mysql-python.sourceforge.net/MySQLdb.html> |
manage.py collectstatic command not found, Django 1.5.1 | 21,741,366 | 6 | 2014-02-12T22:36:08Z | 21,742,031 | 8 | 2014-02-12T23:18:12Z | [
"python",
"django"
] | I am very new to python and when I run the
`$ python manage.py collectstatic`
command, It returns
'unknown command: 'collectstatic''
From what I have found from research there seems to be a problem with settings.py, here is my settings.py:
```
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('', 'y... | Change media url from /media to /media/
Next time if you encounter such a problem, try runserver and check trace if it does not work. |
Check and wait until a file exists to read it | 21,746,750 | 12 | 2014-02-13T06:23:35Z | 21,746,775 | 18 | 2014-02-13T06:25:29Z | [
"python"
] | I need to wait until a file is created then read it in. I have the below code, but sure it does not work:
```
import os.path
if os.path.isfile(file_path):
read file in
else:
wait
```
Any ideas please? | A simple implementation could be:
```
import os.path
import time
while not os.path.exists(file_path):
time.sleep(1)
if os.path.isfile(file_path):
# read file
else:
raise ValueError("%s isn't a file!" % file_path)
```
You wait a certain amount of time after each check, and then read the file when the pat... |
How to check python code's syntax error before running it | 21,747,902 | 2 | 2014-02-13T07:35:16Z | 21,747,933 | 9 | 2014-02-13T07:37:15Z | [
"python",
"syntax-error"
] | I am developing a tool which has to accept a file as an input, check syntax errors, compile it and do something after that.
For example,
I have a file run.py:
```
a=5
b=c
print b
```
This should clearly show a syntax error while compiling because 'c' is not defined
I tried to use
```
try:
py_compile.compile("s... | It's not a syntax error. `b=c` is perfectly valid syntax, whether or not `c` exists. In fact, some other module could have done
```
import __builtin__
__builtin__.c = 3
```
in which case there would be a built-in `c` variable with value 3 available to all modules, and your code would run fine.
For a somewhat less pa... |
2D circular convolution Vs convolution FFT [Matlab/Octave/Python] | 21,751,908 | 2 | 2014-02-13T10:44:41Z | 21,757,317 | 10 | 2014-02-13T14:41:56Z | [
"python",
"matlab",
"signal-processing",
"fft",
"convolution"
] | I am trying to understand the FTT and convolution (cross-correlation) theory and for that reason I have created the following code to understand it. The code is Matlab/Octave, however I could also do it in Python.
In 1D:
```
x = [5 6 8 2 5];
y = [6 -1 3 5 1];
x1 = [x zeros(1,4)];
y1 = [y zeros(1,4)];
c1 = ifft(... | You need to zero-pad one variable with:
* As many zero-columns as the number of columns of other variable minus
one.
* As many zero-rows as the number of rows of the other variable minus one.

In Matlab, it would look in the following way:
```
% 1... |
Python: why pickle? | 21,752,259 | 17 | 2014-02-13T11:00:11Z | 21,752,597 | 9 | 2014-02-13T11:14:36Z | [
"python",
"pickle"
] | I have been using pickle and was very happy, then I saw this article: [Don't Pickle Your Data](http://www.benfrederickson.com/2014/02/12/dont-pickle-your-data.html)
Reading further it seems like:
* [Pickle is slow](http://kovshenin.com/2010/pickle-vs-json-which-is-faster/)
* [Pickle is unsafe](http://stackoverflow.co... | Pickle is unsafe because it constructs arbitrary Python objects by invoking arbitrary functions. However, this is also gives it the power to serialize almost any Python object, without any boilerplate or even white-/black-listing (in the common case). That's very desirable for some use cases:
* Quick & easy serializat... |
Pandas dataframe total row | 21,752,399 | 11 | 2014-02-13T11:06:20Z | 21,755,752 | 9 | 2014-02-13T13:32:43Z | [
"python",
"pandas"
] | I have a dataframe, something like:
```
foo bar qux
0 a 1 3.14
1 b 3 2.72
2 c 2 1.62
3 d 9 1.41
4 e 3 0.58
```
and I would like to add a 'total' row to the end of the dataframe:
```
foo bar qux
0 a 1 3.14
1 b 3 2.72
2 c 2 1.62
3 ... | Append a totals row with
```
df.append(df.sum(numeric_only=True), ignore_index=True)
```
The conversion is necessary only if you have a column of strings or objects.
It's a bit of a fragile solution so I'd recommend sticking to operations on the dataframe, though. eg.
```
baz = 2*df['qux'].sum() + 3*df['bar'].sum()... |
Factorial in numpy and scipy | 21,753,841 | 12 | 2014-02-13T12:09:01Z | 21,753,913 | 18 | 2014-02-13T12:12:11Z | [
"python",
"numpy",
"scipy"
] | How can I import factorial function from numpy and scipy separately in order to see which one is faster?
I already imported factorial from python itself by import math. But, it does not work for numpy and scipy. | You can import them like this:
```
In [7]: import scipy, numpy, math
In [8]: scipy.math.factorial, numpy.math.factorial, math.factorial
Out[8]:
(<function math.factorial>,
<function math.factori... |
Factorial in numpy and scipy | 21,753,841 | 12 | 2014-02-13T12:09:01Z | 21,754,208 | 9 | 2014-02-13T12:25:37Z | [
"python",
"numpy",
"scipy"
] | How can I import factorial function from numpy and scipy separately in order to see which one is faster?
I already imported factorial from python itself by import math. But, it does not work for numpy and scipy. | I didn't find a factorial in NumPy, but SciPy has one: [`scipy.misc.factorial`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.factorial.html)
```
>>> import math
>>> import scipy.misc
>>> math.factorial(6)
720
>>> scipy.misc.factorial(6)
array(720.0)
``` |
Factorial in numpy and scipy | 21,753,841 | 12 | 2014-02-13T12:09:01Z | 21,757,188 | 14 | 2014-02-13T14:35:58Z | [
"python",
"numpy",
"scipy"
] | How can I import factorial function from numpy and scipy separately in order to see which one is faster?
I already imported factorial from python itself by import math. But, it does not work for numpy and scipy. | The answer for Ashwini is great, in pointing out that scipy.math.factorial, numpy.math.factorial, math.factorial are the same functions. However, I'd recommend use the one that Janne mentioned, that scipy.misc.factorial is different. The one from scipy can take np.ndarray as an input, while the other can't.
```
In [12... |
C# equivalent of "value error" in Python | 21,755,882 | 2 | 2014-02-13T13:38:17Z | 21,755,939 | 7 | 2014-02-13T13:40:51Z | [
"c#",
"python",
"error-handling"
] | Is there a C# error exception for a value error? the equivalent of the python "value error" below?
```
except ValueError as e:
``` | Sounds like you probably want [`ArgumentException`](http://msdn.microsoft.com/en-us/library/system.argumentexception%28v=vs.110%29.aspx), or [`ArgumentNullException`](http://msdn.microsoft.com/en-us/library/system.argumentnullexception%28v=vs.110%29.aspx), or [`ArgumentOutOfRangeException`](http://msdn.microsoft.com/en... |
if or elif either true then do something | 21,756,433 | 44 | 2014-02-13T14:04:12Z | 21,756,519 | 19 | 2014-02-13T14:07:30Z | [
"python",
"python-2.7"
] | this is just for academic interest. I encounter the following situation a lot.
```
either_true = False
if x:
...do something1
either_true = True
elif y:
...do something2
either_true = True
if either_true:
..do something3
```
is there any pythonic way of doing it, or in general better programming way of doin... | I would handle this by using nested if statements i.e.
```
if x or y:
if x:
...do something1
elif y:
...do something2
...do something3
```
As some comments have pointed out, the best solution will depend on what x & y are. If easy readability / concise code is your goal then this or other ... |
if or elif either true then do something | 21,756,433 | 44 | 2014-02-13T14:04:12Z | 21,756,598 | 7 | 2014-02-13T14:11:25Z | [
"python",
"python-2.7"
] | this is just for academic interest. I encounter the following situation a lot.
```
either_true = False
if x:
...do something1
either_true = True
elif y:
...do something2
either_true = True
if either_true:
..do something3
```
is there any pythonic way of doing it, or in general better programming way of doin... | You could wrap some of it in a function:
```
def do_stuff():
if x:
...do something1
return True
elif y:
...do something2
return True
else:
return False
if do_stuff():
..do something3
```
Or all of it in a function:
```
def do_stuff()
if x:
...do so... |
if or elif either true then do something | 21,756,433 | 44 | 2014-02-13T14:04:12Z | 21,756,616 | 35 | 2014-02-13T14:12:15Z | [
"python",
"python-2.7"
] | this is just for academic interest. I encounter the following situation a lot.
```
either_true = False
if x:
...do something1
either_true = True
elif y:
...do something2
either_true = True
if either_true:
..do something3
```
is there any pythonic way of doing it, or in general better programming way of doin... | You could also omit the `either_true` flag completely if `doSomething3` is a single line of code (e.g. a function call):
```
if x:
..do something 1
..do something 3
elif y:
..do something 2
..do something 3
```
It maintains the nice property of evaluating `x` and `y` at most once (and `y` won't be evaluated i... |
if or elif either true then do something | 21,756,433 | 44 | 2014-02-13T14:04:12Z | 21,764,553 | 31 | 2014-02-13T20:14:29Z | [
"python",
"python-2.7"
] | this is just for academic interest. I encounter the following situation a lot.
```
either_true = False
if x:
...do something1
either_true = True
elif y:
...do something2
either_true = True
if either_true:
..do something3
```
is there any pythonic way of doing it, or in general better programming way of doin... | Your code is *almost* optimal, as far as code repetition and evaluation are concerned. The only thing I can think of to avoid repetition would be:
```
# be optimistic!
either_true = True
if x:
do_something1
elif y:
do_something2
else:
either_true = False
if either_true:
do_something3
```
This removes... |
How to generate n+1 long list, filled with 0s? | 21,757,991 | 2 | 2014-02-13T15:09:51Z | 21,758,020 | 14 | 2014-02-13T15:10:47Z | [
"python",
"list",
"python-3.x"
] | How to generate n+1 long list, filled with 0s? is there something that looks like `list=[0]+(n+1)?` | Try this:
```
[0] * (n+1) # using the * operator
```
For example:
```
n = 4
lst = [0] * (n+1)
lst
=> [0, 0, 0, 0, 0]
```
Read more about the correct usage of the multiplication operator on lists, [here](http://helloacm.com/multiplication-operator-in-python/) in a blog post. |
How to generate n+1 long list, filled with 0s? | 21,757,991 | 2 | 2014-02-13T15:09:51Z | 21,758,026 | 7 | 2014-02-13T15:11:05Z | [
"python",
"list",
"python-3.x"
] | How to generate n+1 long list, filled with 0s? is there something that looks like `list=[0]+(n+1)?` | ```
lst = [0] * (n+1)
```
(don't use "list" as a variable name, it hides the `list()` function) |
How can I repeat each test multiple times in a py.test run? | 21,764,473 | 5 | 2014-02-13T20:10:09Z | 21,963,558 | 7 | 2014-02-23T02:48:50Z | [
"python",
"py.test"
] | I want to run each selected py.test item an arbitrary number of times, sequentially.
I don't see any standard py.test mechanism for doing this.
I attempted to do this in the `pytest_collection_modifyitems()` hook. I modified the list of items passed in, to specify each item more than once. The first execution of a t... | In order to run each test a number of times, we will programmatically parameterize each test as the tests are being generated.
First, let's add the parser option (include the following in one of your conftest.py's):
```
def pytest_addoption(parser):
parser.addoption('--repeat', action='store',
help='Numbe... |
scaling numbers column by column with pandas [python] | 21,764,475 | 4 | 2014-02-13T20:10:12Z | 21,764,785 | 10 | 2014-02-13T20:27:41Z | [
"python",
"pandas"
] | I have a Pandas data frame 'df' in which I'd like to perform some scalings column by column.
* In column a, I need the maximum number to be 1, the minimum number to be 0, and all other to be spread accordingly.
* In column b, however, I need the **minimum number to be 1**, the **maximum number to be 0**, and all other... | You could subtract by the min then divide by the max (beware 0/0).
```
In [11]: df
Out[11]:
a b
A 14 103
B 90 107
C 90 110
D 96 114
E 91 114
In [12]: df -= df.min() # equivalent to df = df - df.min()
In [13]: df /= df.max() # equivalent to df = df / df.max()
In [14]: df
Out[14]:
a ... |
scaling numbers column by column with pandas [python] | 21,764,475 | 4 | 2014-02-13T20:10:12Z | 21,765,852 | 9 | 2014-02-13T21:27:50Z | [
"python",
"pandas"
] | I have a Pandas data frame 'df' in which I'd like to perform some scalings column by column.
* In column a, I need the maximum number to be 1, the minimum number to be 0, and all other to be spread accordingly.
* In column b, however, I need the **minimum number to be 1**, the **maximum number to be 0**, and all other... | This is how you can do it using `sklearn` and the `preprocessing` module. Sci-Kit Learn has many pre-processing functions for scaling and centering data.
```
In [0]: from sklearn.preprocessing import MinMaxScaler
In [1]: df = pd.DataFrame({'A':[14,90,90,96,91],
'B':[103,107,110,114,114]}).a... |
TypeError: got multiple values for argument | 21,764,770 | 12 | 2014-02-13T20:26:45Z | 21,765,286 | 22 | 2014-02-13T20:54:54Z | [
"python",
"python-3.x"
] | I read the other threads that had to do with this error and it seems that my problem has an interesting distinct difference than all the posts I read so far, namely, all the other posts so far have the error in regards to either a user created class or a builtin system resource. I am experiencing this problem when call... | This happens when a keyword argument is specified that overwrites a positional argument. For example, let's imagine a function that draws a colored box. The function selects the color to be used and delegates the drawing of the box to another function, relaying all extra arguments.
```
def color_box(color, *args, **kw... |
Converting binary to decimal integer output | 21,765,779 | 2 | 2014-02-13T21:23:13Z | 21,765,799 | 10 | 2014-02-13T21:24:33Z | [
"python",
"python-2.7",
"binary",
"integer",
"base-conversion"
] | I need to convert a binary input into a decimal integer. I know how to go from a decimal to a binary:
```
n = int(raw_input('enter a number: '))
print '{0:b}'.format(n)
```
I need to go in the reverse direction. My professor said that when he checks our code, he is going to input `11001`, and he should get `25` back.... | You can use [`int`](http://docs.python.org/2.7/library/functions.html#int) and set the base to `2` (for binary):
```
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>
```
---
However, if you cannot use `int` like that, then you could always do this:
```
binary = raw_input('e... |
h5py: Correct way to slice array datasets | 21,766,145 | 5 | 2014-02-13T21:44:20Z | 21,790,576 | 10 | 2014-02-14T22:24:57Z | [
"python",
"numpy",
"h5py"
] | I'm a bit confused here:
As far as I have understood, h5py's `.value` method reads an entire dataset and dumps it into an array, which is slow and discouraged (and should be generally replaced by `[()]`. The correct way is to use numpy-esque slicing.
However, I'm getting irritating results (with h5py 2.2.1):
```
imp... | For fast slicing with h5py, stick to the "plain-vanilla" slice notation:
```
file['test'][0:300000]
```
or, for example, reading every other element:
```
file['test'][0:300000:2]
```
Simple slicing (slice objects and single integer indices) should be very fast, as it translates directly into HDF5 hyperslab selectio... |
How to read config from string or list? | 21,766,451 | 5 | 2014-02-13T22:00:38Z | 21,766,494 | 9 | 2014-02-13T22:03:11Z | [
"python",
"python-2.7",
"configparser"
] | Is it possible to read the configuration for `ConfigParser` from a string or list?
Without any kind of temporary file on a filesystem
**OR**
Is there any similar solution for this? | You could use a buffer which behaves like a file:
```
import ConfigParser
import StringIO
s_config = """
[example]
is_real: False
"""
buf = StringIO.StringIO(s_config)
config = ConfigParser.ConfigParser()
config.readfp(buf)
print config.getboolean('example', 'is_real')
``` |
Value Error with color array when slicing values for scatter plot | 21,767,526 | 5 | 2014-02-13T23:07:25Z | 21,767,919 | 11 | 2014-02-13T23:33:58Z | [
"python",
"colors",
"matplotlib",
"slice"
] | I want to specify the frequency of markers that are printed in my scatter plot.
After being unsuccessful with markevery ([other stackoverflow question: Problems with using markevery](http://stackoverflow.com/questions/21761437/problems-with-markevery-attributeerror-unknown-property-markevery)) I followed the suggestion... | Your colour list should be the same length as your data. So you need to apply the same slice.
```
timePlot = ax.scatter(x[::5], y[::5], s=50, c=timeList[::5], marker = marker.next(), edgecolors='none', norm=cNorm, cmap = plt.matplotlib.cm.jet)
``` |
How to move pandas data from index to column after multiple groupby | 21,767,900 | 7 | 2014-02-13T23:32:14Z | 21,768,034 | 13 | 2014-02-13T23:42:13Z | [
"python",
"pandas"
] | I have the following pandas dataframe:
```
In [8]: dfalph.head()
Out[8]: token year uses books
386 xanthos 1830 3 3
387 xanthos 1840 1 1
388 xanthos 1840 2 2
389 xanthos 1868 2 2
390 xanthos 1875 1 1
``... | Method #1: `reset_index()`
```
>>> g
uses books
sum sum
token year
xanthos 1830 3 3
1840 3 3
1868 2 2
1875 1 1
[4 rows x 2 columns]
>>> g = g.reset_index()
>>> g
token year uses books
... |
Why does periodically pressing the enter key substantially speed up my code? | 21,768,318 | 7 | 2014-02-14T00:07:11Z | 21,768,393 | 7 | 2014-02-14T00:13:23Z | [
"python",
"python-idle"
] | I inadvertently ran across a phenomenon that has me a bit perplexed. I was using IDLE for some quick testing, and I had some very simple code like this (which I have simplified for the purpose of illustration):
```
from time import clock # I am presently using windows
def test_speedup():
c = clock()
for i in... | Under the covers, IDLE is simulating a terminal on top of a Tk widget, which I'm pretty sure is ultimately derived from [`Text`](http://effbot.org/tkinterbook/text.htm).
The presence of long lines slows down that widget a little bit. And appending to long lines takes longer than appending to short ones. If you really ... |
Selenium with GhostDriver in Python on Windows | 21,768,554 | 9 | 2014-02-14T00:27:45Z | 24,579,327 | 7 | 2014-07-04T18:25:49Z | [
"python",
"selenium",
"phantomjs",
"ghostdriver"
] | This is embarrassing to ask because it seems like something with so slim chance of error. I wouldn't think this would be difficult, but I've been plugging away at this for almost 3 hours now and it's giving me a headache. I've read several dozen stackoverflow threads and Google threads.
I've installed PhantomJS, added... | This may have been a version issue for you, but since I just went through setting this up on my Windows 7 PC without issues I'm going to share my 'journey' here.
First of, I'm more used to the Mac/Linux Terminal and having the python package manager `pip` at my disposal is essential to me. After installing [Python 2.7... |
Free the opened ctypes library in Python | 21,770,419 | 3 | 2014-02-14T03:41:52Z | 21,794,318 | 7 | 2014-02-15T06:41:15Z | [
"python",
"dll",
"ctypes"
] | I was wondering that, if I opened my own dll library compiled from custom c code, like this:
```
import ctypes
my_lib = ctypes.cdll.LoadLibrary('./my_dll.dll')
my_func = my_lib.my_func
# Stuff I want to do with func()
```
Do I need to close the my\_lib object after use, like a file object? Will doing this make the co... | Generally you shouldn't have to free a shared library. Consider that CPython doesn't provide a means to unload a regular extension module from memory. For example, importing sqlite3 will load the \_sqlite3 extension and sqlite3 shared library for the life of the process. Unloading extensions is incompatible with the wa... |
SQLAlchemy - copy schema and data of subquery to another database | 21,770,829 | 10 | 2014-02-14T04:23:41Z | 21,885,556 | 11 | 2014-02-19T15:50:48Z | [
"python",
"sql",
"sqlalchemy"
] | I am trying to copy data from a subquery from postgres (from\_engine) to sqlite database. I can achieve this for copying a table using following command:
```
smeta = MetaData(bind=from_engine)
table = Table(table_name, smeta, autoload=True)
table.metadata.create_all(to_engine)
```
However, I am not sure how to achiev... | One way that works at least in some cases:
1. Use `column_descriptions` of a query object to get some information about the columns in the result set.
2. With that information you can build the schema to create the new table in the other database.
3. Run the query in the source database and insert the results into the... |
Python Set Comprehension | 21,770,885 | 23 | 2014-02-14T04:29:43Z | 21,771,113 | 15 | 2014-02-14T04:52:22Z | [
"python",
"set",
"set-comprehension"
] | So I have these two problems for a homework assignment and I'm stuck on the second one.
1. Use a Python Set Comprehension (Python's equivalent of Set Builder notation) to generate a set of all of the prime numbers that are less than 100. Recall that a prime number is an integer that is greater than 1 and not divisible... | ```
primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}
```
I simplified the test a bit - `if all(x%y` instead of `if not any(not x%y`
I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.
```
p... |
finding non-numeric rows in dataframe in pandas? | 21,771,133 | 13 | 2014-02-14T04:54:02Z | 21,772,078 | 19 | 2014-02-14T06:13:00Z | [
"python",
"pandas",
"dataframe"
] | I have a large dataframe in pandas that apart from the column used as index is supposed to have only numeric values:
```
df = pandas.DataFrame({"item": ["a", "b", "c", "d", "e"], "a": [1,2,3,"bad",5], "b":[0.1,0.2,0.3,0.4,0.5]})
df = df.set_index("item")
```
How can I find the row of the dataframe `df` that has a non... | You could use [`np.isreal`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.isreal.html) to check the type of each element ([applymap](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html) applies a function to each element in the DataFrame):
```
In [11]: df.applymap(np.isreal... |
Multi-tenant SAAS in Django | 21,771,345 | 13 | 2014-02-14T05:13:53Z | 21,959,927 | 14 | 2014-02-22T20:13:58Z | [
"python",
"django",
"web-applications",
"database-design",
"saas"
] | I have developed Multi-tenant SAAS apps in PHP/Laravel but recently I had a challenge to develop one in Django/Python. I am still learning Django though and I really like Django rest framework (DRF). But I have difficulties to figure out the highlighted areas below, If someone shows some light, I will be good to go:
1... | Well...
1. [django-subdomains](https://github.com/tkaemming/django-subdomains)
2. There [are](http://stackoverflow.com/questions/6585373/django-multiple-and-dynamic-databases) [people](http://stackoverflow.com/questions/9908186/django-switch-database-dynamically) who asked in SO questions about dynamic databases in dj... |
Python: How to download file using range of bytes? | 21,775,860 | 2 | 2014-02-14T09:46:05Z | 21,776,292 | 10 | 2014-02-14T10:07:06Z | [
"python",
"python-2.7",
"http-headers",
"http-protocols"
] | I want to download file in multi thread mode and I have following code here:
```
#!/usr/bin/env python
import httplib
def main():
url_opt = '/film/0d46e21795209bc18e9530133226cfc3/7f_Naruto.Uragannie.Hroniki.001.seriya.a1.20.06.13.mp4'
headers = {}
headers['Accept-Language'] = 'en-GB,en-US,en'
head... | Pass [`Range`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35) header with `bytes=start_offset-end_offset` as range specifier.
For example, following code retrieve the first 300 bytes. (`0-299`):
```
>>> import httplib
>>> conn = httplib.HTTPConnection('localhost')
>>> conn.request("GET", '/', header... |
Counting the number of non-NaN elements in a numpy ndarray matrix in Python | 21,778,118 | 14 | 2014-02-14T11:26:25Z | 21,778,195 | 32 | 2014-02-14T11:29:54Z | [
"python",
"numpy",
"matrix",
null
] | I need to calculate the number of non-NaN elements in a numpy ndarray matrix. How would one efficiently do this in Python? Here is my simple code for achieving this:
```
import numpy as np
def numberOfNonNans(data):
count = 0
for i in data:
if not np.isnan(i):
count += 1
return count
`... | ```
np.count_nonzero(~np.isnan(data))
```
`~` inverts the boolean matrix returned from `np.isnan`.
`np.count_nonzero` counts values that is not 0\false. `.sum` should give the same result. But maybe more clearly to use `count_nonzero`
Testing speed:
```
In [23]: data = np.random.random((10000,10000))
In [24]: data... |
Can't run MySql Utilities | 21,781,598 | 6 | 2014-02-14T14:09:58Z | 21,867,552 | 17 | 2014-02-18T23:12:37Z | [
"python",
"mysql",
"mysql-workbench"
] | When I try and run MySQL Utilities from WorkBench I get the following error:
```
h3tr1ck$ mysqluc -e "help utilities"
Traceback (most recent call last):
File "/bin/mysqluc", line 23, in <module>
from mysql.utilities.common.options import license_callback, UtilitiesParser
File "/Library/Python/2.7/site-packages/mys... | MYSQL Utilities assumes that the MySQL Connector for Python has been installed.
If you install it (<http://dev.mysql.com/downloads/connector/python/>), MySQL Utilities should run OK. |
all() returning a generator? | 21,783,066 | 3 | 2014-02-14T15:19:39Z | 21,783,228 | 11 | 2014-02-14T15:27:23Z | [
"python",
"iterator",
"generator"
] | So I want to test if a list is sorted. After reading this [page](http://stackoverflow.com/questions/4710763/how-do-i-check-if-a-list-is-sorted), I did this:
```
ll = [ 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 ]
all(b >= a for a, b in zip(ll, ll[1:]) )
```
Output
```
<generator object <genexpr> at 0x10d9e... | This is a problem of those silly star-imports:
```
from numpy import *
ll = [ 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 ]
all(b >= a for a, b in zip(ll, ll[1:]) )
#>>> <generator object <genexpr> at 0x7f976073fdc0>
```
Python's `all` works fine.
You can access it via `__builtin__` module in python2 and `... |
How to input a word in ncurses screen? | 21,784,625 | 4 | 2014-02-14T16:33:36Z | 21,785,167 | 8 | 2014-02-14T16:57:55Z | [
"python",
"ncurses"
] | I was trying to use `raw_input()` function first, but find it in compatible with ncurses.
Then I tried `window.getch()` function, I can type and show characters on screen, but can't realize input. How can I input a word in `ncurses` and can use if statement to evaluate it?
For example, I wanna realize this in `ncurs... | Function `raw_input( )` doesn't works in curses mode, The `getch()` method returns an integer; it represents the ASCII code of the key pressed. The will not work if you wants to scan string from prompt. You can make use of `getstr` function:
> ### [`window.getstr([y, x])`](http://docs.python.org/3.3/library/curses.htm... |
sqlalchemy IS NOT NULL select | 21,784,851 | 25 | 2014-02-14T16:44:02Z | 21,784,915 | 40 | 2014-02-14T16:46:34Z | [
"python",
"sqlalchemy"
] | How can I add the filter as in SQL to select values that are NOT NULL from a certain column ?
```
SELECT *
FROM table
WHERE YourColumn IS NOT NULL;
```
How can I do the same with SQLAlchemy filters?
```
select = select(table).select_from(table).where(all_filters)
``` | `column_obj != None` will produce a [`IS NOT NULL` constraint](http://docs.sqlalchemy.org/en/rel_1_0/core/sqlelement.html#sqlalchemy.sql.expression.ColumnElement.__ne__):
> In a column context, produces the clause `a != b`. If the target is `None`, produces a `IS NOT NULL`.
or use [`isnot()`](http://docs.sqlalchemy.o... |
sqlalchemy IS NOT NULL select | 21,784,851 | 25 | 2014-02-14T16:44:02Z | 37,196,866 | 12 | 2016-05-12T20:30:30Z | [
"python",
"sqlalchemy"
] | How can I add the filter as in SQL to select values that are NOT NULL from a certain column ?
```
SELECT *
FROM table
WHERE YourColumn IS NOT NULL;
```
How can I do the same with SQLAlchemy filters?
```
select = select(table).select_from(table).where(all_filters)
``` | Starting in version 0.7.9 you can use the filter operator `.isnot` instead of comparing constraints, like this:
`query.filter(User.name.isnot(None))`
This method is only necessary if pep8 is a concern.
source: [sqlalchemy documentation](http://docs.sqlalchemy.org/en/rel_1_0/core/sqlelement.html#sqlalchemy.sql.operat... |
Check if value is between pair of values in a tuple? | 21,784,887 | 4 | 2014-02-14T16:45:42Z | 21,785,006 | 7 | 2014-02-14T16:50:49Z | [
"python",
"conditional",
"tuples"
] | Is there an efficient way (nice syntax) to check if a value is between two values contained in a tuple?
The best thing I could come up with is:
```
t = (1, 2)
val = 1.5
if t[0] <= val <= t[1]:
# do something
```
Is there a nicer way to write the conditional? | No, there is no dedicated syntax, using chained comparisons is the right way to do this already.
The one 'nicety' I can offer is to use tuple unpacking first, but that's just readability icing here:
```
low, high = t
if low <= val <= high:
```
If you are using a tuple subclass produced by [`collection.namedtuple()`]... |
Python class method chaining | 21,785,689 | 10 | 2014-02-14T17:23:57Z | 21,785,906 | 9 | 2014-02-14T17:35:57Z | [
"python",
"python-2.7",
"magic-methods"
] | To avoid getting lost in architectural decisions, I'll ask this with an analogous example:
lets say I wanted a Python class pattern like this:
```
queue = TaskQueue(broker_conn)
queue.region("DFW").task(fn, "some arg")
```
The question here is how do I get a design a class such that certain methods can be "chained" ... | SQLAlchemy produces a clone on such calls, see [`Generative._generate()` method](https://github.com/zzzeek/sqlalchemy/blob/3dc9f9b3db10254f688c6b25b58951a4b1d4a41b/lib/sqlalchemy/sql/base.py#L158) which simply returns a clone of the current object.
On each generative method call (such as `.filter()`, `.orderby()`, etc... |
Purpose of calling function without brackets python | 21,785,933 | 3 | 2014-02-14T17:37:38Z | 21,785,974 | 8 | 2014-02-14T17:39:27Z | [
"python",
"python-3.x"
] | Consider the following:
```
class objectTest():
def __init__(self,a):
self.value = a
def get_value(self):
return self.value
class execute():
def __init__(self):
a = objectTest(1)
b = objectTest(1)
print(a == b)
print(a.get_value() == b.get_value)
... | Functions and methods in Python are also objects themselves. Thus you can compare them just as you would any other object.
```
>>> type(a.get_value)
<type 'instancemethod'>
>>> type(a.get_value())
<type 'int'>
```
Normally of course you wouldn't compare methods to each other or anything else, because it's not terribl... |
How do you edit the default `__author__ = name` line in PyCharm | 21,786,317 | 7 | 2014-02-14T17:58:21Z | 21,786,523 | 9 | 2014-02-14T18:09:24Z | [
"python",
"pycharm"
] | In pycharm, when making a new "Python File" it has some content by default:
`__author__ = 'david'`.
What I want to do, is changing this default content by the following shebang:
```
#!/usr/bin/env python
#-*- coding: utf-8 -*-
```
This way, when opening new python files on pycharm, this content above will already be... | In PyCharm, go to **Preferences** > **IDE Settings** > **File and Code Templates** and then click on the Python Script template and change it from the default to whatever you want.
Thanks for the question, I always thought the `__author__ = blah` was annoying but never took the time to learn how to fix it. |
Pandas left outer join multiple dataframes on multiple columns | 21,786,490 | 15 | 2014-02-14T18:07:39Z | 21,787,325 | 31 | 2014-02-14T18:52:57Z | [
"python",
"sql",
"merge",
"pandas"
] | I am new to using DataFrame and I would like to know how to perform a SQL equivalent of left outer join on multiple columns on a series of tables
Example:
```
df1:
Year Week Colour Val1
2014 A Red 50
2014 B Red 60
2014 B Black 70
2014 C Red 10
2014 D Green 20
df2:
Year Week ... | Merge them in two steps, `df1` and `df2` first, and then the result of that to `df3`.
```
In [33]: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])
```
I dropped year from df3 since you don't need it for the last join.
```
In [39]: df = pd.merge(s1, df3[['Week', 'Colour', 'Val3']],
... |
converting epoch time with milliseconds to datetime | 21,787,496 | 21 | 2014-02-14T19:03:41Z | 21,787,591 | 8 | 2014-02-14T19:08:46Z | [
"python",
"ruby",
"datetime",
"epoch"
] | I have used a ruby script to convert iso time stamp to epoch, the files that I am parsing has following time stamp structure:
```
2009-03-08T00:27:31.807
```
Since I want to keep milliseconds I used following ruby code to convert it to epoch time:
```
irb(main):010:0> DateTime.parse('2009-03-08T00:27:31.807').strfti... | those are miliseconds, just divide them by 1000, since gmtime expects seconds ...
```
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))
``` |
converting epoch time with milliseconds to datetime | 21,787,496 | 21 | 2014-02-14T19:03:41Z | 21,787,689 | 42 | 2014-02-14T19:14:20Z | [
"python",
"ruby",
"datetime",
"epoch"
] | I have used a ruby script to convert iso time stamp to epoch, the files that I am parsing has following time stamp structure:
```
2009-03-08T00:27:31.807
```
Since I want to keep milliseconds I used following ruby code to convert it to epoch time:
```
irb(main):010:0> DateTime.parse('2009-03-08T00:27:31.807').strfti... | Use [`datetime.datetime.fromtimestamp`](http://docs.python.org/2/library/datetime.html#datetime.datetime.fromtimestamp):
```
>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'
```
`%f` directive is only supported by [... |
How to pass along username and password to cassandra in python | 21,787,950 | 6 | 2014-02-14T19:30:23Z | 22,333,258 | 12 | 2014-03-11T18:17:16Z | [
"python",
"authentication",
"cassandra"
] | I'm learning and just setup my cassandra cluster and trying to use python as the client to interact with it. In the yaml, I set the authenticator to be PasswordAuthenticator.
So now I plan to provide my username and password over to the connect function but find no where to put them.
```
cluster = Cluster(hosts)
sess... | Following the ops recommendation use:
```
from cassandra.cluster import Cluster
def getCredential(self):
return {'username': 'foo', 'password': 'bar'}
node_ips = ['0.0.0.0', '0.0.0.1']
cluster = Cluster(node_ips, protocol_version=1, auth_provider=getCredential)
session = cluster.connect()
```
If you're using ... |
How to use PyCharm to debug Scrapy projects | 21,788,939 | 45 | 2014-02-14T20:27:14Z | 22,254,926 | 75 | 2014-03-07T16:04:28Z | [
"python",
"debugging",
"python-2.7",
"scrapy",
"pycharm"
] | I am working on Scrapy 0.20 with Python 2.7. I found PyCharm has a good Python debugger. I want to test my Scrapy spiders using it. Anyone knows how to do that please?
### What I have tried
Actually I tried to run the spider as a scrip. As a result, I built that scrip. Then, I tried to add my Scrapy project to PyChar... | The `scrapy` command is a python script which means you can start it from inside PyCharm.
When you examine the scrapy binary (`which scrapy`) you will notice that this is actually a python script:
```
#!/usr/bin/python
from scrapy.cmdline import execute
execute()
```
This means that a command like
`scrapy crawl Ice... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.