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
page content not rendering properly - python / django?
39,276,536
<p>I am running ubuntu 16.4 with apache2 webserver</p> <p>I am trying to setup this site, downloaded from github: <a href="https://github.com/mozilla/http-observatory-website" rel="nofollow">https://github.com/mozilla/http-observatory-website</a></p> <p>Unfortunately, there is no instructions to follow :(</p> <p>if ...
-1
2016-09-01T16:24:59Z
39,278,131
<p>Based on the source, you'd need the <a href="http://jinja.pocoo.org/" rel="nofollow">Jinja templating engine</a>. The easiest way to install it is by running <code>pip install jinja2</code>. </p> <p>That said, I do recommend that you follow the virtualenv instructions on the DigitalOcean tutorial posted as a commen...
1
2016-09-01T18:01:30Z
[ "python", "jinja2" ]
page content not rendering properly - python / django?
39,276,536
<p>I am running ubuntu 16.4 with apache2 webserver</p> <p>I am trying to setup this site, downloaded from github: <a href="https://github.com/mozilla/http-observatory-website" rel="nofollow">https://github.com/mozilla/http-observatory-website</a></p> <p>Unfortunately, there is no instructions to follow :(</p> <p>if ...
-1
2016-09-01T16:24:59Z
39,324,077
<p>cloning the package this way solved the problem and gave me the right files to add to /var/www</p> <p>git clone -b gh-pages <a href="https://github.com/mozilla/http-observatory-website.git" rel="nofollow">https://github.com/mozilla/http-observatory-website.git</a></p>
0
2016-09-05T04:46:22Z
[ "python", "jinja2" ]
django frontend login: TypeError at /auth/login dict expected at most 1 arguments, got 2
39,276,645
<p>In the project im working on the admin site is working fine and i want to test the frontend. But im Getting: </p> <p>TypeError at /auth/login</p> <p>dict expected at most 1 arguments, got 2</p> <p>Here the full traceback:</p> <pre><code>Environment: Request Method: GET Request URL: http://127.0.0.1:8000/auth/l...
0
2016-09-01T16:31:32Z
39,276,760
<p>The <code>render</code> function is expecting a dictionary not a RequestContext object. Change your return line in your login_view to something like this:</p> <pre><code>return render(request, 'login.html', {'context': context}) </code></pre>
1
2016-09-01T16:39:16Z
[ "python", "django" ]
Python Pandas ValueError on simple query
39,276,650
<p>The following line causes a ValueError (Pandas 17.1), and I'm trying to understand why.</p> <pre><code>x = (matchdf['ANPR Matched_x'] == 1) </code></pre> <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> <p>I'm trying to use it for following conditio...
0
2016-09-01T16:32:06Z
39,276,871
<p>Use <code>loc</code> to set the values.</p> <pre><code>matchdf.loc[matchdf['APNR Matched_x'] == 1, 'FullMatch'] = 1 </code></pre> <p><strong>Example</strong></p> <pre><code>df = pd.DataFrame({'APNR Matched_x': [0, 1, 1, 0], 'Full Match': [False] * 4}) &gt;&gt;&gt; df APNR Matched_x Full Match 0 ...
2
2016-09-01T16:45:35Z
[ "python", "pandas", "numpy" ]
Python Pandas ValueError on simple query
39,276,650
<p>The following line causes a ValueError (Pandas 17.1), and I'm trying to understand why.</p> <pre><code>x = (matchdf['ANPR Matched_x'] == 1) </code></pre> <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> <p>I'm trying to use it for following conditio...
0
2016-09-01T16:32:06Z
39,278,338
<p>If you have this kind of error, first check your dataframe contains what you think it does.</p> <p>I was stupidly ending up with some Series objects being added to one of the columns which should have contained ints!</p>
1
2016-09-01T18:14:12Z
[ "python", "pandas", "numpy" ]
How to connect to MS SQL Server database remotely by IP in Python using mssql and pymssql
39,276,703
<p>How can I connect to MS SQL Server database remotely by IP in Python using mssql and pymssql modules. To connect locally I use link = mssql+pymssql://InstanceName/DataBaseName</p> <p>I enabled TCP/IP Network Configurations. But How can I get the connection link?</p> <p>Thank you.</p>
0
2016-09-01T16:35:20Z
39,276,739
<p>You need to create a <code>Connection</code> object</p> <pre><code>import pymssql ip = '127.0.0.1' database_connection = pymssql.connect(host=ip, port=1433, username='foo', password='bar') </code></pre> <p>If you're using SQLAlchemy, or another ORM that supports connection strings, you can also use the following f...
4
2016-09-01T16:37:56Z
[ "python", "sql-server", "pymssql" ]
Splitting a list into uneven tuples
39,276,740
<p>I'm trying to split a list of strings into a list of tuples of uneven length containing these strings, with each tuple containing strings initially separated with blank strings. Basically I'd need the parameterized split that I could apply to lists. If my initial list looks like:</p> <pre><code>init = ['a', 'b', ''...
6
2016-09-01T16:38:00Z
39,276,854
<p>You can use <code>itertools.groupby</code> function to group the elements based on their sizes, like this</p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; init = ['a', 'b', '', 'c', 'd e', 'fgh', '', 'ij', '', '', 'k', 'l', ''] &gt;&gt;&gt; [tuple(g) for valid, g in groupby(init, key=lambda x:...
4
2016-09-01T16:44:37Z
[ "python", "list", "python-2.7", "group", "list-comprehension" ]
Splitting a list into uneven tuples
39,276,740
<p>I'm trying to split a list of strings into a list of tuples of uneven length containing these strings, with each tuple containing strings initially separated with blank strings. Basically I'd need the parameterized split that I could apply to lists. If my initial list looks like:</p> <pre><code>init = ['a', 'b', ''...
6
2016-09-01T16:38:00Z
39,277,136
<p>Here is a more concise and general approach with <code>groupby</code> if you want to split your list with a special delimiter:</p> <pre><code>&gt;&gt;&gt; delimiter = '' &gt;&gt;&gt; [tuple(g) for k, g in groupby(init, delimiter.__eq__) if not k] [('a', 'b'), ('c', 'd e', 'fgh'), ('ij',), ('k', 'l')] </code></pre>
4
2016-09-01T16:59:34Z
[ "python", "list", "python-2.7", "group", "list-comprehension" ]
Pass user replies across different pages
39,276,874
<p>I'd like to create a small web application with Django.</p> <p>It's about different questions: I have ~20 questions/statements that can be answered with "Agree"/"Don't agree"/"Neutral". Now I need a way to pass the data because at the end, when the user has answered all questions I have to analyse the input.</p> <...
0
2016-09-01T16:46:09Z
39,277,913
<p>I've accomplished this by having all questions be part of the same form, but hiding all questions except for the current one using Javascript. It'd look something like this: 1) Render the form with a class that gives all questions "display: none" except for the first one. 2) Have "Previous" and "Next" buttons that ...
0
2016-09-01T17:48:18Z
[ "python", "django" ]
How can I limit matplotlib contains to one object?
39,276,925
<p>I'm working on a simple GUI with draggable lines to allow a user to visually window some plotted data. </p> <p>Working with <a href="http://matplotlib.org/users/event_handling.html" rel="nofollow">matplotlib's event handling documentation</a> I've been able to implement an initial version of the draggable window li...
2
2016-09-01T16:48:47Z
39,281,093
<p>One approach could be to check the children of the axes for objects that will fire their respective "move" callbacks, see which one is rendered the topmost and only move that one.</p> <p>For the above example I've defined an additional method:</p> <pre><code>def shouldthismove(self, event): # Check to see if t...
2
2016-09-01T21:24:36Z
[ "python", "python-3.x", "matplotlib" ]
Python how to use "try:" not stop when it raises except
39,276,998
<p>I have this code and would like to shorten it. Is this anyway possible? Does not make that much sense to have that often the same code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprin...
0
2016-09-01T16:53:19Z
39,277,034
<p>How about avoiding the exceptions entirely?</p> <p><code>.get()</code> allows you to provide a default value if they key doesn't exist already...</p> <pre><code>years = values.get('year') # Implicitly default to None tracks = values.get('track', None) # Explicitly default to None statuses = values.get('status', ...
10
2016-09-01T16:55:21Z
[ "python", "optimization" ]
Python how to use "try:" not stop when it raises except
39,276,998
<p>I have this code and would like to shorten it. Is this anyway possible? Does not make that much sense to have that often the same code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprin...
0
2016-09-01T16:53:19Z
39,277,052
<p>Here you go. </p> <pre><code>try: years = values['year'] tracks = values['track'] statuses = values['status'] except KeyError: pass </code></pre>
-2
2016-09-01T16:56:10Z
[ "python", "optimization" ]
PyGTK-2.24.0 Installation cannot find NumPy
39,277,078
<p>I am trying to build the PyGTK source from version 2.24.0 with a local (prefix=$HOME/.local) installation of python 3.5.2. Running the configure script produces:</p> <pre><code>$: ./configure --prefix=$HOME/.local .... configure: WARNING: Could not find a valid numpy installation, disabling. .... The following modu...
0
2016-09-01T16:57:07Z
39,344,020
<p>I'm afraid you have some mix-up. Here is what I did :</p> <pre><code>sudo apt-get dist-upgrade sudo apt-get install python3 sudo apt-get install python3-numpy sudo apt-get install python3-matplotlib sudo apt-get install python3-scipy sudo apt-get install python3-pyfits </code></pre> <p>One can also use <code>pip...
1
2016-09-06T08:21:06Z
[ "python", "numpy", "makefile", "pygtk", "configure" ]
broadcasting a comparison of a column of 2d array with multiple columns
39,277,113
<p>What's the right numpy syntax to compare one column against others in a 2d ndarray? </p> <p>After reading <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">some</a> <a href="http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc" rel="nofollow">docs</a> on array broadcastin...
2
2016-09-01T16:58:38Z
39,277,221
<p>You could do something like this -</p> <pre><code>np.flatnonzero((goals[:,None,-1] &gt; goals[:,:-1]).any(1)) </code></pre> <p>Let's go through it in steps.</p> <p><strong>Step #1:</strong> We are introducing a new axis on the last-column sliced version to keep it as <code>2D</code> with the last axis being a sin...
2
2016-09-01T17:04:10Z
[ "python", "arrays", "numpy", "numpy-broadcasting" ]
broadcasting a comparison of a column of 2d array with multiple columns
39,277,113
<p>What's the right numpy syntax to compare one column against others in a 2d ndarray? </p> <p>After reading <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">some</a> <a href="http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc" rel="nofollow">docs</a> on array broadcastin...
2
2016-09-01T16:58:38Z
39,280,176
<p>Just focusing on the <code>newaxis</code> bit:</p> <pre><code>In [332]: goals = np.arange(12).reshape(3,4) In [333]: goals[:,2]&gt;goals[:,:2] ... ValueError: operands could not be broadcast together with shapes (3,) (3,2) </code></pre> <p>So the goal is to make the 1st array of shape (3,1) so it can be broadcast ...
2
2016-09-01T20:13:23Z
[ "python", "arrays", "numpy", "numpy-broadcasting" ]
Concatenating column values into row values in Pandas
39,277,163
<p>I have a dataframe like the below- both columns are strings, with the ValCol being a string of comma separated integers. The index is a generic integer index with no meaning.</p> <pre><code>NameCol ValCol Name1 555, 333 Name2 433 Name1 999 Name3 123 Name2 533 </code></pre> <p>What's the...
1
2016-09-01T17:01:00Z
39,277,222
<p>Using a <code>groupby</code> approach:</p> <pre><code>df = df.groupby('NameCol')['ValCol'].apply(', '.join).reset_index() </code></pre> <p>The resulting output:</p> <pre><code> NameCol ValCol 0 Name1 555, 333, 999 1 Name2 433, 533 2 Name3 123 </code></pre>
4
2016-09-01T17:04:16Z
[ "python", "pandas", "dataframe" ]
django-rest-framework : list parameters in URL
39,277,196
<p>I am pretty new to django and django-rest-framework, but I am trying to pass lists into url parameters to then filter my models by them.</p> <p>Lets say the client application is sending a request that looks something like this... </p> <pre><code> url: "api.com/?something=string,string2,string3&amp;?subthings=sub...
2
2016-09-01T17:02:49Z
39,277,432
<p>Checkout this doc <a href="http://www.django-rest-framework.org/api-guide/filtering/" rel="nofollow">http://www.django-rest-framework.org/api-guide/filtering/</a></p> <p>Query params are normally not validated by url regex</p>
1
2016-09-01T17:17:28Z
[ "python", "django", "rest", "django-rest-framework" ]
django-rest-framework : list parameters in URL
39,277,196
<p>I am pretty new to django and django-rest-framework, but I am trying to pass lists into url parameters to then filter my models by them.</p> <p>Lets say the client application is sending a request that looks something like this... </p> <pre><code> url: "api.com/?something=string,string2,string3&amp;?subthings=sub...
2
2016-09-01T17:02:49Z
39,282,193
<p>To show how I did this thanks to the document links above. Note: I used pipes as my url delimiter and not commas -> '|'.</p> <p>in my <code>urls.py</code></p> <pre><code>url(r'^$', SomethingAPIView.as_view(), name='something'), </code></pre> <p>in my <code>views.py</code></p> <pre><code>class SomethingAPIView(L...
1
2016-09-01T23:17:20Z
[ "python", "django", "rest", "django-rest-framework" ]
What package has this python function?
39,277,332
<p>I found this code in web but it doesn't work.</p> <pre><code>from numpy import * from mayavi import * N = 100 a = 0. b = 1. dt = b / N; q = [1., -1., 1., -1.] qpos = [[0.56, 0.56, 0.50], [0.26, 0.76, 0.50], [0.66, 0.16, 0.50], [0.66, 0.86, 0.50]] x,y,z = mgrid[a:b:dt, a:b:dt, 0.:1.:0.5] ...
-4
2016-09-01T17:11:02Z
39,277,844
<p>First, check out that you have NumPy and Mayavi actually working. Just run <code>python</code> (or IDLE) and when you see the <code>&gt;&gt;&gt;</code> prompt type <code>import numpy</code> and then <code>import mayavi</code>. If you see any <code>ImportError</code> messages (or any other errors), then you don't. No...
1
2016-09-01T17:44:01Z
[ "python", "numpy", "mayavi" ]
Categorize list in Python
39,277,387
<p>What is the best way to categorize a list in python?</p> <p>for example:</p> <pre><code>totalist is below totalist[1] = ['A','B','C','D','E'] totalist[2] = ['A','B','X','Y','Z'] totalist[3] = ['A','F','T','U','V'] totalist[4] = ['A','F','M','N','O'] </code></pre> <p>Say I want to get the list where the first two...
4
2016-09-01T17:14:15Z
39,277,413
<p>You could check the first two elements of each list.</p> <pre><code>for totalist in all_lists: if totalist[:2] == ['A', 'B']: # Do something. </code></pre> <p><strong>Note:</strong> The one-liner solutions suggested by Kasramvd are quite nice too. I found my solution more readable. Though I should say ...
3
2016-09-01T17:16:11Z
[ "python", "list" ]
Categorize list in Python
39,277,387
<p>What is the best way to categorize a list in python?</p> <p>for example:</p> <pre><code>totalist is below totalist[1] = ['A','B','C','D','E'] totalist[2] = ['A','B','X','Y','Z'] totalist[3] = ['A','F','T','U','V'] totalist[4] = ['A','F','M','N','O'] </code></pre> <p>Say I want to get the list where the first two...
4
2016-09-01T17:14:15Z
39,277,486
<p>Basically you can't do this in python with a nested list. But if you are looking for an optimized approach here are some ways:</p> <p>Use a simple list comprehension, by comparing the intended list with only first two items of sub lists:</p> <pre><code>&gt;&gt;&gt; [sub for sub in totalist if sub[:2] == ['A', 'B']...
1
2016-09-01T17:22:11Z
[ "python", "list" ]
Categorize list in Python
39,277,387
<p>What is the best way to categorize a list in python?</p> <p>for example:</p> <pre><code>totalist is below totalist[1] = ['A','B','C','D','E'] totalist[2] = ['A','B','X','Y','Z'] totalist[3] = ['A','F','T','U','V'] totalist[4] = ['A','F','M','N','O'] </code></pre> <p>Say I want to get the list where the first two...
4
2016-09-01T17:14:15Z
39,277,507
<p>You could do this.</p> <pre><code>&gt;&gt;&gt; for i in totalist: ... if ['A','B']==i[:2]: ... print i </code></pre>
1
2016-09-01T17:22:50Z
[ "python", "list" ]
Categorize list in Python
39,277,387
<p>What is the best way to categorize a list in python?</p> <p>for example:</p> <pre><code>totalist is below totalist[1] = ['A','B','C','D','E'] totalist[2] = ['A','B','X','Y','Z'] totalist[3] = ['A','F','T','U','V'] totalist[4] = ['A','F','M','N','O'] </code></pre> <p>Say I want to get the list where the first two...
4
2016-09-01T17:14:15Z
39,277,637
<p>You imply that you are concerned about performance (cost). If you need to do this, and if you are worried about performance, you need a different data-structure. This will add a little "cost" when you making the lists, but save you time when filtering them. </p> <p>If the need to filter based on the first two eleme...
0
2016-09-01T17:30:48Z
[ "python", "list" ]
Categorize list in Python
39,277,387
<p>What is the best way to categorize a list in python?</p> <p>for example:</p> <pre><code>totalist is below totalist[1] = ['A','B','C','D','E'] totalist[2] = ['A','B','X','Y','Z'] totalist[3] = ['A','F','T','U','V'] totalist[4] = ['A','F','M','N','O'] </code></pre> <p>Say I want to get the list where the first two...
4
2016-09-01T17:14:15Z
39,277,683
<p>Just for fun, <code>itertools</code> solution to push per-element work to the C layer:</p> <pre><code>from future_builtins import map # Py2 only; not needed on Py3 from itertools import compress from operator import itemgetter # Generator prefixes = map(itemgetter(slice(2)), totalist) selectors = map(['A','B'].__...
2
2016-09-01T17:33:41Z
[ "python", "list" ]
Python-Invalid syntax does not highligt error
39,277,473
<p>I've been working on this code and when I test it, it says there is a syntax error but it does not highlight my error in IDLE. Any ideas?</p> <pre><code>import os import sys Start=True while Start==True: Operation=input("Please select from the following operations\n" "Add\n" ...
-1
2016-09-01T17:21:18Z
39,277,538
<p>The error is in the line:</p> <pre><code>if Operation==not(in("Add","Subtract")): </code></pre> <p>The correct code should be:</p> <pre><code>if Operation not in("Add","Subtract"): </code></pre> <p>You also should add <code>import time</code> at the beginning of your code for the <code>time.sleep</code> to work....
1
2016-09-01T17:25:07Z
[ "python", "syntax-error" ]
Python-Invalid syntax does not highligt error
39,277,473
<p>I've been working on this code and when I test it, it says there is a syntax error but it does not highlight my error in IDLE. Any ideas?</p> <pre><code>import os import sys Start=True while Start==True: Operation=input("Please select from the following operations\n" "Add\n" ...
-1
2016-09-01T17:21:18Z
39,277,556
<p>Wrong:</p> <pre><code>if Operation==not(in("Add","Subtract")): print("That is not a mathmatical operation.\nPlease try again.") time.sleep(2) os.sys("cls") </code></pre> <p>Should be:</p> <pre><code>if Operation not in ("Add","Subtract"): print("That is not a mathmatical operation.\nPlease try aga...
2
2016-09-01T17:26:02Z
[ "python", "syntax-error" ]
PyMC3 Multinomial Model doesn't work with non-integer observe data
39,277,474
<p>I'm trying to use PyMC3 to solve a fairly simple multinomial distribution. It works perfectly if I have the 'noise' value set to 0.0. However when I change it to anything else, for example 0.01, I get an error in the find_MAP() function and it hangs if I don't use find_MAP(). Is there some reason that the multino...
0
2016-09-01T17:21:21Z
39,363,050
<p>This works for me</p> <pre class="lang-py prettyprint-override"><code>sample_size = 10 number_of_experiments = 100 true_probs = [0.2, 0.1, 0.3, 0.4] k = len(true_probs) noise = 0.01 y = np.random.multinomial(n=number_of_experiments, pvals=true_probs, size=sample_size)+noise with pm.Model() as multinom_test: a...
1
2016-09-07T06:53:12Z
[ "python", "pymc", "pymc3" ]
Pandas - Finding Unique Entries in Daily Census Data
39,277,501
<p>I have census data that looks like this for a full month and I want to find out how many unique inmates there were for the month. The information is taken daily so there are multiples. </p> <pre><code> _id,Date,Gender,Race,Age at Booking,Current Age 1,2016-06-01,M,W,32,33 2,2016-06-01,M,B,25,27 3,201...
3
2016-09-01T17:22:45Z
39,277,721
<p>You could use the <code>df.drop_duplicates()</code> which will return the DataFrame with only unique values, then count the entries.</p> <p>Something like this should work:</p> <pre><code>import pandas as pd df = pd.read_csv('inmates_062016.csv', index_col=0, parse_dates=True) uniqueDF = df.drop_duplicates() coun...
1
2016-09-01T17:37:12Z
[ "python", "pandas", "dataframe", "grouping", "data-cleaning" ]
Pandas - Finding Unique Entries in Daily Census Data
39,277,501
<p>I have census data that looks like this for a full month and I want to find out how many unique inmates there were for the month. The information is taken daily so there are multiples. </p> <pre><code> _id,Date,Gender,Race,Age at Booking,Current Age 1,2016-06-01,M,W,32,33 2,2016-06-01,M,B,25,27 3,201...
3
2016-09-01T17:22:45Z
39,280,402
<p>I think the trick here is to groupby as much as possible and check the differences in those (small) groups through the month:</p> <pre><code>inmates = pd.read_csv('inmates.csv') # group by everything except _id and count number of entries grouped = inmates.groupby( ['Gender', 'Race', 'Age at Booking', 'Current...
1
2016-09-01T20:30:59Z
[ "python", "pandas", "dataframe", "grouping", "data-cleaning" ]
Solving/teaching Python to solve Number Series
39,277,512
<p>Is there a better way of solving Number Series questions using Python other than teaching it basic pattern rules and hoping the rules fit the question? For example. we would have a list of functions that has a rule for each of them and see if the series fits. Is there a Library that does this, and if not am I stuck ...
0
2016-09-01T17:23:19Z
39,278,096
<p>Consider using the <a href="http://oeis.org" rel="nofollow">OEIS</a>. It is a huge database of sequences the you can check against. I would say, because it probably doesn't have every possible arithmetic progression etc., you would get the best coverage by writing a program that checks basic sequences (trying to fin...
0
2016-09-01T17:59:01Z
[ "python" ]
Storing the value that meets a requirement in variable and finding the next value that also meets that requirement
39,277,566
<p>I am trying to write a code that iterates through a list and if i % 10 equals 1, then I store that <code>i</code> in a variable. Then, I want my code to keep iterating through the list and if another i value meets the same requirement than it adds to a count. </p> <p>This is what I have right now but it is just sav...
-2
2016-09-01T17:26:35Z
39,277,636
<p>You're saving the old value too soon</p> <pre><code> old = i % 10 if (old == 1) and (i % 10 == 1): count1_1 += 1 </code></pre> <p>should be</p> <pre><code> if (old == 1) and (i % 10 == 1): count1_1 += 1 old = i % 10 </code></pre> <p>or <code>old</code> and <code>i % ...
1
2016-09-01T17:30:41Z
[ "python" ]
Storing the value that meets a requirement in variable and finding the next value that also meets that requirement
39,277,566
<p>I am trying to write a code that iterates through a list and if i % 10 equals 1, then I store that <code>i</code> in a variable. Then, I want my code to keep iterating through the list and if another i value meets the same requirement than it adds to a count. </p> <p>This is what I have right now but it is just sav...
-2
2016-09-01T17:26:35Z
39,279,711
<p>I still see <code>old</code> as essentially a boolean flag so let's make it one (called <code>previous_1</code>), but this time, instead of only being triggered True once, we'll change it's value based on every <code>i</code> that passes both requirements:</p> <pre><code>count1_1 = 0 previous_1 = False for i in B...
0
2016-09-01T19:43:58Z
[ "python" ]
Elegant way to rearrange dictionary on number in key string
39,277,589
<p>Say I have a dict with these objects:</p> <pre><code>&lt; MultiValueDict: { u 'task-1-t_name': [u 'T2'], u 'task-INITIAL_FORMS': [u '0'], u 'task-1-end_date': [u '1010-01-01'], u 'task-MAX_NUM_FORMS': [u '1000'], u 'order_wizard-current_step': [u 'task'], u 'task-TOTA...
-1
2016-09-01T17:27:43Z
39,277,711
<p>This is the data for a Django formset. Rather than trying to manipulate it separately, you should use the methods available on the formset itself: once you have validated that formset, you can do <code>formset.forms[0].cleaned_data['start_time']</code> for example.</p>
2
2016-09-01T17:36:16Z
[ "python", "arrays" ]
Element-wise minimum of multiple vectors in numpy
39,277,638
<p>I know that in numpy I can compute the element-wise minimum of two vectors with</p> <pre><code>numpy.minimum(v1, v2) </code></pre> <p>What if I have a list of vectors of equal dimension, <code>V = [v1, v2, v3, v4]</code> (but a list, not an array)? Taking <code>numpy.minimum(*V)</code> doesn't work. What's the pre...
2
2016-09-01T17:30:49Z
39,277,693
<p>Convert to NumPy array and perform <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.min.html" rel="nofollow"><code>ndarray.min</code></a> along the first axis -</p> <pre><code>np.asarray(V).min(0) </code></pre> <p>Or simply use <a href="http://docs.scipy.org/doc/numpy/reference/generated/...
3
2016-09-01T17:34:22Z
[ "python", "numpy" ]
Element-wise minimum of multiple vectors in numpy
39,277,638
<p>I know that in numpy I can compute the element-wise minimum of two vectors with</p> <pre><code>numpy.minimum(v1, v2) </code></pre> <p>What if I have a list of vectors of equal dimension, <code>V = [v1, v2, v3, v4]</code> (but a list, not an array)? Taking <code>numpy.minimum(*V)</code> doesn't work. What's the pre...
2
2016-09-01T17:30:49Z
39,279,912
<p><code>*V</code> works if <code>V</code> has only 2 arrays. <code>np.minimum</code> is a <code>ufunc</code> and takes 2 arguments.</p> <p>As a <code>ufunc</code> it has a <code>.reduce</code> method, so it can apply repeated to a list inputs.</p> <pre><code>In [321]: np.minimum.reduce([np.arange(3), np.arange(2,-1...
2
2016-09-01T19:56:54Z
[ "python", "numpy" ]
Set datatype after converting null values while reading from csv to DataFrame with Pandas
39,277,664
<p>I have a .csv file with GPS data which looks like this:</p> <pre><code>ID,GPS_LATITUDE,GPS_LONGITUDE 1,35.66727683,139.7591279 2,35.66727683,139.7591279 3,-1,-1 4,35.66750697,139.7589757 5,,139.7589757 </code></pre> <p>The last row has a blank or "null" value. I would like to read the data into a dataframe and set...
1
2016-09-01T17:32:49Z
39,277,982
<p>First of all, you don't even need to use any conv function:</p> <pre><code>$ cat /tmp/a.csv ID,GPS_LATITUDE,GPS_LONGITUDE 1,35.66727683,139.7591279 2,35.66727683,139.7591279 3,-1,-1 4,35.66750697,139.7589757 5,,139.7589757 In [15]: df = pd.read_csv("/tmp/a.csv", dtype={'GPS_LATITUDE':np.float64,'GPS_LONGITUDE':np....
1
2016-09-01T17:52:37Z
[ "python", "pandas" ]
In Python how do I make a copy of a numpy Matrix column such that any further operations to the copy does not affect the original matrix?
39,277,687
<p>I would normally copy a whole matrix as follows:</p> <pre><code>from copy import copy, deepcopy b=np.array([[2,3],[1,2]]) a = np.empty_like (b) a[:] = b </code></pre> <p>(Note a and b are not what I am using in my code and are just made up for this example). But how do I copy just the first column (or any selected...
3
2016-09-01T17:34:01Z
39,277,771
<p>Just use indexing to slice a column then use <code>copy()</code> attribute of array object to create a copy:</p> <pre><code>&gt;&gt;&gt; b=np.array([[2,3],[1,2]]) &gt;&gt;&gt; b array([[2, 3], [1, 2]]) &gt;&gt;&gt; a = b[:,0].copy() &gt;&gt;&gt; a array([2, 1]) &gt;&gt;&gt; a += 2 &gt;&gt;&gt; a array([4, 3]...
1
2016-09-01T17:40:13Z
[ "python", "arrays", "numpy", "matrix", "copy" ]
Python Dictionary: compare 2 values in 1 key
39,277,724
<p>I have a dataset where there is a list of names in a column, and a response for each name in a separate column. Each name is listed twice, and I want to see if there is agreement between the two recorded responses. i.e.</p> <p>name a | response 1</p> <p>name a | response 2</p> <p>name b | response 1</p> <p>name...
3
2016-09-01T17:37:19Z
39,277,944
<p>I assume what you want to achieve is a list of names that have matching answers.</p> <p>given that you have the dictionary already created:</p> <pre><code>myDict = { 'name 1' : {'response1':'A', 'response2':'B'}, 'name 2' : {'response1':'C', 'response2':'C'}, ... , 'name N' : {'response1':'Z', 'res...
0
2016-09-01T17:49:52Z
[ "python", "python-2.7", "dictionary", "key" ]
Python Dictionary: compare 2 values in 1 key
39,277,724
<p>I have a dataset where there is a list of names in a column, and a response for each name in a separate column. Each name is listed twice, and I want to see if there is agreement between the two recorded responses. i.e.</p> <p>name a | response 1</p> <p>name a | response 2</p> <p>name b | response 1</p> <p>name...
3
2016-09-01T17:37:19Z
39,278,455
<p>I implemented NamesDict class, which could have 2 or more responses for each key (name), compare it and export. To export in csv you can easily use csv library for python: <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">https://docs.python.org/2/library/csv.html</a></p> <p>I put comparison and c...
0
2016-09-01T18:22:01Z
[ "python", "python-2.7", "dictionary", "key" ]
Python Dictionary: compare 2 values in 1 key
39,277,724
<p>I have a dataset where there is a list of names in a column, and a response for each name in a separate column. Each name is listed twice, and I want to see if there is agreement between the two recorded responses. i.e.</p> <p>name a | response 1</p> <p>name a | response 2</p> <p>name b | response 1</p> <p>name...
3
2016-09-01T17:37:19Z
39,278,535
<p>you can use groupby and customer key function to separate two groups </p> <pre><code> from itertools import groupby myDict = { 'name 1' : {'response1':'A', 'response2':'B'}, 'name 2' : {'response1':'C', 'response2':'C'}, 'name N' : {'response1':'Z', 'response2':'Z'}, } for i...
0
2016-09-01T18:26:53Z
[ "python", "python-2.7", "dictionary", "key" ]
Python Dictionary: compare 2 values in 1 key
39,277,724
<p>I have a dataset where there is a list of names in a column, and a response for each name in a separate column. Each name is listed twice, and I want to see if there is agreement between the two recorded responses. i.e.</p> <p>name a | response 1</p> <p>name a | response 2</p> <p>name b | response 1</p> <p>name...
3
2016-09-01T17:37:19Z
39,278,580
<p>Assuming myDict and hospitalDict are the same dictionary, you need just one simple change. Change the line:</p> <pre><code>if hospitalDict[items] != hospitalDict[items]: </code></pre> <p>To the line:</p> <pre><code>if hospitalDict[items]["response1"] != hospitalDict[items]["response2"]: </code></pre> <p>Then <...
0
2016-09-01T18:29:51Z
[ "python", "python-2.7", "dictionary", "key" ]
graphlab SFrame sum all values in a column
39,277,805
<p>How to sum all values in a column of SFrame graphlab. I tried looking into the official documentation and it is given only for SaArray(<a href="https://turi.com/products/create/docs/generated/graphlab.SArray.sum.html#graphlab.SArray.sum" rel="nofollow">doc</a>) without any example.</p>
1
2016-09-01T17:41:58Z
39,283,213
<pre><code>&gt;&gt;&gt; import graphlab as gl &gt;&gt;&gt; sf = gl.SFrame({'foo':[1,2,3], 'bar':[4,5,6]}) &gt;&gt;&gt; sf Columns: bar int foo int Rows: 3 Data: +-----+-----+ | bar | foo | +-----+-----+ | 4 | 1 | | 5 | 2 | | 6 | 3 | +-----+-----+ [3 rows x 2 columns] &gt;&gt;&gt; s...
1
2016-09-02T01:52:35Z
[ "python", "graphlab" ]
graphlab SFrame sum all values in a column
39,277,805
<p>How to sum all values in a column of SFrame graphlab. I tried looking into the official documentation and it is given only for SaArray(<a href="https://turi.com/products/create/docs/generated/graphlab.SArray.sum.html#graphlab.SArray.sum" rel="nofollow">doc</a>) without any example.</p>
1
2016-09-01T17:41:58Z
39,320,324
<p>I think the question from the op was more about how to do this across all (or a list of) columns at once. Here's the comparison between pandas and graphlab.</p> <pre><code># imports import graphlab as gl import pandas as pd import numpy as np # generate data data = np.random.randint(0,10,size=100).reshape(10,...
0
2016-09-04T18:44:02Z
[ "python", "graphlab" ]
Iteratively concatenate columns in pandas with NaN values
39,277,838
<p>I have a <code>pandas.DataFrame</code> data frame:</p> <pre><code>import pandas as pd df = pd.DataFrame({"x": ["hello there you can go home now", "why should she care", "please sort me appropriately"], "y": [np.nan, "finally we were able to go home", "but what about meeeeeeeeeee"], "z": ["", "alright we a...
4
2016-09-01T17:43:40Z
39,278,015
<p><strong><em>Option 1</em></strong></p> <pre><code>pd.Series(df.fillna('').values.tolist()).str.join(' ') 0 hello there you can go home now 1 why should she care finally we were able to go... 2 please sort me appropriately but what about me... dtype: object </code></pre> <p><strong><em>O...
3
2016-09-01T17:54:03Z
[ "python", "pandas" ]
How do I prevent sqlalchemy from creating a transaction on select?
39,277,841
<p>My problem:</p> <p>I have a file with several rows of data in it. I want to <em>try</em> to insert every row into my database, but if <strong>any</strong> of the rows have problems I need to roll back the whole kit and kaboodle. But I want to track the actual errors so rather than just dying on the first record tha...
1
2016-09-01T17:43:41Z
39,280,270
<p>It looks as if <code>begin_nested</code> and <code>with</code> blocks are the way to go.</p> <blockquote> <p><code>begin_nested()</code>, in the same manner as the less often used <code>begin()</code> method... - <a href="http://docs.sqlalchemy.org/en/latest/orm/session_transaction.html#using-savepoint" rel="nof...
1
2016-09-01T20:20:49Z
[ "python", "transactions", "sqlalchemy" ]
SQLAlchemy emitting cross join for no reason
39,277,957
<p>I had a query set up in SQLAlchemy which was running a bit slow, tried to optimize it. The result, for unknown reason, uses an implicit cross join, which is both significantly slower and comes up with entirely the wrong result. I’ve anonymized the table names and arguments but otherwise made no changes. Does anyon...
1
2016-09-01T17:50:49Z
39,278,255
<p>Not sure what you are trying to achieve but it looks like you're trying to do an inner join between the tables, and select only specific columns. </p> <p>So I think you need to do something like:</p> <pre><code>cust_name = u'Bob' proj_name = u'job1' item_color = u'blue' query = (db.session.query(Item.name) ...
1
2016-09-01T18:08:51Z
[ "python", "postgresql", "sqlalchemy" ]
SQLAlchemy emitting cross join for no reason
39,277,957
<p>I had a query set up in SQLAlchemy which was running a bit slow, tried to optimize it. The result, for unknown reason, uses an implicit cross join, which is both significantly slower and comes up with entirely the wrong result. I’ve anonymized the table names and arguments but otherwise made no changes. Does anyon...
1
2016-09-01T17:50:49Z
39,278,757
<p>This is because a <code>joinedload</code> is different from a <code>join</code>. The <code>joinedload</code>ed entities are effectively anonymous, and the later filters you applied refer to different instances of the same tables, so <code>customers</code> and <code>projects</code> gets joined in twice.</p> <p>What ...
2
2016-09-01T18:43:30Z
[ "python", "postgresql", "sqlalchemy" ]
Storing pure python datetime.datetime in pandas DataFrame
39,278,042
<p>Since <code>matplotlib</code> doesn't support <a href="https://github.com/pydata/pandas/issues/8113" rel="nofollow">either</a><code>pandas.TimeStamp</code> <a href="http://stackoverflow.com/questions/22048792/how-do-i-display-dates-when-plotting-in-matplotlib-pyplot">or</a><code>numpy.datetime64</code>, and there a...
3
2016-09-01T17:55:29Z
39,278,421
<p>The use of <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#converting-to-python-datetimes" rel="nofollow">to_pydatetime()</a> is correct.</p> <pre><code>In [87]: t = pd.DataFrame({'date': [pd.to_datetime('2012-12-31'), pd.to_datetime('2013-12-31')]}) In [88]: t.date.dt.to_pydatetime() Out[88]:...
2
2016-09-01T18:19:19Z
[ "python", "python-3.x", "datetime", "pandas" ]
Storing pure python datetime.datetime in pandas DataFrame
39,278,042
<p>Since <code>matplotlib</code> doesn't support <a href="https://github.com/pydata/pandas/issues/8113" rel="nofollow">either</a><code>pandas.TimeStamp</code> <a href="http://stackoverflow.com/questions/22048792/how-do-i-display-dates-when-plotting-in-matplotlib-pyplot">or</a><code>numpy.datetime64</code>, and there a...
3
2016-09-01T17:55:29Z
39,298,633
<p>For me, the steps look like this:</p> <ol> <li>convert timezone with pytz </li> <li>convert to_datetime with pandas and make that the index</li> <li>plot and autoformat</li> </ol> <p>Starting df looks like this:</p> <p><a href="http://i.stack.imgur.com/L2WPm.png" rel="nofollow"><img src="http://i.stack.imgur.com/...
0
2016-09-02T18:22:05Z
[ "python", "python-3.x", "datetime", "pandas" ]
How do I add collision detection to the sides of the window in Tkinter? [Python 3]
39,278,069
<p>I'm making an (admittedly, my first) game in Python, and I've only really made the base of the game (like, moving around), and everything works <em>pretty</em> well, except for the fact that you can move right off the screen. How would I add collision detection to the sides of the window? Here's the code:</p> <pre>...
-1
2016-09-01T17:57:11Z
39,278,300
<p>I assume you want to detect the collision of a rectangle with the edges of the screen. I am stranger to tkinter, however I have experience with pygame, let me explain as well as I can.</p> <p>In pygame, a rectange position are given as left_top corner, a(one side), b(another side). Such as,</p> <pre><code>(x, y) ...
0
2016-09-01T18:12:15Z
[ "python", "tkinter", "collision-detection", "python-3.4", "tkinter-canvas" ]
How do I add collision detection to the sides of the window in Tkinter? [Python 3]
39,278,069
<p>I'm making an (admittedly, my first) game in Python, and I've only really made the base of the game (like, moving around), and everything works <em>pretty</em> well, except for the fact that you can move right off the screen. How would I add collision detection to the sides of the window? Here's the code:</p> <pre>...
-1
2016-09-01T17:57:11Z
39,278,497
<p>You can get the size of your canvas like this:</p> <pre><code>size, _ = self.canvas.winfo_geometry().split('+', maxsplit=1) w, h = (int(_) for _ in size.split('x')) </code></pre> <p>And the position of your <code>Squarey</code> like this:</p> <pre><code>x, y, _, __ = self.canvas.coords(self.id) </code></pre> <p>...
1
2016-09-01T18:24:35Z
[ "python", "tkinter", "collision-detection", "python-3.4", "tkinter-canvas" ]
Python time module - clock_getres(clk_id),clock_gettime(clk_id), clock_settime(clk_id, time)
39,278,092
<p>According to Python 3.5 documenation (time module) all three functions <code>clock_getres(clk_id), clock_gettime(clk_id)</code> and <code>clock_settime(clk_id, time)</code> are available for Unix Systems. According to documentation: </p> <blockquote> <p><code>clock_getres(clk_id)</code> Return the resolution (p...
0
2016-09-01T17:58:32Z
39,278,959
<p>Basically clk_id it is integer id of clock, list of clock you can find at: <a href="https://docs.python.org/3/library/time.html" rel="nofollow">https://docs.python.org/3/library/time.html</a></p> <p>for example <strong>time.CLOCK_REALTIME</strong> == 0 and <strong>time.CLOCK_MONOTONIC</strong> == 1, etc for each cl...
1
2016-09-01T18:56:24Z
[ "python", "python-3.5" ]
What's the command to "reset" a bokeh plot?
39,278,110
<p>I have a bokeh figure that has a reset button in the toolbar. Basically, I want to "reset" the figure when I update the data that I'm plotting in the figure. How can I do that?</p>
4
2016-09-01T17:59:52Z
39,278,173
<p>As of Bokeh <code>0.12.1</code> there is no built in function to do this. It would possible to make a <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/extensions.html" rel="nofollow">custom extension</a> that does this. However, that would take a little work and experimentation and dialogue. If you'd like ...
1
2016-09-01T18:04:21Z
[ "python", "plot", "jupyter", "bokeh" ]
What's the command to "reset" a bokeh plot?
39,278,110
<p>I have a bokeh figure that has a reset button in the toolbar. Basically, I want to "reset" the figure when I update the data that I'm plotting in the figure. How can I do that?</p>
4
2016-09-01T17:59:52Z
39,352,678
<p>Example with a radiogroup callback, that's the best way I found to reset while changing plots, just get the range of the data and set it to the range:</p> <pre><code>from bokeh.plotting import Figure from bokeh.models import ColumnDataSource, CustomJS, RadioGroup from bokeh.layouts import gridplot from bokeh.resour...
1
2016-09-06T15:24:10Z
[ "python", "plot", "jupyter", "bokeh" ]
Trying to get a grip on CachedPropery in clang\cindex.py
39,278,165
<p>This is related to other <a href="http://stackoverflow.com/questions/39194326/libclang-with-python-binding-asserterror">question</a> I had, which left with no answer... I trying to understand what's going on under the hood of the <a href="https://github.com/llvm-mirror/clang/tree/master/bindings/python" rel="nofollo...
1
2016-09-01T18:03:57Z
39,278,313
<p>The <code>CachedProperty</code> object is a <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow">descriptor object</a>; the <code>__get__</code> method is called automatically whenever Python tries to access an attribute on an instance that is only available on the class <em>and</em> has a <code>...
2
2016-09-01T18:12:39Z
[ "python", "clang", "python-decorators", "libclang", "python-descriptors" ]
Limit data range without using xlim - python, matplotlib
39,278,182
<p>I want to put multiple lines on the same plot, but use only part of the data available for some of the lines. Each dataset contains data from 1925 until the present, and I'd like the x-axis to show that entire range, but I only want to show dataset A from 1925 until 1940, dataset B from 1941 to 1958, and so on. <str...
0
2016-09-01T18:05:23Z
39,278,299
<p>There are many ways to select subsets of a pandas dataframe, assuming that's what you have.</p> <p>For instance something like</p> <p><code>data_for_plotting=DF.query("date&gt;'1925-01-01' and date&lt;'1940-01-01'")</code></p> <p>Then pass that instead of DF to the rest of the plotting statements.</p> <p>You can...
1
2016-09-01T18:12:11Z
[ "python", "matplotlib" ]
Python: Plot a bar graph for a pandas data frame with x axis using a given column
39,278,279
<p>I want to plot a bar chart for the following pandas data frame on Jupyter Notebook. </p> <pre><code> | Month | number ------------------------- 0 | Apr | 6.5 1 | May | 7.3 2 | Jun | 3.9 3 | Jul | 5.1 4 | Aug | 4.1 </code></pre> <p>I did:</p> <pre><code>%matplotlib notebook ...
1
2016-09-01T18:10:45Z
39,278,970
<pre><code>store the data in a csv file. example i named my file plot.csv save data in following format in plot.csv Month,number Apr,6.5 May,7.3 Jun,3.9 Jul,5.1 Aug,4.1 import pandas as pd import matplotlib.pyplot as plt import numpy as np import csv #first read the data data = pd.read_csv('plot.csv',...
0
2016-09-01T18:56:50Z
[ "python", "pandas", "jupyter-notebook", "python-ggplot" ]
Python: Plot a bar graph for a pandas data frame with x axis using a given column
39,278,279
<p>I want to plot a bar chart for the following pandas data frame on Jupyter Notebook. </p> <pre><code> | Month | number ------------------------- 0 | Apr | 6.5 1 | May | 7.3 2 | Jun | 3.9 3 | Jul | 5.1 4 | Aug | 4.1 </code></pre> <p>I did:</p> <pre><code>%matplotlib notebook ...
1
2016-09-01T18:10:45Z
39,279,137
<p>You can simply specify <code>x</code> and <code>y</code> in your call to <code>plot</code> to get the bar plot you want.</p> <pre><code>trend_df.plot(x='Month', y='number', kind='bar') </code></pre> <p><a href="http://i.stack.imgur.com/KOJnc.png" rel="nofollow"><img src="http://i.stack.imgur.com/KOJnc.png" alt="en...
1
2016-09-01T19:07:18Z
[ "python", "pandas", "jupyter-notebook", "python-ggplot" ]
How to parse an HTML table with rowspans in Python?
39,278,376
<p><strong>The problem</strong></p> <p>I'm trying to parse an HTML table with rowspans in it, as in, I'm trying to parse my college schedule.</p> <p>I'm running into the problem where if the last row contains a rowspan, the next row is missing a TD where the rowspan is now that TD that is missing.</p> <p>I have no c...
23
2016-09-01T18:16:45Z
39,335,472
<p>Maybe it is better to use bs4 builtin function like "<strong>findAll</strong>" to parse your table.</p> <p>You may use the following code :</p> <pre><code>from pprint import pprint from bs4 import BeautifulSoup import requests r = requests.get("http://rooster.horizoncollege.nl/rstr/ECO/AMR/400-ECO/Roosters/36" ...
2
2016-09-05T17:44:16Z
[ "python", "html", "python-3.x", "beautifulsoup", "html-table" ]
How to parse an HTML table with rowspans in Python?
39,278,376
<p><strong>The problem</strong></p> <p>I'm trying to parse an HTML table with rowspans in it, as in, I'm trying to parse my college schedule.</p> <p>I'm running into the problem where if the last row contains a rowspan, the next row is missing a TD where the rowspan is now that TD that is missing.</p> <p>I have no c...
23
2016-09-01T18:16:45Z
39,336,433
<p>You'll have to track the rowspans on previous rows, one per column.</p> <p>You could do this simply by copying the integer value of a rowspan into a dictionary, and subsequent rows decrement the rowspan value until it drops to <code>1</code> (or we could store the integer value minus 1 and drop to <code>0</code> fo...
12
2016-09-05T19:11:14Z
[ "python", "html", "python-3.x", "beautifulsoup", "html-table" ]
Add an arbitrary element to an xrange()?
39,278,424
<p>In Python, it's more memory-efficient to use <code>xrange()</code> instead of <code>range</code> when iterating.</p> <p>The trouble I'm having is that I want to iterate over a large list -- such that I need to use <code>xrange()</code> and after that I want to check an arbitrary element.</p> <p>With <code>range()<...
2
2016-09-01T18:19:23Z
39,278,445
<p>I would recommend keeping the <code>arbitrary_element</code> check out of the loop, but if you want to make it part of the loop, you can use <a href="https://docs.python.org/2/library/itertools.html#itertools.chain"><code>itertools.chain</code></a>:</p> <pre><code>for i in itertools.chain(xrange(...), [arbitrary_el...
7
2016-09-01T18:21:35Z
[ "python", "generator", "xrange" ]
Add an arbitrary element to an xrange()?
39,278,424
<p>In Python, it's more memory-efficient to use <code>xrange()</code> instead of <code>range</code> when iterating.</p> <p>The trouble I'm having is that I want to iterate over a large list -- such that I need to use <code>xrange()</code> and after that I want to check an arbitrary element.</p> <p>With <code>range()<...
2
2016-09-01T18:19:23Z
39,278,459
<p><a href="https://docs.python.org/3/library/itertools.html#itertools.chain"><code>itertools.chain</code></a> lets you make a combined iterator from multiple iterables without concatenating them (so no expensive temporaries):</p> <pre><code>from itertools import chain # Must wrap arbitrary element in one-element tup...
8
2016-09-01T18:22:12Z
[ "python", "generator", "xrange" ]
Installing PIP on Windows 10 python 3.5
39,278,499
<p>I just started learning <strong>Python</strong>, and successfully downloaded <strong>Python 3.5</strong>. I attempted to download/upgrade PIP 8.1.2 multiple times using get-pip.py, which I ran (successfully I think) but when I attempted to execute <code>python get-pip.py</code> I got the error code:</p> <pre><code>...
-1
2016-09-01T18:24:36Z
39,278,586
<p>Not sure what you are asking. If you want to run <code>python get-pip.py</code> do it in a windows command prompt, not in the python interpreter. But I do not know why you would want to do that.</p>
0
2016-09-01T18:30:13Z
[ "python", "django", "python-3.x", "pip" ]
Installing PIP on Windows 10 python 3.5
39,278,499
<p>I just started learning <strong>Python</strong>, and successfully downloaded <strong>Python 3.5</strong>. I attempted to download/upgrade PIP 8.1.2 multiple times using get-pip.py, which I ran (successfully I think) but when I attempted to execute <code>python get-pip.py</code> I got the error code:</p> <pre><code>...
-1
2016-09-01T18:24:36Z
39,278,973
<p>You already have pip; there is no need to run <code>get-pip</code>. Upgrading can be done by pip itself.</p> <p>But the reason you are getting errors is that all these commands, including <code>pip</code> itself, should be run at the command line, not in the Python interpreter.</p>
0
2016-09-01T18:57:02Z
[ "python", "django", "python-3.x", "pip" ]
Installing PIP on Windows 10 python 3.5
39,278,499
<p>I just started learning <strong>Python</strong>, and successfully downloaded <strong>Python 3.5</strong>. I attempted to download/upgrade PIP 8.1.2 multiple times using get-pip.py, which I ran (successfully I think) but when I attempted to execute <code>python get-pip.py</code> I got the error code:</p> <pre><code>...
-1
2016-09-01T18:24:36Z
39,279,027
<p>You won't need to upgrade pip if you just downloaded python 3.5, go to where you have your Python3.5 file and open the folder Scripts, you will find pip.exe. Open powershell and use the cd command to move to the folder containing pip.exe. From here you can use pip install to get modules. </p> <p>Open Windows Powers...
0
2016-09-01T19:00:36Z
[ "python", "django", "python-3.x", "pip" ]
IntegrityError when creating relationships between objects in flask-sqlalchemy
39,278,555
<p>I struggle to build geo object hierarchy for my ridership-forecasting model.</p> <p>I have the following hierarchy of objects:</p> <pre><code>class Geoobject(m.db.Model): __tablename__ = 'geoobjects' id = m.db.Column(m.db.Integer, primary_key=True) name = m.db.Column(m.db.String) def __init__(self...
0
2016-09-01T18:27:59Z
39,283,708
<p>I've finally understood how it should work. When I add <code>foreign_keys</code> keyword, I should specify a column for it and link it to the relationship. Working code is below:</p> <pre><code>class TransportArea(Geoobject): __tablename__ = 'transport_areas' id = m.db.Column(m.db.Integer, m.db.ForeignKey(...
0
2016-09-02T03:05:30Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
how to insert new value into max heap and apply max_delete to heap
39,278,585
<p><em>Problem 1</em></p> <pre><code> 98 / \ / \ 67 89 / \ / \ / \ / \ 38 42 54 89 / \ / \ 17 25 </code></pre> <p>i want to insert 97 ...
-3
2016-09-01T18:30:13Z
39,281,244
<p>Look for this link so you can access by this link </p> <p><a href="https://cstechwiki.blogspot.in/2016/09/python-week-6-quiz-assignment-nptel.html" rel="nofollow">https://cstechwiki.blogspot.in/2016/09/python-week-6-quiz-assignment-nptel.html</a></p>
0
2016-09-01T21:36:13Z
[ "python", "python-3.x", "heap", "heapsort", "binary-heap" ]
how to insert new value into max heap and apply max_delete to heap
39,278,585
<p><em>Problem 1</em></p> <pre><code> 98 / \ / \ 67 89 / \ / \ / \ / \ 38 42 54 89 / \ / \ 17 25 </code></pre> <p>i want to insert 97 ...
-3
2016-09-01T18:30:13Z
39,283,320
<p>Your answers look correct. Let's take a closer look at why.</p> <p>In the first case, you have the heap:</p> <pre><code>[98,67,89,38,42,54,89,17,25] </code></pre> <p>You want to insert 97. So you add it to the end and then bubble it up:</p> <pre><code>[98,67,89,38,42,54,89,17,25,97] </code></pre> <p>You compare...
0
2016-09-02T02:08:41Z
[ "python", "python-3.x", "heap", "heapsort", "binary-heap" ]
How to Stop a Program Until a Specific Action Happens
39,278,603
<p>Using python and tkinter, is there a way I can run a part of the program, then stop it until the user clicks a specific button and then continue running?</p> <p>I mean:</p> <p>function - stop - click button - continue running.</p> <p>Necessary code for this:</p> <pre><code>def yellowClick(): yellow.configur...
0
2016-09-01T18:31:20Z
39,278,903
<p>have a look at this code sample. it works as is, copy/past it and it will run. There is no loop. It waits for the button click. I think you could initialize the program by loading a random pattern of colors into the "answers" list which could essentially be your levels.<br> <a href="http://stackoverflow.com/a/1...
-1
2016-09-01T18:52:30Z
[ "python", "tkinter" ]
Merging Dicts that have Lists of Dicts in Python 2.7
39,278,641
<p>I am trying to merge two <code>dict</code>s in Python that could be The same or one could have far less info </p> <p>ex.</p> <pre><code>master = {"a": 5564, "c": [{"d2":6}]} daily = { "a": 795, "b": 1337, "c": [{"d1": 2,"d2": 2,"d3": [{"e1": 4,"e2": 4}]}]} </code></pre> <p>They need to be merged so the output is ...
3
2016-09-01T18:34:15Z
39,278,882
<p>Here is a one linear using <code>collections.Counter()</code>:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt; C2 = Counter(daily) &gt;&gt;&gt; C1 = Counter(master) &gt;&gt;&gt; &gt;&gt;&gt; {k:reduce(lambda x,y : Counter(x)+Counter(y), v) if isinstance(v, list) and k in (C1.viewkeys() &amp; C...
5
2016-09-01T18:51:11Z
[ "python", "python-2.7", "dictionary" ]
Merging Dicts that have Lists of Dicts in Python 2.7
39,278,641
<p>I am trying to merge two <code>dict</code>s in Python that could be The same or one could have far less info </p> <p>ex.</p> <pre><code>master = {"a": 5564, "c": [{"d2":6}]} daily = { "a": 795, "b": 1337, "c": [{"d1": 2,"d2": 2,"d3": [{"e1": 4,"e2": 4}]}]} </code></pre> <p>They need to be merged so the output is ...
3
2016-09-01T18:34:15Z
39,279,206
<p>Here is a recursive solution. Though it cannot compete with Kasramvd's answer.</p> <pre><code>def merge(dic1, dic2): merged = dict(dic1, **dic2) # Merge dictionaries without adding values. Just exchanging them. # Similar to .update() but does not override subdicts. for key ...
1
2016-09-01T19:11:46Z
[ "python", "python-2.7", "dictionary" ]
PyCharm / OS X El Capitan / Python 3.5.2 - matplotlib not working in script
39,278,730
<p>Python noob here, apologies if this is has an obvious answer I should know. I'm using Python 3.5.2 via PyCharm in OSX El Capitan and I'm trying to run the following simple script to practise with matplotlib:</p> <pre><code>import matplotlib.pyplot as plt year = [1950,1970,1990,2010] pop = [2.159,3.692,5.263,6.972] ...
0
2016-09-01T18:41:14Z
39,278,934
<p>This can be caused by having another Python script in your project named <code>random.py</code> that is overriding the original library named Random.</p> <p>Try to rename or remove the <code>random.py</code> file and your script should work from within PyCharm and the command line.</p>
1
2016-09-01T18:54:25Z
[ "python", "osx", "matplotlib", "pycharm" ]
PySpark how to read file having string with multiple encoding
39,278,774
<p>I am writing a python spark utility to read files and do some transformation. File has large amount of data ( upto 12GB ). I use sc.textFile to create a RDD and logic is to pass each line from RDD to a map function which in turn split's the line by "," and run some data transformation( changing fields value based on...
3
2016-09-01T18:44:37Z
39,280,205
<p>You can set <code>use_unicode</code> to <code>False</code> when calling <code>textFile</code>. It will give you RDD of <code>str</code> objects (Python 2.x) or <code>bytes</code> objects (Python 3.x) which can further processed using desired encoding.</p> <pre><code>sc.textFile(path, use_unicode=False).map(lambda x...
0
2016-09-01T20:15:18Z
[ "python", "apache-spark", "pyspark" ]
replace certain number in DataFrame
39,278,847
<p>I am pretty new to Python programming and have a question about replacing certain conditional number in a DataFrame. for example, I have a dateframe with 5 days of data in each column, day1, day2, day3, day4 and day5. For each day, I have 5 data points with some of them larger than 5 for each day. Now I want to set...
1
2016-09-01T18:49:00Z
39,281,551
<p>This will iterate over the data in each column and change high values to 1. Iterating by rows instead of columns is an option with <code>iterrows</code> as discussed <a href="http://stackoverflow.com/a/11617194/6085135">here</a>, but it's generally slower.</p> <pre><code>import pandas as pd data = {'day1' : pd.Se...
0
2016-09-01T22:02:31Z
[ "python", "pandas", "replace", "dataframe" ]
replace certain number in DataFrame
39,278,847
<p>I am pretty new to Python programming and have a question about replacing certain conditional number in a DataFrame. for example, I have a dateframe with 5 days of data in each column, day1, day2, day3, day4 and day5. For each day, I have 5 data points with some of them larger than 5 for each day. Now I want to set...
1
2016-09-01T18:49:00Z
39,282,216
<p>To do this without looping (which is usually faster) you can do:</p> <pre><code>df[df &gt; 5] = 1 </code></pre>
1
2016-09-01T23:20:01Z
[ "python", "pandas", "replace", "dataframe" ]
Is it possible to run ubuntu terminal commands using DJango
39,279,007
<p>I am designing a simple website using DJango and my database is HBase. In some Part I need to save some files on HDFS, for example video file, and have it's URI. But my problem is I couldn't find any API for accessing HDFS through DJango so I decided to use ubuntu terminal command to upload and download data on HDFS...
4
2016-09-01T18:59:09Z
39,279,043
<p>have django make a call to a subprocess like the one below. each string in the command should be a string in a list.</p> <pre><code>import subprocess subprocess.call(["ls", "-l"]) </code></pre>
0
2016-09-01T19:01:43Z
[ "python", "django", "hadoop", "hbase", "hdfs" ]
Is it possible to run ubuntu terminal commands using DJango
39,279,007
<p>I am designing a simple website using DJango and my database is HBase. In some Part I need to save some files on HDFS, for example video file, and have it's URI. But my problem is I couldn't find any API for accessing HDFS through DJango so I decided to use ubuntu terminal command to upload and download data on HDFS...
4
2016-09-01T18:59:09Z
39,284,318
<p>You don't need to search for Django implemented libraries, Django is written in python and python is providing libraries for it. </p> <p>An alternative solution</p> <pre><code>import subprocess subprocess.Popen(['python', 'manage.py', 'runserver']) </code></pre> <p>you can excecute shell commands using subprocess...
0
2016-09-02T04:28:17Z
[ "python", "django", "hadoop", "hbase", "hdfs" ]
Iterating a loop using await or yield causes error
39,279,064
<p>I come from the land of <code>Twisted</code>/<a href="https://github.com/twisted/klein" rel="nofollow"><code>Klein</code></a>. I come in peace and to ask for <code>Tornado</code> help. I'm investigating Tornado and how its take on async differs from Twisted. Twisted has something similar to <code>gen.coroutine</co...
1
2016-09-01T19:02:49Z
39,279,258
<p>Let's have a look at <code>gen.Task</code> <a href="http://www.tornadoweb.org/en/stable/gen.html#tornado.gen.Task" rel="nofollow">docs</a>:</p> <blockquote> <p>Adapts a callback-based asynchronous function for use in coroutines.</p> <p>Takes a function (and optional additional arguments) and runs it with tho...
0
2016-09-01T19:14:37Z
[ "python", "python-3.x", "asynchronous", "tornado", "coroutine" ]
Iterating a loop using await or yield causes error
39,279,064
<p>I come from the land of <code>Twisted</code>/<a href="https://github.com/twisted/klein" rel="nofollow"><code>Klein</code></a>. I come in peace and to ask for <code>Tornado</code> help. I'm investigating Tornado and how its take on async differs from Twisted. Twisted has something similar to <code>gen.coroutine</co...
1
2016-09-01T19:02:49Z
39,279,951
<p>You cannot and must not await <code>append</code>, since it isn't a coroutine and doesn't return a Future. If you want to occasionally yield to allow other coroutines to proceed using Tornado's event loop, await <a href="http://www.tornadoweb.org/en/stable/gen.html#tornado.gen.moment" rel="nofollow">gen.moment</a>.<...
1
2016-09-01T19:59:33Z
[ "python", "python-3.x", "asynchronous", "tornado", "coroutine" ]
Iterating a loop using await or yield causes error
39,279,064
<p>I come from the land of <code>Twisted</code>/<a href="https://github.com/twisted/klein" rel="nofollow"><code>Klein</code></a>. I come in peace and to ask for <code>Tornado</code> help. I'm investigating Tornado and how its take on async differs from Twisted. Twisted has something similar to <code>gen.coroutine</co...
1
2016-09-01T19:02:49Z
39,283,598
<p><code>list.append()</code> returns <code>None</code>, so it's a little misleading that your Klein sample looks like it's yielding some object. This is equivalent to <code>jsonlist.append(...); yield</code> as two separate statements. The tornado equivalent would be to do <code>await gen.moment</code> in place of the...
1
2016-09-02T02:47:36Z
[ "python", "python-3.x", "asynchronous", "tornado", "coroutine" ]
How to run django runserver over TLS 1.2
39,279,079
<p>I'm testing Stripe orders on my local Mac OS X machine. I am implementing this code:</p> <pre><code>stripe.api_key = settings.STRIPE_SECRET order = stripe.Order.create( currency = 'usd', email = 'j@awesomecom', items = [ { "type":'sku'...
1
2016-09-01T19:03:33Z
39,300,617
<p>This is not a django issue, but operating system and language issue.</p> <p>I'm using Mac OS X and and a brew version of python. I'm also using virtual env which has its own copy of python and open ssl.</p> <p>I did the following:</p> <p>I first downloaded the most recent version of XCode which updates OpenSSL. ...
0
2016-09-02T20:58:16Z
[ "python", "django", "python-2.7", "ssl", "tls1.2" ]
How to run django runserver over TLS 1.2
39,279,079
<p>I'm testing Stripe orders on my local Mac OS X machine. I am implementing this code:</p> <pre><code>stripe.api_key = settings.STRIPE_SECRET order = stripe.Order.create( currency = 'usd', email = 'j@awesomecom', items = [ { "type":'sku'...
1
2016-09-01T19:03:33Z
39,376,684
<p>If you have already tried to update openssl and python (using brew), and still does not work, make sure your settings have DEBUG = False. </p> <p>Watch this thread for more information <a href="https://code.google.com/p/googleappengine/issues/detail?id=13207" rel="nofollow">https://code.google.com/p/googleappengine...
0
2016-09-07T18:15:21Z
[ "python", "django", "python-2.7", "ssl", "tls1.2" ]
How to run django runserver over TLS 1.2
39,279,079
<p>I'm testing Stripe orders on my local Mac OS X machine. I am implementing this code:</p> <pre><code>stripe.api_key = settings.STRIPE_SECRET order = stripe.Order.create( currency = 'usd', email = 'j@awesomecom', items = [ { "type":'sku'...
1
2016-09-01T19:03:33Z
39,936,720
<p>I solved installing this libraries:</p> <pre><code>pip install urllib3 pip install pyopenssl pip install ndg-httpsclient pip install pyasn1 </code></pre> <p>solution from: </p> <blockquote> <p><a href="https://github.com/pinax/pinax-stripe/issues/267" rel="nofollow">https://github.com/pinax/pinax-stripe/issues/...
0
2016-10-08T19:52:18Z
[ "python", "django", "python-2.7", "ssl", "tls1.2" ]
tarfile - Adding files from different drives
39,279,090
<p>I am trying to archive and compress multiple directories spread along multiple drives using the tarfile library. The problem is that tarfile merges the paths even if two files are stored in different drives. For example:</p> <pre><code>import tarfile with tarfile.open(r"D:\Temp\archive.tar.gz", "w:gz") as tf: t...
4
2016-09-01T19:04:11Z
39,279,182
<p>You'll need to use <code>tarfile.addfile()</code> instead of <code>tarfile.add()</code> :</p> <p>With TarInfo you can specify the filename which will be used in the archive.</p> <p>Exemple :</p> <pre><code>with open(r"C:\files\foo", "rb") as ff: ti = tf.gettarinfo(arcname="C/files/foo", fileobj=ff) tf.add...
3
2016-09-01T19:09:44Z
[ "python", "gzip", "tar", "tarfile" ]
tarfile - Adding files from different drives
39,279,090
<p>I am trying to archive and compress multiple directories spread along multiple drives using the tarfile library. The problem is that tarfile merges the paths even if two files are stored in different drives. For example:</p> <pre><code>import tarfile with tarfile.open(r"D:\Temp\archive.tar.gz", "w:gz") as tf: t...
4
2016-09-01T19:04:11Z
39,290,513
<p>Thanks <strong>Loïc</strong> for your answer, it helped me find the actual answer I was looking for. (And also made me waste about a hour because I got really confused with the linux and windows style paths you mixed up in your answer)...</p> <pre><code>import os import tarfile def create_archive(paths, arc_paths...
0
2016-09-02T10:46:04Z
[ "python", "gzip", "tar", "tarfile" ]
Setting the n_estimators argument using **kwargs (Scikit Learn)
39,279,121
<p>I am trying to follow <a href="http://blog.yhat.com/posts/predicting-customer-churn-with-sklearn.html" rel="nofollow">this</a> tutorial to learn the machine learning based prediction but I have got two questions on it?</p> <p>Ques1. How to set the <code>n_estimators</code> in the below piece of code, otherwise it w...
2
2016-09-01T19:06:37Z
39,282,189
<p>For your first question, in the above code you would call <code>run_cv(X,y,SVC,n_classifiers=100)</code>, the <code>**kwargs</code> will pass this to the classifier initializer with the step <code>clf = clf_class(**kwargs)</code>.</p> <p>For your second question, the cross validation in the code you've linked is ju...
2
2016-09-01T23:16:55Z
[ "python", "machine-learning", "scikit-learn" ]
Curl error when downloading json object
39,279,291
<p>getting the following error...</p> <pre><code>curl: (56) GnuTLS recv error (-54): Error in the pull function. </code></pre> <p>...when using the following command to curl a json file</p> <pre><code>curl -L -o commerce.json http://www.commerce.gov/data.json </code></pre> <p>Any advice? I'm not familiar with curl....
1
2016-09-01T19:17:07Z
39,279,400
<p>the error code 56 means the following, as described here <a href="https://curl.haxx.se/docs/manpage.html" rel="nofollow">https://curl.haxx.se/docs/manpage.html</a></p> <blockquote> <p>56 Failure in receiving network data.</p> </blockquote> <p>you should use a <strong>-v</strong> to see what's happen.</p> <p>I d...
1
2016-09-01T19:24:12Z
[ "python", "json", "bash", "curl" ]
Curl error when downloading json object
39,279,291
<p>getting the following error...</p> <pre><code>curl: (56) GnuTLS recv error (-54): Error in the pull function. </code></pre> <p>...when using the following command to curl a json file</p> <pre><code>curl -L -o commerce.json http://www.commerce.gov/data.json </code></pre> <p>Any advice? I'm not familiar with curl....
1
2016-09-01T19:17:07Z
39,279,784
<p>In bash you can use:</p> <pre><code>wget -O commerce.json http://www.commerce.gov/data.json </code></pre> <p>Otherwise, a Python solution to this would be:</p> <p>First you will need to install the Python <code>wget</code> library, then you can use the code:</p> <pre><code>import wget url = 'http://www.commerce....
1
2016-09-01T19:48:29Z
[ "python", "json", "bash", "curl" ]
Python function definition
39,279,298
<pre><code>def CsMatrix(X not None): </code></pre> <p>I meet this piece of code. For <strong><em>X not None</em></strong>, I haven't met this kind of syntax? So I write my test code:</p> <pre><code>def test(x not None): pass </code></pre> <p>However, I got SyntaxError: invalid syntax. Can anyone explain this sy...
-4
2016-09-01T19:17:31Z
39,279,330
<p>You can not do that. What you can do is</p> <pre><code>def test(x): if x is None: return ... # All the further actions with x </code></pre>
0
2016-09-01T19:19:18Z
[ "python" ]
Python function definition
39,279,298
<pre><code>def CsMatrix(X not None): </code></pre> <p>I meet this piece of code. For <strong><em>X not None</em></strong>, I haven't met this kind of syntax? So I write my test code:</p> <pre><code>def test(x not None): pass </code></pre> <p>However, I got SyntaxError: invalid syntax. Can anyone explain this sy...
-4
2016-09-01T19:17:31Z
39,279,514
<p>That's not valid syntax neither for <a href="https://docs.python.org/2.0/ref/function.html" rel="nofollow">python 2.x</a> nor <a href="http://www.python-course.eu/python3_functions.php" rel="nofollow">python 3.x</a>, maybe you wanted to declare your function with a <code>None</code> default value, something like thi...
0
2016-09-01T19:31:03Z
[ "python" ]
Python function definition
39,279,298
<pre><code>def CsMatrix(X not None): </code></pre> <p>I meet this piece of code. For <strong><em>X not None</em></strong>, I haven't met this kind of syntax? So I write my test code:</p> <pre><code>def test(x not None): pass </code></pre> <p>However, I got SyntaxError: invalid syntax. Can anyone explain this sy...
-4
2016-09-01T19:17:31Z
39,279,797
<pre><code>def CsMatrix(X not None): pass </code></pre> <p>Is it possible that you mis-read it? Definitely not valid... If you have the link to thesite where you seen it, could you post it?</p> <p>You also said "For x not None" implying it might be used in a for loop as well? This would also be bad syntax. You c...
0
2016-09-01T19:49:14Z
[ "python" ]
Quickly count the number of objects in bson document
39,279,323
<p>I'd like to calculated the number of documents stored in a mongodb bson file without having to import the file into the db via mongo restore. </p> <p>The best I've been able to come up with in python is </p> <pre><code>bson_doc = open('./archive.bson','rb') it = bson.decode_file_iter(bson_doc) total = sum(1 for _...
2
2016-09-01T19:18:51Z
39,279,826
<p>I don't have a file at hand to try, but I believe there's a way - if you'll parse the data by hand.</p> <p>The <a href="https://github.com/mongodb/mongo-python-driver/blob/0b34f9702ca8bed45792a53287d33a2292b99152/bson/__init__.py#L855" rel="nofollow">source for <code>bson.decode_file_iter</code></a> (sans the docst...
1
2016-09-01T19:51:18Z
[ "python", "mongodb", "bson" ]
Create RDD of arrays
39,279,334
<p><sub>As I live in agony for <a href="http://stackoverflow.com/questions/39260820/is-sparks-kmeans-unable-to-handle-bigdata">Is Spark&#39;s KMeans unable to handle bigdata?</a>, I want to create a minimal example to demonstrate the drama. For that, I want to create the data, rather than read it.</sub></p> <p>Here is...
1
2016-09-01T19:19:32Z
39,279,755
<p>Spark provides utilities for generating random RDDs out-of-the box. In PySpark these are located in <code>pyspark.mllib.random.RandomRDDs</code>. For example:</p> <pre><code>from pyspark.mllib.random import RandomRDDs rdd = RandomRDDs.uniformVectorRDD(sc, 100000000, 64) type(rdd.first()) ## numpy.ndarray rdd.fir...
3
2016-09-01T19:46:46Z
[ "python", "arrays", "apache-spark", "bigdata", "distributed-computing" ]
Adding labels to stacked bar chart
39,279,404
<p>I'm plotting a cross-tabulation of various offices within certain categories. I'd like to put together a horizontal stacked bar chart where each office and its value is labeled. </p> <p>Here's some example code: </p> <pre><code>df = pd.DataFrame({'office1': pd.Series([1,np.nan,np.nan], index=['catA', 'catB', 'catC...
1
2016-09-01T19:24:25Z
39,280,239
<p>Figured it out. If I iterate through the columns of each row of the dataframe I can build up a list of the labels I need that matches the progression of the rectangles in <code>ax.patches</code>. Solution below: </p> <pre><code>labels = [] for j in df.columns: for i in df.index: label = str(j)+": " + st...
1
2016-09-01T20:18:35Z
[ "python", "pandas", "matplotlib" ]
Adding labels to stacked bar chart
39,279,404
<p>I'm plotting a cross-tabulation of various offices within certain categories. I'd like to put together a horizontal stacked bar chart where each office and its value is labeled. </p> <p>Here's some example code: </p> <pre><code>df = pd.DataFrame({'office1': pd.Series([1,np.nan,np.nan], index=['catA', 'catB', 'catC...
1
2016-09-01T19:24:25Z
39,280,262
<p>You could have also just changed the function <code>annotateBars()</code> to:</p> <pre><code>def annotateBars(row, ax=ax): curr_value = 0 for col in row.index: value = row[col] if (str(value) != 'nan'): ax.text(curr_value + (value)/2, labeltonum(row.name), col+","+str(value), ha...
1
2016-09-01T20:20:20Z
[ "python", "pandas", "matplotlib" ]
Append dataframe to dict
39,279,439
<p>I've created a dict of dicts structured in such a way that the key is the department ('ABC') then the date (01.08) is the key and values are { product name (A), Units (0), Revenue (0)}. This structure continues for several departments. See dict of dict printout below. </p> <pre><code>'ABC': ...
0
2016-09-01T19:26:16Z
39,279,677
<p>Skipping to question #2: I'd recommend using a single dataframe to store all of your information. It will be much easier to work with than keeping columnar data in a dict of dicts. Set the date as the main index and either use a separate column for each field ('deptA-revenue') or use multi-indexing. You can then sto...
0
2016-09-01T19:41:39Z
[ "python", "pandas", "dictionary" ]
Append dataframe to dict
39,279,439
<p>I've created a dict of dicts structured in such a way that the key is the department ('ABC') then the date (01.08) is the key and values are { product name (A), Units (0), Revenue (0)}. This structure continues for several departments. See dict of dict printout below. </p> <pre><code>'ABC': ...
0
2016-09-01T19:26:16Z
39,280,902
<p>To print in the desired order, you need to transpose the rows &amp; columns in the dates dictionary. It is probably easiest to total the rows while doing that. This makes the second object you mentioned unnecessary. Except for the formatting, something like this should work:</p> <pre><code>for dept, dates in df...
0
2016-09-01T21:09:57Z
[ "python", "pandas", "dictionary" ]
ValueError: RDD is empty-- Pyspark (Windows Standalone)
39,279,702
<p>I am trying to create an RDD but spark not creating it, throwing back error, pasted below;</p> <pre><code>data = records.map(lambda r: LabeledPoint(extract_label(r), extract_features(r))) first_point = data.first() Py4JJavaError Traceback (most recent call last) &lt;ipython-input-19-d71...
0
2016-09-01T19:43:14Z
39,292,939
<p>Your <code>records</code> is empty. You could verify by calling <code>records.first()</code>.</p> <p>Calling <code>first</code> on an empty RDD raises error, but not <code>collect</code>. For example,</p> <pre><code>records = sc.parallelize([]) records.map(lambda x: x).collect() </code></pre> <blockquote> <p>[...
0
2016-09-02T12:53:10Z
[ "python", "pyspark", "rdd" ]
scipy.spatial ValueError when trying to run kdtree
39,279,781
<p><strong>Background:</strong> I am trying to run a nearest neighbor using the <code>cKDtree</code> function on a shapefile that has 201 records with lat/lons against a time series dataset of 8760 hours (total hours in a year). I am getting an error, naturally I looked it up. I found this: <a href="http://stackoverflo...
1
2016-09-01T19:48:23Z
39,280,874
<p>So it seems I need to read up on the differences of <code>vstack</code> &amp; <code>column_stack</code> and the use of transpose i.e. <code>.T</code>. If anyone has the same issue here is what I changed to make the <code>cKDtree</code> work. Hopefully it will help if someone else runs into this issue. Many thanks to...
2
2016-09-01T21:06:59Z
[ "python", "numpy", "kdtree" ]
Python dictionary update and refinement loop
39,279,782
<p>I am trying to create a loop that will further refine a user defined dictionary after original pass and parse of user string:</p> <pre><code>product_info = {'make': [], 'year': [], 'color': []} make = ['honda','bmw','acura'] year = ['2013','2014','2015','2016'] colors = ['black','grey','red','blue'] user_input = ...
1
2016-09-01T19:48:24Z
39,280,250
<pre><code>while [] in product_info.values(): for key in product_info: if product_info[key] == []: print("What",key) user_input = raw_input() for each in user_input.split(' '): if each in make: key = 'make' product_...
1
2016-09-01T20:19:45Z
[ "python", "dictionary" ]