title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Parallel Construction of Compressed Sparse Column Matrix
37,630,617
<p>Compressed Sparse Column Matrix (csc) with m columns, as defined <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.html" rel="nofollow">here</a>.</p> <p>It has three arrays: Data, Indices, and Indptr.</p> <ul> <li>indptr is a 1D array with a size of m+1</li> <li>indices is row in...
0
2016-06-04T13:10:18Z
37,632,130
<p>It sounds like you have created a <code>csr</code> matrix, and are then modifying the 3 attribute arrays directly. And that you do so by appending to the existing arrays. While I have manipulated the <code>data</code> attribute of a csr, I have no experience directly changing the others. Seems that would be hard ...
1
2016-06-04T15:46:30Z
[ "python", "matrix", "parallel-processing", "scipy", "sparse-matrix" ]
Improving performance of numpy mapping operation
37,630,661
<p>I have a numpy array of size (4, X, Y), where the first dimension stands for an (R,G,B,A) quadruplet. My aim is to transpose each <code>X*Y</code> RGBA quadruplets to <code>X*Y</code> floating-point values, given a dictionary matching them.</p> <p>My current code is as follows:</p> <pre><code>codeTable = { (25...
7
2016-06-04T13:15:10Z
37,644,801
<p>Here's an approach that returns your expected result, but with such a small amount of data it's hard to know if this will be faster for you. Since I've avoided the double for loop, however, I imagine you'll see a pretty decent speedup.</p> <pre><code>import numpy import pandas as pd codeTable = { (253, 254, 2...
1
2016-06-05T17:31:23Z
[ "python", "performance", "numpy" ]
Improving performance of numpy mapping operation
37,630,661
<p>I have a numpy array of size (4, X, Y), where the first dimension stands for an (R,G,B,A) quadruplet. My aim is to transpose each <code>X*Y</code> RGBA quadruplets to <code>X*Y</code> floating-point values, given a dictionary matching them.</p> <p>My current code is as follows:</p> <pre><code>codeTable = { (25...
7
2016-06-04T13:15:10Z
37,772,674
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) contains a vectorized nd-array capable variant of list.index, which can be used to solve your problem efficiently and concisely:</p> <pre><code>import numpy_indexed as npi ma...
1
2016-06-12T09:27:02Z
[ "python", "performance", "numpy" ]
Multiple conditions on while loop python .isdigit()
37,630,694
<p>I am trying to create a program that stores a user input between 1 and 0.</p> <p>It works fine when I only input numbers, however, the program fails when anything else is inputted.</p> <p>I tried adding a third clause into the while statement but that made the whole program fail.</p> <p>I suspect <code>float(inpu...
0
2016-06-04T13:18:26Z
37,631,500
<p>I'm not sure what you are trying to accomplish:</p> <p>Do you want something like:</p> <pre><code>juvenile_survival = 3 while juvenile_survival &lt; 0 or juvenile_survival &gt; 1: try: juvenile_survival = int(input("What is your juvenile survival rate? Remember this should be between 0 and 1: ")) e...
2
2016-06-04T14:45:02Z
[ "python", "while-loop" ]
Creating a slice object in python
37,630,714
<p>If I have an array <code>a</code>, I understand how to slice it in various ways. Specifically, to slice from an arbitrary first index to the end of the array I would do <code>a[2:]</code>.</p> <p>But how would I create a slice object to achieve the same thing? The two ways to create slice objects that are <a href="...
1
2016-06-04T13:20:04Z
37,630,790
<p>Use <code>None</code> everywhere the syntax-based <code>slice</code> uses a blank value:</p> <pre><code>someseq[slice(2, None)] </code></pre> <p>is equivalent to:</p> <pre><code>someseq[2:] </code></pre> <p>Similarly, <code>someseq[:10:2]</code> can use a preconstructed <code>slice</code> defined with <code>slic...
4
2016-06-04T13:28:20Z
[ "python", "python-3.x", "slice" ]
Python- tkinter: Opening One Another image in another window?
37,630,747
<p>Hello I am doing a job that I need (from a tkinter window containing an image) call another window that contains another imagem.I tried the following:</p> <pre><code>from tkinter import* def abrir1(): b =Tk() imagen = PhotoImage(file= "F2.png") la = Label(b,image =imagen) la.pack() def abrir2(): ...
-2
2016-06-04T13:24:25Z
37,631,361
<p>You have two problems in your code.</p> <p>The first problem is that you are creating two instances of <code>Tk</code>. A tkinter program needs to have exactly one instance. </p> <p>The second problem is that the image you are creating is saved as a local variable. When the function returns, the variable is garbag...
0
2016-06-04T14:28:12Z
[ "python", "tkinter", "tkinter-canvas", "toplevel", "photoimage" ]
Having trouble with creating a variable that adds to itself
37,630,776
<p>I have a variable in my code (named totalPrice) which will set itself to a price given and then when the user adds a product to their list it will add that price to totalPrice. However, when running it, it resets the variable to 0. I believe it has something to do with the placement of it as I have placed it inside ...
0
2016-06-04T13:27:02Z
37,631,069
<p><code>totalPrice</code> is not global within <code>restart()</code>.</p> <p>also think of re-designing your code, there's a lot of dangerous recursion and global variables. E.g. <code>if quantity.isdigit() == False:</code> within <code>quantityQuestion</code> calls <code>quantityQuestion</code> and continues despit...
1
2016-06-04T13:56:32Z
[ "python", "csv", "variables" ]
Django first project import Error
37,630,855
<p><strong>My package:</strong> <kbd>Python 2.7.11+</kbd> <kbd>Django 1.9.6</kbd></p> <p>In my <code>urls.py</code> I have imported:</p> <p><code>from django.conf.urls import patterns, url, include</code></p> <p>but it's dysplays an error when I type <code>python manage.py runserver</code>:</p> <blockquote> <p>Im...
0
2016-06-04T13:35:21Z
37,630,897
<p>Since Django 1.7, the urlconf is a simple list and no longer requires the patterns import. So remove patterns from your import, and see the example here on the syntax to use: <a href="https://docs.djangoproject.com/en/1.9/topics/http/urls/#example" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/http/url...
2
2016-06-04T13:39:45Z
[ "python", "django" ]
How can i get tweets into csv from the data i got from twitter with stream api
37,630,902
<p>I am getting data from Twitter with Tweepy and using Stream API... Here is my t_stream.py file:</p> <pre><code>access_token = "my token" access_token_secret = "my t_secret" consumer_key = "my key" consumer_secret = "my c_secret" class StdOutListener(StreamListener): def on_data(self, raw_data): data = ...
0
2016-06-04T13:40:04Z
37,630,942
<p>some example from the <a href="https://docs.python.org/3.5/library/csv.html" rel="nofollow">python3 docs</a>:</p> <pre><code>import csv with open('eggs.csv', 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spa...
0
2016-06-04T13:44:12Z
[ "python", "csv", "twitter", "stream" ]
How can i get tweets into csv from the data i got from twitter with stream api
37,630,902
<p>I am getting data from Twitter with Tweepy and using Stream API... Here is my t_stream.py file:</p> <pre><code>access_token = "my token" access_token_secret = "my t_secret" consumer_key = "my key" consumer_secret = "my c_secret" class StdOutListener(StreamListener): def on_data(self, raw_data): data = ...
0
2016-06-04T13:40:04Z
37,635,532
<p>Not a python example, but you can do this with jq filters pretty easy piping the output of the stream.</p> <pre><code>$ oksocial https://stream.twitter.com/1.1/statuses/sample.json | jq -r 'select(.id?) | [.user.name, .retweet_count, .user.followers_count, .text] | @csv' "˗ˏˋ molly ˎˊ˗",0,176,"RT @Real_Liam...
0
2016-06-04T22:15:17Z
[ "python", "csv", "twitter", "stream" ]
Python Code for text detection in video not working?
37,631,011
<p>I have this code for text detection in video and it's giving this error every time I try to run it.</p> <p>Here is my Code :</p> <pre><code>import cv2 import numpy as np #from pytesser import * def text_detection(): cap=cv2.VideoCapture(0) while True: ret,img=cap.read() gray=cv2.cvtColor(im...
0
2016-06-04T13:50:49Z
37,631,544
<p>It looks like you forgot to open() the cam.</p> <pre><code>import cv2 cam = cv2.VideoCapture(0) cam.open(0) results = [ cam.read()[0] for i in range(100) ] print results </code></pre> <p>this code snippet should setup, open and verify that the capture is working for a 100 captures.</p>
0
2016-06-04T14:49:47Z
[ "python", "opencv", "opencv3.0" ]
Error when trying to test interrupts with raspberry pi
37,631,014
<pre><code># Test interrupts. import os import select write_once(os.path.join('/sys/class/gpio', 'export'), '22') # Pin to work with pin_base = '/sys/class/gpio/gpio22/' def write_once(path, value): with open(path, 'w') as f: f.write(value) f = open(os.path.join(pin_base, 'value'), 'r') write_once(os.pa...
1
2016-06-04T13:51:11Z
37,631,052
<p>Move:</p> <pre><code>def write_once(path, value): with open(path, 'w') as f: f.write(value) </code></pre> <p>up toward the top of the file, before the first call to it.</p> <p>Statements are executed in order, one at a time, so you're calling it before it's defined. Alternatively, put the calls your maki...
0
2016-06-04T13:55:12Z
[ "python", "python-2.7", "raspberry-pi", "raspberry-pi3" ]
How to decode JSON and faithfully represent backslashes in Python using the json library
37,631,015
<p>I have a config file which I'm trying to pull apart and then reassemble with updated sections. The config file is in a json format, and I'm trying to extract components of it out to update before inserting back into another json file.</p> <p>The problem I'm finding is that sections of the JSON file use <code>"\/"</...
0
2016-06-04T13:51:16Z
37,631,107
<p>Yes, the <code>\</code> backslash is an escape character, and a proper JSON decoder will honour such a character as an escape. The Python JSON decoder is no exception. See <a href="https://tools.ietf.org/html/rfc7159#section-7" rel="nofollow">section 7 of RFC 7159</a>:</p> <blockquote> <p>Any character may be esc...
0
2016-06-04T14:00:29Z
[ "python", "json", "python-2.7" ]
How to compute fast the containment order of all intersections of a collection of sets
37,631,049
<p>This is a follow-up to <a href="http://stackoverflow.com/questions/37622153">How to get all intersections of sets in python fast</a>:</p> <p>I have a finite collection A = {A1,...Ak} of finite sets Ai of integers and I want to compute in <code>Python</code> the following:</p> <ol> <li><p>All intersections of subse...
3
2016-06-04T13:54:35Z
37,631,626
<p>could you just let me know the running time for the following changes?</p> <pre><code>def all_intersections(lists): sets = allIntersections([frozenset(s) for s in lists]) return list(sets) A = ... F = all_intersections(A) F.sort(key=len) pairs = [(x,y) for x,y in combinations(F,2) if y.issuperset(x)] </c...
0
2016-06-04T14:56:44Z
[ "python", "algorithm" ]
How to compute fast the containment order of all intersections of a collection of sets
37,631,049
<p>This is a follow-up to <a href="http://stackoverflow.com/questions/37622153">How to get all intersections of sets in python fast</a>:</p> <p>I have a finite collection A = {A1,...Ak} of finite sets Ai of integers and I want to compute in <code>Python</code> the following:</p> <ol> <li><p>All intersections of subse...
3
2016-06-04T13:54:35Z
37,645,498
<p>Here's a function that takes advantage of the assumption that the lists in the input are the facets of an abstract polytope. Instead of taking all intersections of collections of facets, this function assumes the input is a complete list of M-faces (polytopes of rank M) within a polytope of rank M + 1. It then perf...
2
2016-06-05T18:44:16Z
[ "python", "algorithm" ]
How to compute fast the containment order of all intersections of a collection of sets
37,631,049
<p>This is a follow-up to <a href="http://stackoverflow.com/questions/37622153">How to get all intersections of sets in python fast</a>:</p> <p>I have a finite collection A = {A1,...Ak} of finite sets Ai of integers and I want to compute in <code>Python</code> the following:</p> <ol> <li><p>All intersections of subse...
3
2016-06-04T13:54:35Z
37,664,957
<p>Here is an alternative algorithm which only uses the graded-ness assumption above. The idea is that</p> <ol> <li><p>every intersection except the union of <code>A</code> has a cover which is computable rather quickly</p></li> <li><p>this produces a spanning tree of the order starting at the top element give by unio...
0
2016-06-06T19:00:24Z
[ "python", "algorithm" ]
Django DetailView dynamic model
37,631,057
<p>I'm trying to create one view for several Models for a django app. The app basically is an admin backend with some customized functions.</p> <p>In the update view of each item, I think is better to have only one DetailView defined and dynamically getting the model name. </p> <p>1) Is it a correct approach or is be...
2
2016-06-04T13:55:34Z
37,631,478
<p>You can override the <code>get_queryset()</code> method to return the appropriate model's queryset after getting the model from <code>model_kwarg</code>. </p> <p>To get the model from the <code>model_type</code> kwarg, you can create a <code>MODEL_TYPE_KWARGS_TO_MODEL_MAPPING</code> dictionary. It will return the m...
1
2016-06-04T14:41:53Z
[ "python", "django", "django-models", "views" ]
In Django, how can I get an instance of the class-based-view that a URI resolves to?
37,631,110
<p>I'm developing a navigation system, and I need to get a <code>class based view</code> from a URI that points to it.</p> <p>Where I'm at now is using <code>resolve('/path/to/whatever/')</code> to get a ResolverMatch. A <a href="https://docs.djangoproject.com/en/dev/ref/urlresolvers/#django.urls.ResolverMatch" rel="...
0
2016-06-04T14:00:37Z
37,631,949
<p>The following should work to get you the view class and an instance thereof if needed:</p> <pre><code>import importlib rm = resolve('/path/to/whatever/') # ResolverMatch module_name = rm.func.__module__ # 'path.to.views' view_name = rm.func.func_name #'FooView' views = importlib.import_module(module_name) # &l...
0
2016-06-04T15:29:36Z
[ "python", "django", "uri", "resolve" ]
In Django, how can I get an instance of the class-based-view that a URI resolves to?
37,631,110
<p>I'm developing a navigation system, and I need to get a <code>class based view</code> from a URI that points to it.</p> <p>Where I'm at now is using <code>resolve('/path/to/whatever/')</code> to get a ResolverMatch. A <a href="https://docs.djangoproject.com/en/dev/ref/urlresolvers/#django.urls.ResolverMatch" rel="...
0
2016-06-04T14:00:37Z
37,632,134
<p>I've found that there is a property <code>resolver_match.func.view_class</code>, and I can just call <code>resolver_match.func.view_class()</code> to get an instance of the class-based-view.</p> <p>Thanks to @schwobaseggl for pointing out that <code>resolver_match.func</code> is an object with properties. It's wei...
0
2016-06-04T15:46:36Z
[ "python", "django", "uri", "resolve" ]
Easiest way to interrupt pyqt4?
37,631,123
<p>I'm building a simple speed reader in Python as an exercise. Basically a <a href="http://spritzinc.com/" rel="nofollow">Spritz</a> clone. </p> <p>What's the correct way to stop the printword() function once I run it? Should I put it in a thread? With threading or QThread? I'm a bit lost.</p> <pre><code>#!/usr/bin/...
0
2016-06-04T14:01:32Z
37,631,385
<p>I would use timers with a callback, to avoid the use of threads or sleep in Qt. You could try something like this:</p> <pre><code>def initUI(self): ... self.btn = QtGui.QPushButton('Play', self) self.btn.move(20, 50) self.btn.clicked.connect(self.play) self.btn = QtGui.QPushButton('Stop', self)...
0
2016-06-04T14:31:02Z
[ "python", "multithreading", "pyqt", "pyqt4" ]
Easiest way to interrupt pyqt4?
37,631,123
<p>I'm building a simple speed reader in Python as an exercise. Basically a <a href="http://spritzinc.com/" rel="nofollow">Spritz</a> clone. </p> <p>What's the correct way to stop the printword() function once I run it? Should I put it in a thread? With threading or QThread? I'm a bit lost.</p> <pre><code>#!/usr/bin/...
0
2016-06-04T14:01:32Z
37,632,668
<p>Here is my solution of using <code>QThread</code>, please check. And I also used the <code>slot</code> and <code>signal</code> mechanism to transfer the data between the main thread and the worker thread. </p> <p>Well, initially I thought it would be easy to change it as this way. But it turned out quite some chang...
0
2016-06-04T16:43:09Z
[ "python", "multithreading", "pyqt", "pyqt4" ]
calculating the area of an irregular shape from coordinates in a csv file using python
37,631,259
<p>i am using Python to import a csv file with coordinates in it, passing it to a list and using the contained data to calculate the area of each irregular figure. The data within the csv file looks like this. </p> <pre><code>ID Name DE1 DN1 DE2 DN2 DE3 DN3 88637 Zack Fay -0.026841782 -0.071375637 0.160...
-1
2016-06-04T14:15:23Z
37,631,637
<p>Your problem appears to be in the <code>calculate</code> function.</p> <p>You are trying to access various indexes of <code>row</code> without first confirming they exist. One naive approach might be to consider the values to be zero if they are not present, except that:</p> <pre><code>+ ((dn9 * de1) - (de9 * dn1)...
0
2016-06-04T14:57:56Z
[ "python", "csv", "area" ]
How to GET data in Flask from AJAX post
37,631,388
<p>I want to retrieve the data from the variable 'clicked' so I can use it in SQL queries in Flask.</p> <p>JQuery</p> <pre><code>$(document).ready(function(){ var clicked; $(".favorite").click(function(){ clicked = $(this).attr("name"); $.ajax({ type : 'POST', url : "{{url_for('test')}}", ...
1
2016-06-04T14:31:14Z
37,631,988
<p>you can compose your payload in your ajax request as</p> <pre><code>$(document).ready(function(){ var clicked; $(".favorite").click(function(){ clicked = $(this).attr("name"); $.ajax({ type : 'POST', url : "{{url_for('test')}}", contentType: 'application/json;charset=UTF-8', data : {'data':clicked} }); });...
1
2016-06-04T15:33:28Z
[ "jquery", "python", "ajax", "flask" ]
python selenium driver.quit() inside except block
37,631,436
<p>My application is such that if it throws an exception I want the driver to close, I tried the following code but it is throwing exception .</p> <p>My code: where url is the url I want to open</p> <pre><code>driver=webdriver.Firefox() try: driver.get(url) except: driver.quit() </code></pre> <p>It is closi...
1
2016-06-04T14:37:39Z
37,631,513
<p>You could try using <code>driver.close()</code> instead. In the example below there's no stacktrace displayed, the exception is caught and the driver/firefox window closes gracefully.</p> <pre><code>driver = webdriver.Firefox() try: raise WebDriverException except WebDriverException: driver.close() </code><...
1
2016-06-04T14:46:22Z
[ "python", "selenium-webdriver" ]
Grab 2 keys with highest values for nested dictionary
37,631,458
<p>I have a dictionary which looks like this:</p> <pre><code>bigdict = { 'a': {'foo':2, 'bar':3, 'baz':7, 'qux':1}, 'b': {'foo':6, 'bar':4, 'baz':3, 'qux':0}, 'c': {'foo':4, 'bar':5, 'baz':1, 'qux':6} } </code></pre> <p>And for each dictionary, I want to be able to grab the 2 keys with the highest values and put th...
2
2016-06-04T14:39:58Z
37,631,623
<p>it can be done pretty easily using <a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="nofollow">pandas</a> module:</p> <pre><code>In [97]: bigdict = { ....: 'a': {'foo':2, 'bar':3, 'baz':7, 'qux':1}, ....: 'b': {'foo':6, 'bar':4, 'baz':3, 'qux':0}, ....: 'c': {'foo':4, 'bar':5, 'baz':1, ...
0
2016-06-04T14:56:23Z
[ "python", "dictionary" ]
Grab 2 keys with highest values for nested dictionary
37,631,458
<p>I have a dictionary which looks like this:</p> <pre><code>bigdict = { 'a': {'foo':2, 'bar':3, 'baz':7, 'qux':1}, 'b': {'foo':6, 'bar':4, 'baz':3, 'qux':0}, 'c': {'foo':4, 'bar':5, 'baz':1, 'qux':6} } </code></pre> <p>And for each dictionary, I want to be able to grab the 2 keys with the highest values and put th...
2
2016-06-04T14:39:58Z
37,631,646
<p>This can be solved easily using a <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">dictionary comprehension.</a> See this post for more explanation about a <a href="http://stackoverflow.com/questions/14507591/python-dictionary-comprehension">Python Dictionary Comprehension</a> </p> <pre><code>&gt...
1
2016-06-04T14:58:57Z
[ "python", "dictionary" ]
Variables and memory allocated for them?
37,631,554
<p>I have a question about Python deal with memory to copy variables.</p> <p>For example, I have a list(or string, tuple, dictionary, set) variable</p> <pre><code>A = [1,2,3] </code></pre> <p>then I assign the value of A to another variable B</p> <pre><code>B = A </code></pre> <p>then if I do "some changes" to A,...
2
2016-06-04T14:50:25Z
37,631,728
<p>Lists are objects and therefore 'call-by-reference'. When you write <code>B=A</code> you'll get a reference (c-pointer) on the object behind A (not A itself!), so basically, as your code is telling you already, <code>A is B == True</code>. The reference is not on A but on the object that A points to, so if you chang...
0
2016-06-04T15:09:02Z
[ "python", "memory" ]
Variables and memory allocated for them?
37,631,554
<p>I have a question about Python deal with memory to copy variables.</p> <p>For example, I have a list(or string, tuple, dictionary, set) variable</p> <pre><code>A = [1,2,3] </code></pre> <p>then I assign the value of A to another variable B</p> <pre><code>B = A </code></pre> <p>then if I do "some changes" to A,...
2
2016-06-04T14:50:25Z
37,631,730
<p>Your first understanding was correct. When you do</p> <pre><code>B = A </code></pre> <p>you now have two names pointing to the same object in memory.</p> <p>Your misunderstanding is what happens when you do </p> <pre><code>A = [5, 6] </code></pre> <p>This doesn't copy <code>[5, 6]</code> to that location in mem...
3
2016-06-04T15:09:11Z
[ "python", "memory" ]
Variables and memory allocated for them?
37,631,554
<p>I have a question about Python deal with memory to copy variables.</p> <p>For example, I have a list(or string, tuple, dictionary, set) variable</p> <pre><code>A = [1,2,3] </code></pre> <p>then I assign the value of A to another variable B</p> <pre><code>B = A </code></pre> <p>then if I do "some changes" to A,...
2
2016-06-04T14:50:25Z
37,631,781
<p>you assign new obj to a at second time</p> <pre><code>&gt;&gt;&gt; &gt;&gt;&gt; a= [1,2,3] &gt;&gt;&gt; id(a) 4353139632 &gt;&gt;&gt; b = a &gt;&gt;&gt; id(b) 4353139632 &gt;&gt;&gt; a= [4,5] &gt;&gt;&gt; id(a) 4353139776 &gt;&gt;&gt; id(b) 4353139632 </code></pre>
0
2016-06-04T15:13:19Z
[ "python", "memory" ]
Variables and memory allocated for them?
37,631,554
<p>I have a question about Python deal with memory to copy variables.</p> <p>For example, I have a list(or string, tuple, dictionary, set) variable</p> <pre><code>A = [1,2,3] </code></pre> <p>then I assign the value of A to another variable B</p> <pre><code>B = A </code></pre> <p>then if I do "some changes" to A,...
2
2016-06-04T14:50:25Z
37,632,156
<p>Lists, tuples, and objects are <strong><em>referenced</em></strong> in Python. You can see these variable names as pointers in C. So, A is a <em>pointer</em> to some location, storing an array, when you did <code>B = A</code> you copied the <strong><em>reference</em></strong> to that location ( the address ) to B.</...
0
2016-06-04T15:48:53Z
[ "python", "memory" ]
How to resize image?
37,631,611
<p>I'm trying to resize an image to 500x500px but got this error: </p> <pre><code>File "C:\Python27\lib\site-packages\PIL\Image.py", line 1681, in save save_handler = SAVE[format.upper()] KeyError: 'JPG' </code></pre> <p>This is the code: </p> <pre><code>from PIL import Image img = Image.open('car.jpg') new_img...
1
2016-06-04T14:55:58Z
37,631,799
<p>You need to set the format parameter in your call to the save function to 'JPEG':</p> <pre><code>from PIL import Image img = Image.open('car.jpg') new_img = img.resize((500,500)) new_img.save("car_resized.jpg", "JPEG", optimize=True) </code></pre>
1
2016-06-04T15:15:30Z
[ "python", "image-resizing" ]
Visualize a co-occurrence matrix in pandas/numpy
37,631,649
<p>I have calculated an array with how many % of the total number of permutations contain all different pairs combinations. Now I want to visualise this as for example a heat map. I have the following code for calculation:</p> <pre><code>#occurrences matrix a = np.array(np.array_split(np.random.binomial(1,.5,30),10), ...
2
2016-06-04T14:59:19Z
37,631,783
<p>what about this?</p> <pre><code>plt.imshow(acov,interpolation='nearest', cmap='Reds') plt.colorbar() plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/koi2k.png" rel="nofollow"><img src="http://i.stack.imgur.com/koi2k.png" alt="enter image description here"></a></p> <p>using <a href="https://stanford....
0
2016-06-04T15:13:42Z
[ "python", "arrays", "numpy", "pandas", "matplotlib" ]
make file by socket.makefile on a selected directory, not current script directory
37,631,703
<p>The part in my code is :</p> <pre><code> def upload_action(client): """ uploads the requested file by socket to server receives: socket - client socket returns: nothing """ file, filename = get_file_and_filename(client.makefile('r')) write_to_file(file, filename) </code></pr...
1
2016-06-04T15:05:45Z
37,632,037
<p>By default the working directory is from where the script was run.<br> All relative paths are relative to the working directory.<br> A file name is just a relative path pointing to files in that working directory.</p> <p>If you need to write a file to an arbitrary directory, you need to provide an absolute path to ...
0
2016-06-04T15:38:27Z
[ "python", "file", "sockets", "makefile", "directory" ]
Python pip install errors (feather-format)
37,631,810
<p>I've been trying to install the Feather file format for Python (<a href="https://pypi.python.org/pypi/feather-format" rel="nofollow">https://pypi.python.org/pypi/feather-format</a>) for the last few days with no luck. I'm using Anaconda2 on Windows 10. I get the following errors when I try to pip install feather-for...
1
2016-06-04T15:16:30Z
39,088,898
<p>I have faced the same problem when I was installing Feather Format for Python. You can try this code on your Command Line</p> <pre><code>conda install feather-format -c conda-forge </code></pre> <p>The reason of the error might be the wrong compiler for C++, you can use conda-forge as a compiler. This has already...
2
2016-08-22T21:19:27Z
[ "python", "c++" ]
Python pygame error using font: no such file or directory
37,631,974
<p>i have a python pygame program that simulates a racecar, driving and dodging blocks, this program worked 100% until i tried it today, now it gives me a error, the error is:</p> <pre><code> Warning (from warnings module): File "/home/vandeventer/Documents/Pieter/pygame.resies.py", line 50 largeText ...
0
2016-06-04T15:32:05Z
37,632,721
<p>Try to change <code>largeText = pygame.font.Font(None,75)</code> to <code>largeText = pygame.font.SysFont(None,75)</code></p>
1
2016-06-04T16:48:54Z
[ "python", "fonts", "pygame" ]
Python pygame error using font: no such file or directory
37,631,974
<p>i have a python pygame program that simulates a racecar, driving and dodging blocks, this program worked 100% until i tried it today, now it gives me a error, the error is:</p> <pre><code> Warning (from warnings module): File "/home/vandeventer/Documents/Pieter/pygame.resies.py", line 50 largeText ...
0
2016-06-04T15:32:05Z
37,752,439
<p>it was actuely very weird, today i decided to try and figure it out, and it worked perfectly fine, anyway, its fixed now</p>
0
2016-06-10T15:52:33Z
[ "python", "fonts", "pygame" ]
Calling Function with Decorators
37,632,019
<p>I started learning decorators in python. I have below query ?</p> <pre><code>def add(a): print 'This is an addition function' return a @add def dollar(): print 'Am i getting the concept ?' dollar() </code></pre> <p>This call giving me the output as </p> <pre><code>This is an addition function Am i gettin...
0
2016-06-04T15:36:15Z
37,632,068
<p>A decorator must return a callable/function which it doesn't in your second version.</p> <pre><code>@add def dollar(): print 'Am i getting the concept ?' </code></pre> <p>is short for:</p> <pre><code>def dollar(): print 'Am i getting the concept ?' dollar = add(dollar) </code></pre> <p>Hence:</p> <pre>...
3
2016-06-04T15:40:54Z
[ "python", "python-2.7", "python-3.x" ]
Calling Function with Decorators
37,632,019
<p>I started learning decorators in python. I have below query ?</p> <pre><code>def add(a): print 'This is an addition function' return a @add def dollar(): print 'Am i getting the concept ?' dollar() </code></pre> <p>This call giving me the output as </p> <pre><code>This is an addition function Am i gettin...
0
2016-06-04T15:36:15Z
37,632,290
<p>Decorator is a method that operates on other methods before execution of that method. So it must return and function object at the end of the decorator function. Removing the return statement is returning None, and preventing the execution of dollar method</p>
0
2016-06-04T16:00:48Z
[ "python", "python-2.7", "python-3.x" ]
What should be used as User id?
37,632,055
<p>Flask-login required me to provide the following callback:</p> <pre><code>@login_manager.user_loader def load_user(user_id): return User.get(user_id) </code></pre> <p>But what should be used as id? Can I just use username? If yes, what should I return in case of user_loader("admin").is_authenticated()? How do ...
0
2016-06-04T15:40:02Z
37,632,139
<p>using</p> <pre><code>class User: def get_id(self): return id(self) </code></pre> <p>should guarantee that two <code>User</code> objects only return the same id when they are the same Object.</p>
-1
2016-06-04T15:47:22Z
[ "python", "flask", "flask-login" ]
What should be used as User id?
37,632,055
<p>Flask-login required me to provide the following callback:</p> <pre><code>@login_manager.user_loader def load_user(user_id): return User.get(user_id) </code></pre> <p>But what should be used as id? Can I just use username? If yes, what should I return in case of user_loader("admin").is_authenticated()? How do ...
0
2016-06-04T15:40:02Z
37,633,242
<p>user_id is from User model, add the following code under User model:</p> <pre><code>class User(db.Model): ''' def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return unicode(self.i...
0
2016-06-04T17:44:24Z
[ "python", "flask", "flask-login" ]
Python 2d grid : Assigning values to coordinates in the grid
37,632,069
<p>I'm just a beginner Python user so bear with me,</p> <p>I've created a 2d XY grid using np.meshgrid, and would like to know how to assign values to some of the points in the grid. The application is to set a mass to certain points in the grid to model point masses. My code as of now is as follows:</p> <pre><code>i...
0
2016-06-04T15:40:56Z
37,634,153
<p>Since you're a beginner Python user, I highly recommend you take the time to check out the documentation for the packages you are using. Does this <a href="http://matplotlib.org/examples/mplot3d/surface3d_demo.html" rel="nofollow">example from matplotlib's documentation</a> answer your question?</p> <pre><code>from...
1
2016-06-04T19:22:57Z
[ "python", "numpy" ]
optparse handling ArugmentException
37,632,081
<p>So what i am trying to do is simple is launch a simple help dialog when i do -h.. That works fine, the issue comes when i try to do anything besides -h. what is the best practice of taking care of this. There will be many more paramters being passed just starting out with -h for now. here is my <strong>main</strong>...
1
2016-06-04T15:41:46Z
37,632,118
<p>OptionParser is now depreciated, you should consider using the ArgumentParser:</p> <pre><code>from argparse import ArgumentParser parser = ArgumentParser(description='Your argument parser') parser.add_argument('--a', dest='a', help='a option') parser.add_argument('--b', dest='b', help='b option') parsed_args = par...
1
2016-06-04T15:45:21Z
[ "python", "command-line", "optparse" ]
optparse handling ArugmentException
37,632,081
<p>So what i am trying to do is simple is launch a simple help dialog when i do -h.. That works fine, the issue comes when i try to do anything besides -h. what is the best practice of taking care of this. There will be many more paramters being passed just starting out with -h for now. here is my <strong>main</strong>...
1
2016-06-04T15:41:46Z
37,632,650
<p>-h is built into optparse also so when i was doing calling options.hlpBool that is unnecessary </p>
0
2016-06-04T16:40:50Z
[ "python", "command-line", "optparse" ]
From a defaultdict, find the pair of keys with highest values
37,632,099
<p>Given a <code>defaultdict(dict)</code> with both the keys as strings and their value is float, then how do I find the k keys based on descending order of the value from the entire defaultdict.</p> <p>I can write 2 loops and trivially store a list of 100 pairs, and replace the list with a new entry if something with...
2
2016-06-04T15:43:51Z
37,632,334
<p>Whenever you're extracting largest and smallests values, the <a href="https://docs.python.org/2.7/library/heapq.html#heapq.nlargest" rel="nofollow">heapq.nlargest</a> and <a href="https://docs.python.org/2.7/library/heapq.html#heapq.nsmallest" rel="nofollow">heapq.nsmallest</a> functions are your new best friend:</p...
2
2016-06-04T16:06:03Z
[ "python", "collections", "defaultdict" ]
Python error when trying to create an AWS stack using a template
37,632,202
<p>I am a python newbie trying to execute an aws cloudformation script via python 2.7. The script works flawlessly from the aws console and from the command line. However, when I try to run from within python I get error "Template format error: JSON not well-formed. (line 1, column 5)"</p> <pre><code>def create_sta...
1
2016-06-04T15:53:17Z
37,633,825
<p><code>template_body</code> expects a string. Try <code>template_url</code> instead or use some other code to load the file on the local disk into a string</p> <p>See <a href="http://boto3.readthedocs.io/en/latest/reference/services/cloudformation.html" rel="nofollow">http://boto3.readthedocs.io/en/latest/reference...
1
2016-06-04T18:50:19Z
[ "python", "amazon-web-services", "amazon-cloudformation" ]
Fast Numpy calculation of a slight variation of the repeat and choose functions
37,632,203
<p>I would like to use numpy to solve a problem that is very similar, but not quite identical, to the problem solved by the numpy.repeat function. I do not see how to solve this problem using any of the numpy functions I am familiar with, so I'm looking for help to see whether this can be done with numpy. My arrays are...
2
2016-06-04T15:53:28Z
37,633,474
<p>Here's one way.</p> <p>First, your example code:</p> <pre><code>In [102]: objID = np.array([0, 0, 5, 5, 5, 7, 8, 8]) In [103]: unique_objIDs, idx_unique_objIDs = np.unique(objID, return_index=True) </code></pre> <p><em>[[Note: <code>unique()</code> sorts its argument. You know your input is already sorted, so a...
4
2016-06-04T18:07:57Z
[ "python", "arrays", "performance", "numpy", "scientific-computing" ]
Fast Numpy calculation of a slight variation of the repeat and choose functions
37,632,203
<p>I would like to use numpy to solve a problem that is very similar, but not quite identical, to the problem solved by the numpy.repeat function. I do not see how to solve this problem using any of the numpy functions I am familiar with, so I'm looking for help to see whether this can be done with numpy. My arrays are...
2
2016-06-04T15:53:28Z
37,633,981
<p>Another suggestion, with <code>return_counts</code> instead of <code>return_index</code>:</p> <pre><code>unique_objIDs, objID_counts = np.unique(objID, return_counts=True) num_unique_objIDs = len(unique_objIDs) yesno = np.tile([True, False], num_unique_objIDs) amounts = np.c_[occupations, objID_counts-occupations]...
2
2016-06-04T19:05:55Z
[ "python", "arrays", "performance", "numpy", "scientific-computing" ]
How to makedirs from a list and include a list of subdirectories in python?
37,632,207
<p>Made directories from a list using this: </p> <pre><code>import os cwd = os.getcwd() folders = ['file1','file2','file3'] for folder in folders: os.mkdir(os.path.join(cwd,folder)) </code></pre> <p>Would also like to add three subdirectories within each of those files, e.g ['sub1','sub2','sub3']</p> <p>Tried s...
1
2016-06-04T15:53:51Z
37,632,254
<pre><code>import os cwd = os.getcwd() folders = ['file1','file2','file3'] subfolders = ['sub1','sub2','sub3'] for folder in folders: os.mkdir(os.path.join(cwd, folder)) # Create sub-folders. for sub in subfolders: os.mkdir(os.path.join(cwd, folder, sub)) </code></pre>
2
2016-06-04T15:57:35Z
[ "python" ]
How to makedirs from a list and include a list of subdirectories in python?
37,632,207
<p>Made directories from a list using this: </p> <pre><code>import os cwd = os.getcwd() folders = ['file1','file2','file3'] for folder in folders: os.mkdir(os.path.join(cwd,folder)) </code></pre> <p>Would also like to add three subdirectories within each of those files, e.g ['sub1','sub2','sub3']</p> <p>Tried s...
1
2016-06-04T15:53:51Z
37,632,481
<p>There is no need to create parent directory explicitly, for <code>makedirs</code> automatically create parent folder if not exists. For your solution, A workable concise code snippet as follows: </p> <pre><code>import os cwd = os.getcwd(); folders = ['file1','file2','file3'] subfolders = ['sub1','sub2','sub3'] pa...
0
2016-06-04T16:23:21Z
[ "python" ]
python datetime formatting to 1/10 second
37,632,265
<p>I'm trying to produce a date time string down to .1 second accuracy, with the form:</p> <pre><code> 201606041552015 </code></pre> <p>I have the following:</p> <pre><code> from datetime import datetime d = datetime.utcnow() format1 = "%Y%m%d%H%M%S%f" print (d.strftime(format1)) </code></pre> <p>Thi...
0
2016-06-04T15:58:28Z
37,632,309
<p>Just remove the last 5 digits from your current formatting. I'd also add conventional placeholders, like so. </p> <pre><code>&gt;&gt;&gt; d = datetime.utcnow() &gt;&gt;&gt; print (d.strftime('%Y-%m-%d %H:%M:%S.%f')[:-5]) 2016-06-04 16:00:53.9 </code></pre>
1
2016-06-04T16:02:15Z
[ "python", "datetime" ]
python datetime formatting to 1/10 second
37,632,265
<p>I'm trying to produce a date time string down to .1 second accuracy, with the form:</p> <pre><code> 201606041552015 </code></pre> <p>I have the following:</p> <pre><code> from datetime import datetime d = datetime.utcnow() format1 = "%Y%m%d%H%M%S%f" print (d.strftime(format1)) </code></pre> <p>Thi...
0
2016-06-04T15:58:28Z
37,632,318
<p>To get a 1/10 of a second accuracy you need to remove the last 5 digits</p> <pre><code>d.strftime(format1)[:-5] </code></pre>
1
2016-06-04T16:04:00Z
[ "python", "datetime" ]
python datetime formatting to 1/10 second
37,632,265
<p>I'm trying to produce a date time string down to .1 second accuracy, with the form:</p> <pre><code> 201606041552015 </code></pre> <p>I have the following:</p> <pre><code> from datetime import datetime d = datetime.utcnow() format1 = "%Y%m%d%H%M%S%f" print (d.strftime(format1)) </code></pre> <p>Thi...
0
2016-06-04T15:58:28Z
37,632,634
<p>Suppose the date is <code>2016-06-04 23:59:59.999999</code>. If you would like the date to be rounded to <code>2016-06-05 00:00:00.0</code> instead of truncated to <code>2016-06-04 23:59:59.9</code>, then you could use:</p> <pre><code>import datetime as DT now = DT.datetime(2016,6,4,23,59,59,999999) def myformat(d...
2
2016-06-04T16:39:27Z
[ "python", "datetime" ]
openpyxl: assign value or apply format to a range of Excel cells without iteration
37,632,327
<p>I would like to apply a specific format or assign a value to a range of Excel cells without iterating over each cell. I am currently using this script:</p> <pre><code>from openpyxl import Workbook from openpyxl.styles import Font wb = Workbook() ws = wb.active ## With iterations # Apply style for i, rowOfCellObje...
1
2016-06-04T16:05:10Z
37,632,553
<p>I'm not sure there is a module that offers such capability, because it might be confusing for a range of cells to take up cell attributes directly. You can do something similar to what you have, but much more readable with:</p> <pre><code>for row in ws.iter_rows('A1':'C4'): for cell in row: cell.value =...
0
2016-06-04T16:30:06Z
[ "python", "openpyxl" ]
openpyxl: assign value or apply format to a range of Excel cells without iteration
37,632,327
<p>I would like to apply a specific format or assign a value to a range of Excel cells without iterating over each cell. I am currently using this script:</p> <pre><code>from openpyxl import Workbook from openpyxl.styles import Font wb = Workbook() ws = wb.active ## With iterations # Apply style for i, rowOfCellObje...
1
2016-06-04T16:05:10Z
37,645,437
<p>In Excel styles <strong>must</strong> be applied to individual cells because this is how the file format works. Because of the way it works, openpyxl does not provide the desired functionality, but it is possible with <a href="https://xlsxwriter.readthedocs.io/" rel="nofollow">xlsxwriter</a>.</p>
0
2016-06-05T18:37:33Z
[ "python", "openpyxl" ]
Tkinter objects not working on linux
37,632,362
<p>So, I've recently switched from windows to Linux Ubuntu. My norm is using Tkinter for GUI applications. But from the switch i also realized the Tkinter objects aren't recognized.</p> <p>I.E</p> <pre><code>#!/usr/bin/env python import Tkinter Window = Tkinter.Tk() Welcome = Label(Window,"Welcome to Dragive") Welcom...
-5
2016-06-04T16:09:34Z
37,635,353
<p>The errors have nothing to do with linux vs windows. The same code would give you the same errors on either platform.</p> <p>If you import Tkinter with <code>import Tkinter</code>, then you must prefix all tkinter objects with <code>Tkinter.</code>:</p> <pre><code>Welcome = Tkinter.Label(...) </code></pre> <p>Thi...
0
2016-06-04T21:49:41Z
[ "python", "linux", "tkinter" ]
how to close tensorboard server with jupyter notebook
37,632,393
<p>what is the proper way to close tensorboard with jupyter notebook? </p> <p>I'm coding tensorflow on my jupyter notebook. To launch, I'm doing: 1. </p> <ol> <li><code>!tensorboard --logdir = logs/</code></li>...
0
2016-06-04T16:13:24Z
37,682,991
<p>The jupyter stuff seems fine. In general, if you don't close TensorBoard properly, you'll find out as soon as you try to turn on TensorBoard again and it fails because port 6006 is taken. If that isn't happening, then your method is fine.</p> <p>As regards the logdir, passing in the top level logdir is generally be...
0
2016-06-07T15:04:45Z
[ "python", "tensorflow", "jupyter-notebook", "tensorboard" ]
Huge cost of Memory in Python
37,632,526
<p>I am writing a piece of code that use Objects in Python. I have 1.1GB of files which needs to be parsed and transformed to Objects.</p> <p>However, <strong>with 1.1GB of files</strong>, it consumes <strong>more than 7GB of memory</strong> (and I stopped it, because it can go further...), which is quite big. I used ...
2
2016-06-04T16:28:14Z
37,632,773
<p>I'm not surprised the least.</p> <p>Reading in a CSV generates a list of rows, each of which points to a list of elements.</p> <p>Now, <em>each</em> of those is a <code>PyObject</code>, meaning that it has a typeref, which uses <code>size_t</code>, usually, I think, and the list containing it has to contain its id...
4
2016-06-04T16:54:10Z
[ "python", "memory-management", "out-of-memory" ]
Found array with 0 sample(s) (shape=(0, 40)) while a minimum of 1 is required
37,632,550
<p>I'm testing a simple prediction program with Python 2.7, sklearn 0.17.1, numpy 1.11.0. I got matrix with propabilities from LDA model, and now I want create RandomForestClassifier to predict results by propabilities. My code is:</p> <pre><code>maxlen = 40 props = [] for doc in corpus: topics = model.get_docume...
-1
2016-06-04T16:29:55Z
37,639,285
<p>This is the original code from the scikit-learn repo (<a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py#L409" rel="nofollow">validation.py#L409</a>):</p> <pre class="lang-py prettyprint-override"><code>if ensure_min_samples &gt; 0: n_samples = _num_samples(array) if...
0
2016-06-05T06:59:19Z
[ "python", "numpy", "scikit-learn" ]
controlling VTK through Matlab
37,632,614
<p>I have a Matlab function that takes a 3D binary object as input, saves it as temporary file, then loads a python script through cmd (I made this before Matlab's python integration). The python script loads and reorganizes the 3D data and displays them through VTK. </p> <p>The python script also creates some VTK con...
0
2016-06-04T16:36:58Z
37,661,211
<p>I kind of got it to work. Here's what I did:</p> <ol> <li><p>matlab session running the GUI converts to shared session through <code>matlab.engine.shareEngine('shared_matlab_session')</code> and keeps track of the matlab GUI slider position in <code>matlab_slider_pos</code> variable</p></li> <li><p>the python scrip...
0
2016-06-06T15:26:21Z
[ "python", "matlab", "vtk" ]
Normalize the elements of columns in an array to 1 or -1 depending on their sign
37,632,654
<p>I want to normalize the elements of columns in array ‘x’, which contains both positive and negative numbers, to -1, or 1.</p> <p>Negative elements of x should be normalized to x.min of each column where x.min becomes - 1, and positive elements of x should be normalized to x.max of each column where x.max become...
5
2016-06-04T16:41:07Z
37,632,737
<p>You can check the condition with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html">np.where</a> and apply two different normalizations based on the condition:</p> <pre><code>np.where(x&lt;0, -x / x.min(axis=0), x / x.max(axis=0)) Out[6]: array([[ 0.5 , 0.42857143, 0.5 ...
6
2016-06-04T16:51:04Z
[ "python", "arrays", "numpy", "normalize" ]
Python connection to Firebird gdb file
37,632,656
<p>I want to access a gdb file with python. I'm new to firebird and interbase.</p> <p>I can access my file with this command: (Debian 8.4) isql-fb mydb.gdb</p> <p>How can I connect to same file with Python? I tried fdb and kinterbasdb and always get an error message:</p> <p>I have tried these lines:</p> <pre><code>...
0
2016-06-04T16:41:32Z
37,635,468
<p>Thank you all for your time. I solved it changing sysdba password with gsec. The password was ok in config file but not in security database.</p>
0
2016-06-04T22:04:18Z
[ "python", "firebird", "interbase" ]
NameError when running pyglet
37,632,704
<p>I'm trying to do my uni project and I'm using pyglet for the task . This is part of the code that makes me a problem.</p> <pre><code>from pyglet.gl import * from pyglet.window import key from pyglet.window import mouse window=pyglet.window.Window(resizable=True) @window.event def on_draw(): glutInitDisplayM...
0
2016-06-04T16:45:57Z
37,633,144
<p>So, <code>glutInitDisplayMode</code> is a GL function but as far as I know, it's not made avilable by Pyglet because it's not really needed.</p> <p>Now, these are some what speculations and correct me if I'm wrong.<br> But calling the following will set up the context for you:</p> <pre><code>pyglet.window.Window(....
0
2016-06-04T17:33:22Z
[ "python", "python-3.x", "nameerror", "pyglet", "pyopengl" ]
Python function returns empty list
37,632,730
<p>I've been working on this task for a while, the task is to write a function that translated a text in english to swedish. I've created a dicitonary with key &amp; value, where key is the english word and value is the swedish word.</p> <p><strong>HOW I'VE BEEN THINKING:</strong> I was thinking of that there should b...
2
2016-06-04T16:50:09Z
37,632,785
<p>I think this is what you were looking for:</p> <pre><code>trs = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"Ã¥r"} translated = [] for i in a.split(" "): # loop over sentence and try to translate every word if i in trs: # the word to be translated is a key in your dict...
2
2016-06-04T16:55:39Z
[ "python" ]
Python function returns empty list
37,632,730
<p>I've been working on this task for a while, the task is to write a function that translated a text in english to swedish. I've created a dicitonary with key &amp; value, where key is the english word and value is the swedish word.</p> <p><strong>HOW I'VE BEEN THINKING:</strong> I was thinking of that there should b...
2
2016-06-04T16:50:09Z
37,632,851
<pre><code>def translate(a): trs = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"ar"} translated = [] for i in a.split(" "): for k, v in trs.iteritems(): if i == k: translated.append(trs[i]) return translated print translate("m...
1
2016-06-04T17:02:00Z
[ "python" ]
Python function returns empty list
37,632,730
<p>I've been working on this task for a while, the task is to write a function that translated a text in english to swedish. I've created a dicitonary with key &amp; value, where key is the english word and value is the swedish word.</p> <p><strong>HOW I'VE BEEN THINKING:</strong> I was thinking of that there should b...
2
2016-06-04T16:50:09Z
37,632,853
<p>There are multiple problems with your code.</p> <p>The first one is that you iterate over the key-value pairs in the dictionary, and later try to use the values as keys here: <code>if trs[k] == i:</code> and here <code>translated.append(trs[v])</code> These should be just <code>k</code> and <code>v</code> instead o...
3
2016-06-04T17:02:12Z
[ "python" ]
Python function returns empty list
37,632,730
<p>I've been working on this task for a while, the task is to write a function that translated a text in english to swedish. I've created a dicitonary with key &amp; value, where key is the english word and value is the swedish word.</p> <p><strong>HOW I'VE BEEN THINKING:</strong> I was thinking of that there should b...
2
2016-06-04T16:50:09Z
37,632,890
<ul> <li><p>You want to preserve word order in the translation, which means that iteration over the original words should drive the algorithm (not iteration over your translation dictionary).</p></li> <li><p>There is no need to iterate over the dictionary: the purpose of a key-value data structure is to allow you to re...
3
2016-06-04T17:06:23Z
[ "python" ]
Python function returns empty list
37,632,730
<p>I've been working on this task for a while, the task is to write a function that translated a text in english to swedish. I've created a dicitonary with key &amp; value, where key is the english word and value is the swedish word.</p> <p><strong>HOW I'VE BEEN THINKING:</strong> I was thinking of that there should b...
2
2016-06-04T16:50:09Z
37,633,060
<pre><code>def translate(a): trs = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"Ã¥r"} translated = [] for i in a.split(" "): for k, v in trs.iteritems(): if k == i: translated.append(trs[k]) return translated </code></pre> <p><cod...
0
2016-06-04T17:24:41Z
[ "python" ]
python pandas: get fiscal quarter from fiscal year and month (for UK)
37,632,766
<p>I have a dataframe with two useful columns 1) fiscal year, 2) date. I want to add a new column which shows the fiscal quarter.</p> <p>FYI - UK Financial year runs from 1 April to 31 March</p> <p>my data looks like:</p> <pre><code> fiscal year date FY15/16 2015-11-01 FY14/15 2014-10-01 FY...
1
2016-06-04T16:53:50Z
37,632,916
<pre><code>import pandas as pd df = pd.DataFrame({'date': ['2015-11-01', '2014-10-01', '2016-02-01'], 'fiscal year': ['FY15/16', 'FY14/15', 'FY15/16']}) df['Quarter'] = pd.PeriodIndex(df['date'], freq='Q-MAR').strftime('Q%q') print(df) </code></pre> <p>yields</p> <pre><code> date fiscal yea...
3
2016-06-04T17:09:06Z
[ "python", "date", "pandas", "fiscal" ]
Optimize python if statement
37,632,825
<p>What is a more pythonic way to write this statement?</p> <pre><code>if soup.find(title="Email"): profile['email'] = soup.find(title="Email").a.string </code></pre> <p>What I want to avoid is the repetition of <code>soup.find(title="Email")</code></p>
0
2016-06-04T16:59:10Z
37,632,876
<p>I do not know if this is more pythonic. I do this with most languages I use. On the top of my head, something like this should avoid the repetition.</p> <pre><code>soupByEmail = soup.find(title="Email") if soupByEmail: profile['email'] = soupByEmail.a.string </code></pre>
3
2016-06-04T17:04:48Z
[ "python", "python-3.x" ]
Optimize python if statement
37,632,825
<p>What is a more pythonic way to write this statement?</p> <pre><code>if soup.find(title="Email"): profile['email'] = soup.find(title="Email").a.string </code></pre> <p>What I want to avoid is the repetition of <code>soup.find(title="Email")</code></p>
0
2016-06-04T16:59:10Z
37,632,887
<p>It's not a matter of pythonic it's more about coding style. And as an elegant alternative you use <a href="https://docs.python.org/2/glossary.html#term-eafp" rel="nofollow">EAFP principle</a> (Easier to ask for forgiveness than permission) and wrap your snippet with a <code>try-except</code> expression:</p> <pre><c...
0
2016-06-04T17:05:57Z
[ "python", "python-3.x" ]
QComboBox adjust drop down width
37,632,845
<p>Not sure why I cant get it to work, so maybe one of you will be able to see my mistake... :</p> <pre><code> combo_type = QComboBox() combo_type.setMaximumWidth(50) combo_type.addItems(["TEsst1111","TEsst11111111111111","TEsst1111111111111111111111111"]) combo_type.setStyleSheet('''* QComboBox QAb...
0
2016-06-04T17:01:28Z
37,633,297
<p>Sorted... it was naming error. Correct answer posted below.</p> <pre><code>combo_type.setStyleSheet('''* QComboBox QAbstractItemView { min-width: 150px; } ''') </code></pre>
2
2016-06-04T17:50:16Z
[ "python", "pyqt", "pyqt4", "qcombobox" ]
QComboBox adjust drop down width
37,632,845
<p>Not sure why I cant get it to work, so maybe one of you will be able to see my mistake... :</p> <pre><code> combo_type = QComboBox() combo_type.setMaximumWidth(50) combo_type.addItems(["TEsst1111","TEsst11111111111111","TEsst1111111111111111111111111"]) combo_type.setStyleSheet('''* QComboBox QAb...
0
2016-06-04T17:01:28Z
37,633,917
<p>Using the <a href="http://doc.qt.io/qt-4.8/qlistview.html#gridSize-prop" rel="nofollow"><code>QListView</code></a>:</p> <pre><code>combo_type = QComboBox() combo_type.SizeAdjustPolicy(QComboBox.AdjustToContentsOnFirstShow) view = QListView() # creat a ListView view.setFixedWidth(200) # set the ListView with fixed...
1
2016-06-04T18:59:45Z
[ "python", "pyqt", "pyqt4", "qcombobox" ]
Dynamically assembling scrapy GET request string
37,632,965
<p>I've been working with firebug and I've got the following dictionaries to query an api.</p> <pre><code>url = "htp://my_url.aspx#top" querystring = {"dbkey":"x1","stype":"id","s":"27"} headers = { 'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", 'upgrade-insecure-requ...
1
2016-06-04T17:15:23Z
37,633,001
<p>Look at the signature of the <code>Request</code> initialization method:</p> <pre><code>class scrapy.http.Request(url[, callback, method='GET', headers, body, cookies, meta, encoding='utf-8', priority=0, dont_filter=False, errback]) </code></pre> <p><code>GET</code> string in your case is used as a positional valu...
1
2016-06-04T17:20:25Z
[ "python", "scrapy" ]
Implementing minimization method
37,633,007
<p>I have a function in 2 variables <code>x1,x2</code></p> <p><code>f = 3*x1^2 + 4*x2^2 + 5*x1 + 6*x2 + 10</code></p> <p>Consider <code>x</code> is a row vector such that <code>x = [x5,x6]</code>, where <code>x5,x6</code> are components of the vector. If the notation is confusing, let us consider <code>x = [x1,x1]</c...
1
2016-06-04T17:20:42Z
37,633,170
<p>you can use eval convert string to function </p> <pre><code>f = 'x+a*y' x = 4 y = 3 for a in xrange(3): print eval(f) output: 4 7 10 </code></pre>
-1
2016-06-04T17:36:13Z
[ "python", "c", "algorithm", "matlab", "optimization" ]
Implementing minimization method
37,633,007
<p>I have a function in 2 variables <code>x1,x2</code></p> <p><code>f = 3*x1^2 + 4*x2^2 + 5*x1 + 6*x2 + 10</code></p> <p>Consider <code>x</code> is a row vector such that <code>x = [x5,x6]</code>, where <code>x5,x6</code> are components of the vector. If the notation is confusing, let us consider <code>x = [x1,x1]</c...
1
2016-06-04T17:20:42Z
37,689,661
<p>I'm rephrasing your question in my own words, because the question in its current form is confusing:</p> <p><em>You have a function <code>f(x1,x2) = 3*x1^2 + 4*x2^2 + 5*x1 + 6*x2 + 10</code>. <code>x1</code> and <code>x2</code> are the components of a 2D vector obtained from summing <code>x</code> with the product ...
1
2016-06-07T21:25:39Z
[ "python", "c", "algorithm", "matlab", "optimization" ]
How to login to this website with Python
37,633,009
<p>I am trying to login to a website with requests library in Python. I tried different codes with no luck. This is my code:</p> <pre><code>url = 'https://www.damejidlo.cz/en/profile/prihlaseni' login_data = {'email': 'test', 'password': 'password', 'do': 'loginForm-submit'} session = reque...
1
2016-06-04T17:20:45Z
37,642,071
<p>It is very simple, you just need to add a user-agent:</p> <pre><code>In [7]: import requests In [8]: from bs4 import BeautifulSoup In [9]: login = "https://www.damejidlo.cz/en/profile/prihlaseni" In [10]: data = {"email": "xxxxxxxxx@gmail.com", ....: "password": "xxxxxxxx", ....: "do": "log...
0
2016-06-05T12:45:41Z
[ "python", "login", "python-requests" ]
AttributeError: 'list' object has no attribute 'items'
37,633,031
<p>I have looked around the site and I can't find out how to get an output I just keep on getting the same error:</p> <pre><code>AttributeError: 'list' object has no attribute 'items' </code></pre> <p>I can't figure out why I keep on getting this error any help will be a appreciated!</p> <pre><code>import json from ...
-1
2016-06-04T17:22:09Z
37,633,151
<p>You only pass positional arguments to the <code>Request</code> constructor:</p> <pre><code>Request("https://api.samsara.com/v1/sensors/temperature?access_token=", 518, [2]) </code></pre> <p>Given the <code>init</code> signature of <code>Request</code> (<a href="https://docs.python.org/3/library/urllib.request.html...
0
2016-06-04T17:34:01Z
[ "python", "python-3.x", "urllib2" ]
Sockets: How would Peer to Peer chat work?
37,633,073
<p>I am trying to make a P2P chat without manually adding users IP Address.</p> <hr> <p>These scripts would send and receive UTF-8 message with UDP packets by manually specifying IP address.</p> <pre><code># Send # Let's say this code is executed from PC1. import socket PC2_IP = '192.160.4.169' # IP address is no...
0
2016-06-04T17:25:53Z
37,635,928
<p>In the 1:1 case the first program doesn't need to know the address of anyone else. It just starts and waits. The second program needs to know the address of the first. As soon as it sends a "hello" the first program now knows the address of the second via recvfrom.</p> <p>If you want <strong>no</strong> known addre...
0
2016-06-04T23:15:24Z
[ "python", "sockets", "network-programming" ]
How in pyqt change text in QPlainTextEdit() if slider's value is 1, and don't change if the value is 0?
37,633,165
<pre><code>message = QtGui.QPlainTextEdit() slider = QtGui.QSlider() def slider_func(): if slider.value() == 0: '''what to write here ?''' if slider.value() == 1: m = str(message.toPlainText()) translated = '' i = len(m) - 1 while i &gt;= 0: translated = trans...
-1
2016-06-04T17:34:52Z
37,633,400
<p>Here is an example of how to watch the value of the slider, and modify a <code>QPlainText</code> when the value is at certain values.</p> <pre><code>from PyQt4.QtGui import * from PyQt4.Qt import * import sys class Window(QWidget): def __init__(self, *args, **kwargs): super(Window, self).__init__(*arg...
0
2016-06-04T18:01:25Z
[ "python", "pyqt", "pyqt4" ]
Counting total number of element occurrences in different length vectors
37,633,306
<p>I have 3 very long (100K+ elements) vectors of different products names. Each vector has different length. What I want to do is to count in how many vectors each product is. So something like this:</p> <pre><code>v1 = ['product1','product2','product3'] v2 = ['product3','product1','product5','product7','product10'] ...
3
2016-06-04T17:51:43Z
37,633,385
<p>You can use <a href="https://docs.python.org/2/library/collections.html#collections.Counter"><code>Counter</code></a> and <a href="https://docs.python.org/2/library/itertools.html#itertools.chain"><code>chain</code></a> to do this in a few lines:</p> <pre><code>from collections import Counter from itertools import ...
6
2016-06-04T17:59:14Z
[ "python", "numpy", "pandas" ]
Counting total number of element occurrences in different length vectors
37,633,306
<p>I have 3 very long (100K+ elements) vectors of different products names. Each vector has different length. What I want to do is to count in how many vectors each product is. So something like this:</p> <pre><code>v1 = ['product1','product2','product3'] v2 = ['product3','product1','product5','product7','product10'] ...
3
2016-06-04T17:51:43Z
37,634,236
<p>Just use Python build-in function <code>count</code></p> <pre><code>(v1+v2+v3).count('product1') Out[4]: 3 </code></pre> <p>If you want to build a <code>dict</code>:</p> <pre><code>v=v1+v2+v3 dict((x,v.count(x)) for x in v) Out[17]: {'product1': 3, 'product10': 2, 'product2': 1, 'product3': 2, 'product5': 1,...
0
2016-06-04T19:32:56Z
[ "python", "numpy", "pandas" ]
Treat separate files as one file object in python
37,633,328
<p>I have a splitted file (lets say name.a0, name.a1, name.a2, ...)</p> <p>Is there a way to have one readable file-like object, that will be a concatenation of those, without using a temporary file and without loading them all to the memory?</p>
1
2016-06-04T17:53:40Z
37,633,433
<p>You can always create a proxy object that treats a series of files as one. You need to implement just enough of the <a href="https://docs.python.org/2/library/stdtypes.html#file-objects" rel="nofollow">file object interface</a> to satisfy your program's needs.</p> <p>For example, if all you do is iterate over the l...
0
2016-06-04T18:04:14Z
[ "python", "file", "concatenation" ]
Treat separate files as one file object in python
37,633,328
<p>I have a splitted file (lets say name.a0, name.a1, name.a2, ...)</p> <p>Is there a way to have one readable file-like object, that will be a concatenation of those, without using a temporary file and without loading them all to the memory?</p>
1
2016-06-04T17:53:40Z
37,633,491
<p>The <a href="https://docs.python.org/3/library/fileinput.html" rel="nofollow">fileinput</a> module in the python standard library is used for exactly this purpose.</p> <pre><code>import fileinput with fileinput.input(files=('name.a0', 'name.a1', 'name.a2')) as f: for line in f: process(line) </code></pr...
3
2016-06-04T18:10:10Z
[ "python", "file", "concatenation" ]
How does matrix decomposition help fill in a sparse utility/ratings matrix for new users?
37,633,390
<p>This is my first attempt at machine learning. I'm writing a very simple recommendation engine using the yelp dataset. It's written in python using pandas and numpy libraries for (data processing). I've already narrowed the data down first to restaurants(millions), then only restaurants in vegas(thousands), then only...
1
2016-06-04T18:00:06Z
38,597,560
<p>Reducing the amount of ratings is not a good solution to improve the accuracy of your recommendation (at least directly). Said that, sparsity is not a "big" problem. Indeed, factorization algorithms for recommendation are designed to deal with this kind of sparsities going up to: 99%, 98%, 95% level of sparsity.</p>...
1
2016-07-26T18:39:54Z
[ "python", "matrix", "scikit-learn", "recommendation-engine", "yelp" ]
Moving a circle in an elliptical pattern in tkinter
37,633,443
<p>Okay so I'd like to make a circle move in an elliptical pattern with a button in tkinter. I previously made it move back and forth 10px at a time but I have no idea how to make it go in an ellipse</p> <p>My back and forth code looks like this:</p> <pre><code>from Tkinter import * def ball(gd, hb): global x1, ...
-1
2016-06-04T18:05:03Z
37,636,119
<h1>Option 1</h1> <p>Okay so if you have meant that you just want to have an elliptical shape all the time you can use <code>x1,y1,x1+60,y1+30</code> instead of x1+30,y1+30.</p> <hr> <h1>Option 2</h1> <p>If you have meant to reshape the ball like the ball bounces you have to think about some factors.</p> <p><li> W...
0
2016-06-04T23:49:51Z
[ "python", "tkinter", "circle", "ellipse" ]
Django form selected option not recognized, failed if statement
37,633,453
<p>I have a select field that should keep it's selected value even after an error (e.g. a required filed is empty), but it cannot match the current value.</p> <pre><code>&lt;label for="{{ form.movie.id_for_label }}" class="col-sm-3 control-label"&gt;Movie:&lt;/label&gt; &lt;select id="{{ form.movie.id_for_label }}" na...
0
2016-06-04T18:05:55Z
37,641,190
<p>The problem is that <strong><em>form.fields.movie.choices</em></strong> returns the id as a number (int I guess), and the data in <strong><em>form.movie.value</em></strong> is a string, so to compare the two the <strong><em>x</em></strong> needs to be casted to string like so: <strong><em>x|stringformat:"s"</em></st...
0
2016-06-05T11:14:13Z
[ "python", "django", "django-forms", "django-templates" ]
Problems with installing Django with Python3
37,633,463
<p>I have installed <code>virtualenv</code></p> <pre><code>sudo pip3 install virtualenv </code></pre> <p>Then created a new <code>virtualenv</code></p> <p><code>virtualenv --python=/usr/bin/python3.5 venv</code></p> <p>It returned </p> <pre><code>Running virtualenv with interpreter /usr/bin/python3.5 Using base pr...
0
2016-06-04T18:07:12Z
37,633,509
<p>When using pip to install packages inside the virtual env, do not sudo. It makes packages be installed globally. Simply remove sudo from beginning of the command and it should install it in the venv you are currently working on.</p>
3
2016-06-04T18:12:38Z
[ "python", "django", "virtualenv", "python-3.5" ]
Problems with installing Django with Python3
37,633,463
<p>I have installed <code>virtualenv</code></p> <pre><code>sudo pip3 install virtualenv </code></pre> <p>Then created a new <code>virtualenv</code></p> <p><code>virtualenv --python=/usr/bin/python3.5 venv</code></p> <p>It returned </p> <pre><code>Running virtualenv with interpreter /usr/bin/python3.5 Using base pr...
0
2016-06-04T18:07:12Z
37,633,568
<p>You installed django into a system python 3.4.</p> <p>When you ran install command first time without sudo, did it complain about permissions? That should have been your clue that it's not the right <code>pip</code>. My guess is <code>pip3</code> only exists in system python and not your virtualenv. You can use <co...
0
2016-06-04T18:18:03Z
[ "python", "django", "virtualenv", "python-3.5" ]
Problems with installing Django with Python3
37,633,463
<p>I have installed <code>virtualenv</code></p> <pre><code>sudo pip3 install virtualenv </code></pre> <p>Then created a new <code>virtualenv</code></p> <p><code>virtualenv --python=/usr/bin/python3.5 venv</code></p> <p>It returned </p> <pre><code>Running virtualenv with interpreter /usr/bin/python3.5 Using base pr...
0
2016-06-04T18:07:12Z
37,633,838
<p>Don't do <code>sudo</code> and just use <code>pip</code> for installing all the packages. You have already installed python3 in your virtualenv, so there is no need of using pip3. Just do e.g. <code>pip install django</code>. or for other packages <code>pip install &lt;package_name&gt;</code></p>
0
2016-06-04T18:52:15Z
[ "python", "django", "virtualenv", "python-3.5" ]
usage of speech to text in kivy
37,633,476
<p>How to use pyttsx module in kivy app?</p> <pre><code>import kivy import sys kivy.require('1.9.0') from kivy.app import App from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button class My(App): def build(sel...
-1
2016-06-04T18:08:21Z
37,633,640
<p>Use the text to speech functions in <a href="https://github.com/kivy/plyer" rel="nofollow">plyer</a>. These will call the Android api for the task.</p>
1
2016-06-04T18:27:09Z
[ "android", "python", "kivy" ]
Converting an array containing the power set of a positive integer d to an array with standard elementary vectors in d-dimensional space
37,633,485
<p>Example of what I am trying to do: convert the power set of d = 2 using range(2): </p> <pre><code>[(), (0,), (1,), (0, 1)] </code></pre> <p>or using range(1, 3, 1):</p> <pre><code>[(), (1,), (2,), (1, 2)] </code></pre> <p>into the following array of arrays: </p> <pre><code>[[0, 0], [1, 0], [0, 1], [1, 1]] </cod...
0
2016-06-04T18:09:20Z
37,662,132
<p>Good friends of mine helped me in answering this question. </p> <p>Here is one alternative solution: </p> <pre><code>def pwr(d,r): out = [] for n in range(2**d): p = [r*int(i) for i in list(bin(n)[2:])] while len(p) &lt; d: p = [0] + p out.append(p) return out pr...
0
2016-06-06T16:10:26Z
[ "python", "python-3.x", "vector", "powerset", "basis" ]
How to read only some lines from a large file in python?
37,633,523
<p>I have a large data file with 7000 lines (not very large though!) which looks like this: </p> <pre><code> # data can be obtained from pastebin # filename = input.csv # lots of comments # wave flux err 0.807172 7.61973e-11 1.18177e-13 0.807...
0
2016-06-04T18:13:43Z
37,633,721
<p>You could call <code>np.genfromtxt(f, max_rows=chunksize)</code> in a loop to read the file in chunks. This way you can retain the convenience and speed of NumPy arrays while controlling the amount of memory required by adjusting <code>chunksize</code>.</p> <pre><code>import numpy as np import warnings # genfromtxt...
4
2016-06-04T18:36:24Z
[ "python", "csv", "numpy", "pandas", "memory" ]
How to read only some lines from a large file in python?
37,633,523
<p>I have a large data file with 7000 lines (not very large though!) which looks like this: </p> <pre><code> # data can be obtained from pastebin # filename = input.csv # lots of comments # wave flux err 0.807172 7.61973e-11 1.18177e-13 0.807...
0
2016-06-04T18:13:43Z
37,633,744
<p>Try This:</p> <pre><code>import pandas as pd df = pd.read_csv('large_data.csv', usecols=(0,1,2), skiprows=57) df.columns = [ 'wave', 'flux' , 'err'] df = df[(df['wave'] &gt;= 0.807375) &amp; (df['wave'] &lt;= 0.807982) ] print df wave flux err 1 0.807375 7.5866...
1
2016-06-04T18:38:34Z
[ "python", "csv", "numpy", "pandas", "memory" ]
How to read only some lines from a large file in python?
37,633,523
<p>I have a large data file with 7000 lines (not very large though!) which looks like this: </p> <pre><code> # data can be obtained from pastebin # filename = input.csv # lots of comments # wave flux err 0.807172 7.61973e-11 1.18177e-13 0.807...
0
2016-06-04T18:13:43Z
37,736,115
<p>Reading the anwers by @ubuntu and @Merlin, The following could also be a good solution. </p> <p><strong>Note:</strong> The answer given by @ubuntu works absolutely fine.</p> <p>The answer given by @Merlin doesnot work, is incomplete, but is a good template to start with. </p> <p><strong>Note:</strong> the input f...
0
2016-06-09T21:02:03Z
[ "python", "csv", "numpy", "pandas", "memory" ]
Python embeddable zip
37,633,550
<p>With the 3.5.0 release, <a href="https://www.python.org/" rel="nofollow">Python.org</a> has introduced a distribution billed as <em>embeddable zip file</em>.</p> <p>Unfortunately the zipped file comes without a help file (not even a readme). The <a href="https://www.python.org/downloads/windows" rel="nofollow">d...
6
2016-06-04T18:16:43Z
37,634,202
<p>As you can see from the <a href="https://docs.python.org/3.5/using/windows.html#embedded-distribution" rel="nofollow">documentation</a>, it is mainly meant for running Python based applications on ms-windows and for embedding Python in an application. As you can see, they left out <code>tkinter</code>. Maybe to keep...
3
2016-06-04T19:28:18Z
[ "python", "python-3.x", "pip" ]
How to interpolate between values on a dataframe using Python and/or R
37,633,711
<p>I have a dataset that looks like this:</p> <p><a href="http://i.stack.imgur.com/SvE8g.png" rel="nofollow"><img src="http://i.stack.imgur.com/SvE8g.png" alt="image of a dataset"></a></p> <p>Which I imported into a pandas dataframe using pandas.read_csv with the Year and Country column as indexes. What I need to do...
0
2016-06-04T18:34:54Z
37,634,333
<p>First, reindex the frame. Then use <code>df.apply</code> and <code>Series.interpolate</code></p> <p>Something like:</p> <pre><code>import pandas as pd df = pd.read_csv(r'folder/file.txt') rows = df.shape[0] df.index = [x for x in range(0, 5*rows, 5)] df = df.reindex(range(0, 5*rows)) df.apply(pandas.Series.interp...
0
2016-06-04T19:44:07Z
[ "python", "dataframe", "interpolation", "panel-data" ]
How to interpolate between values on a dataframe using Python and/or R
37,633,711
<p>I have a dataset that looks like this:</p> <p><a href="http://i.stack.imgur.com/SvE8g.png" rel="nofollow"><img src="http://i.stack.imgur.com/SvE8g.png" alt="image of a dataset"></a></p> <p>Which I imported into a pandas dataframe using pandas.read_csv with the Year and Country column as indexes. What I need to do...
0
2016-06-04T18:34:54Z
37,634,477
<p>This is a tough one, but I think I have it.</p> <p>Here's a example with a sample dataframe:</p> <pre><code>df = pd.DataFrame({'country': ['australia', 'australia', 'belgium','belgium'], 'year': [1980, 1985, 1980, 1985], 'data1': [1,5, 10, 15], 'data2': [10...
1
2016-06-04T19:59:44Z
[ "python", "dataframe", "interpolation", "panel-data" ]
How to interpolate between values on a dataframe using Python and/or R
37,633,711
<p>I have a dataset that looks like this:</p> <p><a href="http://i.stack.imgur.com/SvE8g.png" rel="nofollow"><img src="http://i.stack.imgur.com/SvE8g.png" alt="image of a dataset"></a></p> <p>Which I imported into a pandas dataframe using pandas.read_csv with the Year and Country column as indexes. What I need to do...
0
2016-06-04T18:34:54Z
37,634,715
<ul> <li><p>If you give your DataFrame a DatetimeIndex, then you can take advantage of the <code>df.resample</code> and <code>df.interpolate('time')</code> methods.</p></li> <li><p>To make <code>df.index</code> a DatetimeIndex you might be tempted to use <code>set_index('Year')</code>. However, the <code>Year</code> by...
1
2016-06-04T20:29:47Z
[ "python", "dataframe", "interpolation", "panel-data" ]
How to create lists from every item of an existing list in python 2.7.11?
37,633,841
<p>I am trying to generate lists from the elements of a list in python. For example: there is a list with the following information: <code>list=['AB4', 'AB3','AC3', 'BC4', 'BC5']</code> This is the exact format of the elements of the list. I suppouse to create list for every element, separate for the letters (consi...
3
2016-06-04T18:52:44Z
37,633,952
<p>You can use regexes (the <a href="https://docs.python.org/2/library/re.html" rel="nofollow"><code>re</code></a> module) and a <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> to accomplish this. The following will work for arbitrary leng...
3
2016-06-04T19:03:06Z
[ "python", "list" ]
How to create lists from every item of an existing list in python 2.7.11?
37,633,841
<p>I am trying to generate lists from the elements of a list in python. For example: there is a list with the following information: <code>list=['AB4', 'AB3','AC3', 'BC4', 'BC5']</code> This is the exact format of the elements of the list. I suppouse to create list for every element, separate for the letters (consi...
3
2016-06-04T18:52:44Z
37,633,968
<p>This will do it:</p> <pre><code>from collections import defaultdict l=['AB4', 'AB3','AC3', 'BC4', 'BC5'] result=defaultdict(list) for item in l: #If you want numbers to be numbers and not strings replace item[2:] with int(item[2:]) result[item[:2]].append(item[2:]) result[item[2:]].append(item[:2]) ...
2
2016-06-04T19:04:45Z
[ "python", "list" ]