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
Outputting difference in two pandas dataframes side by side - highlighting the difference
17,095,101
28
2013-06-13T19:08:16Z
17,095,620
37
2013-06-13T19:39:44Z
[ "python", "html", "dataframe", "pandas" ]
I am trying to highlight exactly what changed between two dataframes. Suppose I have two Python Pandas dataframe ``` "StudentRoster Jan-1": id Name score isEnrolled Comment 111 Jack 2.17 True He was late to class 112 Nick 1.11 ...
The first part is similar to Constantine, you can get the boolean of which rows are empty\*: ``` In [21]: ne = (df1 != df2).any(1) In [22]: ne Out[22]: 0 False 1 True 2 True dtype: bool ``` Then we can see which entries have changed: ``` In [23]: ne_stacked = (df1 != df2).stack() In [24]: changed = ne_s...
Outputting difference in two pandas dataframes side by side - highlighting the difference
17,095,101
28
2013-06-13T19:08:16Z
17,096,675
7
2013-06-13T20:41:36Z
[ "python", "html", "dataframe", "pandas" ]
I am trying to highlight exactly what changed between two dataframes. Suppose I have two Python Pandas dataframe ``` "StudentRoster Jan-1": id Name score isEnrolled Comment 111 Jack 2.17 True He was late to class 112 Nick 1.11 ...
``` import pandas as pd import io texts = ['''\ id Name score isEnrolled Comment 111 Jack 2.17 True He was late to class 112 Nick 1.11 False Graduated 113 Zoe 4.12 ...
Outputting difference in two pandas dataframes side by side - highlighting the difference
17,095,101
28
2013-06-13T19:08:16Z
23,088,780
10
2014-04-15T15:57:24Z
[ "python", "html", "dataframe", "pandas" ]
I am trying to highlight exactly what changed between two dataframes. Suppose I have two Python Pandas dataframe ``` "StudentRoster Jan-1": id Name score isEnrolled Comment 111 Jack 2.17 True He was late to class 112 Nick 1.11 ...
I have faced this issue, but found an answer before finding this post : Based on unutbu's answer, load your data... ``` import pandas as pd import io texts = ['''\ id Name score isEnrolled Date 111 Jack True 2013-05-01 12:00:00 112...
Error 32, Python, file being used by another process
17,095,309
7
2013-06-13T19:20:29Z
17,095,492
7
2013-06-13T19:31:20Z
[ "python" ]
I have a simple program, which looks for all compressed folders in a directory, targets one compressed file, gets an excel file located inside the compressed file and moves it to another location (it does this for every excel file, for how many ever compressed folders): ``` path = 'C:\Users\me\Documents\Extract' new_p...
``` path = 'C:\Users\me\Documents\Extract' destination_path = 'C:\Users\me\Documents\Test' i = 0 for folder in os.listdir(path): path_to_zip_file = os.path.join(path, folder) zfile = zipfile.ZipFile(path_to_zip_file) for name in zfile.namelist(): if name.endswith('.xls'): new_name = str...
Copying python lists
17,096,298
8
2013-06-13T20:20:57Z
17,096,347
10
2013-06-13T20:23:45Z
[ "python", "list", "deep-copy" ]
Just when I thought I had understood how Python lists work... ``` >>> a = [1,2,3] >>> b = a[:] >>> b [1,2,3] >>> b[1]=100 >>> b [1,100,3] >>> a [1,2,3] ``` So far,so good. I am initializing b with the contents of a, so that b points to a different object. As a consequence, changes in b don't affect a. Now take a loo...
The slicing operation `x[:]` makes a *shallow copy*. That means, the outer list is different, but is contains the exact same elements. assume `a = [[1]]`: ``` b = a[:] # is the same as: b = [x for x in a] >>> a[0] is b[0] True ``` The double slicing (`[:][:]`) is doing nothing more than that - again: ``` b = a[:][:...
How to replace values with None in Pandas data frame in Python?
17,097,236
19
2013-06-13T21:17:31Z
17,097,397
25
2013-06-13T21:29:01Z
[ "python", "replace", "pandas", null, "nonetype" ]
Is there any method to replace values with `None` in Pandas in Python? You can use `df.replace('pre', 'post')` and can replace a value with another, but this can't be done if you want to replace with `None` value, which if you try, you get a strange result. So here's an example: ``` df = DataFrame(['-',3,2,5,1,-5,-1...
Actually in later versions of pandas this will give a TypeError: ``` df.replace('-', None) TypeError: If "to_replace" and "value" are both None then regex must be a mapping ``` You can do it by passing either a list or a dictionary: ``` In [11]: df.replace('-', df.replace(['-'], [None]) # or .replace('-', {0: None})...
Flask 0.10 giving unicode error on session cookie
17,097,258
6
2013-06-13T21:18:46Z
17,097,373
10
2013-06-13T21:27:25Z
[ "python", "flask", "flask-login" ]
After upgrading to Flask 0.10, I get this error: ``` flask.debughelpers.UnexpectedUnicodeError UnexpectedUnicodeError: A byte string with non-ASCII data was passed to the session system which can only store unicode strings. Consider base64 encoding your string (String was 'iB\rOU#\xf7BO\x08^\xa6\xd1)v\xad') Tracebac...
That's currently an issue with [Flask-Login](https://github.com/maxcountryman/flask-login). As far as I know it's fixed in the git version of the extension.
UnboundLocalError: local variable … referenced before assignment
17,097,273
2
2013-06-13T21:19:52Z
17,097,379
8
2013-06-13T21:27:47Z
[ "python", "python-2.7" ]
``` import hmac, base64, hashlib, urllib2 base = 'https://.......' def makereq(key, secret, path, data): hash_data = path + chr(0) + data secret = base64.b64decode(secret) sha512 = hashlib.sha512 hmac = str(hmac.new(secret, hash_data, sha512)) header = { 'User-Agent': 'My-First-test', ...
If you assign to a variable anywhere in a function, that variable will be treated as a local variable *everywhere* in that function. So you would see the same error with the following code: ``` foo = 2 def test(): print foo foo = 3 ``` In other words, you cannot access the global or external variable if there...
search for "does-not-contain" on a dataframe in pandas
17,097,643
13
2013-06-13T21:43:26Z
17,097,777
13
2013-06-13T21:51:44Z
[ "python", "pandas", "contains" ]
I've done some searching and can't figure out how to filter a dataframe by `df["col"].str.contains(word)`, however I'm wondering if there is a way to do the reverse: filter a dataframe by that set's compliment. eg: to the effect of `!(df["col"].str.contains(word))`. Can this be done through a `DataFrame` method?
You can use the invert (~) operator (which acts like a not for boolean data): ``` ~df["col"].str.contains(word) ``` *contains also accepts a regular expression...*
manage.py runserver in virtualenv using wrong django version
17,098,092
3
2013-06-13T22:15:45Z
17,099,087
7
2013-06-13T23:53:11Z
[ "python", "django", "virtualenv" ]
I created a virtualenv and installed Django 1.5 in it ``` (virtpy33) c:\django_projects>python Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.VERSION (1, 5, 1, 'final...
When you run `manage.py` on its own, Windows is pulling it off of the main Windows `PATH`, and then running it off of the main Windows association with Python, which is your default installed version of Python, and thus outside your virtualenv. Inside your virtualenv, try running `python manage.py runserver` and see w...
How to store data frame using PANDAS, Python
17,098,654
71
2013-06-13T23:05:36Z
17,098,736
101
2013-06-13T23:13:34Z
[ "python", "pandas" ]
Right now I'm importing a fairly large `CSV` as a dataframe every time I run the script. Is there a good solution for keeping that dataframe constantly available in between runs so I don't have to spend all that time waiting for the script to run?
The easiest way is to [pickle](http://docs.python.org/2/library/pickle.html) it using [`to_pickle`](http://pandas.pydata.org/pandas-docs/stable/io.html#pickling): ``` df.to_pickle(file_name) # where to save it, usually as a .pkl ``` Then you can load it back using: ``` df = pd.read_pickle(file_name) ``` *Note: bef...
How to store data frame using PANDAS, Python
17,098,654
71
2013-06-13T23:05:36Z
17,098,885
11
2013-06-13T23:28:07Z
[ "python", "pandas" ]
Right now I'm importing a fairly large `CSV` as a dataframe every time I run the script. Is there a good solution for keeping that dataframe constantly available in between runs so I don't have to spend all that time waiting for the script to run?
If I understand correctly, you're already using `pandas.read_csv()` but would like to speed up the development process so that you don't have to load the file in every time you edit your script, is that right? I have a few recommendations: 1. you could load in only part of the CSV file using `pandas.read_csv(..., nrow...
How to store data frame using PANDAS, Python
17,098,654
71
2013-06-13T23:05:36Z
33,570,065
8
2015-11-06T15:24:10Z
[ "python", "pandas" ]
Right now I'm importing a fairly large `CSV` as a dataframe every time I run the script. Is there a good solution for keeping that dataframe constantly available in between runs so I don't have to spend all that time waiting for the script to run?
Although there are already some answers I found a nice comparison in which they tried several ways to serialize Pandas DataFrames: [Efficiently Store Pandas DataFrames](http://matthewrocklin.com/blog/work/2015/03/16/Fast-Serialization/) [Edit: page has been deleted, but still available on [web.archive.org](https://web....
Searching text in a PDF using Python?
17,098,675
5
2013-06-13T23:07:39Z
17,099,530
14
2013-06-14T00:52:40Z
[ "python", "parsing", "pdf", "text" ]
**Problem** I'm trying to determine what type a document is (e.g. pleading, correspondence, subpoena, etc) by searching through its text, preferably using python. All PDFs are searchable, but I haven't found a solution to parsing it with python and applying a script to search it (short of converting it to a text file...
This is called PDF scraping, and is very hard because: * PDF is a document format designed to be printed, not to be parsed. Inside a PDF document, text is in no particular order (unless order is important for printing), most of the time the original text structure is lost (letters may not be grouped as words and...
Why do int keys of a python dict turn into strings when using json.dumps?
17,099,556
19
2013-06-14T00:56:41Z
17,099,566
26
2013-06-14T00:58:18Z
[ "python", "json", "serialization" ]
According to [this conversion table](http://docs.python.org/2/library/json.html#py-to-json-table), Python ints get written as JSON numbers when serialized using the JSON module--as I would expect and desire. I have a dictionary with an integer key and integer value: ``` >>> d = {1:2} >>> type(d.items()[0][0]) <type '...
The simple reason is that [JSON does not allow integer keys.](http://json.org/) ``` object {} { members } members pair pair , members pair string : value # Keys *must* be strings. ``` As to how to get around this limitation - you will first need to ensure that the receiving implementation can ha...
Lambdas Python for loop
17,100,061
7
2013-06-14T02:07:51Z
17,100,088
10
2013-06-14T02:12:12Z
[ "python", "lambda" ]
I wanted to use lambdas inside for loops to return if certain elements are non-numerical: ``` strs = ['1234', 'hello', '6787'] ``` I can use a `for` loop and iterate through each element: ``` for elem in strs: ``` and check `elem.islpha()`. However, is there a way to use `lambdas` coupled with a `for` loop to retu...
Try this, it's easy using a list comprehension: ``` lst = ['1234', 'hello', '6787'] [x for x in lst if x.isalpha()] => ['hello'] ``` Or if you definitely want to use a lambda: ``` filter(lambda x: x.isalpha(), lst) => ['hello'] ``` Notice that you'll rarely use lambdas for filtering inside a `for` loop, it's not...
Trying to use Pyglet - what does this error mean?
17,100,289
9
2013-06-14T02:38:12Z
19,395,468
10
2013-10-16T04:51:01Z
[ "python", "osx", "compiler-errors", "runtime-error", "pyglet" ]
I am running Mac OS X Mountain Lion, with Python 2.7. I did a source install of Pyglet that seemed to go without errors, but any time I try to run a program I get a longish error that I don't understand. It sounds like it has something to do with QuickTime?? Every program I've tried gives the same error. The programs ...
Similar to above, installing my own did the trick best. I adapted the instructions I found on this site: <http://twistedpairdevelopment.wordpress.com/2012/02/21/installing-pyglet-in-mac-os-x/> All I had to do was use pip to install direct from the repository. > pip install hg+<https://pyglet.googlecode.com/hg/> Job ...
Vagrant has detected that you have a version of VirtualBox installed that is not supported
17,100,926
3
2013-06-14T04:07:25Z
17,116,809
8
2013-06-14T20:32:22Z
[ "python", "django", "virtualbox", "vagrant" ]
I am working my way through <http://gettingstartedwithdjango.com/en/lessons/introduction-and-launch/> I am working on win7 and using git-bash for my terminal. I have gotten to : ``` Shared Folders After the ./postinstall.sh step, exit SSH Run vagrant halt. ``` I tried to run vagrant halt and got: ``` vagrant@precis...
You have an old version of vagrant. Just uninstall the current one, and install the latest one. <https://releases.hashicorp.com/vagrant/>
How to travese two dictionaries in a single for loop?
17,100,977
4
2013-06-14T04:14:28Z
17,100,984
13
2013-06-14T04:15:06Z
[ "python", "dictionary" ]
I want to generate the following effect : ``` for i, j in d.items() and k, v in c.items(): print i, j, k, v ``` This is wrong. I want to know how can I achieve this?
``` for (i, j), (k, v) in zip(d.items(), c.items()): print i, j, k, v ``` Remember the order will be arbitrary unless your dictionaries are `OrderedDict`s. To be memory efficient In Python 2.x (where `dict.items` and `zip` create lists) you can do the following: ``` from itertools import izip for (i, j), (k, v) i...
How to change a tuple within a value of a dictionary?
17,103,112
3
2013-06-14T07:17:40Z
17,103,167
8
2013-06-14T07:21:29Z
[ "python", "dictionary", "tuples" ]
I have a dictionary of the format : ``` d[key] = [(val1, (Flag1, Flag2)), (val2, (Flag1, Flag2)), (val3, (Flag1, Flag2))] ``` I want to make it : ``` d[key] = [(val1, Flag1), (val2, Flag1), (val3, Flag1)] ``` How can I do it?
Using `tuple` unpacking: ``` d[key] = [(x, y) for (x, (y, z)) in d[key]] ```
Plotting large arrays in pyqtgraph
17,103,698
6
2013-06-14T07:54:38Z
17,108,463
14
2013-06-14T12:25:22Z
[ "python", "pyqt", "pyqtgraph" ]
For an electrophysiology data analysis set I need to plot a large 2D array (dim approx 20.000 x 120) of points. I used to embed a Matplotlib widget in my PyQt application, but went looking for other solutions because the plotting took quite long. Still, plotting the data with pyqtgraph also takes much longer then expec...
See this discussion: <https://groups.google.com/forum/?fromgroups#!searchin/pyqtgraph/arraytoqpath/pyqtgraph/CBLmhlKWnfo/jinNoI07OqkJ> Pyqtgraph does not redraw after every call to plot(); it will wait until control returns to the Qt event loop before redrawing. However, it is possible that your code forces the event ...
how to order dictionary python (sorting)
17,104,903
3
2013-06-14T09:05:47Z
17,104,945
13
2013-06-14T09:08:08Z
[ "python", "sorting", "dictionary" ]
I use Python dictionary: ``` >>> a = {} >>> a["w"] = {} >>> a["a"] = {} >>> a["s"] = {} >>> a {'a': {}, 's': {}, 'w': {}} ``` I need: ``` >>> a {'w': {}, 'a': {}, 's': {}} ``` How can I get the order in which I filled the dictionary?
<http://docs.python.org/2/library/collections.html#collections.OrderedDict> > An OrderedDict is a dict that remembers the order that keys were first > inserted. If a new entry overwrites an existing entry, the original > insertion position is left unchanged. Deleting an entry and > reinserting it will move it to the e...
pypdf Merging multiple pdf files into one pdf
17,104,926
18
2013-06-14T09:07:06Z
17,304,537
40
2013-06-25T18:10:21Z
[ "python", "pypdf" ]
If I have 1000+ pdf files need to be merged into one pdf, ``` input = PdfFileReader() output = PdfFileWriter() filename0000 ----- filename 1000 input = PdfFileReader(file(filename, "rb")) pageCount = input.getNumPages() for iPage in range(0, pageCount): output.addPage(input.getPage(iPage)) outputSt...
I recently came across this exact same problem, so I dug into PyPDF2 to see what's going on, and how to resolve it. *Note: I am assuming that `filename` is a well-formed file path string. Assume the same for all of my code* **The Short Answer** Use the `PdfFileMerger()` class instead of the `PdfFileWriter()` class. ...
Calculate logistic regression in python
17,105,154
5
2013-06-14T09:19:55Z
17,109,483
8
2013-06-14T13:20:25Z
[ "python", "numpy", "pandas", "networkx", "statsmodels" ]
I tried to calculate logical regression. I have the data as csv file. it looks like ``` node_id,second_major,gender,major_index,year,dorm,high_school,student_fac 0,0,2,257,2007,111,2849,1 1,0,2,271,2005,0,51195,2 2,0,2,269,2007,0,21462,1 3,269,1,245,2008,111,2597,1 .......................... ``` This is my coding. `...
There's nothing wrong with your code. My guess is that you have missing values in your data. Try a `dropna` or use `missing='drop'` to Logit. You might also check that the right hand side is full rank `np.linalg.matrix_rank(data[train_cols].values)`
Parsing data from text file
17,105,456
4
2013-06-14T09:35:10Z
17,105,653
7
2013-06-14T09:46:28Z
[ "python", "file", "parsing" ]
I have a text file that has content like this: ``` ******** ENTRY 01 ******** ID: 01 Data1: 0.1834869385E-002 Data2: 10.9598489301 Data3: -0.1091356549E+001 Data4: 715 ``` And then an empty line, and repeats more similar blocks, all of them with ...
It is very far from CSV, actually. You can use the file as an iterator; the following generator function yields complete sections: ``` def load_sections(filename): with open(filename, 'r') as infile: line = '' while True: while not line.startswith('****'): line = next(...
matplotlib.pyplot will not forget previous plots - how can I flush/refresh?
17,106,288
3
2013-06-14T10:21:25Z
17,107,568
7
2013-06-14T11:36:01Z
[ "python", "matplotlib" ]
How do you get `matplotlib.pyplot` to "forget" previous plots I am trying to plot multiple time using `matplotlib.pyplot` The code looks like this: ``` def plottest(): import numpy as np import matplotlib.pyplot as plt a=np.random.rand(10,) b=np.random.rand(10,) c=np.random.rand(10,) plt....
I would rather use `plt.gcf().clear()` after every `plt.show()`. It will just clear the figure instead of closing and reopening it, keeping the window size and giving you a better performance too.
How to pass all arguments from __init__ to super class
17,106,662
6
2013-06-14T10:43:55Z
17,106,700
19
2013-06-14T10:46:29Z
[ "python", "inheritance", "variable-length-arguments" ]
IS there any magic I can use in Python to to effectively use super constructor by just adding some extra arguments? Ideally I'd like to use something like: ``` class ZipArchive(zipfile.ZipFile): def __init__(self, verbose=True, **kwargs): """ Constructor with some extra params. For other ...
You are almost there: ``` class ZipArchive(zipfile.ZipFile): def __init__(self, *args, **kwargs): """ Constructor with some extra params: * verbose: be verbose about what we do. Defaults to True. For other params see: zipfile.ZipFile """ self.verbose = kwargs.pop('...
Accessing Python dict values with the key start characters
17,106,819
4
2013-06-14T10:52:24Z
17,106,842
14
2013-06-14T10:53:42Z
[ "python", "dictionary" ]
I was wondering: would it be possible to access dict values with uncomplete keys (as long as there are not more than one entry for a given string)? For example: ``` my_dict = {'name': 'Klauss', 'age': 26, 'Date of birth': '15th july'} print my_dict['Date'] >> '15th july' ``` Is this possible? How could it be done?
You can't do such directly with `dict[keyword]`, you've to iterate through the dict and match each key against the keyword and return the corresponding value if the keyword is found. This is going to be an `O(N)` operation. ``` >>> my_dict = {'name': 'Klauss', 'age': 26, 'Date of birth': '15th july'} >>> next(v for k,...
Efficient python way for recursive equations
17,108,162
5
2013-06-14T12:08:25Z
17,109,192
8
2013-06-14T13:06:16Z
[ "python", "performance", "numpy", "cython" ]
I am trying to optimize a Loop that I have in a piece of my code. I thought that writing it in a more numpy way would make it faster, but is slower now! the equations takes as input a numpy.array vec of length n: ``` from numpy import * def f(vec): n=len(vec) aux=0 for i in range(n): aux = aux + (...
That's what happens when a linear algorithms gets replaced by a quadratic one: No matter how fast it's executed, the better algorithm always wins (for a problem big enough). It's pretty clear that `f` runs in linear time, and `f2` runs in quadractic time because that's the time complexity of a matrix-vector dot produc...
Efficiently Read last 'n' rows of CSV into DataFrame
17,108,250
4
2013-06-14T12:14:12Z
17,109,187
9
2013-06-14T13:05:50Z
[ "python", "csv", "numpy", "pandas" ]
A few methods to do this: 1. Read the entire CSV and then use `df.tail` 2. Somehow reverse the file (whats the best way to do this for large files?) and then use `nrows` argument to read 3. Somehow find the number of rows in the CSV, then use `skiprows` and read required number of rows. 4. Maybe do chunk read discardi...
I don't think pandas offers a way to do this in [`read_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html). Perhaps the neatest (in one pass) is to use [`collections.deque`](http://docs.python.org/2/library/collections.html#collections.deque): ``` from collections import deque...
Identical databases in Flask-SQLAlchemy
17,109,528
5
2013-06-14T13:22:51Z
17,140,915
7
2013-06-17T05:28:44Z
[ "python", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I've already asked a similar question, but I thought maybe I could rephrase it, or show what I've done further to shed some light onto what's going on here. Currently I have 2 identical databases, and I've attempted to solve the problem (as per another question I saw) like this: ``` class BaseTable(db.Model): __t...
I don't know what `__bind_key__` is, but there are many approaches to using a single Session with multiple binds. Session itself can be bound directly: to do this, SubTable1 and SubTable2 need to be mapped individually and not part of an inheritance hierarchy, as the Session locates the bind based on the base-most mapp...
change figure size and figure format in matplotlib
17,109,608
3
2013-06-14T13:27:28Z
17,109,681
7
2013-06-14T13:30:49Z
[ "python", "python-2.7", "python-3.x", "matplotlib" ]
I want to obtain fig1 exactly of 4 by 3 inch sized, and in tiff format correcting the program below: ``` import matplotlib.pyplot as plt list1 = [3,4,5,6,9,12] list2 = [8,12,14,15,17,20] plt.plot(list1, list2) plt.savefig('fig1.png', dpi = 300) plt.close() ``` Any help?
The first part (setting the output size explictly) isn't too hard: ``` import matplotlib.pyplot as plt list1 = [3,4,5,6,9,12] list2 = [8,12,14,15,17,20] fig = plt.figure(figsize=(4,3)) ax = fig.add_subplot(111) ax.plot(list1, list2) fig.savefig('fig1.png', dpi = 300) fig.close() ``` But after a quick google search on...
change figure size and figure format in matplotlib
17,109,608
3
2013-06-14T13:27:28Z
17,109,830
9
2013-06-14T13:38:01Z
[ "python", "python-2.7", "python-3.x", "matplotlib" ]
I want to obtain fig1 exactly of 4 by 3 inch sized, and in tiff format correcting the program below: ``` import matplotlib.pyplot as plt list1 = [3,4,5,6,9,12] list2 = [8,12,14,15,17,20] plt.plot(list1, list2) plt.savefig('fig1.png', dpi = 300) plt.close() ``` Any help?
You can set the figure size if you explicitly create the figure with ``` plt.figure(figsize=(3,4)) ``` To change the format of the saved figure just change the extension in the file name. However I don't know if any of matplotlib backends support tiff
How to show multiple images in one figure?
17,111,525
9
2013-06-14T15:03:04Z
17,111,578
14
2013-06-14T15:05:51Z
[ "python", "image", "matplotlib" ]
I use Python lib `matplotlib` to plot functions, and I know how to plot several functions in different \**subplot*\*s in one figure, like this one, ![enter image description here](http://i.stack.imgur.com/teDM5.png) And when handling images, I use **imshow()** to plot images, but how to plot multiple images together i...
The [documentation](http://matplotlib.org/users/image_tutorial.html) provides an example (about three quarters of the way down the page): ``` import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np fig = plt.figure() a=fig.add_subplot(1,2,1) img = mpimg.imread('../_static/stinkbug.png') lum...
Firebase Using Floating-Point Number as Key
17,113,401
2
2013-06-14T16:41:33Z
17,113,734
7
2013-06-14T17:04:35Z
[ "python", "json", "firebase" ]
I realized that I get 400 HTTP Bad Request from the server when pushing some JSON data into my Firebase storage whose keys are floating-point numbers. Here is the response I got: ``` {"error" : "Invalid data; couldn't parse JSON object, array, or value. Perhaps you're using invalid characters in your key names."} ...
It's valid JSON, but it's not valid Firebase. It doesn't appear to like the periods. If you really have to use floats for your property names (which sounds questionable), you can try replacing the periods with other characters, like underscores or commas. Taken from the [Creating References](https://www.firebase.com/d...
python pandas replacing strings in dataframe with numbers
17,114,904
8
2013-06-14T18:20:02Z
17,115,229
13
2013-06-14T18:41:32Z
[ "python", "replace", "dataframe", "pandas" ]
Is there anyway to use the mapping function or something better to replace values in an entire dataframe? I only know how to perform the mapping on series. I would like to replace the strings in the 'tesst' and 'set' column with a number for example set = 1, test =2 Here is a example of my dataset: (Original dataset...
What about [`DataFrame.replace`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html)? ``` In [9]: mapping = {'set': 1, 'test': 2} In [10]: df.replace({'set': mapping, 'tesst': mapping}) Out[10]: Unnamed: 0 respondent brand engine country aware aware_2 aware_3 age \ 0 ...
how to access my 127.0.0.1:8000 from android tablet
17,116,718
13
2013-06-14T20:24:51Z
17,116,791
8
2013-06-14T20:29:56Z
[ "android", "python", "django", "web", "localhost" ]
I am developing a webpage in django (on my pc with windows 7) and now i need to test some pages in tablet pcs. suddenly the thought came if i can have an access to my localhost in windows from android tablet. is that possible? I am in the same wifi connection in both devices at home. i read a lot questions and answers...
You can find out what the ip address of your PC is with the `ipconfig` command in a Windows command prompt. Since you mentioned them being connected over WiFi look for the IP address of the wireless adapter. Since the tablet is also in this same WiFi network, you can just type that address into your tablet's browser, ...
how to access my 127.0.0.1:8000 from android tablet
17,116,718
13
2013-06-14T20:24:51Z
17,117,060
11
2013-06-14T20:50:50Z
[ "android", "python", "django", "web", "localhost" ]
I am developing a webpage in django (on my pc with windows 7) and now i need to test some pages in tablet pcs. suddenly the thought came if i can have an access to my localhost in windows from android tablet. is that possible? I am in the same wifi connection in both devices at home. i read a lot questions and answers...
So, there are a couple of issues it seems. The question most of the answers are addressing is "how do you connect to another server in your local network?" (or variants). There are two answers, you can use the computer's IP directly, or you can use the computer's name (you may need to append `.local`). For example, my ...
pandas: How do I split text in a column into multiple rows?
17,116,814
72
2013-06-14T20:32:46Z
17,116,976
113
2013-06-14T20:44:53Z
[ "python", "pandas", "dataframe" ]
I'm working with a large csv file and the next to last column has a string of text that I want to split by a specific delimiter. I was wondering if there is a simple way to do this using pandas or python? ``` CustNum CustomerName ItemQty Item Seatblocks ItemExt 32363 McCartney, Paul 3 ...
This splits the Seatblocks by space and gives each its own row. ``` In [43]: df Out[43]: CustNum CustomerName ItemQty Item Seatblocks ItemExt 0 32363 McCartney, Paul 3 F04 2:218:10:4,6 60 1 31316 Lennon, John 25 F01 1:13:36:1,12 1:13:37:1,13 ...
pandas: How do I split text in a column into multiple rows?
17,116,814
72
2013-06-14T20:32:46Z
21,032,532
37
2014-01-09T22:25:55Z
[ "python", "pandas", "dataframe" ]
I'm working with a large csv file and the next to last column has a string of text that I want to split by a specific delimiter. I was wondering if there is a simple way to do this using pandas or python? ``` CustNum CustomerName ItemQty Item Seatblocks ItemExt 32363 McCartney, Paul 3 ...
Differently from Dan, I consider his answer quite elegant... but unfortunately it is also very very inefficient. So, since the question mentioned *"a large csv file"*, let me suggest to try in a shell Dan's solution: ``` time python -c "import pandas as pd; df = pd.DataFrame(['a b c']*100000, columns=['col']); print d...
Python Accessing Values in A List of Dictionaries
17,117,912
4
2013-06-14T22:03:50Z
17,117,976
11
2013-06-14T22:08:14Z
[ "python", "list", "dictionary" ]
Say I have a List of dictionaries that have Names and ages and other info, like so: ``` thisismylist= [ {'Name': 'Albert' , 'Age': 16}, {'Name': 'Suzy', 'Age': 17}, {'Name': 'Johnny', 'Age': 13} ] ``` How would I go about print the following using a for loop: ``` Albert Su...
If you're just looking for values associated with 'Name', your code should look like: ``` for d in thisismylist: print d['Name'] ```
How to add readonly inline on django admin
17,118,320
14
2013-06-14T22:43:00Z
17,118,321
21
2013-06-14T22:43:00Z
[ "python", "django", "admin" ]
I am using django 1.4 and I have a many2many field, so when creating the admin site I wanted to add this field as an inline, here is some code: ``` class SummaryInline(admin.TabularInline): model = ParserError.summaries.through class MyClassAdmin(admin.ModelAdmin): list_display = ('classifier', 'name', 'err_...
After a while of trying to find the name I figured out thanks to [this answer](http://stackoverflow.com/questions/13817525/django-admin-make-all-fields-readonly), so I checked the names at `self.opts.local_fields` and found the name of the middle table and added it to [`readonly_fields`](https://docs.djangoproject.com/...
How to add readonly inline on django admin
17,118,320
14
2013-06-14T22:43:00Z
30,704,608
9
2015-06-08T08:41:53Z
[ "python", "django", "admin" ]
I am using django 1.4 and I have a many2many field, so when creating the admin site I wanted to add this field as an inline, here is some code: ``` class SummaryInline(admin.TabularInline): model = ParserError.summaries.through class MyClassAdmin(admin.ModelAdmin): list_display = ('classifier', 'name', 'err_...
Additionally, if you do not want the ability to add/delete the rows, you can add these definitions. ``` def has_add_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False ```
python argparse: unrecognized arguments
17,118,999
7
2013-06-15T00:14:33Z
17,119,118
15
2013-06-15T00:35:27Z
[ "python", "argparse" ]
Following is my Code. When I run `parsePlotSens.py -s bw hehe`, it shows that "hehe" is unrecognized argument. However, if I run `parsePlotSens.py hehe -s bw`, it's OK. Ideally, I would like it work for both cases. Any tips? Thanks ``` if __name__ == '__main__' : parser = argparse.ArgumentParser(prog='parsePlotS...
Do not pass `sys.argv` as an argument to `parse_args`. Just use ``` option = parser.parse_args() ``` If you do pass `sys.argv` to `parse_args`, then the path or name of the script itself is the first item in `sys.argv` and thus becomes the value of `option.filename`. The `hehe` then becomes an unknown argument. If y...
Compute a chain of functions in python
17,122,644
10
2013-06-15T10:29:50Z
17,122,666
14
2013-06-15T10:33:02Z
[ "python", "functional-programming" ]
I want to get the result of a chain of computations from an initial value. I'm actually using the following code: ``` def function_composition(function_list, origin): destination = origin for func in function_list: destination = func(destination) return destination ``` With each function in `funct...
Fold while calling. ``` destination = reduce((lambda x, y: y(x)), function_list, origin) ```
How to use list[list.index('')] queries in python
17,125,390
7
2013-06-15T15:52:22Z
17,125,454
12
2013-06-15T15:59:03Z
[ "python", "list", "indexing" ]
I tried the following code in python IDLE. But I didn't seem to find the elements swapped. ``` >>> a = [1,2,3,4,5,6,7] >>> if(a.index(2)<a.index(4)): ... a[a.index(2)],a[a.index(4)] = a[a.index(4)],a[a.index(2)] ``` According to the code, It should reverse the positions of 2 and 4. Correct me If I am wrong.
The assignment list expressions are evaluated left-to-right *while assigning*. Here is what happens: * The right-hand-expression is evaluated to yield `(4, 2)` * `a[a.index(2)]` is evaluated to assign `4` to, `a[2]` is altered, the list becomes `[1, 4, 3, 4, 5, 6, 7]` * `a[a.index(4)]` is evaluated to assign `2` to, ...
Django `with` tag not recognizing keyword argument
17,125,501
3
2013-06-15T16:04:58Z
17,125,558
8
2013-06-15T16:13:51Z
[ "python", "django" ]
I have the following code in my template: ``` {% include "entry_table/cell.html" with data_items = data_fields class="entry_table_title" only%} ``` Which gives me the following error: ``` "with" in 'include' tag needs at least one keyword argument. ``` I've tried replacing data\_field (which is a variable I passed ...
Looks like Django is quite picky about whitespace in this instance. If I change... ``` {% include "entry_table/cell.html" with data_items = data_fields class="entry_table_title" only%} ``` ...to... ``` {% include "entry_table/cell.html" with data_items=data_fields class="entry_table_title" only%} ``` ...it works fo...
Changing the text on a label
17,125,842
7
2013-06-15T16:48:43Z
17,126,015
20
2013-06-15T17:13:07Z
[ "python", "python-3.x", "tkinter" ]
I am having trouble with using a key binding to change the value of a label or any parameter. This is my code: ``` from tkinter import* class MyGUI: def __init__(self): self.__mainWindow = Tk() #self.fram1 = Frame(self.__mainWindow) self.labelText = 'Enter amount to deposit' self.depositLabel = Labe...
``` self.labelText = 'change the value' ``` Above sentence make labelText to reference 'change the value', but not change depositLabel's text. To change depositLabel's text, use one of following setences: ``` self.depositLabel['text'] = 'change the value' ``` OR ``` self.depositLabel.config(text='change the value'...
python program very slow
17,125,891
4
2013-06-15T16:54:15Z
17,125,900
13
2013-06-15T16:55:23Z
[ "python", "performance", "itertools", "words" ]
This program generates letter combinations and checks to see if they are words, but the program is extremely slow generating only a few words a second. please tell me why it is very slow, and what i need to make it faster ``` import itertools for p1 in itertools.combinations('abcdefghijklmnopqrstuvwxyz', 4): wit...
It is slow because you are re-reading a file *for each loop iteration*, and create a new function object. Neither of these two things are dependent on the loop variable; move these out of the loop to only run *once*. Furthermore, the simple function can be inlined; calling a function is relatively expensive. And don't...
How can I get the list slice using a list of indexes in Python?
17,126,026
2
2013-06-15T17:14:51Z
17,126,038
7
2013-06-15T17:15:44Z
[ "python", "slice" ]
In Perl I can easily select multiple array elements using a list of indexes, e.g. ``` my @array = 1..11; my @indexes = (0,3,10); print "@array[ @indexes ]"; # 1 4 11 ``` What's the canonical way to do this in Python?
use `operator.itemgetter`: ``` from operator import itemgetter array = range(1, 12) indices = itemgetter(0, 3, 10) print indices(array) # (1, 4, 11) ``` Then present that tuple however you want..., eg: ``` print ' '.join(map(str, indices(array))) # 1 4 11 ```
How to delete only the content of file in python
17,126,037
18
2013-06-15T17:15:33Z
17,126,137
35
2013-06-15T17:27:42Z
[ "python", "file-io", "seek" ]
I have a temporary file with some content and a python script generating some output to this file. I want this to repeat N times, so I need to reuse that file (actually array of files). I'm deleting the whole content, so the temp file will be empty in the next cycle. For deleting content I use this code: ``` def delet...
> How to delete only the content of file in python There is several ways of set the logical size of a file to 0, depending how you access that file: To empty an open file: ``` def deleteContent(pfile): pfile.seek(0) pfile.truncate() ``` --- To empty a open file whose file descriptor is known: ``` def dele...
Tornado/Twisted - Celery - Gevent Comparison
17,126,625
16
2013-06-15T18:22:37Z
17,133,576
12
2013-06-16T12:56:59Z
[ "python", "twisted", "celery", "tornado", "gevent" ]
I'm having a bit of trouble understanding the differences between these three frameworks: * [Tornado](http://www.tornadoweb.org/en/stable/)/[Twisted](http://twistedmatrix.com/trac/) * [Celery](http://www.celeryproject.org/) * [Gevent](http://www.gevent.org/) These three frameworks can be used to run code at the same ...
1. Gevent uses [greenlets](http://en.wikipedia.org/wiki/Light-weight_process) instead of threads on an IO loop implicitly, so there is no reactor / IO loop to manually start in the case of Twtisted/Tornado. It also has the ability to monkey patch existing libraries to support it's evented operation, Tornado and Twisted...
python recursive function that prints from 0 to n?
17,127,355
5
2013-06-15T19:53:51Z
17,127,379
9
2013-06-15T19:57:39Z
[ "python", "recursion" ]
I am trying to write a recursive function that prints from 0 to n, but I have no idea how to do it. I accidentally made one that prints from n to 0 though: ``` def countdown(n): print(n) if n == 0: return 0 return countdown(n - 1) ``` I don't know if that helps or not, maybe I can change something...
You're about 99% there. Think of your base case and your recursive step - when you hit 0, what do you want to do? When you're still working your way down from `n`, what do you want to happen? If you reverse the order in which you print the value, you'll reach your desired result. ``` def countdown(n): if n != 0:...
Can't delete row from SQLAlchemy due to wrong session
17,127,922
4
2013-06-15T21:12:01Z
17,225,665
12
2013-06-20T23:48:17Z
[ "python", "flask", "flask-sqlalchemy" ]
I am trying to delete an entry from my table. This is my code for the delete function. ``` @app.route("/delete_link/<link_id>", methods=['GET', 'POST']) def delete_link(link_id): link = models.Link.query.filter(models.Link.l_id == link_id).first() db.session.delete(link) db.session.commit() return flas...
You are creating 2 instances of the `db` object, inherently creating 2 different sessions. In models.py: ``` ... 5. from config import app 6. 7. db = SQLAlchemy(app) ``` In erika.py: ``` ... 16. from config import app ... 23. db = SQLAlchemy(app) ``` then when you try to delete the element: ``` link = model...
Why is numpy.any so slow over large arrays?
17,128,116
41
2013-06-15T21:33:41Z
17,140,470
25
2013-06-17T04:34:39Z
[ "python", "arrays", "performance", "numpy" ]
I'm looking for the most efficient way to determine whether a large array contains at least one nonzero value. At first glance `np.any` seems like the obvious tool for the job, but it seems unexpectedly slow over large arrays. Consider this extreme case: ``` first = np.zeros(1E3,dtype=np.bool) last = np.zeros(1E3,dty...
As has been guessed in the comments, I can confirm that the processing of the array is being done in chunks. First, I will show you where things are in the code and then I will show you how you can change the chunk size and the effect that doing so has on your benchmark. ## Where to find the reduction processing in th...
Python Request Module - Google App Engine
17,128,130
4
2013-06-15T21:36:06Z
17,128,168
10
2013-06-15T21:40:34Z
[ "python", "google-app-engine" ]
I'm trying to import the requests module for my app which I want to view locally on Google App Engine. I am getting a log console error telling me that "no such module exists". I've installed it in the command line (using `pip`) and even tried to install it in my project directory. When I do that the shell tells me: ...
You need to put the requests module i.e. [the contents of the requests folder](https://github.com/kennethreitz/requests/tree/master/requests) within your project directory. Just for the sake of clarity, your app directory should look like ``` /myapp/app.yaml /myapp/main.py /myapp/requests/packages/ /myapp/requests/__i...
Python/pandas idiom for if/then/else
17,128,302
13
2013-06-15T22:00:32Z
17,128,356
17
2013-06-15T22:07:10Z
[ "python", "pandas" ]
After performing calculations on an entire pandas dataframe, I need to go back and override variable calculations (often setting to zero) based on the value of another variable(s). Is there a more succinct/idiomatic way to perform this kind of operation? ``` df['var1000'][df['type']==7] = 0 df['var1001'][df['type']==7...
``` df.ix[df.type==7, ['var1001', 'var1002']] = 0 ``` If you're doing it on all columns, you can just do `df.ix[df.type==7] = 0`. Or of course if you have a list of the columns whose values you want to replace, you can pass that list in the second slot: ``` columnsToReplace = ['var1001', 'var1002', ...] df.ix[df.type...
Get max keys of a list of dictionaries
17,128,914
4
2013-06-15T23:36:57Z
17,128,929
8
2013-06-15T23:39:12Z
[ "python", "list", "dictionary" ]
If I have: ``` dicts = [{'a': 4,'b': 7,'c': 9}, {'a': 2,'b': 1,'c': 10}, {'a': 11,'b': 3,'c': 2}] ``` How can I get the maximum keys only, like this: ``` {'a': 11,'c': 10,'b': 7} ```
Use [`collection.Counter()` objects](http://docs.python.org/2/library/collections.html#counter-objects) instead, or convert your dictionaries: ``` from collections import Counter result = Counter() for d in dicts: result |= Counter(d) ``` or even: ``` from collections import Counter from operator import or_ re...
How to set ticks on Fixed Position , matplotlib
17,129,947
16
2013-06-16T03:33:20Z
17,130,203
31
2013-06-16T04:29:06Z
[ "python", "matplotlib" ]
Can anyone help me set the ticks on a fixed position using matplotlib? I've tried using FixedPosition as this tutorial describes: ``` ax = pl.gca() ax.xaxis.set_major_locator(eval(locator)) ``` <http://scipy-lectures.github.io/intro/matplotlib/matplotlib.html#figures-subplots-axes-and-ticks> But when I try to run, i...
Just use `ax.set_xticks(positions)` or `ax.set_yticks(positions)`. For example: ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.set_xticks([0.15, 0.68, 0.97]) ax.set_yticks([0.2, 0.55, 0.76]) plt.show() ``` ![enter image description here](http://i.stack.imgur.com/6fnzL.png)
What is causing this error on part 3 of Django tutorial?
17,130,026
6
2013-06-16T03:51:12Z
17,130,750
7
2013-06-16T06:22:00Z
[ "python", "django" ]
I have run into an issue while working through the Django tutorial, specifically when adding more views to the poll application. For reference, this is the beginning of the section that trips me up: <https://docs.djangoproject.com/en/1.5/intro/tutorial03/#writing-more-views> Prior to that section, I can get the *polls...
Looks like Python cannot import polls.urls - that's why `__import__(name)` fails. The "name" here would be your module name, 'polls.urls'. To find out why the system cannot import your polls.urls, try importing it interactively. ``` $ python manage.py shell Python ... blah blah ... > import polls.urls ``` This w...
xlwt set style making error: More than 4094 XFs (styles)
17,130,516
8
2013-06-16T05:36:30Z
17,140,488
10
2013-06-17T04:37:46Z
[ "python", "excel", "xlwt" ]
I use Xlwt for writing an excel file. it's cells has some style (color, alignment ,borders , ... ) when i use XFStyle and set borders and other attr of style, in some cases it make error: More than 4094 XFs (styles) why? what should i do with this error? thanks
I read and trace functions and methods that calls during execution. i find solution: ``` wb = xlwt.Workbook(style_compression=2) ``` use : style\_compression=2 its work!
Python vs Cpython
17,130,975
123
2013-06-16T07:00:18Z
17,130,986
214
2013-06-16T07:02:38Z
[ "python", "cpython" ]
What's all this fuss about Python and CPython *(Jython,IronPython)*, I don't get it: [python.org](http://www.python.org/) mentions that CPython is: > *The "traditional" implementation of Python (nicknamed CPython)* [yet another Stack Overflow question](http://stackoverflow.com/a/2324217/2425215) mentions that: > *C...
## So what is CPython CPython is the *original* Python implementation. It is the implementation you download from Python.org. People call it CPython to distinguish it from other, later, Python implementations, and to distinguish the implementation of the language engine from the Python *programming language* itself. ...
Python vs Cpython
17,130,975
123
2013-06-16T07:00:18Z
17,131,014
26
2013-06-16T07:07:24Z
[ "python", "cpython" ]
What's all this fuss about Python and CPython *(Jython,IronPython)*, I don't get it: [python.org](http://www.python.org/) mentions that CPython is: > *The "traditional" implementation of Python (nicknamed CPython)* [yet another Stack Overflow question](http://stackoverflow.com/a/2324217/2425215) mentions that: > *C...
You need to distinguish between a language and an implementation. Python is a language, According to [Wikipedia](http://en.wikipedia.org/wiki/Programming_language), "A programming language is a notation for writing programs, which are specifications of a computation or algorithm". This means that it's simply the rules...
Python vs Cpython
17,130,975
123
2013-06-16T07:00:18Z
21,915,160
17
2014-02-20T17:25:00Z
[ "python", "cpython" ]
What's all this fuss about Python and CPython *(Jython,IronPython)*, I don't get it: [python.org](http://www.python.org/) mentions that CPython is: > *The "traditional" implementation of Python (nicknamed CPython)* [yet another Stack Overflow question](http://stackoverflow.com/a/2324217/2425215) mentions that: > *C...
This [article](http://www.toptal.com/python/why-are-there-so-many-pythons) thoroughly explains the difference between different implementations of Python. Like the article puts it: > The first thing to realize is that ‘Python’ is an interface. There’s a > specification of what Python should do and how it should ...
Same value for id(float)
17,132,047
11
2013-06-16T09:55:39Z
17,132,057
17
2013-06-16T09:57:13Z
[ "python" ]
As far as I know, everything is object in Python and the **id()** should (am I right?) return a different number for each object. In my case, `id(1)` returns `4298178968`, `id(2)` returns `4298178944` but I get the same values for all float types, `id(1.1)` returns `4298189032`, `id(2.2)` also returns `4298189032` and...
Python can reuse memory positions. When you run: ``` id(1.1) ``` you create a float value, ask for its `id()`, and then Python *deletes* the value again because nothing refers to it. When you then create *another* float value, Python can reuse the same memory position and thus `id(2.2)` is likely to return the same ...
Obtaining length of list as a value in dictionary in Python 2.7
17,133,000
6
2013-06-16T11:49:59Z
17,133,196
13
2013-06-16T12:11:58Z
[ "python", "list", "python-2.7", "dictionary" ]
I have two lists and dictionary as follows: ``` >>> var1=[1,2,3,4] >>> var2=[5,6,7] >>> dict={1:var1,2:var2} ``` I want to find the size of the mutable element from my dictionary i.e. the length of the value for a key. After looking up the `help('dict')`, I could only find the function to return number of keys i.e. `...
`dict.items()` is a list containing all key/value-tuples of the dictionary, e.g.: ``` [(1, [1,2,3,4]), (2, [5,6,7])] ``` So if you write `len(dict.items()[0])`, then you ask for the length of the first tuple of that items-list. Since the tuples of dictionaries are always 2-tuples (pairs), you get the length `2`. If y...
Convert DataFrame column type from string to datetime
17,134,716
58
2013-06-16T15:14:58Z
17,134,750
103
2013-06-16T15:18:23Z
[ "python", "pandas", "dataframe" ]
How can I convert a DataFrame column of strings (in dd/mm/yyyy format) to datetimes?
The easiest way is to use [`to_datetime`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html): ``` df['col'] = pd.to_datetime(df['col']) ``` It also offers a `dayfirst` argument for European times (but beware [this isn't strict](https://github.com/pydata/pandas/issues/3341)). Here it is in...
pandas DataFrame output end of csv
17,134,942
9
2013-06-16T15:40:40Z
17,135,044
19
2013-06-16T15:52:32Z
[ "python", "csv", "pandas", "dataframe" ]
I wonder how to add new DataFrame data onto the end of an existing csv file? The to\_csv doesn't mention such functionality. Thank you in advance.
You can append using [`to_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html) by passing a file which is [open in append mode](http://docs.python.org/2/library/functions.html#open): ``` with open(file_name, 'a') as f: df.to_csv(f, header=False) ``` *Use `header=None`, so as n...
pandas DataFrame output end of csv
17,134,942
9
2013-06-16T15:40:40Z
17,910,713
15
2013-07-28T17:14:18Z
[ "python", "csv", "pandas", "dataframe" ]
I wonder how to add new DataFrame data onto the end of an existing csv file? The to\_csv doesn't mention such functionality. Thank you in advance.
You can also pass the file mode as an argument to the to\_csv method ``` df.to_csv(file_name, header=False, mode = 'a') ```
URL routing conflicts for static files in Flask dev server
17,135,006
7
2013-06-16T15:48:18Z
17,146,563
12
2013-06-17T11:36:11Z
[ "python", "flask", "werkzeug" ]
I want to define a url rule with three variable components, like: ``` @app.route('/<var_1>/<var_2>/<var3>/') ``` But I find that the development server evaluates such rules before trying to match for static files. So anything like: ``` /static/images/img.jpg ``` will be caught by my url rule, rather than being forw...
This is werkzeug route optimization feature. See [`Map.add`](https://github.com/mitsuhiko/werkzeug/blob/5cdc596fd1b725cd25b457072e1f545958c78226/werkzeug/routing.py#L1080), [`Map.update`](https://github.com/mitsuhiko/werkzeug/blob/5cdc596fd1b725cd25b457072e1f545958c78226/werkzeug/routing.py#L1214) and [`Rule.match_comp...
Whatsapp API (java/python)
17,135,496
43
2013-06-16T16:43:31Z
17,283,356
18
2013-06-24T19:18:37Z
[ "java", "python", "api", "whatsapp" ]
I am looking for WhatsApp API. I prefer Python or Java libraries for it. I tried [Yowsup](https://github.com/tgalal/yowsup). But I could not get my number registered. I am based out of India and I am not sure if that has got anything to do with it. Also [WhatAPI](https://github.com/venomous0x/WhatsAPI) python is not wo...
After trying everything, Yowsup library worked for me. The bug that I was facing was recently fixed. Anyone trying to do something with Whatsapp should try it.
Whatsapp API (java/python)
17,135,496
43
2013-06-16T16:43:31Z
17,710,523
7
2013-07-17T21:24:31Z
[ "java", "python", "api", "whatsapp" ]
I am looking for WhatsApp API. I prefer Python or Java libraries for it. I tried [Yowsup](https://github.com/tgalal/yowsup). But I could not get my number registered. I am based out of India and I am not sure if that has got anything to do with it. Also [WhatAPI](https://github.com/venomous0x/WhatsAPI) python is not wo...
This is the developers page of the Open WhatsApp official page: <http://openwhatsapp.org/develop/> You can find a lot of information there about Yowsup. Or, you can just go the the library's link (which I copied from the Open WhatsApp page anyway): <https://github.com/tgalal/yowsup> Enjoy!
Whatsapp API (java/python)
17,135,496
43
2013-06-16T16:43:31Z
19,609,069
7
2013-10-26T16:30:51Z
[ "java", "python", "api", "whatsapp" ]
I am looking for WhatsApp API. I prefer Python or Java libraries for it. I tried [Yowsup](https://github.com/tgalal/yowsup). But I could not get my number registered. I am based out of India and I am not sure if that has got anything to do with it. Also [WhatAPI](https://github.com/venomous0x/WhatsAPI) python is not wo...
Yowsup provide best solution with example.you can download api from <https://github.com/tgalal/yowsup> let me know if you have any issue.
eval to import a module
17,136,772
9
2013-06-16T19:13:11Z
17,136,796
13
2013-06-16T19:14:59Z
[ "python", "eval" ]
It seems that I can't import a module using the eval() function. So, I have a function where if I do `import vfs_tests as v` it works. However, the same import using eval() like `eval('import vfs_tests as v')` throws a syntax error. Why is this so?
Use `exec`: ``` exec 'import vfs_tests as v' ``` `eval` works only on expressions, `import` is a statement. `exec` is a function in py3.x : `exec('import vfs_tests as v')` To import a module using a string you should use `importlib` module: ``` import importlib mod = importlib.import_module('vfs_tests') ``` for p...
Psycopg2 on Amazon Elastic Beanstalk
17,137,346
20
2013-06-16T20:22:19Z
20,274,732
33
2013-11-28T21:05:17Z
[ "python", "amazon-web-services", "psycopg2", "elastic-beanstalk" ]
I'm trying upload my project (in python) that uses Psycopg2 for Amazon Elastic Beanstalk. I'm doing this with a zip file containing my project and an requirements.txt file. But I'm receiving this error: > Downloading/unpacking psycopg2>=2.4.6 (from -r > /opt/python/ondeck/app/requirements.txt (line 3)) Running setup....
Need postgresql-devel in your container. Create a file '.ebextensions/packages.config' with the contents: ``` packages: yum: postgresql94-devel: [] ``` Replace `94` in `postgresql94-devel` with whatever version of postgres you need. For example, `postgresql93-devel` for postgres 9.3. <http://docs.aws.amazon.co...
Psycopg2 on Amazon Elastic Beanstalk
17,137,346
20
2013-06-16T20:22:19Z
26,935,877
20
2014-11-14T17:44:53Z
[ "python", "amazon-web-services", "psycopg2", "elastic-beanstalk" ]
I'm trying upload my project (in python) that uses Psycopg2 for Amazon Elastic Beanstalk. I'm doing this with a zip file containing my project and an requirements.txt file. But I'm receiving this error: > Downloading/unpacking psycopg2>=2.4.6 (from -r > /opt/python/ondeck/app/requirements.txt (line 3)) Running setup....
Tried to comment on the accepted answer but don't have the reputation to do so. Recent forum posts from AWS support indicate that the package name is "postgresql93-devel". postgresql-devel does not work in the 2014.09 AMIs.
Numpy: outer product of n vectors
17,138,393
8
2013-06-16T22:38:12Z
17,139,044
8
2013-06-17T00:34:26Z
[ "python", "arrays", "numpy" ]
I'm trying to do something simple in numpy, and I'm sure there should be an easy way of doing it. Basically, I have a list of `n` vectors with various lengths. If `v1[i]` is the `i`'th entry of the first vector then I want to find a `n`-dimensional array, A, such that ``` A[i,j,k...] = v1[i] v2[j] v3[k] ... ``` My p...
You use use following one line code: ``` reduce(np.multiply, np.ix_(*vs)) ``` `np.ix_()` will do the outer broadcast, you need reduce, but you can pass the ufunc `np.multiply` without lambda function. Here is the comparing: ``` import numpy as np vs = [np.r_[1,2,3.0],np.r_[4,5.0],np.r_[6,7,8.0]] shape = map(len, vs...
Confusion in array operation in numpy
17,139,470
2
2013-06-17T01:57:17Z
17,139,552
8
2013-06-17T02:11:06Z
[ "python", "matlab", "numpy" ]
I generally use `MATLAB` and `Octave`, and i recently switching to `python` `numpy`. In numpy when I define an array like this ``` >>> a = np.array([[2,3],[4,5]]) ``` it works great and size of the array is ``` >>> a.shape (2, 2) ``` which is also same as MATLAB But when i extract the first entire column and see th...
A 1D numpy array\* is literally 1D - it has no size in any second dimension, whereas in MATLAB, a '1D' array is actually 2D, with a size of 1 in its second dimension. If you want your array to have size 1 in its second dimension you can use its `.reshape()` method: ``` a = np.zeros(5,) print(a.shape) # (5,) # explic...
Read time from excel sheet using xlrd, in time format and not in float
17,140,652
4
2013-06-17T04:57:14Z
23,432,565
10
2014-05-02T16:14:08Z
[ "python", "datetime", "floating-point", "xlrd" ]
I am trying to read some data from a excel file. One of the columns has time values in the format HH:MM:SS. Xlrd reads this time and converts it into float. I have another time values in my python file which I want to compare with the excel-imported time values. I am not able to do that as long as one of them is a "tim...
The xlrd library has a built-in, xldate\_as\_tuple() function for getting you most of the way there: ``` import xlrd from datetime import time wb=xlrd.open_workbook('datasheet.xls') date_values = xlrd.xldate_as_tuple(cell_with_excel_time, wb.datemode) # date_values is now a tuple with the values: (year, month, day...
How to parse a string and return a nested array?
17,140,850
8
2013-06-17T05:20:41Z
17,141,441
7
2013-06-17T06:19:35Z
[ "python", "arrays", "string", "parsing", "nested" ]
I want a Python function that takes a string, and returns an array, where each item in the array is either a character, or another array of this kind. Nested arrays are marked in the input string by starting with '(' and ending with ')'. Thus, the function would act like this: ``` 1) foo("abc") == ["a", "b", "c"] 2) ...
``` def foo(s): def foo_helper(level=0): try: token = next(tokens) except StopIteration: if level != 0: raise Exception('missing closing paren') else: return [] if token == ')': if level == 0: rai...
Can anyone explain why this sorting won't work?
17,141,255
6
2013-06-17T06:03:40Z
17,141,264
14
2013-06-17T06:04:33Z
[ "python", "sorting" ]
For example if I have a list like this: ``` List1 =[7,6,9] List1 = List1.sort() ```
`list.sort()` sorts the list in-place and returns `None`, so you were actually assigning that return value to `List1`, i.e `None`. ``` >>> List1 =[7,6,9] >>> repr(List1.sort()) 'None' #return Value of list.sort >>> List1 #though list is sorted [6, 7, 9] ``` On the other hand the b...
How to sort a dataFrame in python pandas by two or more columns?
17,141,558
36
2013-06-17T06:28:47Z
17,141,755
63
2013-06-17T06:43:07Z
[ "python", "python-2.7", "pandas", "data-analysis" ]
Suppose I have a data-Frame with columns a b & c, I want to sort the data-Frame by column b in ascending, and by column c in descending, how do I do this?
As commented, the `sort` method is now deprecated in favor of [`sort_values`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html). The arguments (and results) remain the same: ``` df.sort_values(['a', 'b'], ascending=[True, False]) ``` --- You can use the ascending argument of [`...
How to sort a dataFrame in python pandas by two or more columns?
17,141,558
36
2013-06-17T06:28:47Z
33,837,592
7
2015-11-20T23:11:35Z
[ "python", "python-2.7", "pandas", "data-analysis" ]
Suppose I have a data-Frame with columns a b & c, I want to sort the data-Frame by column b in ascending, and by column c in descending, how do I do this?
As of pandas 0.17.0, `DataFrame.sort()` is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is `DataFrame.sort_values` As such, the answer to your question would now be ``` df.sort_values(['b', 'c'], ascending=[True, False], inplace=True) ```
Round a Floating Point Number Down to the Nearest Integer?
17,141,979
37
2013-06-17T07:00:53Z
17,142,025
12
2013-06-17T07:04:19Z
[ "python", "floating-point", "integer", "rounding", "number-rounding" ]
As the title suggests, I want to take a floating point number and round it down to the nearest integer. However, if it's not a whole, I ALWAYS want to round down the variable, regardless of how close it is to the next integer up. Is there a way to do this?
I think you need a floor function : [math.floor(x)](http://docs.python.org/2/library/math.html)
Round a Floating Point Number Down to the Nearest Integer?
17,141,979
37
2013-06-17T07:00:53Z
17,142,031
37
2013-06-17T07:05:17Z
[ "python", "floating-point", "integer", "rounding", "number-rounding" ]
As the title suggests, I want to take a floating point number and round it down to the nearest integer. However, if it's not a whole, I ALWAYS want to round down the variable, regardless of how close it is to the next integer up. Is there a way to do this?
One of these should work: ``` import math math.trunc(1.5) > 1 math.trunc(-1.5) > -1 math.floor(1.5) > 1 math.floor(-1.5) > -2 ```
Round a Floating Point Number Down to the Nearest Integer?
17,141,979
37
2013-06-17T07:00:53Z
17,142,719
54
2013-06-17T07:51:30Z
[ "python", "floating-point", "integer", "rounding", "number-rounding" ]
As the title suggests, I want to take a floating point number and round it down to the nearest integer. However, if it's not a whole, I ALWAYS want to round down the variable, regardless of how close it is to the next integer up. Is there a way to do this?
Simple ``` print int(x) ``` will work as well.
Python 2.7 and 3.3.2, why int('0.0') does not work?
17,142,088
6
2013-06-17T07:09:10Z
17,142,118
10
2013-06-17T07:11:18Z
[ "python", "string", "integer", "type-conversion" ]
As the title says, in Python (I tried in 2.7 and 3.3.2), why `int('0.0')` does not work? It gives this error: ``` ValueError: invalid literal for int() with base 10: '0.0' ``` If you try `int('0')` or `int(eval('0.0'))` it works...
From the docs on `int`: ``` int(x=0) -> int or long int(x, base=10) -> int or long ``` 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 the given base. So, `'0.0'` is an invalid integer literal for base 10. You need: ``` >>> int(float('0.0')...
replace string/value in entire dataframe
17,142,304
21
2013-06-17T07:23:17Z
17,142,595
27
2013-06-17T07:43:01Z
[ "python", "replace", "dataframe", "pandas" ]
I have a very large dataset were I want to replace strings with numbers. I would like to operate on the dataset without typing a mapping function for each key (column) in the dataset. (similar to the fillna method, but replace specific string with assosiated value). Is there anyway to do this? Here is an example of my...
Use [replace](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.replace.html) ``` In [126]: df.replace(['very bad', 'bad', 'poor', 'good', 'very good'], [1, 2, 3, 4, 5]) Out[126]: resp A B C 0 1 3 3 4 1 2 4 3 4 2 3 5 5 5 3 4 2 3 ...
How to convert this list into dictionary in Python?
17,144,889
6
2013-06-17T10:02:21Z
20,097,564
12
2013-11-20T13:41:25Z
[ "python", "list", "dictionary" ]
I have a list like this: ``` paths = [['test_data', 'new_directory', 'ok.txt'], ['test_data', 'reads_1.fq'], ['test_data', 'test_ref.fa']] ``` I want to convert this into dictionary like this: ``` {'test_data': ['ok.txt', 'reads_1.fq'], 'test_data/new_directory', ['ok.txt']} ``` The list is dynamic. The purpose of ...
can try this also, ``` list1=['a','b','c','d'] list2=[1,2,3,4] ``` we want to zip these two lists and create a dictionary dict\_list ``` dict_list = zip(list1, list2) dict(dict_list) ``` this will give: ``` dict_list = {'a':1, 'b':2, 'c':3, 'd':4 } ```
How to map func_closure entries to variable names?
17,145,260
6
2013-06-17T10:23:34Z
17,145,475
12
2013-06-17T10:35:15Z
[ "python", "python-2.x", "cpython" ]
I have a lambda object that is created in this function: ``` def add_url_rule(self, rule, endpoint=None, view_func=None, **options): self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options)) ``` Using `func_closure` of the lambda function object I can access the closure scope of the lamb...
The closures are created by the `LOAD_CLOSURE` bytecode, in the same order as their bytecodes are ordered: ``` >>> dis.dis(add_url_rule) 2 0 LOAD_FAST 0 (self) 3 LOAD_ATTR 0 (record) 6 LOAD_CLOSURE 0 (endpoint) 9 LOAD_CLOSU...
Setting a default role in flask-security
17,146,724
2
2013-06-17T11:44:43Z
17,150,839
7
2013-06-17T15:07:54Z
[ "python", "flask", "flask-sqlalchemy", "flask-security" ]
I am trying to set a default role when a user registers with my site, currently no roles are set when the user registers. I have created the roles I need, so I just need to define it somehow. Not sure how though. The code I have is pretty much copy paste from the quick start guide. Anyway, here it is: ``` # Define m...
I fixed it using information from this [git issue](https://github.com/mattupstate/flask-security/issues/94) with this: ``` @user_registered.connect_via(app) def user_registered_sighandler(app, user, confirm_token): default_role = user_datastore.find_role("User") user_datastore.add_role_to_user(user, default_ro...
Django CMS - check if placeholder is empty
17,147,720
5
2013-06-17T12:40:19Z
17,148,137
14
2013-06-17T13:02:54Z
[ "python", "html", "django", "django-cms" ]
I use: * DjangoCMS 2.4 * Django 1.5.1 * Python 2.7.3 I would like to check if my placeholder is empty. ``` <div> {% placeholder "my_placeholder" or %} {% endplaceholder %} </div> ``` I don't want the html between the placeholder to be created if the placeholder is empty. ``` {% if placeholder "my_placehold...
There is no built-in way to do this at the moment in django-cms, so you have to write a custom template tag. There are some old discussions about this on the `django-cms` Google Group: * <https://groups.google.com/forum/#!topic/django-cms/WDUjIpSc23c/discussion> * <https://groups.google.com/forum/#!msg/django-cms/iAuZ...
Verify rabbitmq credentials are valid
17,148,683
13
2013-06-17T13:29:10Z
17,155,386
24
2013-06-17T19:36:32Z
[ "python", "rabbitmq" ]
I'd like to write a simple smoke test that runs after deployment to verify that the RabbitMQ credentials are valid. What's the simplest way to check that rabbitmq username/password/vhost are valid? *Edit:* Preferably, check using a bash script. Alternatively, using a Python script.
As you haven't provided any details about language, etc.: You could simply issue a HTTP GET request to the management api. ``` $ curl -i -u guest:guest http://localhost:15672/api/whoami ``` See [RabbitMQ Management HTTP API](http://hg.rabbitmq.com/rabbitmq-management/raw-file/rabbitmq_v3_1_1/priv/www/api/index.html)
Verify rabbitmq credentials are valid
17,148,683
13
2013-06-17T13:29:10Z
17,950,138
8
2013-07-30T14:42:32Z
[ "python", "rabbitmq" ]
I'd like to write a simple smoke test that runs after deployment to verify that the RabbitMQ credentials are valid. What's the simplest way to check that rabbitmq username/password/vhost are valid? *Edit:* Preferably, check using a bash script. Alternatively, using a Python script.
Here's a way to check using Python: ``` #!/usr/bin/env python import socket from kombu import Connection host = "localhost" port = 5672 user = "guest" password = "guest" vhost = "/" url = 'amqp://{0}:{1}@{2}:{3}/{4}'.format(user, password, host, port, vhost) with Connection(url) as c: try: c.connect() ...
How to iterate through dictionary passed from Python/Tornado handler to Tornado's template?
17,148,732
3
2013-06-17T13:30:40Z
17,149,160
7
2013-06-17T13:48:11Z
[ "python", "tornado" ]
How to iterate through dictionary passed from Python/Tornado handler to Tornado's template ? I tried like ``` <div id="statistics-table"> {% for key, value in statistics %} {{key}} : {{value['number']}} {% end %} </div> ``` but it doesn't work, where statistics is dict...
``` >>> from tornado import template >>> t = template.Template(''' ... <div id="statistics-table"> ... {% for key, value in statistics.items() %} ... {{key}} : {{value['number']}} ... {% end %} ... </div> ... ''') >>> statistics = { 1 : {'number' : 2}, 2 : {'number' : 8}} >>> print(t.generate(statistics=st...
How to find a value in a list of python dictionaries?
17,149,561
25
2013-06-17T14:06:20Z
17,149,592
38
2013-06-17T14:07:44Z
[ "python", "list", "dictionary" ]
Have a list of python dictionaries in the following format. How would you do a search to find a specific name exists? ``` label = [{'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347), 'name': 'Test', 'pos': 6}, {'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347), ...
You'd have to search through all dictionaries in your list; use [`any()`](http://docs.python.org/2/library/functions.html#any) with a generator expression: ``` any(d['name'] == 'Test' for d in label) ``` This will short circuit; return `True` when the *first* match is found, or return `False` if none of the dictionar...
How to find a value in a list of python dictionaries?
17,149,561
25
2013-06-17T14:06:20Z
17,149,651
17
2013-06-17T14:10:56Z
[ "python", "list", "dictionary" ]
Have a list of python dictionaries in the following format. How would you do a search to find a specific name exists? ``` label = [{'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347), 'name': 'Test', 'pos': 6}, {'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347), ...
You might also be after: ``` >>> match = next((l for l in label if l['name'] == 'Test'), None) >>> print match {'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347), 'name': 'Test', 'pos': 6} ``` Or possibly more clearly: ``` for l in label: if l['name'] == 'Test': match = l break else: ...
Matplotlib - Force plot display and then return to main code
17,149,646
3
2013-06-17T14:10:44Z
17,149,933
10
2013-06-17T14:24:24Z
[ "python", "matplotlib", "enthought" ]
This is a MWE of what I'm after, adapted from [this question](http://stackoverflow.com/questions/458209/is-there-a-way-to-detach-matplotlib-plots-so-that-the-computation-can-continue): ``` from matplotlib.pyplot import plot, draw, show def make_plot(): plot([1,2,3]) draw() print 'continue computation' pr...
You may use `plt.show(block=False)`, which gets rid of the blocking directly. For your example, this could read ``` from matplotlib.pyplot import plot, draw, show def make_plot(): plot([1,2,3]) show(block=False) print 'continue computation' print('Do something before plotting.') # Now display plot in a ...
How to restore a builtin that I overwrote by accident?
17,152,760
11
2013-06-17T16:50:20Z
17,152,796
20
2013-06-17T16:52:20Z
[ "python", "builtin" ]
I accidentally overwrote `set` by using it as a variable name in an interactive python session - is there any way that I can get access to the original `set` function without just restarting my session? (I have so much stuff in that session that I'd rather not have to do that, although of course I can if necessary.)
Just delete the name that is masking the builtin: ``` >>> set = 'oops' >>> set 'oops' >>> del set >>> set <type 'set'> ``` You can always still access the original built-in through the `__builtins__` namespace; use this if you want to override the built-in but want to defer to the original still from the override: `...
How can I print variable and string on same line in Python?
17,153,779
25
2013-06-17T17:58:08Z
17,153,791
41
2013-06-17T17:58:57Z
[ "python", "string", "variables", "printing" ]
I am using python to work out how many children would be born in 5 years if a child was born every 7 seconds. The problem is on my last line. How do I get a variable to work when I'm printing text either side of it? Here is my code: ``` currentPop = 312032486 oneYear = 365 hours = 24 minutes = 60 seconds = 60 # seco...
Use `,` to separate strings and variables while printing: ``` print "If there was a birth every 7 seconds, there would be: ",births,"births" ``` `,` in print statement separtes the items by a single space: ``` >>> print "foo","bar","spam" foo bar spam ``` or better use [string formatting](http://docs.python.org/2/l...