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
How to filter rows containing a string pattern from a Pandas dataframe
27,975,069
10
2015-01-15T23:44:22Z
27,975,230
17
2015-01-15T23:59:55Z
[ "python", "pandas" ]
Assume we have a data frame in Python Pandas that looks like this: ``` df = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': [u'aball', u'bball', u'cnut', u'fball']}) ``` Or, in table form: ``` ids vals aball 1 bball 2 cnut 3 fball 4 ``` How do I filter rows which contain the key word "ball?" For example, the...
``` In [3]: df[df['ids'].str.contains("ball")] Out[3]: ids vals 0 aball 1 1 bball 2 3 fball 4 ```
How to filter rows containing a string pattern from a Pandas dataframe
27,975,069
10
2015-01-15T23:44:22Z
27,975,789
9
2015-01-16T01:04:57Z
[ "python", "pandas" ]
Assume we have a data frame in Python Pandas that looks like this: ``` df = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': [u'aball', u'bball', u'cnut', u'fball']}) ``` Or, in table form: ``` ids vals aball 1 bball 2 cnut 3 fball 4 ``` How do I filter rows which contain the key word "ball?" For example, the...
``` df[df['ids'].str.contains('ball')] ``` Step-by-step explanation (from inner to outer): * `df['ids']` selects the `ids` column of the data frame (techincally, the object `df[ids]` is of type `pandas.Series`) * `df['ids'].str` allows us to apply vectorized string methods (e.g., `lower`, `contains`) to the Series * ...
ForeignKeys clashing when using abstract multiple inheritance in Django
27,975,449
5
2015-01-16T00:25:43Z
27,975,706
7
2015-01-16T00:54:31Z
[ "python", "django", "inheritance", "django-models" ]
I am trying to set up a Django Model that works as a base class for other models. The Base model has two ForeignKey fields to other objects of the same class (TestForeign). I can get the models working using multitable inheritance but I want to use abstract model inheritance because I have read that there are some [per...
Use `%(class)s` and `%(app_label)s` in your related name, as specified in [the docs](https://docs.djangoproject.com/en/1.7/topics/db/models/#abstract-related-name).
How to PATCH a single field using Django Rest Framework?
27,980,390
11
2015-01-16T09:04:16Z
27,991,592
9
2015-01-16T19:42:49Z
[ "python", "django", "api", "django-rest-framework", "http-patch" ]
I have a model 'MyModel' with many fields and I would like to update a field 'status' using PATCH method. I'm using class based views. Is there any way to implement PATCH?
Serializers allow [partial updates by specifying `partial=True`](http://www.django-rest-framework.org/api-guide/serializers/#partial-updates) when initializing the serialzer. This is how [`PATCH` requests are handled](https://github.com/tomchristie/django-rest-framework/blob/4ce4132e08ba7764f120c71eeebdbaefee281689/res...
Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6
27,981,545
57
2015-01-16T10:07:19Z
28,002,687
166
2015-01-17T18:17:20Z
[ "python", "python-2.6", "suppress-warnings", "urllib3", "pyvmomi" ]
I am writing scripts in Python2.6 with use of [pyVmomi](https://github.com/vmware/pyvmomi) and while using one of the connection methods: ``` service_instance = connect.SmartConnect(host=args.ip, user=args.user, pwd=args.password) ``` I g...
The reason doing `urllib3.disable_warnings()` didn't work for you is because it looks like you're using a separate instance of urllib3 vendored inside of requests. I gather this based on the path here: `/usr/lib/python2.6/site-packages/requests/packages/urllib3/connectionpool.py` To disable warnings in requests' vend...
How to express classes on the axis of a heatmap in Seaborn
27,988,846
3
2015-01-16T16:51:49Z
27,992,943
7
2015-01-16T21:22:14Z
[ "python", "matplotlib", "heatmap", "seaborn" ]
I created a very simple heatmap chart with Seaborn displaying a similarity square matrix. Here is the one line of code I used: ``` sns.heatmap(sim_mat, linewidths=0, square=True, robust=True) sns.plt.show() ``` and this is the output I get: ![enter image description here](http://i.stack.imgur.com/vMrGt.png) What I'...
There are two options: First, `heatmap` is an Axes level figure, so you could set up a main large main heatmap axes for the correlation matrix and flank it with heatmaps that you then pass class colors to yourself. This will be a little bit of work, but gives you lots of control over how everything works. This is mor...
How do I dissolve a pattern in a numpy array?
27,989,374
18
2015-01-16T17:22:27Z
27,990,017
12
2015-01-16T18:01:38Z
[ "python", "arrays", "numpy" ]
Excuse the strange title, I couldn't really think of a suitable wording. Say I have an array like: ``` arr = [[0 1 1 1 1 1 1 1 0], [0 0 1 1 1 1 1 0 0], [0 0 0 1 1 1 0 0 0], [0 0 0 0 1 0 0 0 0], [0 0 0 0 0 0 0 0 0]] ``` I'm looking to "etch" away the `1`s that touch `0`s, which would resul...
Consider convolving with a cross-shaped kernel. ``` import numpy as np from scipy.signal import convolve2d kernel = np.array([[0,1,0], [1,1,1], [0,1,0]]) mask = convolve2d(arr, kernel, boundary='symm', mode='same') arr[mask!=5] = 0 ``` This method works correctly for all inputs: ``` In [143]: D = np.random.random_in...
How do I dissolve a pattern in a numpy array?
27,989,374
18
2015-01-16T17:22:27Z
27,990,027
22
2015-01-16T18:02:03Z
[ "python", "arrays", "numpy" ]
Excuse the strange title, I couldn't really think of a suitable wording. Say I have an array like: ``` arr = [[0 1 1 1 1 1 1 1 0], [0 0 1 1 1 1 1 0 0], [0 0 0 1 1 1 0 0 0], [0 0 0 0 1 0 0 0 0], [0 0 0 0 0 0 0 0 0]] ``` I'm looking to "etch" away the `1`s that touch `0`s, which would resul...
[Morpholocial erosion](http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.morphology.binary_erosion.html) can be used here. Morphological erosion sets a pixel at (i, j) to the minimum over all pixels in the neighborhood centered at (i, j). [source](http://scikit-image.org/docs/dev/auto_examples/a...
Appending "<>" to each item in a list
27,990,383
2
2015-01-16T18:24:54Z
27,990,397
9
2015-01-16T18:25:54Z
[ "python", "append" ]
I have this code in Python 2.7 I've been working on, and i got stuck. I'm trying to go from `["bob","sally","jim"])` to `'bob<>sally<>jim'` Here's what i have so far. ``` def long_winded(my_str): result = [] for i in my_str: result += i + "<>" return result print long_winded(["sally","bob","jim"]) ```
You can just use the [`.join`](https://docs.python.org/2/library/stdtypes.html#str.join) string method: ``` my_lst = ['sally', 'bob', 'jim'] result = '<>'.join(my_lst) ``` And, of course you can always wrap all of this up in a function, but you probably don't need to: ``` def long_winded(lst): return '<>'.join(lst...
How to delete an RDD in PySpark for the purpose of releasing resources?
27,990,616
7
2015-01-16T18:39:23Z
28,028,286
7
2015-01-19T15:41:03Z
[ "python", "apache-spark", "pyspark" ]
If I have an RDD that I no longer need, how do I delete it from memory? Would the following be enough to get this done: ``` del thisRDD ``` Thanks!
No, `del thisRDD` is not enough, it would just delete the pointer to the RDD. You should call `thisRDD.unpersist()` to remove the cached data. For you information, Spark uses a model of lazy computations, which means that when you run this code: ``` >>> thisRDD = sc.parallelize(xrange(10),2).cache() ``` you won't ha...
C++ equivalent of Python String Slice?
27,992,264
5
2015-01-16T20:28:43Z
27,992,321
8
2015-01-16T20:32:32Z
[ "python", "c++", "string" ]
In python I was able to slice part of a string; in other words just print the characters after a certain position. Is there an equivalent to this in C++? Python Code: ``` text= "Apple Pear Orange" print text[6:] ``` Would print: `Pear Orange`
Yes, it is the [`substr`](http://en.cppreference.com/w/cpp/string/basic_string/substr) method: ``` basic_string substr( size_type pos = 0, size_type count = npos ) const; ``` > Returns a substring [pos, pos+count). If the requested substring extends past the end of the string, or if count == npos...
How to run a Python unit test with the Atom editor?
27,994,928
4
2015-01-17T00:39:12Z
27,994,929
7
2015-01-17T00:39:12Z
[ "python", "unit-testing", "atom-editor" ]
I'm trying out the Atom editor and was wondering how I can run Python unit tests with a keyboard shortcut.
**Installation** 1. Install the [Atom](https://atom.io) editor 2. Install the [Script](https://atom.io/packages/script) package like this: a) Start Atom b) Press `Ctrl`+`Shift`+`P`, type "install packages and themes" and press `Enter` to open the package view c) Search for "script" and install the package ...
How to "join" two text files with python?
27,997,400
3
2015-01-17T07:48:08Z
27,997,436
7
2015-01-17T07:54:12Z
[ "python", "file", "python-2.7" ]
I have two txt files like this: txt1: ``` Foo Foo Foo Foo ``` txt2: ``` Bar Bar Bar Bar ``` How can I concatenate them in a new file by the left and the right side let's say like this: ``` Bar Foo Bar Foo Bar Foo Bar Foo ``` I tried the following: ``` folder = ['/Users/user/Desktop/merge1.txt', '/Users/user/Desk...
Use [`itertools.izip`](https://docs.python.org/2/library/itertools.html#itertools.izip) to combine the lines from both the files, like this ``` from itertools import izip with open('res.txt', 'w') as res, open('in1.txt') as f1, open('in2.txt') as f2: for line1, line2 in zip(f1, f2): res.write("{} {}\n".for...
Which authentication to be used when using Django Rest Framework and IOS app?
27,997,483
7
2015-01-17T08:01:16Z
28,005,538
12
2015-01-17T23:34:39Z
[ "python", "ios", "django", "django-rest-framework" ]
I have an iOS app that uses an API powered by Django REST framework to store, update, fetch data from a database. I need to provide the two more following functionalities which stores the user data at the server: 1. Login with Email 2. Login with Facebook There appears to be two different authentication systems that ...
When you are using Django REST framework with iOS, unless you are using a browser, the standard Django authentication system is out of the question. This is exposed through the [DRF authentication system as `SessionAuthentication`](http://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication) an...
Install OpenCV 3.0 with extra modules (sift, surf...) for python
28,000,772
5
2015-01-17T15:05:56Z
28,000,851
8
2015-01-17T15:14:02Z
[ "python", "opencv" ]
I tried to install (many many times) OpenCV 3.0 for python with extra package (sift, surf...) but I always fails, I really get stuck. I tried in main environment then in virtual ones, Here is what I did: ``` cd git git clone https://github.com/Itseez/opencv_contrib.git cd .. wget https://github.com/Itseez/opencv/arch...
``` >>> help(cv2.xfeatures2d) Help on module cv2.xfeatures2d in cv2: NAME cv2.xfeatures2d FILE (built-in) FUNCTIONS SIFT_create(...) SIFT_create([,nfeatures[,nOctaveLayers[,contrastThreshold[,edgeThreshold[,sigma]]]]) -> retval SURF_create(...) SURF_create([,hessianThreshold[,nOctave...
QPython or Kivy for Android programming with Python - producing installable apk
28,001,100
15
2015-01-17T15:38:43Z
28,001,298
11
2015-01-17T15:59:07Z
[ "android", "python", "kivy", "sl4a", "qpython" ]
Having read several Q&A's on SO, I realize that one has 2 options i.e. QPython and Kivy to do programming for Android, however, apparently both take different approaches. I am trying to validate my understanding and see if I am missing some key piece of information. * QPython allows usage of Kivy library for developin...
> QPython allows usage of Kivy library for developing graphical applications Yes, qpython is an interpreter + associated tools, and has some nice kivy integration. You can't compile the kivy code to a standalone apk with qpython+android alone though. > QPython and Kivy both use SL4A, while QPython has expanded standa...
Pandas : Proper way to set values based on condition for subset of multiindex dataframe
28,002,197
5
2015-01-17T17:29:42Z
28,002,262
7
2015-01-17T17:38:07Z
[ "python", "pandas", "multi-index" ]
I'm not sure of how to do this without chained assignments (which probably wouldn't work anyways because I'd be setting a copy). I wan't to take a subset of a multiindex pandas dataframe, test for values less than zero and set them to zero. For example: ``` df = pd.DataFrame({('A','a'): [-1,-1,0,10,12], ...
This is an application of (and one of the main motivations for using MultiIndex slicers), see docs [here](http://pandas-docs.github.io/pandas-docs-travis/advanced.html#using-slicers) ``` In [20]: df = pd.DataFrame({('A','a'): [-1,-1,0,10,12], ('A','b'): [0,1,2,3,-1], ('B','a'): [-...
Can I use += on multiple variables on one line?
28,002,548
4
2015-01-17T18:04:28Z
28,002,587
9
2015-01-17T18:07:24Z
[ "python", "variables", "reference", "addition", "augmented-assignment" ]
While shortening my code I was cutting down a few variable declarations onto one line- ``` ##For example- going from- Var1 =15 Var2 = 26 Var3 = 922 ##To- Var1, Var2, Var3 = 15, 26, 922 ``` However, when I tried doing the same thing to this code- ``` User_Input += Master_Key[Input_ref] Key += Master_Key[Key_ref] Key...
No, you cannot. You cannot use augmented assignment together with multiple targets. You can see this in the [*Augmented assignment statements* section](https://docs.python.org/2/reference/simple_stmts.html#augmented-assignment-statements) you linked to: > ``` > augmented_assignment_stmt ::= augtarget augop (expressi...
Wheel file installation
28,002,897
15
2015-01-17T18:36:06Z
28,002,930
25
2015-01-17T18:40:03Z
[ "python", "install", "python-wheel" ]
How do I install a .whl file? I have the Wheel library but I don't know how to use it to install those files. I have the .whl file but I don't know how to run it. Please help.
You normally use a tool like `pip` to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI. For this to work, you do need to install the `wheel` package: ``` pip install wheel ``` You can then tell `pip` to install the project (and it'll download the wheel if...
How do I elegantly/efficiently write the __init__ function for a Python class that takes lots of instance variables?
28,004,358
3
2015-01-17T21:10:32Z
28,004,413
10
2015-01-17T21:17:07Z
[ "python", "class" ]
Let's say you have a class that takes many (keyword) arguments, most of which are meant to be stored as instance variables: ``` class ManyInitVariables(): def __init__(a=0, b=2, c=1, d=0, e=-1, ... , x=100, y=0, z=9): ``` How would you initialize them in `__init__`? You could do something like this: ``` class Ma...
I'm sure there are many other similar solutions out there on the web for this very common issue, but this is one, for example: ``` import functools import inspect def absorb_args(f): args, _, _, defs = inspect.getargspec(f) args = args[1:] # ignore the leading `self` @functools.wraps(f) def do_absorb...
Python Speech Recognition: 'module' object has no attribute 'microphone'
28,004,954
3
2015-01-17T22:17:08Z
33,032,574
7
2015-10-09T07:37:12Z
[ "python", "python-2.7", "python-3.x", "speech-recognition", "microphone" ]
Running the following code on a macbook air 64 bit, testing the code on python 2.7 and python 3.4 ``` import speech_recognition as sr r = sr.Recognizer() with sr.microphone() as source: audio = r.listen(source) try: print("You said " + r.recognize(audio)) except LookupError: print("Could not understand au...
**Fix found -** ``` pip install SpeechRecognition pip install pyaudio ``` If you found error - ``` sudo apt-get install python-pyaudio sudo apt-get install libjack-jackd2-dev portaudio19-dev ``` Then again - ``` pip install pyaudio ```
sudo pip install django
28,004,960
14
2015-01-17T22:17:48Z
28,005,086
15
2015-01-17T22:35:12Z
[ "python", "django", "pip" ]
So this is my first attempt at trying to install Django, and when I ran it, it successfully installed Django-1.7.3 but I received these warnings below. I wasn't able to find any information about it online so I was hoping someone could clarify what they mean, if I need to fix them, and how I could go about doing that? ...
These messages are just telling you that after issuing `sudo` the current user has changed to `root` and `root` isn't the owner of those directories or one of the parent directories. `sudo -H` sets the `$HOME` environment variable to `/root` and would probably hide these but the way you did it is perfectly fine. I'm ...
How to view an RGB image with pylab
28,005,669
2
2015-01-17T23:53:16Z
28,006,059
7
2015-01-18T00:52:41Z
[ "python", "image", "numpy", "matplotlib" ]
I'm trying to view an 32x32 pixel RGB image in CIFAR-10 format. It's a numpy array where pixel values (uint8) are arranged as follows: "The first 1024 bytes are the red channel values, the next 1024 the green, and the final 1024 the blue. The values are stored in row-major order, so the first 32 bytes are the red chann...
Try changing the order. By default, it is C-contiguous (which is in fact [row-major](https://en.wikipedia.org/wiki/Row-major_order#Programming_Languages)), but for matplotlib, you'll want the red channel values in `[:,:,0]`. That means you should read that data in in Fortran order so that it first fills the "columns" (...
How to view an RGB image with pylab
28,005,669
2
2015-01-17T23:53:16Z
32,279,611
9
2015-08-28T20:53:35Z
[ "python", "image", "numpy", "matplotlib" ]
I'm trying to view an 32x32 pixel RGB image in CIFAR-10 format. It's a numpy array where pixel values (uint8) are arranged as follows: "The first 1024 bytes are the red channel values, the next 1024 the green, and the final 1024 the blue. The values are stored in row-major order, so the first 32 bytes are the red chann...
I know it's been a while since the question was posted but I want to correct Oliver's answer. If you order by Fortran, the image is inverted and rotated by 90 degrees CCW. You can still train on this data of course if you format all of your images this way. But to prevent you from going insane, you should do the follo...
Pandas DataFrame to List of Lists
28,006,793
15
2015-01-18T03:14:21Z
28,006,809
26
2015-01-18T03:18:39Z
[ "python", "pandas" ]
It's easy to turn a list of lists into a pandas dataframe: ``` import pandas as pd df = pd.DataFrame([[1,2,3],[3,4,5]]) ``` But how do I turn df back into a list of lists? ``` lol = df.what_to_do_now? print lol # [[1,2,3],[3,4,5]] ```
You could access the underlying array and call its `tolist` method: ``` >>> df = pd.DataFrame([[1,2,3],[3,4,5]]) >>> lol = df.values.tolist() >>> lol [[1L, 2L, 3L], [3L, 4L, 5L]] ```
How to to make a file private by securing the url that only authenticated users can see
28,007,770
7
2015-01-18T06:37:16Z
28,008,035
7
2015-01-18T07:28:18Z
[ "python", "django", "url", "authentication", "file-access" ]
I was wondering if there is a way to secure an image or a file to be hidden when it is not authenticated. Suppose there is an image in my website which can only be seen if that user is authenticated. But the thing is I can copy the url or open the image in the new tab. `http://siteis.com/media/uploaded_files/14214998...
By securing any media file not to serve by anonymous user, better way url protection. **Code ( Updated ):** ``` from django.conf.urls import patterns, include, url from django.contrib.auth.decorators import login_required from django.views.static import serve from django.conf import settings from django.core.excepti...
Get weekday/day-of-week for Datetime column of DataFrame
28,009,370
9
2015-01-18T11:54:32Z
28,009,526
14
2015-01-18T12:14:03Z
[ "python", "pandas" ]
I have a DataFrame `df` like the following (excerpt, 'Timestamp' are the index): ``` Timestamp Value 2012-06-01 00:00:00 100 2012-06-01 00:15:00 150 2012-06-01 00:30:00 120 2012-06-01 01:00:00 220 2012-06-01 01:15:00 80 ...and so on. ``` I need a new column `df['weekday']` with the r...
Use the new [`dt.dayofweek`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tseries.common.DatetimeProperties.dayofweek.html#pandas.tseries.common.DatetimeProperties.dayofweek) property: ``` In [2]: df['weekday'] = df['Timestamp'].dt.dayofweek df Out[2]: Timestamp Value weekday 0 2012-06-0...
How to fade color
28,015,400
7
2015-01-18T22:12:34Z
28,033,054
11
2015-01-19T20:35:10Z
[ "python", "image", "image-processing", "colors", "pixel" ]
I would like to fade the color of a pixel out toward white, but obviously maintain the same color. If I have a pixel `(200,120,40)`, will adding 10 to each value to make `(210,130,50)` make it the same color, just lighter, or will it change the color entirely? For example, I know that `(100,100,100)` going to `(110,110...
There are a bunch of ways to do this. How you choose to do it will depend on whether you value speed and simplicity or perceptual uniformity. If you need it to be truly uniform you will need to define you RGB colors with a color profile and you'll need the primaries of the profile so you can convert to XYZ and then to ...
Will pandas dataframe object work with sklearn kmeans clustering?
28,017,091
11
2015-01-19T02:17:48Z
30,111,487
11
2015-05-07T20:57:10Z
[ "python", "pandas", "scikit-learn", "cluster-analysis", "k-means" ]
dataset is pandas dataframe. This is sklearn.cluster.KMeans ``` km = KMeans(n_clusters = n_Clusters) km.fit(dataset) prediction = km.predict(dataset) ``` This is how I decide which entity belongs to which cluster. ``` for i in range(len(prediction)): cluster_fit_dict[dataset.index[i]] = prediction[i] ``` ...
Assuming all the values in the dataframe are numeric, ``` # Convert DataFrame to matrix mat = dataset.as_matrix() # Using sklearn km = sklearn.cluster.KMeans(n_clusters=5) km.fit(mat) # Get cluster assignment labels labels = km.labels_ # Format results as a DataFrame results = pandas.DataFrame([dataset.index,labels])....
Django update on queryset to change ID of ForeignKey
28,019,516
4
2015-01-19T07:07:14Z
32,165,969
7
2015-08-23T11:09:37Z
[ "python", "django", "django-queryset" ]
I am trying to update the ids of a bunch of objects and a related table that refers to the objects. ``` class Test(models.Model): id=models.IntegerField(primary_key=True) class Question(models.Model): id=models.AutoField(primary_key=True) test=models.ForeignKey('Test',db_column='testId') d={1:2,5:10} f...
Implemented in Django 1.8 Usage: ``` Bar.objects.filter(pk=foo.id).update(a_id=bar.id) Bar.objects.filter(pk=foo.id).update(a=bar.id) ``` See [ticket](https://code.djangoproject.com/ticket/21144) and [commit](https://github.com/django/django/commit/c21e86ab9e3e5ebd6d245d038cb0cb352cd84c3a).
Indentation in function does not work as expected
28,021,409
2
2015-01-19T09:28:20Z
28,021,465
7
2015-01-19T09:32:17Z
[ "python", "python-2.7" ]
I found something that doesn't make sense to me. I am hoping that someone can explain it. ``` def test(word): total = 0 for l in word: print l test('python') ``` The result is 'p y t h o n' (each letter appears on its own line). ``` def test(word): total = 0 for l in word: print l ...
I am 100% sure that "return total" in second function is on the same level (indented exactly) as print. Probably you use mixed space characters (tab or space)
Indentation in function does not work as expected
28,021,409
2
2015-01-19T09:28:20Z
28,021,522
7
2015-01-19T09:35:04Z
[ "python", "python-2.7" ]
I found something that doesn't make sense to me. I am hoping that someone can explain it. ``` def test(word): total = 0 for l in word: print l test('python') ``` The result is 'p y t h o n' (each letter appears on its own line). ``` def test(word): total = 0 for l in word: print l ...
The only way you'd get the behaviour you see is if you indented `return total` to be part of the `for` loop. If it doesn't *look* like that in your editor, it's because you have used a TAB character for your `return` line: ``` >>> code_as_posted = '''\ ... def test(word): ... total = 0 ... for l in word: ... ...
Receiving RTP packets after RTSP setup
28,022,432
6
2015-01-19T10:24:51Z
28,188,102
24
2015-01-28T08:57:25Z
[ "python", "sockets", "udp", "rtsp", "rtp" ]
I'm trying to stream RTP packets from an IP camera using Python. I am able to send the describe, setup & play commands using RTSP protocol, however, I am unable to start streaming the actual videostream using RTP. Here is the code: ``` import socket def printrec(recst): recs=recst.split('\r\n') for rec in recs...
So, After heavy sessions of googling and wireshark-analysis, I came up with the right solutions. I am posting the resulting demo-code here .. I thought it might be usefull for the community. If you ever wanted to read ip-cams with python and dump the H264 stream into an edible file, this is the thing you're looking ...
pip install error: cannot import name 'unpack_url'
28,031,277
6
2015-01-19T18:29:24Z
28,274,130
14
2015-02-02T09:03:26Z
[ "python", "python-3.x", "pip", "importerror" ]
I'm using Python 3.4.1 64-bit on a Windows 8.1 machine. Pip has been giving me problems lately, specifically this error: ``` C:\Users\Charlie\Desktop>pip install wxPython_Phoenix-3.0.3.dev78341-cp34-none-w in_amd64.whl Traceback (most recent call last): File "C:\Python34\Scripts\pip-script.py", line 9, in <module> ...
I used: `easy_install -U pip` problem solved
HDF5-DIAG: Error detected in HDF5 (1.8.11)
28,031,841
4
2015-01-19T19:08:02Z
28,032,495
7
2015-01-19T19:53:11Z
[ "python", "numpy", "hdf5", "caffe" ]
I am trying to load hdf5 in caffe, it is not working. I checked the paths and even able to view hdf file using viewer. Everything is ok but caffe cant seem to load. I write the hdf5 using a python script like this, where X and labels are numpy arrays. ``` f = h5py.File("facialkp.hd5", "w") f.create_dataset("data", da...
Solved :) i created a text file, placed the path of real .hd5 file inside it. The caffe prototxt file points to text file and it worked :) ``` hdf5_data_param { source: "train.txt" batch_size: 10 } ``` train.txt contains line.. ``` facialkp.hd5 ```
Creating a RESTful API using Flask?
28,032,278
10
2015-01-19T19:38:35Z
28,046,800
18
2015-01-20T13:41:15Z
[ "python", "api", "rest", "flask" ]
The Flask tutorial site [here](https://flask-restful.readthedocs.org/en/0.3.1/quickstart.html#a-minimal-api) says that to create a RESTful API, you would write classes that extend `restful.Resource`, then add them to the API by: ``` app = Flask(__name__) api = restful.Api(app) class HelloWorld(restful.Resource): d...
**Short answer**: restful.Resource is from a [Flask-Restful](https://flask-restful.readthedocs.org/en/0.3.1/index.html) extension, which is not Flask itself. [Miguel's tutorial](http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask) uses [Flask](http://flask.pocoo.org/) to write a restful i...
Code coverage for jinja2 templates in Django
28,034,446
8
2015-01-19T22:15:42Z
28,115,310
10
2015-01-23T17:21:45Z
[ "python", "django", "code-coverage", "jinja2", "coverage.py" ]
Following Ned Batchelder's [Coverage.py for Django templates](http://nedbatchelder.com/blog/201501/coveragepy_for_django_templates.html) blog post and the [django\_coverage\_plugin](https://github.com/nedbat/django_coverage_plugin) plugin for measuring code coverage of Django templates. I would really like to see temp...
The plugin support in coverage.py is still in an alpha state. I've implemented the Django template support and half of the Mako support. A Jinja plugin would be appreciated. It might need changes in Jinja to make it feasible, in particular, to map the compiled Python code execution back to template line numbers. If yo...
creating a list of tuples using for loop
28,034,735
3
2015-01-19T22:39:34Z
28,034,757
7
2015-01-19T22:41:11Z
[ "python", "list" ]
I want to create a list of tuples from a list and position of each element in list. Here is what I am trying. ``` def func_ (lis): ind=0 list=[] for h in lis: print h return h ``` Let's say argument of function: ``` lis=[1,2,3,4,5] ``` I was wondering how to make use if ind. Desired outpu...
You can do this a lot easier with [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate) and a [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions): ``` >>> lis=[1,2,3,4,5] >>> [(x, i) for i, x in enumerate(lis)] [(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)] >>...
Should I be adding the Django migration files in the .gitignore file?
28,035,119
23
2015-01-19T23:10:31Z
28,035,246
22
2015-01-19T23:22:37Z
[ "python", "django", "git" ]
Should I be adding the Django migration files in the .gitignore file? I've recently been getting a lot of git issues due to migration conflicts and was wondering if I should be marking migration files as ignore. If so, how would I go about adding all of the migrations that I have in my apps, and adding them to the .g...
Quoting from the [Django migrations documentation](https://docs.djangoproject.com/en/1.7/topics/migrations/): > The migration files for each app live in a “migrations” directory inside of that app, and are designed to be committed to, and distributed as part of, its codebase. You should be making them once on your...
Improper use of __new__ to generate classes?
28,035,685
6
2015-01-20T00:05:06Z
28,076,300
9
2015-01-21T20:33:38Z
[ "python", "factory", "factory-pattern" ]
I'm creating some classes for dealing with filenames in various types of file shares (nfs, afp, s3, local disk) etc. I get as user input a string that identifies the data source (i.e. `"nfs://192.168.1.3"` or `"s3://mybucket/data"`) etc. I'm subclassing the specific filesystems from a base class that has common code. ...
I don't think using `__new__()` to do what you want is improper. For example, I disagree with the accepted answer to this [question](http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init) and that Factory functions are always the "best way to do it". If you really want to avoid using it, then the only ...
How to delete a column from a data frame with pandas?
28,035,839
2
2015-01-20T00:22:23Z
28,036,014
8
2015-01-20T00:43:22Z
[ "python", "python-2.7", "pandas", "io", "tsv" ]
I have the following data: ``` id text 363.327 text1 366.356 text2 37782 textn ``` So ``` import pandas as pd df = pd.read_csv('/path/file.tsv', header=0, delimiter='\t') print df ``` then: ``` id text 0 361.273 text1... 1 374.350 text2... 2 374.350 text3... ``` How can ...
`df.drop(colname, axis=1)` (or `del df[colname]`) is the correct method to use to delete a column. If a `ValueError` is raised, it means the column name is not exactly what you think it is. Check `df.columns` to see what Pandas thinks are the names of the columns.
Django REST Framework upload image: "The submitted data was not a file"
28,036,404
14
2015-01-20T01:34:44Z
28,036,805
21
2015-01-20T02:27:13Z
[ "python", "angularjs", "django", "django-rest-framework" ]
I am leaning how to upload file in Django, and here I encounter a should-be-trivial problem, with the error: > The submitted data was not a file. Check the encoding type on the form. Below is the detail. --- **Note:** I also looked at [Django Rest Framework ImageField](http://stackoverflow.com/questions/20303252/dj...
The problem that you are hitting is that Django REST framework [expects files to be uploaded as multipart form data](http://www.django-rest-framework.org/api-guide/fields/#file-upload-fields), through the standard file upload methods. This is [typically a `file` field](https://developer.mozilla.org/en-US/docs/Using_fil...
IndexError: too many indices for array
28,036,812
8
2015-01-20T02:28:24Z
28,042,958
9
2015-01-20T10:25:25Z
[ "python", "excel", "csv", "error-handling", "indexing" ]
I know there is a ton of these threads but all of them are for very simple cases like 3x3 matrices and things of that sort and the solutions do not even begin to apply to my situation. So I'm trying to graph G versus l1 (that's not an eleven, but an L1). The data is in the file that I loaded from an excel file. The exc...
I think the problem is given in the error message, although it is not very easy to spot: ``` IndexError: too many indices for array xs = data[:, col["l1" ]] ``` 'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining becau...
NetBeans 8.0.2 not recognizing python plataform. How to solve this issue?
28,037,159
3
2015-01-20T03:12:05Z
28,310,975
10
2015-02-03T23:46:08Z
[ "python", "netbeans-8" ]
I have installed in my pc the free version of [Enthought Canopy](https://www.enthought.com/products/canopy/) that works good as python interpreter. But I was trying to move to a free IDE and I choose to make my Netbeans 8.0.2 to be able to run Python. After some research I found this [post](https://blogs.oracle.com/ge...
I ran into the same problem and fixed the issue by downloading Python separately and manually adding it to the list of available platforms. It's very easy to do, and only takes a few minutes. After you're done following the instructions for installing the Python plugin (<https://blogs.oracle.com/geertjan/entry/python_i...
What is the iterator doing when it returns iterables in a for-in statement?
28,037,400
2
2015-01-20T03:41:08Z
28,037,422
8
2015-01-20T03:43:27Z
[ "python", "python-2.7" ]
I don't understand why this works: ``` a = [(1,2)] for x, y in a: print x, y ``` And this doesn't: ``` a = ((1,2)) for x, y in a: print x, y ``` I believe what happens in the first case is we create an iterator that returns a single value, (1,2). That tuple is unpacked, assigning 1 to x and 2 to y. In the ...
`a = ((1,2))` is a single `tuple` of 2 elements - the `()`s around it do nothing - it's the same as `a = (1,2)`, to create a 1-tuple, you need a trailing comma, eg: `a = ((1,2),)` which is a 1-tuple containing a 2-tuple.
ImportError: dynamic module does not define init function
28,040,833
5
2015-01-20T08:38:11Z
28,040,930
8
2015-01-20T08:44:46Z
[ "python", "c++" ]
I am trying to reproduce the following tutorial <https://csl.name/post/c-functions-python/>. My Python extension in **C++** looks like: ``` #include <Python.h> static PyObject* py_myFunction(PyObject* self, PyObject* args) { char *s = "Hello from C!"; return Py_BuildValue("s", s); } static PyObject* py_myOtherF...
Because the function `initextPy` is a C++ function which causes the C++ compiler to [*mangle* the name](https://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_C.2B.2B) so it's not recognizable. You need to mark the function as `extern "C"` to inhibit the name mangling: ``` extern "C" void initextPy(void) { ...
Cannot import name simplejson - After installing simplejson
28,048,943
8
2015-01-20T15:19:51Z
28,049,024
17
2015-01-20T15:23:22Z
[ "python", "django" ]
I have Django Version 1.7 and Python Version 2.7.5 - I used pip install simplejson and apt-get install python-simplejson commands to solve this problem but it still shows me this exception. Is there any compatibility issue between Django and Python or what is the solution to get out of this exception: ``` Traceback (m...
Your code isn't compatible with the version of Django you are using. Django used to ship with `simplejson` in `django.utils`, but this was [removed in Django 1.5](https://docs.djangoproject.com/en/1.7/releases/1.5/#django-utils-simplejson): > # django.utils.simplejson > > Since Django 1.5 drops support for Python 2.5...
Split list of strings into list of sublists based on a string
28,050,350
3
2015-01-20T16:25:35Z
28,050,421
7
2015-01-20T16:29:17Z
[ "python", "string", "list" ]
This problem is most easily illustrated in pseudo-code. I have a list like this: ``` linelist = ["a", "b", "", "c", "d", "e", "", "a"] ``` I would like to get it in the format: ``` questionchunks = [["a", "b"], ["c", "d", "e"], ["a"]] ``` My first attempt is this: ``` questionchunks = [] qlist = [] for line in li...
You are almost near your goal, this is the minimal edit required ``` linelist = ["a", "b", "", "c", "d", "e", "", "a"] questionchunks = [] qlist = [] linelist.append('') # append an empty str at the end to avoid the other condn for line in linelist: if (line != "" ): questionchunks.append(line) # add...
Combining two forms in one Django view
28,054,991
2
2015-01-20T20:56:17Z
28,059,352
7
2015-01-21T03:54:41Z
[ "python", "django" ]
I am working on adding more functionality to the polls app that is made in the official Django tutorial. One of the things I am working on is making Polls/Choices creatable by logged in users (instead of in an admin screen, where the tutorial leaves us). I am looking to create a view where a user can create the a Poll...
[Formsets](https://docs.djangoproject.com/en/1.7/topics/forms/formsets/) are the way to do it in django. First add `default` value for `Poll.pub_date` field: ``` class Poll(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published', default=timezone.now) `...
How to build and fill pandas dataframe from for loop?
28,056,171
4
2015-01-20T22:17:35Z
28,056,359
7
2015-01-20T22:33:12Z
[ "python", "pandas" ]
Here is a simple example of the code I am running, and I would like the results put into a pandas dataframe (unless there is a better option): ``` for p in game.players.passing(): print p, p.team, p.passing_att, p.passer_rating() R.Wilson SEA 29 55.7 J.Ryan SEA 1 158.3 A.Rodgers GB 34 55.8 ``` Using this code: ...
Try this using list comprehension: ``` d = df[[p, p.team, p.passing_att, p.passer_rating()] for p in game.players.passing()] ```
How to build and fill pandas dataframe from for loop?
28,056,171
4
2015-01-20T22:17:35Z
28,058,264
7
2015-01-21T01:44:32Z
[ "python", "pandas" ]
Here is a simple example of the code I am running, and I would like the results put into a pandas dataframe (unless there is a better option): ``` for p in game.players.passing(): print p, p.team, p.passing_att, p.passer_rating() R.Wilson SEA 29 55.7 J.Ryan SEA 1 158.3 A.Rodgers GB 34 55.8 ``` Using this code: ...
The simplest answer is what Paul H said: ``` d = [] for p in game.players.passing(): d.append({'Player': p, 'Team': p.team, 'Passer Rating': p.passer_rating()}) pd.DataFrame(d) ``` But if you really want to "build and fill a dataframe from a loop", (which, btw, I wouldn't recommend), here's how you'd do ...
Understanding execute async script in Selenium
28,057,338
16
2015-01-20T23:52:52Z
28,057,738
11
2015-01-21T00:40:24Z
[ "javascript", "python", "selenium", "selenium-webdriver", "protractor" ]
I've been using `selenium` (with [python bindings](http://selenium-python.readthedocs.org/) and through [`protractor`](http://angular.github.io/protractor/#/) mostly) for a rather long time and every time I needed to execute a javascript code, I've used `execute_script()` method. For example, [for scrolling the page](h...
Here's the [reference](http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/JavascriptExecutor.html) to the two APIs (well it's Javadoc, but the functions are the same), and here's an excerpt from it that highlights the difference > [executeAsyncScript] Execute an asynchronous piece of JavaScript...
Understanding execute async script in Selenium
28,057,338
16
2015-01-20T23:52:52Z
28,066,902
15
2015-01-21T12:09:09Z
[ "javascript", "python", "selenium", "selenium-webdriver", "protractor" ]
I've been using `selenium` (with [python bindings](http://selenium-python.readthedocs.org/) and through [`protractor`](http://angular.github.io/protractor/#/) mostly) for a rather long time and every time I needed to execute a javascript code, I've used `execute_script()` method. For example, [for scrolling the page](h...
> When should I use `execute_async_script()` instead of the regular `execute_script()`? When it comes to checking conditions on the browser side, **all checks you can perform with `execute_async_script` can be performed with `execute_script`. Even if what you are checking is asynchronous.** I know because once upon a ...
Write to StringIO object using Pandas Excelwriter?
28,058,563
6
2015-01-21T02:21:36Z
28,065,603
11
2015-01-21T11:03:14Z
[ "python", "excel", "pandas", "stringio", "xlsxwriter" ]
I can pass a StringIO object to pd.to\_csv() just fine: ``` io = StringIO.StringIO() pd.DataFrame().to_csv(io) ``` But when using the excel writer, I am having a lot more trouble. ``` io = StringIO.StringIO() writer = pd.ExcelWriter(io) pd.DataFrame().to_excel(writer,"sheet name") writer.save() ``` Returns an ``` ...
Pandas expects a filename path to the ExcelWriter constructors although each of the writer engines support `StringIO`. Perhaps that should be raised as a bug/feature request in Pandas. In the meantime here is a workaround example using the Pandas `xlsxwriter` engine: ``` import pandas as pd import StringIO io = Stri...
Python: how to find common values in three lists
28,061,223
4
2015-01-21T06:52:33Z
28,061,267
15
2015-01-21T06:55:00Z
[ "python", "python-2.7", "python-3.x" ]
I try to find common list of values for three different lists: ``` a = [1,2,3,4] b = [2,3,4,5] c = [3,4,5,6] ``` of course naturally I try to use the `and` operator however that way I just get the value of last `list` in expression: ``` >> a and b and c out: [3,4,5,6] ``` Is any short way to find the common values ...
Use sets: ``` >>> a = [1, 2, 3, 4] >>> b = [2, 3, 4, 5] >>> c = [3, 4, 5, 6] >>> set(a) & set(b) & set(c) {3, 4} ``` Or as Jon suggested: ``` >>> set(a).intersection(b, c) {3, 4} ``` Using sets has the benefit that you don’t need to repeatedly iterate the original lists. Each list is iterated once to create the s...
Random state (Pseudo-random number)in Scikit learn
28,064,634
8
2015-01-21T10:17:50Z
28,069,274
7
2015-01-21T14:10:26Z
[ "python", "scikit-learn" ]
I want to implement machine learning algorithim in scikit learn, but I dont understand what does this parameter random state does?? Why should I use it? I also couldnt understand what is Pseudo-random number. Thanks in advance.
`train_test_split` splits arrays or matrices into random train and test subsets. That means that everytime you run it without specifying `random_state`, you will get a different result, this is expected behaviour. For example: **Run 1:** ``` >>> a, b = np.arange(10).reshape((5, 2)), range(5) >>> train_test_split(a, b...
Python: Disable images in Selenium Google ChromeDriver
28,070,315
5
2015-01-21T15:01:20Z
31,581,387
13
2015-07-23T07:58:48Z
[ "python", "google-chrome", "selenium", "web-scraping", "web-crawler" ]
I spend a lot of time searching about this. At the end of the day I combined a number of answers and it works. I share my answer and I'll appreciate it if anyone edits it or provides us with an easier way to do this. 1- The answer in [Disable images in Selenium Google ChromeDriver](http://stackoverflow.com/questions/1...
Thanks. Here is another way to disable images, ``` chromeOptions = webdriver.ChromeOptions() prefs = {"profile.managed_default_content_settings.images":2} chromeOptions.add_experimental_option("prefs",prefs) driver = webdriver.Chrome(chrome_options=chromeOptions) ``` I found it below: <http://nullege.com/codes/show/...
Animating "growing" line plot in Python/Matplotlib
28,074,461
4
2015-01-21T18:41:18Z
28,077,104
7
2015-01-21T21:23:53Z
[ "python", "animation", "graphics", "matplotlib" ]
I want to produce a set of frames that can be used to animate a plot of a growing line. In the past, I have always used plt.draw() and set\_ydata() to redraw the y-data as it changed over time. This time, I wish to draw a "growing" line, moving across the graph with time. Because of this, set\_ydata doesn't work (xdata...
A couple of notes: First off, the reason that things become progressively slower is that you're drawing more and more and more overlapping lines in the same position. A quick fix is to clear the plot each time: ``` import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 10, 100) y = np.sin(x) plt.fig...
freeTDS: Missing libtdsodbc.so file on OSX?
28,074,751
6
2015-01-21T18:59:08Z
28,075,292
9
2015-01-21T19:30:19Z
[ "python", "osx", "freetds" ]
I am trying to connect to a SQL server from a python script on a Mac OSX and after installing freeTDS using `brew install freeTDS` I can't seem to find the driver "`libtdsodbc.so`" anywhere on my machine so that I can place it in the connection string. Has anyone ever encountered this problem or knows why it's happeni...
So according to [This thread here](https://github.com/Homebrew/homebrew/issues/24550) the issue is with the way freeTDS is built now, you need to use `brew install freetds --with-unixodbc` and I can verify this fixed my problem.
numpy.sin function in degrees?
28,077,733
6
2015-01-21T22:06:28Z
28,077,771
12
2015-01-21T22:09:18Z
[ "python", "math", "numpy", "trigonometry", "sin" ]
I'm working on a problem that has to do with calculating angles of refraction and what not. However, it seems that I'm unable to use the numpy.sin() function in degrees. I have tried to use numpy.degrees() and numpy.rad2deg(). ``` numpy.sin(90) numpy.degrees(numpy.sin(90)) ``` Both return ~ 0.894 and ~ 51.2 respecti...
You don't want to convert *to* degrees, because you already have your number (90) in degrees. You need to convert 90 *from* degrees to radians, and you need to do it *before* you take the sine: ``` >>> np.sin(np.deg2rad(90)) 1.0 ``` (You can use either `deg2rad` or `radians`.)
Django Rest Framework writable nested serializers
28,078,092
8
2015-01-21T22:33:05Z
28,246,994
10
2015-01-31T00:54:35Z
[ "python", "django", "serialization", "django-rest-framework" ]
I'm writing a recipe organizer as a sample project for a class. I'm not very experienced with DRF other than using some very basic functionality. Here's the objective: Create a new Recipe with associated Ingredients. Create the Ingredient objects at the same time as creating the Recipe object. **models.py:** ``` cla...
I figured out that ManyToMany relationships can't be established until all of the uncreated objects have been created. (See the Django Docs [page on many-to-many relationships](https://docs.djangoproject.com/en/1.7/topics/db/examples/many_to_many/#many-to-many-relationships).) Here's the working code: **serializers.p...
Print real roots only in numpy
28,081,247
4
2015-01-22T04:21:35Z
28,084,225
8
2015-01-22T08:33:08Z
[ "python", "python-3.x", "numpy" ]
I have something like this: ``` coefs = [28, -36, 50, -22] print(numpy.roots(coefs)) ``` Of course the result is: ``` [ 0.35770550+1.11792657j 0.35770550-1.11792657j 0.57030329+0.j ] ``` However, by using this method, how do I get it only to print the real roots if any (as floats)? Meaning just this for my exampl...
Do NOT use `.iscomplex()` or `.isreal()`, because `roots()` is a numerical algorithm, and it returns the numerical approximation of the actual roots of the polynomial. This can lead to spurious imaginary parts, that are interpreted by the above methods as solutions. Example: ``` # create a polynomial with these real-...
Is list[i:j] guaranteed to be an empty list if list[j] precedes list[i]?
28,086,896
38
2015-01-22T10:49:45Z
28,086,905
45
2015-01-22T10:50:25Z
[ "python", "list", "slice" ]
[The Python tutorial](https://docs.python.org/2/tutorial/introduction.html#strings) explains slice behavior when indices are negative, but I can't find documentation describing the behavior when the end index precedes the start index. (I've also looked at [Explain Python's slice notation](http://stackoverflow.com/quest...
Yes, if `j <= i` is true, the resulting slice is empty, for *standard Python types*. To get the results in reverse order, you need to add a negative stride: ``` list[i:j:-1] ``` because *explicit is better than implicit*. This is documented in [*Common Sequence Operations*](https://docs.python.org/3/library/stdtypes...
python keyword string formatting with '%' confusing error : unsupported format character 'p'
28,089,861
3
2015-01-22T13:22:50Z
28,089,893
7
2015-01-22T13:24:13Z
[ "python", "string", "string-formatting" ]
I have the following setup ``` cred_dict={'admin_id':'user','admin_password':'pass'} cred_template='-id=%(admin_id) -pa=%(admin_password)' ``` When I try ``` cred_template % cred_dict ``` I get ``` ValueError: unsupported format character 'p' (0x70) at index 17 ``` and I can't figure out why.
You are missing a crucial element: the formatting *type* indicator: ``` cred_template='-id=%(admin_id)s -pa=%(admin_password)s' # ^ ^ ``` The `s` indicates you want to format the values as strings. Without those indicators, Python keeps looking for the type and finds t...
Difference between "fill" and "expand" options for tkinter pack method
28,089,942
8
2015-01-22T13:26:25Z
28,090,362
10
2015-01-22T13:48:26Z
[ "python", "tkinter" ]
I know this is a too trivial question, but I am new to python, and I have just started using the `tkinter` module. I have actually looked up about it everywhere, and I am unable to find the satisfactory answer. I found the following: > `fill` option: it determines whether to use up more space or keep > "one's own" dim...
From [effbot](http://effbot.org/tkinterbook/pack.htm): > The **fill** option tells the manager that the widget wants fill the entire space assigned to it. The value controls how to fill the space; **BOTH** means that the widget should expand both horisontally and vertically, **X** means that it should expand only hori...
How to get the datetime from a string containing '2nd' for the date in Python?
28,091,947
3
2015-01-22T15:03:01Z
28,092,019
7
2015-01-22T15:06:02Z
[ "python", "string", "datetime" ]
I've got a couple strings from which I want to get the datetime. They are formatted like this: ``` Thu 2nd May 2013 19:00 ``` I know almost how I can convert this to a datetime, except for that I'm having trouble with the "2**nd**". I now have the following ``` >>> datetime.strptime('Thu 02 May 2013 19:00', '%a %d %...
Consider using [`dateutil.parser.parse`](https://labix.org/python-dateutil#head-a23e8ae0a661d77b89dfb3476f85b26f0b30349c). It's a third party library that has a powerful parser which can handle these kinds of things. ``` from dateutil.parser import parse s = 'Thu 2nd May 2013 19:00' d = parse(s) print(d, type(d)) #...
Why is "from ... import *" in a function not allowed?
28,094,146
3
2015-01-22T16:43:53Z
28,094,312
8
2015-01-22T16:51:50Z
[ "python", "function", "python-3.x", "python-import" ]
From [the documentation](https://docs.python.org/3/reference/simple_stmts.html#the-import-statement): > The wild card form of import — `from module import *` — is only allowed at the module level. Attempting to use it in class or function definitions will raise a `SyntaxError`. Why? What's the sense of avoiding t...
The CPython implementation uses a special optimisation for local variables: They aren't dynamically looked up at runtime from a dictionary, as globals are, but rather are assigned indices statically at *compile time*, and are looked up by index at runtime, which is a lot faster. This requires the Python compiler to be ...
Python: iterate through a list
28,095,258
9
2015-01-22T17:41:24Z
28,095,451
9
2015-01-22T17:51:07Z
[ "python", "list", "loops" ]
I´ve a mind challenge riddle that i want to resolve using python. They give 4 numbers (25, 28, 38, 35) and they want us to place the numbers in ...+...-...=... One possible solution is 25+38-35=28. I´ve tried to, making a list from the numbers, iterate them with some loops and an if: lst=[25, 28, 38, 35] ``` for z i...
As Luis' comment hinted, a good approach is ``` import itertools for z, x, c, v in itertools.permutations(lst): if z+x-c==v: print z,x,c,v ``` "flat is better than nested", as `import this` at an interactive Python prompt will remind you:-)
Pandas merge two dataframes with different columns
28,097,222
4
2015-01-22T19:37:02Z
28,097,336
10
2015-01-22T19:44:42Z
[ "python", "pandas", "dataframe", "data-munging" ]
I'm surely missing something simple here. Trying to merge two dataframes in pandas that have mostly the same column names, but the right dataframe has some columns that the left doesn't have, and vice versa. ``` >df_may id quantity attr_1 attr_2 0 1 20 0 1 1 2 23 1 1 2 3 ...
I think in this case [`concat`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html#pandas.concat) is what you want: ``` In [12]: pd.concat([df,df1], axis=0, ignore_index=True) Out[12]: attr_1 attr_2 attr_3 id quantity 0 0 1 NaN 1 20 1 1 1 NaN 2 ...
How `eval()` is not 'dangerous' in this example
28,100,471
3
2015-01-22T23:18:49Z
28,100,947
7
2015-01-23T00:08:11Z
[ "python", "eval", "python-3.4" ]
I was checking a calculator example, in the example used `eval()` which is dangerous normally, but here is a part of that example; ``` if button == "=": #Check carefully how we using the 'dangerous' eval() total = eval(str1,{"__builtins__":None},{}) str1 = str(total) print (str1) ``` I checked it but ...
The code is not safe in the slightest. It's relatively easy to get access to the `builtins` module just by accessing attributes of literals. eg. ``` result = eval("""[klass for klass in ''.__class__.__base__.__subclasses__() if klass.__name__ == "BuiltinImporter"][0].load_module("builtins")""", {"__bu...
In Python, why is 'r+' but not 'rw' used to mean "read & write"?
28,100,993
14
2015-01-23T00:13:21Z
28,101,025
29
2015-01-23T00:16:18Z
[ "python" ]
In Python, when opening a file, we use `'r'` to indicate read-only and `'w'` write-only. Then we use `'r+'` to mean "read and write". Why not use `'rw'`? Doesn't `'rw'` looks more natural than `'r+'`? --- Edit on Jan. 25th: Oh.. I guess my question looks a little confusing.. What I was trying to ask is: `'r'` is th...
Python copies the modes from [C's `fopen()` call](http://en.cppreference.com/w/cpp/io/c/fopen). `r+` is what C uses, and Python stuck with the 40-year-old convention.
Match letter frequency within a word against 26 letters in R (or python)
28,104,250
2
2015-01-23T06:31:19Z
28,104,290
8
2015-01-23T06:34:33Z
[ "python", "string" ]
Currently, I have a string `"abdicator"`. I would like find out frequency of letters from this word compared against all English alphabets (i.e., 26 letters), with an output in the form as follows. Output: ``` a b c d e f g h i ... o ... r s t ... x y z 2 1 1 0 0 0 0 0 1..0..1..0..1 0 1 ... 0 ... ``` This output can...
In R: ``` table(c(letters, strsplit("abdicator", "")[[1]]))-1 # a b c d e f g h i j k l m n o p q r s t u v w x y z # 2 1 1 1 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 0 ``` And extending that a bit to handle the possibility of multiple words and/or capital letters: ``` words <- c("abdicator", "Syzygy") letterCount...
Why does `False is False is False` evaluate to `True`?
28,104,393
38
2015-01-23T06:45:09Z
28,104,457
60
2015-01-23T06:49:17Z
[ "python", "python-internals" ]
Why in Python it is evaluated this way: ``` >>> False is False is False True ``` but when tried with parenthesis is behaving as expected: ``` >>> (False is False) is False False ```
Chaining operators like `a is b is c` is equivalent to `a is b and b is c`. So the first example is `False is False and False is False`, which evaluates to `True and True` which evaluates to `True` Having parenthesis leads to the result of one evaluation being compared with the next variable (as you say you expect), ...
Why does `False is False is False` evaluate to `True`?
28,104,393
38
2015-01-23T06:45:09Z
28,104,483
14
2015-01-23T06:51:33Z
[ "python", "python-internals" ]
Why in Python it is evaluated this way: ``` >>> False is False is False True ``` but when tried with parenthesis is behaving as expected: ``` >>> (False is False) is False False ```
Your expression ``` False is False is False ``` is treated as ``` (False is False) and (False is False) ``` So you get ``` True and True ``` and that evaluates to `True`. You can use this kind of chaining with other operators too. ``` 1 < x < 10 ```
Why does `False is False is False` evaluate to `True`?
28,104,393
38
2015-01-23T06:45:09Z
28,104,537
24
2015-01-23T06:55:24Z
[ "python", "python-internals" ]
Why in Python it is evaluated this way: ``` >>> False is False is False True ``` but when tried with parenthesis is behaving as expected: ``` >>> (False is False) is False False ```
Quoting [Python official documentation](https://docs.python.org/2/reference/expressions.html#not-in), > Formally, if `a`, `b`, `c`, ..., `y`, `z` are expressions and `op1`, `op2`, ..., `opN` are comparison operators, then `a op1 b op2 c ... y opN z` is equivalent to `a op1 b and b op2 c and ... y opN z`, except that e...
AttributeError with Django REST Framework and a ManyToMany relationship
28,108,600
3
2015-01-23T11:10:26Z
28,108,641
11
2015-01-23T11:12:20Z
[ "python", "django", "many-to-many", "django-rest-framework" ]
Trying to access my json page I get this error! ``` AttributeError at /project/api/1.json Got AttributeError when attempting to get a value for field `title` on serializer `TaskSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance. Original exc...
In that question they set `many=False`. You *do* have a Many-to-Many, so set `many=True` It's that simple. In fact if you look closely, that's how the example shows you to do it: ``` class TrackListingField(serializers.RelatedField): def to_representation(self, value): duration = time.strftime('%M:%S', ti...
findContours and drawContours errors in opencv 3 beta/python
28,113,221
4
2015-01-23T15:29:33Z
28,113,744
7
2015-01-23T15:56:47Z
[ "python", "opencv" ]
I try to run an example from [here](http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_contours/py_contours_begin/py_contours_begin.html#contours-getting-started). ``` import numpy as np import cv2 img = cv2.imread('final.jpg') imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,12...
opencv 3 has a slightly [changed syntax](http://docs.opencv.org/trunk/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#findcontours) here, the return values differ: ``` cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) → image, contours, hierarchy ```
findContours and drawContours errors in opencv 3 beta/python
28,113,221
4
2015-01-23T15:29:33Z
31,865,966
7
2015-08-06T21:17:03Z
[ "python", "opencv" ]
I try to run an example from [here](http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_contours/py_contours_begin/py_contours_begin.html#contours-getting-started). ``` import numpy as np import cv2 img = cv2.imread('final.jpg') imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,12...
Following on berak's answer, just adding `[-2:]` to `findContours()` calls makes them work for both OpenCV 2.4 and 3.0: ``` contours, hierarchy = cv2.findContours(...)[-2:] ```
Boto [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed while connecting to S3
28,115,250
6
2015-01-23T17:18:11Z
28,116,567
7
2015-01-23T18:40:15Z
[ "python", "amazon-web-services", "amazon-s3", "amazon", "boto" ]
I am trying to connect to S3 using boto, but it seems to fail. I've tried some workarounds, but they don't seem to work. Can anyone please help me with this. Below is the code. ``` import boto if not boto.config.has_section('Credentials'): boto.config.add_section('Credentials') boto.config.set('Credentials', 'aws...
I found a way, used `is_secure=False` in `connect_s3()`.
Python - ERROR - failed to write data to stream: <open file '<stdout>', mode 'w' at 0x104c8f150>
28,115,375
8
2015-01-23T17:25:15Z
30,648,904
25
2015-06-04T16:08:53Z
[ "python", "django" ]
I'm doing an import data from a CSV file, after entering 210 lines, it returns me this error. I'm doing this from Django shell (manage.py shell) ``` ERROR - failed to write data to stream: <open file '<stdout>', mode 'w' at 0x104c8f150> ```
This is a problem with the IPython encoding that is not UTF-8. `export PYTHONIOENCODING=UTF-8` will solve it.
Python/psycopg2 WHERE IN statement
28,117,576
8
2015-01-23T19:46:07Z
28,117,658
13
2015-01-23T19:51:45Z
[ "python", "psycopg2", "where-in" ]
What is the correct method to have the list (countryList) be available via %s in the SQL statement? ``` # using psycopg2 countryList=['UK','France'] sql='SELECT * from countries WHERE country IN (%s)' data=[countryList] cur.execute(sql,data) ``` As it is now, it errors out after trying to run "WHERE country in (ARRA...
For the `IN` operator, you want a [tuple](http://initd.org/psycopg/docs/usage.html#tuples-adaptation) instead of [list](http://initd.org/psycopg/docs/usage.html#lists-adaptation), and remove parentheses from the SQL string. ``` # using psycopg2 data=('UK','France') sql='SELECT * from countries WHERE country IN %s' cu...
Python urllib2 returning an empty string
28,118,611
2
2015-01-23T20:57:51Z
28,118,744
8
2015-01-23T21:06:10Z
[ "python", "urllib2" ]
I'm trying to retrieve the following URL: <http://www.winkworth.co.uk/sale/property/flat-for-sale-in-masefield-court-london-n5/HIH140004>. ``` import urllib2 response = urllib2.urlopen('http://www.winkworth.co.uk/rent/property/terraced-house-to-rent-in-mill-road--/WOT140129') response.read() ``` However I'm getting a...
I got a response when using the `requests` library but not when using `urllib2`, so I experimented with HTTP request headers. As it turns out, the server expects an `Accept` header; `urllib2` doesn't send one, `requests` and cURL send `*/*`. Send one with `urllib2` as well: ``` url = 'http://www.winkworth.co.uk/sale...
Quickest way to make a get_dummies type dataframe from a column with a multiple of strings
28,121,682
2
2015-01-24T02:25:53Z
28,121,795
7
2015-01-24T02:48:31Z
[ "python", "pandas", "split", "dataframe" ]
I have a column, 'col2', that has a list of strings. The current code I have is too slow, there's about 2000 unique strings (the letters in the example below), and 4000 rows. Ending up as 2000 columns and 4000 rows. ``` In [268]: df.head() Out[268]: col1 col2 0 6 A,B 1 15 C,G,A 2 25 B ``` ...
You can use: ``` >>> df['col2'].str.get_dummies(sep=',') A B C G 0 1 1 0 0 1 1 0 1 1 2 0 1 0 0 ``` To join the Dataframes: ``` >>> pd.concat([df, df['col2'].str.get_dummies(sep=',')], axis=1) col1 col2 A B C G 0 6 A,B 1 1 0 0 1 15 C,G,A 1 0 1 1 2 25 B 0 1 0 0...
Is django prefetch_related supposed to work with GenericRelation
28,127,135
22
2015-01-24T15:38:39Z
28,274,847
15
2015-02-02T09:46:10Z
[ "python", "django", "django-models", "django-orm" ]
**UPDATE:** An Open Ticked about this issue: [24272](https://code.djangoproject.com/ticket/24272) What's all about? Django has a [GenericRelation](https://docs.djangoproject.com/en/1.9/ref/contrib/contenttypes/#django.contrib.contenttypes.fields.GenericRelation) class, which adds a **“reverse” generic relationshi...
If you want to retrieve `Book` instances and prefetch the related tags use `Book.objects.prefetch_related('tags')`. No need to use the reverse relation here. You can also have a look at the related tests in the [Django source code](https://github.com/django/django/blob/master/tests/prefetch_related/tests.py#L738). Al...
How to install PyGame on Python 3.4?
28,127,730
8
2015-01-24T16:40:30Z
28,127,864
14
2015-01-24T16:51:55Z
[ "python", "pygame", "pip", "python-3.4" ]
So I have this little problem. When I try to install PyGame for Python 3.4 I download a .whl (wheel?) file and don't know how to use it. Some guys told me something about pip but don't know how to use/install it.
You can install the wheel file for Python 3.4 [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame): First you have to install the wheel package from `pip` then install Pygame. ``` pip install wheel pip install pygame‑1.9.2a0‑cp34‑none‑win_amd64.whl ``` Here's a video to help you install pip on [Youtube...
How to set default column value in the db using django 1.7.3/postgres migrations?
28,129,991
6
2015-01-24T20:37:24Z
28,131,933
8
2015-01-25T00:36:23Z
[ "python", "django", "postgresql", "django-models", "django-migrations" ]
It seems like default value on columns is only on the ORM layer, and is not actually setting a default value in the DB. At the same time, the ID key for example has a default modifier in the database, which tells me it is possible to do that, but not sure how? Example code: ``` class Host(models.Model): name = mo...
I would put your code in a [`RunSQL` operation](https://docs.djangoproject.com/en/dev/ref/migration-operations/#runsql), something like: ``` class Migration(migrations.Migration): dependencies = [ ('myapp', 'previous_migration'), ] operations = [ migrations.RunSQL("alter table myapp_host alter column created...
How to apply a function on a backreference?
28,133,001
2
2015-01-25T03:46:04Z
28,133,012
7
2015-01-25T03:48:57Z
[ "python", "regex", "function", "backreference" ]
Say I have strings like the following: ``` old_string = "I love the number 3 so much" ``` I would like to spot the integer numbers (in the example above, there is only one number, `3`), and replace them with a value larger by 1, i.e., the desired result should be ``` new_string = "I love the number 4 so much" ``` I...
In addition to having a replace string, `re.sub` allows you to use a function to do the replacements: ``` >>> import re >>> old_string = "I love the number 3 so much" >>> def f(match): ... return str(int(match.group(1)) + 1) ... >>> re.sub('([0-9])+', f, old_string) 'I love the number 4 so much' >>> ``` From the ...
Convert Pandas Series to DateTime in a DataFrame
28,133,018
2
2015-01-25T03:49:57Z
28,133,042
7
2015-01-25T03:55:12Z
[ "python", "datetime", "pandas", "dataframe" ]
I have a Pandas DataFrame as below ``` ReviewID ID Type TimeReviewed 205 76032930 51936827 ReportID 2015-01-15 00:05:27.513000 232 76032930 51936854 ReportID 2015-01-15 00:06:46.703000 233 76032930 51936855 ReportID 2015-01-15 00:06:56.707000 413 76032930 5193703...
You can't: `DataFrame` columns are `Series`, by definition. That said, if you make the `dtype` (the type of all the elements) datetime-like, then you can access the quantities you want via the `.dt` accessor ([docs](http://pandas.pydata.org/pandas-docs/stable/basics.html#dt-accessor)): ``` >>> df["TimeReviewed"] = pd....
Concatenate two dataframes in pandas
28,135,436
5
2015-01-25T10:35:54Z
28,135,445
12
2015-01-25T10:37:10Z
[ "python", "pandas", "dataframe" ]
I need to concatenate two dataframes `df_a` and`df_b` having equal number of rows (`nRow`) one after another without any consideration of keys. This function is similar to `cbind` in `R programming language`. The number of columns in each dataframe may be different. The resultant dataframe will have the same number of...
call [`concat`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html#pandas.concat) and pass param `axis=1` to concatenate column-wise: ``` In [5]: pd.concat([df_a,df_b], axis=1) Out[5]: AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \ 0 ELVISLIVES A 1 ...
Installing python-sympy in a Docker image
28,135,571
3
2015-01-25T10:53:41Z
28,137,536
8
2015-01-25T14:33:37Z
[ "python", "docker", "sympy" ]
I am trying to install Sympy in a Docker image based on Debian using a Dockerfile: ``` FROM debian:jessie RUN apt-get update && apt-get install -y \ python \ build-essential \ make \ gcc \ pandoc \ lrslib \ dos2unix \ python-dev \ python-pygments \ python-numpy \ python-pip...
I guess those 900MB are not dependencies, but recommendations. ``` $ apt-cache show python-sympy Package: python-sympy Priority: optional Section: universe/python Installed-Size: 14889 Maintainer: Ubuntu Developers <[email protected]> Original-Maintainer: Georges Khaznadar <[email protected]> Arc...
How do I make the same iteration for several different lists at the same time in Python
28,135,824
3
2015-01-25T11:26:27Z
28,135,842
11
2015-01-25T11:28:49Z
[ "python", "list", "python-2.7", "iterator" ]
if i have multiple lists at different lengths is there a simple way to make the same iteration on all of them. so insted of writing something like: ``` for item in list1: function(item) for item in list2: function(item) . . . for item in listn: function(item) ``` i just write something like: ``` for item...
Tasks which have to do with iteration are covered by the [`itertools` module](https://docs.python.org/2/library/itertools.html). There you have a [`chain()` function](https://docs.python.org/2/library/itertools.html#itertools.chain) which can do ``` import itertools for item in itertools.chain(list1, list2, list3): ...
Skip iterations in enumerated list object (python)
28,138,392
4
2015-01-25T16:05:44Z
28,138,445
7
2015-01-25T16:10:41Z
[ "python", "loops", "skip" ]
I have the code ``` for iline, line in enumerate(lines): ... if <condition>: <skip 5 iterations> ``` I would like, as you can read, have the for loop skip 5 iterations if the condition is met. I can be sure that, if the condition is met, there are 5 or more objects left in the "lines" object. lines e...
``` iline = 0 while iline < len(lines): line = lines[iline] if <condition>: place_where_skip_happened = iline iline += 5 iline += 1 ``` If you are iterating over a file object you can skip lines using next or make lines an iterator: ``` lines = iter(range(20)) for l in lines: if l == ...
pip install numpy (python 2.7) fails with errorcode 1
28,142,839
5
2015-01-25T23:29:38Z
28,142,945
23
2015-01-25T23:44:21Z
[ "python", "numpy", "pip" ]
I'm installing numpy through pip on python 2.7.9... I checked `pip list`, and it returns `pip (1.5.6), setuptools (12.0.4)`. I'm running on Windows 7 64-bit, and I've tried both Python 32 and 64-bit versions. `pip install numpy` ends with: ``` Command C:\Python27\python.exe -c "import setuptools, tokenize;__file__='c...
Download the wheel (.whl file) file from [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy) and install with pip: 1. `pip install wheel` to install support for wheel files. 2. `pip install numpy‑1.9.1+mkl‑cp27‑none‑win32.whl` to install the wheel.
SQLAlchemy: Convert column value back and forth between internal and database format
28,143,557
4
2015-01-26T01:18:24Z
28,143,787
9
2015-01-26T01:53:43Z
[ "python", "orm", "sqlalchemy", "data-conversion" ]
In my database, I have some columns where data is stored in some weird format. Since the database is used by other code, too, I cannot change the data format. For example, one of the weird formats is that a time value is represented as a string like `23:42:30`. I would like to have some magic that allows me to always ...
Use a [type decorator](http://sqlalchemy.readthedocs.org/en/rel_0_9/core/custom_types.html#augmenting-existing-types) that handles converting to and from the custom format. Use this type rather than `String` when defining your column. ``` class MyTime(TypeDecorator): impl = String def __init__(self, length=No...
How do you copy and Paste in Pycharm?
28,144,352
6
2015-01-26T03:16:14Z
28,388,454
8
2015-02-07T22:55:31Z
[ "python", "pycharm" ]
Every time I try to copy and paste a web url into PyCharm, I even tried Paste Simple, I see nothing. Is there any force that could potentially block out people who try to paste information in? I really have no clue what's going on.
PyCharm version 4.04 does not allow me to paste text from a source (like a text editor, url, document) into a file open in PyCharm. I can cut and paste between two files open in PyCharm. Reverting back to PyCharm version 4.01 returned the expected paste operation for me. Running PyCharm on windows 8
Will a Python dict literal be evaluated in the order it is written?
28,156,687
10
2015-01-26T18:49:31Z
28,156,733
14
2015-01-26T18:52:12Z
[ "python", "dictionary" ]
Let's say that I've got a situation like this in Python: ``` _avg = {'total':0.0, 'count':0} # HACK: side-effects stored here def procedure(n): _avg['count'] += 1 _avg['total'] += n return n def get_average(): return _avg['total'] / _avg['count'] my_dict = { 'key0': procedure(0), 'key2': procedure(2)...
Dictionary evaluation order **should** be the same as written, but there is a [outstanding bug](http://bugs.python.org/issue11205) where *values* are evaluated before the *keys*. (The bug was finally fixed in Python 3.5). Quoting from the [reference documentation](http://docs.python.org/2/reference/expressions.html#ev...
Avoid to write '\n' to the last line of a file in python
28,158,403
2
2015-01-26T20:44:05Z
28,158,452
7
2015-01-26T20:46:51Z
[ "python", "file", "line" ]
I'm writing multiple lines to a new file (could be up to several GB), like this: ``` for item in record: output_pass.write('%s\n' %item) ``` However, I got a blank line due to the '\n' of my last record, such as: Start of the file ``` record111111 reocrd222222 record333333 ---a blank line--- ``` End of a fi...
This should be a simple solution: ``` for item in record[:-1]: output_pass.write("%s\n" % item) output_pass.write("%s" % item[-1]) ``` Using `join` is *not* recommended if you said the file was large - it will create the entire file content string in memory.
Python Numpy mask NaN not working
28,160,590
5
2015-01-26T23:21:10Z
28,160,691
7
2015-01-26T23:28:08Z
[ "python", "numpy" ]
I'm simply trying to use a masked array to filter out some `nan`entries. ``` import numpy as np # x = [nan, -0.35, nan] x = np.ma.masked_equal(x, np.nan) print x ``` This outputs the following: ``` masked_array(data = [ nan -0.33557216 nan], mask = False, fill_value = nan) ``` Calling `np...
You can use [`np.ma.masked_invalid`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.masked_invalid.html): ``` import numpy as np x = [np.nan, 3.14, np.nan] mx = np.ma.masked_invalid(x) print(repr(mx)) # masked_array(data = [-- 3.14 --], # mask = [ True False True], # fill_value = 1...
Sort Pandas Dataframe by Date
28,161,356
7
2015-01-27T00:35:37Z
28,161,433
11
2015-01-27T00:45:58Z
[ "python", "pandas" ]
I have a pandas dataframe as follows: ``` Symbol Date A 02/20/2015 A 01/15/2016 A 08/21/2015 ``` I want to sort it by `Date`, but the column is just an `object`. I tried to make the column a date object, but I ran into an issue where that format is not the format needed. The format needed is `2015...
You can use `pd.to_datetime()` to convert to a datetime object. It takes a format parameter, but in your case I don't think you need it. ``` >>> import pandas as pd >>> df = pd.DataFrame( {'Symbol':['A','A','A'] , 'Date':['02/20/2015','01/15/2016','08/21/2015']}) >>> df Date Symbol 0 02/20/2015 A 1 ...
Convert html to pdf using Python/Flask
28,165,704
4
2015-01-27T08:00:47Z
28,165,767
7
2015-01-27T08:06:12Z
[ "python", "pdf", "flask", "wkhtmltopdf", "xhtml2pdf" ]
I want to generate pdf file from html using Python + Flask. To do this, I use xhtml2pdf. Here is my code: ``` def main(): pdf = StringIO() pdf = create_pdf(render_template('cvTemplate.html', user=user)) pdf_out = pdf.getvalue() response = make_response(pdf_out) return response def create_pdf(pdf_d...
The page need render, You can use pdfkit: <https://pypi.python.org/pypi/pdfkit> <https://github.com/JazzCore/python-pdfkit> Example in document. ``` import pdfkit pdfkit.from_url('http://google.com', 'out.pdf') pdfkit.from_file('test.html', 'out.pdf') pdfkit.from_string('Hello!', 'out.pdf') # Is your requirement?...