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 |
|---|---|---|---|---|---|---|---|---|---|
Unable to import even after installing the packages | 37,879,138 | <p>I have installed numpy, scipy, scikit learn and other required packages. Still when I try to import them in python, it shows no module found.</p>
<pre><code>pip install -U numpy scipy scikit-learn
Requirement already up-to-date: numpy in /usr/lib/python2.7/dist-packages
Collecting scipy
Downloading scipy-0.17.1-c... | 1 | 2016-06-17T10:23:45Z | 37,879,249 | <p>You haven't installed the libs you got error 13 permission denied. Reinstall them using the command:</p>
<pre><code>sudo pip install numpy scipy scikit-learn
</code></pre>
| 2 | 2016-06-17T10:28:11Z | [
"python",
"ubuntu",
"numpy",
"scipy",
"scikit-learn"
] |
Find values in a pandas dataframe containing a substring | 37,879,217 | <p>I have a pandas dataframe with string values and I would like to be able to return a subset of the dataframe where the values contain some substring. This is easy to do on a series in this way (example adapted from pandas documentation):</p>
<pre><code>import pandas as pd
import numpy as np
s4 = pd.Series(['A', 'B'... | 1 | 2016-06-17T10:26:46Z | 37,879,428 | <p>Another solution is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>contains</code></a>:</p>
<pre><code>mask = df.app... | 2 | 2016-06-17T10:35:17Z | [
"python",
"string",
"pandas",
"dataframe",
"contains"
] |
How to change the value of an entire array based on one value in Python | 37,879,289 | <p>Let's say I have this array:</p>
<pre><code>import numpy as np
np.array([[0,2,7],[-3,4,0],[12,10,12]])
</code></pre>
<p>I'm trying to change the values of one column if one or more values in the column are less than zero. The code should be general and not just for this array
How do I set all of the values in the ... | 0 | 2016-06-17T10:30:12Z | 37,880,210 | <p>You could use <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">a mask</a> to filter the columns where some values are negative. That same mask can then be used to also select the replacement value: in the example below the columns where at least o... | 2 | 2016-06-17T11:16:17Z | [
"python",
"arrays",
"numpy"
] |
Python 2.7 - Help on pandas_reader | 37,879,296 | <p>Am replicating the code I have got from another website where in "pandas.io.data" has been commented out. Instead am using "pandas_datareader"</p>
<pre><code># Commodity Channel Index Python Code
# Load the necessary packages and modules
import pandas as pd
#import pandas.io.data as web
import pandas_datareader.da... | 1 | 2016-06-17T10:30:31Z | 37,879,692 | <p>In version <code>0.18.0</code> was API changed - <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#window-functions-are-now-methods" rel="nofollow">window functions are now methods</a>:</p>
<p>So use:</p>
<pre><code>CCI = pd.Series((TP - TP.rolling(ndays).mean()) / (0.015 * TP.rolling(ndays).std()... | 1 | 2016-06-17T10:48:40Z | [
"python",
"pandas",
"dataframe"
] |
Doing math with formatting characters | 37,879,499 | <p>I'm quite new to programming and just started learning some python.
I've come across a problem that I can't find a solution for. Hope you can help.</p>
<pre><code>height = 74.0 # inches
cm = 2.54 # inches
print "He's %f * %f centimeters tall." % (height, cm)
</code></pre>
<p>So the problem is I want the console ... | 0 | 2016-06-17T10:39:28Z | 37,879,535 | <p>Not sure if this is what your'e asking<br>
But <code>print "He's %f centimeters tall." % (height * cm)</code><br>
Will print one number and it will be <code>height</code> multiplied by <code>cm</code></p>
| 1 | 2016-06-17T10:41:26Z | [
"python",
"formatting",
"character"
] |
Django REST Framework - can't override list in ListAPIView | 37,879,675 | <p>I am using Django REST Framework to create an endpoint that will produce a PDF document. The PDF document will have information that corresponds to a particular <code>Department</code>. I have two desired functionalities -- to be able to download a PDF document, and to be able to preview the document within the brow... | 1 | 2016-06-17T10:48:05Z | 37,883,036 | <p>replace list method with below code, I think it will work </p>
<pre><code>class ResultDocumentDetailView(generics.ListAPIView):
queryset = Department.objects.all()
lookup_field = 'department_pk'
lookup_url_kwarg = 'department_pk'
def list(self, request, *args, **kwargs):
queryset = self.ge... | 1 | 2016-06-17T13:36:19Z | [
"python",
"django",
"rest",
"django-rest-framework"
] |
Django REST Framework - can't override list in ListAPIView | 37,879,675 | <p>I am using Django REST Framework to create an endpoint that will produce a PDF document. The PDF document will have information that corresponds to a particular <code>Department</code>. I have two desired functionalities -- to be able to download a PDF document, and to be able to preview the document within the brow... | 1 | 2016-06-17T10:48:05Z | 37,886,516 | <p>In your <code>document_app/urls.py</code>, you are incorrectly passing <code>ResultDocumentDetailView</code> as an argument instead of a viewset. </p>
<p><strong>Router <a href="http://www.django-rest-framework.org/api-guide/routers/#usage" rel="nofollow">while registering</a> accepts a <code>ViewSet</code> instead... | 1 | 2016-06-17T16:43:49Z | [
"python",
"django",
"rest",
"django-rest-framework"
] |
Create all combinations of a single column from a file into two columns using awk or shell script or python | 37,879,707 | <p>I have a file which contains airport code like below</p>
<pre><code>ATQ
HYD
BLR
GOI
AMD
CCJ
TRV
</code></pre>
<p>from the same file i have to create source destination mapping like below in gawk.</p>
<pre><code> src dest
ATQ HYD
ATQ BLR
ATQ GOI
ATQ AMD
ATQ CCJ
ATQ TRV
HYD ATQ
HYD BLR
HYD AMD
....
..... | -2 | 2016-06-17T10:49:18Z | 37,880,606 | <p>A simple <code>awk</code> script could do this. Just store all the elements of the line in array and run a loop for each element for every other element without repetitions which don't make sense. </p>
<pre><code>$ awk 'BEGIN {printf("%s\t%s\n" ,"src", "dest")}
{
line[++c] = $1
}
END {
for ( i = 1... | 1 | 2016-06-17T11:36:54Z | [
"python",
"shell",
"awk"
] |
Create all combinations of a single column from a file into two columns using awk or shell script or python | 37,879,707 | <p>I have a file which contains airport code like below</p>
<pre><code>ATQ
HYD
BLR
GOI
AMD
CCJ
TRV
</code></pre>
<p>from the same file i have to create source destination mapping like below in gawk.</p>
<pre><code> src dest
ATQ HYD
ATQ BLR
ATQ GOI
ATQ AMD
ATQ CCJ
ATQ TRV
HYD ATQ
HYD BLR
HYD AMD
....
..... | -2 | 2016-06-17T10:49:18Z | 37,880,627 | <p>Version in bash assuming your airport list is in <code>a.txt</code> file:</p>
<pre><code>echo "src dest";
for src in `cat a.txt`; do
for dest in `cat a.txt`; do
if [ $src != $dest ]; then
echo "$src $dest";
fi
done;
done
</code></pre>
| 0 | 2016-06-17T11:38:01Z | [
"python",
"shell",
"awk"
] |
Create all combinations of a single column from a file into two columns using awk or shell script or python | 37,879,707 | <p>I have a file which contains airport code like below</p>
<pre><code>ATQ
HYD
BLR
GOI
AMD
CCJ
TRV
</code></pre>
<p>from the same file i have to create source destination mapping like below in gawk.</p>
<pre><code> src dest
ATQ HYD
ATQ BLR
ATQ GOI
ATQ AMD
ATQ CCJ
ATQ TRV
HYD ATQ
HYD BLR
HYD AMD
....
..... | -2 | 2016-06-17T10:49:18Z | 37,883,089 | <p>One liner:</p>
<pre><code> echo "src dest"; cat /tmp/air | while read s; do for d in `cat /tmp/air`; do if [ $s != $d ]; then echo $s $d; fi; done; done
</code></pre>
<p>Will output:</p>
<pre><code>src dest
ATQ HYD
ATQ BLR
ATQ GOI
ATQ AMD
ATQ CCJ
ATQ TRV
HYD ATQ
HYD BLR
HYD GOI
HYD AMD
HYD CCJ
HYD TRV
BLR ATQ
BLR... | 1 | 2016-06-17T13:38:59Z | [
"python",
"shell",
"awk"
] |
Python: float number get part before "e" | 37,879,737 | <p>I am doing some calculation using Python. In a step, there will be array which looks like</p>
<pre><code>[1.23e-21, 2.32e-14, 8.87e-12, .....]
</code></pre>
<p>I just want to get the part before <code>e..</code>, i.e., I want to get array</p>
<pre><code>[1.23, 2.32, 8.87,.....]
</code></pre>
<p>Is there any meth... | 1 | 2016-06-17T10:51:01Z | 37,879,849 | <p>one of possibly many solutions:</p>
<pre><code>from math import floor, log10
x = [1.23e-21, 2.32e-14, 8.87e-12, 1.51, 1.214e10]
res = [t/10**floor(log10(abs(t))) if t!= 0 else 0 for t in x]
</code></pre>
| 4 | 2016-06-17T10:57:09Z | [
"python",
"arrays",
"floating-point"
] |
Python: float number get part before "e" | 37,879,737 | <p>I am doing some calculation using Python. In a step, there will be array which looks like</p>
<pre><code>[1.23e-21, 2.32e-14, 8.87e-12, .....]
</code></pre>
<p>I just want to get the part before <code>e..</code>, i.e., I want to get array</p>
<pre><code>[1.23, 2.32, 8.87,.....]
</code></pre>
<p>Is there any meth... | 1 | 2016-06-17T10:51:01Z | 37,879,885 | <p>You could convert the entries to strings and split them at the <code>e</code>. Combine that with list comprehension and you get:</p>
<pre><code>numbers = [1.23e-21, 2.32e-14, 8.87e-12]
result = [float(str(i).split('e')[0]) for i in numbers]
</code></pre>
<p>If all of your numbers have exactly two decimal place... | 2 | 2016-06-17T10:59:13Z | [
"python",
"arrays",
"floating-point"
] |
How to extract data from SQL query and assign it to Odoo class columns? | 37,879,787 | <p>I have been trying to extract data from a .mdb database and get it into Odoo 8 class columns. </p>
<p>This is my .py file</p>
<pre><code> class attendance_biometric(osv.Model):
_name="attendance.biometric"
_rec_name='name'
_columns={
'fdate':fields.datetime('From Date'),
'tdate':field... | 7 | 2016-06-17T10:53:49Z | 37,883,579 | <p>You need to understand the fetch types in odoo.</p>
<pre><code> - cr.dictfetchall()
It will returns the list of dictionary.
Example:
[{'column1':'value_column1',}, {'column2':'value_column2',}]
- cr.dictfetchone()
It will return dictionary (Single record)
Example:
... | 2 | 2016-06-17T14:01:08Z | [
"python",
"ms-access",
"odoo-8",
"openerp-8",
"odoo-9"
] |
How to extract data from SQL query and assign it to Odoo class columns? | 37,879,787 | <p>I have been trying to extract data from a .mdb database and get it into Odoo 8 class columns. </p>
<p>This is my .py file</p>
<pre><code> class attendance_biometric(osv.Model):
_name="attendance.biometric"
_rec_name='name'
_columns={
'fdate':fields.datetime('From Date'),
'tdate':field... | 7 | 2016-06-17T10:53:49Z | 37,915,331 | <p>Try to install /upgrade pyodbc version .. refer <a href="https://code.google.com/archive/p/pyodbc/wikis/Building.wiki" rel="nofollow">this</a> link</p>
| 0 | 2016-06-20T05:47:22Z | [
"python",
"ms-access",
"odoo-8",
"openerp-8",
"odoo-9"
] |
How can I change datetime format of x-axis values in matplotlib using python? | 37,879,842 | <p>How can I make this plot's x-axis looks better?</p>
<p><a href="http://i.stack.imgur.com/Zxy7W.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zxy7W.png" alt="image"></a></p>
<p>I tried using <code>plt.xticks(rotation=70)</code> but it still cuts my numbers..</p>
<p>As you can see, it shows the date in the... | 0 | 2016-06-17T10:56:41Z | 37,879,972 | <p>You have to set date formatter, look at the example from <a href="http://matplotlib.org/examples/pylab_examples/date_demo1.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/date_demo1.html</a>:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.finance import quotes_historical_yahoo_och... | 0 | 2016-06-17T11:03:27Z | [
"python",
"datetime",
"pandas",
"matplotlib",
"plot"
] |
urllib alongwith json to save to a variable | 37,879,971 | <p>Please correct my code. I am trying to save the result of this web page in json format to a variable in python.</p>
<hr>
<p><strong>Error</strong>:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Varen/Desktop/json_v1.py", line 5, in <module>
json.dump(link, f)
File "C:\Python27\lib... | 0 | 2016-06-17T11:03:17Z | 37,880,095 | <p>You need to read the data from the file like object returned by <code>urlopen()</code>:</p>
<pre><code>import urllib
import json
link = urllib.urlopen("http://www.saferproducts.gov/RestWebServices/Recall?RecallDateStart=2015-01-01&RecallDateEnd=2015-12-31&format=json")
with open('link.json', 'w') as f:
... | 0 | 2016-06-17T11:10:11Z | [
"python",
"json",
"python-2.7"
] |
Concatenation of pandas DataFrames including rows' source-dataframe/-category | 37,880,032 | <p>I need to <code>pandas.concatenate(...,axis=0,...)</code> multiple DataFrames so that the resulting DataFrame has a new column holding information about which dataset a row belongs to, but drop the implicit indices of the original DataFrames.</p>
<p>In this MWE for example, we have from multiple countries (A and B,... | 0 | 2016-06-17T11:07:02Z | 37,880,444 | <p>Using both <code>ignore_index</code> and <code>keys</code> is somewhat conflicting - the first says to toss away the index information, and the second says to use it to make a <code>MultiIndex</code>. That said, I think pandas could give a better message (maybe just raise a <code>ValueError</code>) if you pass both... | 0 | 2016-06-17T11:28:43Z | [
"python",
"pandas"
] |
Getting text from a URL and transforming before entry in array - Python | 37,880,066 | <p>I'm getting this from web page:</p>
<pre><code>channels = getting_channels.group()
</code></pre>
<p>)/AV1/AV2/AV3/AV4</p>
<p>and I want to put in array the next values:
{"emite":"AV1"},{"emite":"AV2"},{"emite":"AV3"},{"emite":"AV4"}</p>
<p>¿Is it possible? </p>
| 0 | 2016-06-17T11:08:51Z | 37,880,393 | <p>The following code assumes that the there is going to be a string before the first slash that is useless to you. The total number of slashes is irrelevant (they don't have to be 4)</p>
<pre><code>astring = ')/AV1/AV2/AV3/AV4'
result = []
for i in range(1, len(astring.split('/'))):
result.append({'emite':astring... | 1 | 2016-06-17T11:25:55Z | [
"python",
"arrays",
"parsing"
] |
Can't render videos loaded through OpenCV in PyQt4 gui on another computer through a python standalone executable. giving no errors does nothing | 37,880,073 | <p>Here is the py2exe setup script:</p>
<pre><code> from setuptools import setup
import py2exe
from glob import glob
import numpy
import sys
import cv2
SETUP_DICT = {
'windows': [{
'script': 'C:\\Users\\Codemen1\\Documents\\Python Scripts\\video.py',
}],
'zipfile': 'lib/library.zip',
'data_files': (
('... | -1 | 2016-06-17T11:09:12Z | 37,914,738 | <p>I solved the problem. py2exe couldn't fetch all the ffmpeg,highgui & other dll & pyd files. So have to manually import all those file to my standable executable files & it solved the problem. Thank you. </p>
| 0 | 2016-06-20T04:42:27Z | [
"python",
"opencv",
"video",
"pyqt",
"py2exe"
] |
environment variable for django settings? | 37,880,196 | <p>I've been using Django for over a year and have never needed to 'define the environment variable DJANGO_SETTINGS_MODULE as I am asked to do in the following error message:</p>
<pre><code>E
======================================================================
ERROR: setUpClass (__main__.SmokeTest)
-----------------... | 0 | 2016-06-17T11:15:30Z | 37,880,514 | <p>Are you sure in your <strong>manage.py</strong> have something like this</p>
<pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projectname.settings")
</code></pre>
<p><a href="https://docs.djangoproject.com/en/1.9/ref/django-admin/" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/django-admin/</... | 0 | 2016-06-17T11:32:33Z | [
"python",
"django",
"environment-variables"
] |
environment variable for django settings? | 37,880,196 | <p>I've been using Django for over a year and have never needed to 'define the environment variable DJANGO_SETTINGS_MODULE as I am asked to do in the following error message:</p>
<pre><code>E
======================================================================
ERROR: setUpClass (__main__.SmokeTest)
-----------------... | 0 | 2016-06-17T11:15:30Z | 37,881,709 | <blockquote>
<p>"@brunodesthuilliers in the command line I am in my app directory, I run python tests.py "</p>
</blockquote>
<p>Well that's not going to work (at least not that easily). Why don't you just use the builtin management "test" command ?</p>
<pre><code> #> cd your/project/root
#> python manage.py... | 1 | 2016-06-17T12:33:56Z | [
"python",
"django",
"environment-variables"
] |
django-autocomplete-light: Select2 static files not checked out | 37,880,262 | <p>I'm trying the Django-autocomplete-light package following <a href="https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html" rel="nofollow">this tutorial</a> and I'm stuck in this error:</p>
<blockquote>
<p>?: (dal_select2.E001) Select2 static files not checked out </p>
<p>HINT: Run git subm... | 0 | 2016-06-17T11:18:51Z | 38,395,546 | <p>I am having the same issue. Were you able to solve this?</p>
<p>Edit: I found a solution for this. Please note that pip install of zip/archive of the repo will not include submodules automatically. Thus you need to install the package using following command. This will install the latest master version of the packa... | 0 | 2016-07-15T11:56:39Z | [
"python",
"django",
"select2",
"django-autocomplete-light"
] |
2D discrete colour plot using discrete variables | 37,880,399 | <p>I am looking for a way to graph some data in a human readable format. I have data from simulations that contains a frame number, protein residue number and protein secondary structure state. Frame number as integers and the secondary structure state as strings. For example:</p>
<p>0 1&n... | 2 | 2016-06-17T11:26:17Z | 37,882,152 | <p>How about the following example:</p>
<ol>
<li>You define the data first (or you'll read these in from a file).</li>
<li>define a color mapping for the single values (see <code>colormap</code>, below and the <a href="http://matplotlib.org/1.3.1/api/colors_api.html" rel="nofollow">color documentation of matplotlib</a... | 1 | 2016-06-17T12:56:55Z | [
"python",
"matplotlib",
"plot",
"simulation",
"contour"
] |
2D discrete colour plot using discrete variables | 37,880,399 | <p>I am looking for a way to graph some data in a human readable format. I have data from simulations that contains a frame number, protein residue number and protein secondary structure state. Frame number as integers and the secondary structure state as strings. For example:</p>
<p>0 1&n... | 2 | 2016-06-17T11:26:17Z | 37,890,148 | <p>Here is an alternate method using a <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html" rel="nofollow">Seaborn heatmap</a> that may be better suited for large datasets.</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors im... | 0 | 2016-06-17T20:46:15Z | [
"python",
"matplotlib",
"plot",
"simulation",
"contour"
] |
Bluetooth Bluepy not finding all characteristics | 37,880,453 | <p>I am using the <a href="https://github.com/IanHarvey/bluepy" rel="nofollow">bluepy library</a> to communicate with a bluetooth device but it is not showing me all the characteristics.</p>
<p>When I run the following using gatttool I get:</p>
<pre><code>[EE:50:F0:F8:3C:FF][LE]> char-desc 0x0019 0xffff
handle: 0x... | 1 | 2016-06-17T11:29:13Z | 39,514,501 | <p>You are mistaken as to what those additional characteristics are. The uuids that begin with <code>000028xx</code> are characteristic "declarations" as seen here: <a href="https://www.bluetooth.com/specifications/gatt/declarations" rel="nofollow">gatt declaration spec</a>, and the uuids that begin with <code>000029xx... | 0 | 2016-09-15T15:06:44Z | [
"python",
"bluetooth",
"bluetooth-lowenergy",
"characteristics"
] |
Change resources available to the processes from Python | 37,880,469 | <p>Is there a way to change resources available to a running process from <code>Python</code>? Namely I would like to change <code>Max open files</code> <code>soft</code>:<code>hard</code> limit.</p>
<p>I know I can use <code>ulimit -n 1024000</code> and spawn process from that shell, but that would require stopping t... | 0 | 2016-06-17T11:29:52Z | 37,880,680 | <p>Take another look at the <code>resource</code> library. The function <a href="https://docs.python.org/3/library/resource.html#resource.prlimit" rel="nofollow"><code>resource.prlimit()</code></a> takes a <code>pid</code> as its first argument, and raises <code>ProcessLookupError</code> if a process by that ID cannot ... | 1 | 2016-06-17T11:40:46Z | [
"python",
"linux",
"python-2.7"
] |
Python2.7 search zipfiles for .kml containing string without unzipping | 37,880,611 | <p>I am trying to write my first python script below. I want to search through a read only archive on an HPC to look in zipfiles contained within folders with a variety of other folder/file types. If the zip contains a .kml file I want to print the line in there starting with the string <code><coordinates></code>... | 0 | 2016-06-17T11:37:09Z | 37,880,795 | <p>When you run:</p>
<pre><code>kfile = file('*.kml')
</code></pre>
<p>You are trying to open a single file named exactly <code>*.kml</code>, which is not what you want. If you want to process all <code>*.kml</code> files, you will need to (a) get a list of matching files and then (b) process those files in a list.<... | 1 | 2016-06-17T11:47:23Z | [
"python",
"python-2.7",
"kml",
"zipfile"
] |
How to preserve the index from pivoting? | 37,880,669 | <p>I have a dataframe (fx_return):</p>
<pre><code>index_date ccy rate
====================================
2016-06-01 CHF 1.013017272
2016-06-01 EUR 1.1178
2016-06-01 GBP 1.44255
2016-06-01 USD 1
2016-06-02 CHF 1.010560356
2016-06-02 EUR 1.11615
2016-06-0... | 1 | 2016-06-17T11:40:14Z | 37,880,735 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> instead <code>melt</code>:</p>
<pre... | 1 | 2016-06-17T11:43:53Z | [
"python",
"pandas",
"dataframe",
"pivot",
"reshape"
] |
How to illustrate different ranges on an x-axis? | 37,880,671 | <p>How to illustrate different ranges on an x-axis?</p>
<p>In a previous post (<a href="http://stackoverflow.com/questions/21560861/how-to-create-box-plot-based-on-min-and-max-alone">How to create box plot based on min and max alone</a>) it was described how to create a box plot based on min and max alone. It is clos... | 0 | 2016-06-17T11:40:22Z | 37,880,822 | <p>there's a <a href="http://matplotlib.org/examples/pylab_examples/boxplot_demo.html" rel="nofollow">matplotlib example</a> which provides different layouts, including horizontal ranges. I've condensed this example to the following code:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
# fake up som... | 0 | 2016-06-17T11:48:31Z | [
"python",
"ggplot2"
] |
Multiplication of two positive numbers gives a negative output in Python 3 | 37,880,740 | <p>I have a DataFrame <code>df1</code> : </p>
<pre><code>df1.head() =
wght num_links
id_y id_x
3 133 0.000203 2
186 0.000203 2
5 6 0.000203 2
98 0.000203 2
184 0.000203 ... | 6 | 2016-06-17T11:44:03Z | 37,881,207 | <p>If you get the type of <code>count()</code> (i.e. <code>type(df1['wght'].count())</code>) you'll receive:</p>
<pre><code><class 'numpy.int32'>
</code></pre>
<p>So try your computation with:</p>
<pre><code>n = df1['wght'].count().astype(np.int64)
n*(n-1)*2
</code></pre>
| 2 | 2016-06-17T12:08:15Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Multiplication of two positive numbers gives a negative output in Python 3 | 37,880,740 | <p>I have a DataFrame <code>df1</code> : </p>
<pre><code>df1.head() =
wght num_links
id_y id_x
3 133 0.000203 2
186 0.000203 2
5 6 0.000203 2
98 0.000203 2
184 0.000203 ... | 6 | 2016-06-17T11:44:03Z | 37,881,228 | <p>You are experiencing <code>np.int32</code> overflow, so just use <code>len(df)</code> instead of <code>df.column.count()</code>.</p>
<p>Here is a small demo:</p>
<pre><code>In [149]: x = pd.DataFrame(np.random.randint(0,100,size=(137736, 3)), columns=list('ABC'))
In [150]: x.A.count() * (x.A.count() - 1) * 2
Out[... | 6 | 2016-06-17T12:09:17Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Multiplication of two positive numbers gives a negative output in Python 3 | 37,880,740 | <p>I have a DataFrame <code>df1</code> : </p>
<pre><code>df1.head() =
wght num_links
id_y id_x
3 133 0.000203 2
186 0.000203 2
5 6 0.000203 2
98 0.000203 2
184 0.000203 ... | 6 | 2016-06-17T11:44:03Z | 37,881,466 | <p>You can pass <code>df1['wght'].count()</code> to long constructor like this, to ensure it is long.</p>
<pre><code>N = long(df1['wght'].count())
</code></pre>
<p>Although storing to any variable </p>
<pre><code>N = df1['wght'].count()
</code></pre>
<p>should work as the class int has a <code>__mul__</code> metho... | 1 | 2016-06-17T12:21:33Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
scheduling pyspark notebooks | 37,880,908 | <p>I have an ipython notebook that contains some PySpark code on a cluster. Currently we are using oozie to run these notebooks on Hadoop via HUE. The setup feels less than ideal and we were wondering if there is an alternative. </p>
<p>We first convert the <code>.ipynb</code> file into a <code>.py</code> file and mov... | 1 | 2016-06-17T11:53:12Z | 37,883,585 | <p><a href="https://issues.apache.org/jira/browse/OOZIE-2482" rel="nofollow">OOZIE-2482</a> was added to Oozie's master lately, which should make running PySpark jobs easier. It's not in a release yet unfortunately.</p>
<p>A Spark Action can be added to your workflow, the py file should be specified in the tag. The p... | 0 | 2016-06-17T14:01:33Z | [
"python",
"hadoop",
"pyspark",
"oozie",
"jupyter-notebook"
] |
How to do a line break in python? | 37,881,201 | <p>this is my first question on stackoverflow.
I'm trying to do problem sets on OCW online classes in Python, and I don't know how to debug my code. I work with IDLE, and Python 2.7.</p>
<p>Here is my code:</p>
<pre><code>balance = float(raw_input("Enter the outstanding balance on your credit card: "))
annual_itst = ... | -3 | 2016-06-17T12:07:44Z | 37,881,610 | <p>To print out a newline, use a string containing a newline: <code>"\n"</code>.</p>
<p>To print out a complex string like you want, you can use multiple <code>print</code> statements (which normally add their own newlines), or assemble your string and then print it.</p>
<pre><code>print("Month:", i)
print("Minimum m... | 0 | 2016-06-17T12:28:26Z | [
"python",
"python-2.7",
"line-breaks"
] |
How to do a line break in python? | 37,881,201 | <p>this is my first question on stackoverflow.
I'm trying to do problem sets on OCW online classes in Python, and I don't know how to debug my code. I work with IDLE, and Python 2.7.</p>
<p>Here is my code:</p>
<pre><code>balance = float(raw_input("Enter the outstanding balance on your credit card: "))
annual_itst = ... | -3 | 2016-06-17T12:07:44Z | 37,882,042 | <p>Here it is,
learn about operators and formatting to print output</p>
<pre><code>balance = float(raw_input("Enter the outstanding balance on your credit card: "))
annual_itst = float(raw_input("Enter the annual credit card interest rate as a decimal: "))
min_paymt_rate = float(raw_input("Enter the minimum monthly pa... | 0 | 2016-06-17T12:51:14Z | [
"python",
"python-2.7",
"line-breaks"
] |
How to do a line break in python? | 37,881,201 | <p>this is my first question on stackoverflow.
I'm trying to do problem sets on OCW online classes in Python, and I don't know how to debug my code. I work with IDLE, and Python 2.7.</p>
<p>Here is my code:</p>
<pre><code>balance = float(raw_input("Enter the outstanding balance on your credit card: "))
annual_itst = ... | -3 | 2016-06-17T12:07:44Z | 37,882,060 | <p>You have to convert int to string for concatenation and you can print each line separately to print in different lines.</p>
<pre><code>balance = float(raw_input("Enter the outstanding balance on your credit card: "))
annual_itst = float(raw_input("Enter the annual credit card interest rate as a decimal: "))
min_pay... | 0 | 2016-06-17T12:52:16Z | [
"python",
"python-2.7",
"line-breaks"
] |
Python - cx_oracle print variable amount of column names | 37,881,202 | <p>Based on a given SQL-Statement, I extract from a database to CSV with thefollowing function:</p>
<pre><code>def extract_from_db():
with open('myfile.csv','w') as outfile:
for row in cursor:
outfile.write(str(row[0])+";"+str(row[1])+";"+str(row[2])+";"+str(row[3])+";"+str(row[4])+";"+str(row[... | 0 | 2016-06-17T12:07:47Z | 37,883,021 | <p>You could use the <a href="http://cx-oracle.readthedocs.io/en/latest/cursor.html#Cursor.description" rel="nofollow">description</a></p>
<pre><code>desc = cursor.description
</code></pre>
<p>function. It returns a sequence of 7 item sequences and you can get the column names from</p>
<pre><code>for seq in desc:
... | 1 | 2016-06-17T13:35:31Z | [
"python",
"database",
"csv",
"export-to-csv",
"cx-oracle"
] |
Python - cx_oracle print variable amount of column names | 37,881,202 | <p>Based on a given SQL-Statement, I extract from a database to CSV with thefollowing function:</p>
<pre><code>def extract_from_db():
with open('myfile.csv','w') as outfile:
for row in cursor:
outfile.write(str(row[0])+";"+str(row[1])+";"+str(row[2])+";"+str(row[3])+";"+str(row[4])+";"+str(row[... | 0 | 2016-06-17T12:07:47Z | 37,898,480 | <p>Ebrahim Jackoet has already mentioned that you can use cursor.description to get the column names from your query. If you don't have a very large number of rows to process, though, the <a href="https://docs.python.org/3/library/csv.html%20csv" rel="nofollow">csv module</a> is built in and makes writing rows simple. ... | 1 | 2016-06-18T15:13:14Z | [
"python",
"database",
"csv",
"export-to-csv",
"cx-oracle"
] |
Creating a maze-like game with links between objects | 37,881,300 | <p>I'm writing a text-based RPG that will create its own cave system according to the following rules:</p>
<ol>
<li><p>It must randomly generate links</p></li>
<li><p>One cave may only link to another once</p></li>
<li><p>Each cave must have four links in total</p></li>
</ol>
<p>This is what I have so far:</p>
<pre>... | 1 | 2016-06-17T12:13:02Z | 37,881,840 | <p>Why not create an matrix (n, m) where each element is a possible cave. This way every cave will have 4 neighbors except the caves on the "borders".</p>
<p>Considering you are on the cave (i, j), your neighbors are (i-1, j), (i+1, j), (i, j-1) and (i, j+1).</p>
<p>And for encapsulation, a CaveContainer object would... | 1 | 2016-06-17T12:40:59Z | [
"python",
"class",
"python-3.x"
] |
Creating a maze-like game with links between objects | 37,881,300 | <p>I'm writing a text-based RPG that will create its own cave system according to the following rules:</p>
<ol>
<li><p>It must randomly generate links</p></li>
<li><p>One cave may only link to another once</p></li>
<li><p>Each cave must have four links in total</p></li>
</ol>
<p>This is what I have so far:</p>
<pre>... | 1 | 2016-06-17T12:13:02Z | 37,882,947 | <p>Here's a fairly simple brute-force algorithm. We use sets to hold the links for each cave. The <code>make_links</code> function tries to assign 4 random bidirectional links to each cave. If it fails, it returns <code>None</code> and we simply call it again until we get a valid cave system. </p>
<pre><code>from ran... | 1 | 2016-06-17T13:32:34Z | [
"python",
"class",
"python-3.x"
] |
How to click multiple times on QRadioButton but only run function once? | 37,881,408 | <p>I have 2 radio buttons. The first one, <code>radio1</code>, is connected to a function <code>func()</code> and inside this function connects a push button, <code>pushButton</code>, to another function <code>print_me()</code>.</p>
<p>This is the code stripped down:</p>
<pre><code>radio = self.dockwidget.radioButton... | 0 | 2016-06-17T12:18:39Z | 37,881,667 | <p>Have a global variable and set it to either <code>True</code> or <code>False</code>. Then add an <code>if</code> statement to your code (In this example the global variable name is <code>clicked_radio_button</code>):</p>
<pre><code>radio = self.dockwidget.radioButton
radio.clicked.connect(func)
clicked_radio_button... | 1 | 2016-06-17T12:31:06Z | [
"python",
"qt-designer",
"qpushbutton",
"qradiobutton"
] |
Reshaping Numpy Arrays to a multidimensional array | 37,881,420 | <p>For a numpy array I have found that</p>
<pre><code>x = numpy.array([]).reshape(0,4)
</code></pre>
<p>is fine and allows me to append (0,4) arrays to x without the array losing its structure (ie it dosnt just become a list of numbers). However, when I try</p>
<pre><code>x = numpy.array([]).reshape(2,3)
</code></pr... | 1 | 2016-06-17T12:19:10Z | 37,881,727 | <p><code>reshape</code> is not an 'append' function. It reshapes the array you give it to the dimensions you want. </p>
<p><code>np.array([]).reshape(0,4)</code> works because you reshape a zero element array to a 0x4(=0 elements) array.<br>
<code>np.reshape([]).reshape(2,3)</code> doesn't work because you're trying t... | 0 | 2016-06-17T12:34:45Z | [
"python",
"numpy"
] |
Reshaping Numpy Arrays to a multidimensional array | 37,881,420 | <p>For a numpy array I have found that</p>
<pre><code>x = numpy.array([]).reshape(0,4)
</code></pre>
<p>is fine and allows me to append (0,4) arrays to x without the array losing its structure (ie it dosnt just become a list of numbers). However, when I try</p>
<pre><code>x = numpy.array([]).reshape(2,3)
</code></pr... | 1 | 2016-06-17T12:19:10Z | 37,881,803 | <p>This out put will explain what it mean to reshape an array... </p>
<pre><code>np.array([2, 3, 4, 5, 6, 7]).reshape(2, 3)
</code></pre>
<p>Output - </p>
<pre><code>array([[2, 3, 4],
[5, 6, 7]])
</code></pre>
<p>So reshaping just means <strong>reshaping an array</strong>. reshape(0, 4) means convert the ... | 1 | 2016-06-17T12:38:18Z | [
"python",
"numpy"
] |
Pybrain - Neural Network Accuracy is very low | 37,881,447 | <pre><code>i=0
noofclasses = 2
alldata = ClassificationDataSet(400, 1, noofclasses)
while i<len(data):
alldata.addSample(data[i],labels[i])
i=i+1
tstdata_temp, trndata_temp = alldata.splitWithProportion( 10 )
tstdata = ClassificationDataSet(400, 1, noofclasses)
for n in xrange(0, tstdata_temp.getLength()):... | -3 | 2016-06-17T12:20:52Z | 37,916,548 | <p>sorry, After adding bias term, Accuracy was pretty good.</p>
<p>fnn = buildNetwork( trndata.indim, 10, trndata.outdim, bias = True, outclass=SoftmaxLayer )</p>
| 0 | 2016-06-20T07:13:32Z | [
"python",
"neural-network",
"pybrain"
] |
How do I convert a numpy ND-array to a CFFI C++ array and back again? | 37,881,503 | <p>I want to pass a numpy array into some(one else's) C++ code via CFFI. Assume I cannot (in any sense) change the C++ code, whose interface is:</p>
<pre><code>double CompactPD_LH(int Nbins, double * DataArray, void * ParamsArray ) {
...
}
</code></pre>
<p>I pass Nbins as a python integer, ParamsArray as a dict -... | 1 | 2016-06-17T12:23:28Z | 37,895,696 | <p>Thanks @morningsun!</p>
<pre><code>dd=np.ascontiguousarray(data.T)
DataArray = ffi.cast("double *",dd.ctypes.data)
result=lib.CompactPD_LH(Nbins,DataArray,ParamsArray)
</code></pre>
<p>works!</p>
| 2 | 2016-06-18T10:00:01Z | [
"python",
"c++",
"arrays",
"numpy",
"python-cffi"
] |
Split SQL insert statement into key-value pairs | 37,881,660 | <p>Given the following statement as a string</p>
<pre><code>stmt = "insert into table (col1, col2, col3) values (100, '() string with parantheses ()', 2.3);"
</code></pre>
<p>I am trying to find a regular expression (or any other way if there is a better one) to split that string into a list <code>["(col1, col2, col3... | 1 | 2016-06-17T12:30:45Z | 37,881,842 | <p>I have run into this problem before, having multiple parentheses in a statement makes regex pretty difficult. You could tokenize the string and treat the parentheses as one token. To handle the nested parentheses have a variable called parenCount or something and start it 1 when you find the first left parentheses. ... | -1 | 2016-06-17T12:41:06Z | [
"python",
"regex"
] |
Split SQL insert statement into key-value pairs | 37,881,660 | <p>Given the following statement as a string</p>
<pre><code>stmt = "insert into table (col1, col2, col3) values (100, '() string with parantheses ()', 2.3);"
</code></pre>
<p>I am trying to find a regular expression (or any other way if there is a better one) to split that string into a list <code>["(col1, col2, col3... | 1 | 2016-06-17T12:30:45Z | 37,882,014 | <p>Well, this is not beautiful but assuming the string you work with will always be an insert statement (based on their characteristics), this should work:</p>
<pre><code>stmt = "insert into table (col1, col2, col3) values (100, '() string with parantheses ()', 2.3);"
# if it will always be an insert statement, the f... | 0 | 2016-06-17T12:50:12Z | [
"python",
"regex"
] |
Split SQL insert statement into key-value pairs | 37,881,660 | <p>Given the following statement as a string</p>
<pre><code>stmt = "insert into table (col1, col2, col3) values (100, '() string with parantheses ()', 2.3);"
</code></pre>
<p>I am trying to find a regular expression (or any other way if there is a better one) to split that string into a list <code>["(col1, col2, col3... | 1 | 2016-06-17T12:30:45Z | 37,882,278 | <p>If your statement is always in the same format, you can use some basic string operations and <code>ast.literal_eval</code> to evaluate the values... Note that this will also end up with the values having types of int, str and float.</p>
<pre><code>import ast
import csv
stmt = "insert into table (col1, col2, col3) ... | 1 | 2016-06-17T13:02:36Z | [
"python",
"regex"
] |
Split SQL insert statement into key-value pairs | 37,881,660 | <p>Given the following statement as a string</p>
<pre><code>stmt = "insert into table (col1, col2, col3) values (100, '() string with parantheses ()', 2.3);"
</code></pre>
<p>I am trying to find a regular expression (or any other way if there is a better one) to split that string into a list <code>["(col1, col2, col3... | 1 | 2016-06-17T12:30:45Z | 37,882,550 | <p>Why mess with these ugly hacks? Let SQL parse SQL. Here's a complete program to turn any insert statement into tuples:</p>
<pre><code>my_insert = """insert into some_table (col1, col2, col3) values (100,
'() string with parantheses ()', 2.3);"""
import sqlite3
conn = sqlite... | 1 | 2016-06-17T13:15:08Z | [
"python",
"regex"
] |
Split SQL insert statement into key-value pairs | 37,881,660 | <p>Given the following statement as a string</p>
<pre><code>stmt = "insert into table (col1, col2, col3) values (100, '() string with parantheses ()', 2.3);"
</code></pre>
<p>I am trying to find a regular expression (or any other way if there is a better one) to split that string into a list <code>["(col1, col2, col3... | 1 | 2016-06-17T12:30:45Z | 37,883,115 | <p>If you really want this, your regex will end up being complicated with <em>assertion expressions</em>:</p>
<blockquote>
<p>don't have to split the string by 'values'</p>
</blockquote>
<pre><code>match = re.findall("""(?<!\') # No preceeding ' before (
\(
(?!\)) # A c... | 0 | 2016-06-17T13:39:37Z | [
"python",
"regex"
] |
Plotting an average | 37,881,778 | <p>I want to plot an average of 24 arrays, but had an error message ''list' object has no attribute 'shape''. Where's the mistake?</p>
<pre><code>empty_array=numpy.zeros[2,30,100]
for x in range (1,25):
array = array[x,:,:,:]
empty_array += array
average = map(lambda x:x/24,empty_array)
plt.figure(1)
plt.pcol... | 0 | 2016-06-17T12:37:14Z | 37,881,833 | <p><code>empty_array=[2,30,100]</code> does not create an empty array. It is a list containing three numbers. You are looking for <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.zeros.html" rel="nofollow">numpy.zeros</a></p>
| 1 | 2016-06-17T12:40:32Z | [
"python",
"arrays",
"plot"
] |
Plotting an average | 37,881,778 | <p>I want to plot an average of 24 arrays, but had an error message ''list' object has no attribute 'shape''. Where's the mistake?</p>
<pre><code>empty_array=numpy.zeros[2,30,100]
for x in range (1,25):
array = array[x,:,:,:]
empty_array += array
average = map(lambda x:x/24,empty_array)
plt.figure(1)
plt.pcol... | 0 | 2016-06-17T12:37:14Z | 37,883,226 | <p>It looks like you want to compute the average in one of the axis. You can simply use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.mean.html" rel="nofollow"><code>np.mean()</code></a> for this. Example from docs:</p>
<pre><code>>>> a = np.array([[1, 2], [3, 4]])
>>> np.... | 1 | 2016-06-17T13:44:13Z | [
"python",
"arrays",
"plot"
] |
NameError: global name 'PlotDataItem' is not defined | 37,881,784 | <p>I would want to plot the amplitude of an audio signal using pyqtgraph library in python. I'm using PlotDataItem(xValues, yValues) defined here : <a href="http://www.pyqtgraph.org/documentation/graphicsItems/plotdataitem.html" rel="nofollow">http://www.pyqtgraph.org/documentation/graphicsItems/plotdataitem.html</a>
S... | 0 | 2016-06-17T12:37:26Z | 37,882,144 | <p>The documentation you linked to says</p>
<blockquote>
<p>Instances of PlotDataItem are usually created by plot() methods such as pyqtgraph.plot() and PlotItem.plot()</p>
</blockquote>
<p>So you have to import pyqtgraph and then call plot like this:</p>
<pre><code>import pyqtgraph
plot = pyqtgraph.plot(length, ... | 0 | 2016-06-17T12:56:32Z | [
"python",
"pyqtgraph"
] |
Why does it start counting the elements in this list from list[-1] instead of list[0]? (Python 3) | 37,881,859 | <p>(It's easier to explain if I show the code first)</p>
<pre><code>import random
inventory = 100
while True:
print('inventory: $' + str(inventory))
print('how much do you wager?')
wager = input()
keys = ['a', 'b']
cA = random.sample(keys, 1)
print('pick "a" or "b"')
guess = input()
if ... | 0 | 2016-06-17T12:41:57Z | 37,881,878 | <p>Your list has only <strong>one</strong> element in it:</p>
<pre><code>cA = random.sample(keys, 1)
</code></pre>
<p>You asked for a random sample of length 1.</p>
<p><code>-1</code> works because that is an index relative to the end. With a list of length 1, <code>listobj[-1]</code> is the same object as <code>lis... | 4 | 2016-06-17T12:43:03Z | [
"python",
"list",
"python-3.x",
"indexing"
] |
Why does it start counting the elements in this list from list[-1] instead of list[0]? (Python 3) | 37,881,859 | <p>(It's easier to explain if I show the code first)</p>
<pre><code>import random
inventory = 100
while True:
print('inventory: $' + str(inventory))
print('how much do you wager?')
wager = input()
keys = ['a', 'b']
cA = random.sample(keys, 1)
print('pick "a" or "b"')
guess = input()
if ... | 0 | 2016-06-17T12:41:57Z | 37,881,924 | <pre><code>import random
inventory = 100
while True:
print('inventory: $' + str(inventory))
print('how much do you wager?')
wager = input()
keys = ['a', 'b']
cA = random.sample(keys, 1)
print('pick "a" or "b"')
guess = input()
if guess == cA <------------ cA has the element that ... | 0 | 2016-06-17T12:45:32Z | [
"python",
"list",
"python-3.x",
"indexing"
] |
How to decode JSON where the values are separated in lines | 37,881,870 | <p>I have this JSON encoded text:</p>
<pre><code>{"port":27277,"velocityX":-0.4,"time":199888,"powerup":"Wall","player":0,"positionX":2331,"velocityY":4.2,"positionY":1130,"type":"powerupUse"}
{"port":27277,"velocityX":0,"time":199921,"powerup":"Homing Missile","player":0,"positionX":2319,"velocityY":0,"positionY":117... | 0 | 2016-06-17T12:42:35Z | 37,881,939 | <p>The problem is that you have more jsons in the file, not only one. Split the text with "\n" separator and then call json.loads for every row.</p>
| 1 | 2016-06-17T12:46:10Z | [
"python",
"json",
"python-3.x"
] |
How to decode JSON where the values are separated in lines | 37,881,870 | <p>I have this JSON encoded text:</p>
<pre><code>{"port":27277,"velocityX":-0.4,"time":199888,"powerup":"Wall","player":0,"positionX":2331,"velocityY":4.2,"positionY":1130,"type":"powerupUse"}
{"port":27277,"velocityX":0,"time":199921,"powerup":"Homing Missile","player":0,"positionX":2319,"velocityY":0,"positionY":117... | 0 | 2016-06-17T12:42:35Z | 37,881,970 | <p><code>json.loads</code> loads <em>a single JSON object</em>. In your case, <code>log.txt</code> contains multiple JSON objects separated by <code>"\n"</code>. You can iterate over the lines in the file and call <code>json.loads</code> on each of them:</p>
<pre><code>with open("log.txt") as log:
jsondata = [json... | 4 | 2016-06-17T12:48:15Z | [
"python",
"json",
"python-3.x"
] |
How to decode JSON where the values are separated in lines | 37,881,870 | <p>I have this JSON encoded text:</p>
<pre><code>{"port":27277,"velocityX":-0.4,"time":199888,"powerup":"Wall","player":0,"positionX":2331,"velocityY":4.2,"positionY":1130,"type":"powerupUse"}
{"port":27277,"velocityX":0,"time":199921,"powerup":"Homing Missile","player":0,"positionX":2319,"velocityY":0,"positionY":117... | 0 | 2016-06-17T12:42:35Z | 37,882,371 | <p>I would do something like this: </p>
<pre><code>import json
jsondata = 0
with open("log.txt") as log_file:
jsondata = [json.loads(line) for line in log_file]
for line in jsondata:
if 'port' in line:
print("Port: {}".format(line['port']))
if 'time' in line:
print("Time: {}".format(line... | 0 | 2016-06-17T13:07:06Z | [
"python",
"json",
"python-3.x"
] |
How do I see which python loggers have been created by the logging module? | 37,881,894 | <p>How can I obtain a list or dict of <code>logging.Logger</code> objects which have been created in the current Python process by the <code>logging.getLogger()</code> method?</p>
<p><em>Note: this already has an answer <a href="http://code.activestate.com/lists/python-list/621740/" rel="nofollow">here</a>, but I thou... | 0 | 2016-06-17T12:43:58Z | 37,881,919 | <p>You can retrieve a dict of loggers with <code>logging.Logger.manager.LoggerDict</code>.</p>
<p>This is a dict of the format:</p>
<pre><code>{
'<name passed in logging.getLogger(name) call>': <logging.Logger instance>,
...
}
</code></pre>
| 0 | 2016-06-17T12:45:22Z | [
"python",
"logging"
] |
Django admin sessions: change default value | 37,881,916 | <p>How can I change the default expiration time value for the session in Django admin? what is the function to override?</p>
<p>Thanks.</p>
| 0 | 2016-06-17T12:45:12Z | 37,883,181 | <p>Djangos <code>set_expiry</code> is used to set expiration time for a session.</p>
<p>You can read about it <a href="https://docs.djangoproject.com/en/1.9/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.set_expiry" rel="nofollow">here</a>.</p>
<p>You usually will set it before logging in the... | 0 | 2016-06-17T13:42:07Z | [
"python",
"django",
"django-admin"
] |
Django admin sessions: change default value | 37,881,916 | <p>How can I change the default expiration time value for the session in Django admin? what is the function to override?</p>
<p>Thanks.</p>
| 0 | 2016-06-17T12:45:12Z | 37,894,159 | <p>You can use </p>
<pre><code>SESSION_COOKIE_AGE = 5 * 60
</code></pre>
<p>This is for every user and also independent of whether user is active or inactive.</p>
| 1 | 2016-06-18T06:51:54Z | [
"python",
"django",
"django-admin"
] |
Error: IOStream has no fileno - SUMO | 37,882,022 | <p>I am trying to run SUMO through traci interface. I copy pasted this example from this <a href="http://sumo.dlr.de/wiki/TraCI/Interfacing_TraCI_from_Python" rel="nofollow">link</a>. The code is as follows</p>
<pre><code>import os, sys
import subprocess
if 'SUMO_HOME' in os.environ:
tools = os.path.join(os.envi... | -2 | 2016-06-17T12:50:18Z | 37,882,511 | <p>Looks like you're running in an <code>ipython</code> notebook. They have non-standard "standard" I/O streams that can't be used like a "true" file object (because they're really data queues, not pipes, so they don't have a file descriptor to use for low level I/O).</p>
<p>You can't use them with libraries (like <co... | 2 | 2016-06-17T13:13:20Z | [
"python"
] |
Error: IOStream has no fileno - SUMO | 37,882,022 | <p>I am trying to run SUMO through traci interface. I copy pasted this example from this <a href="http://sumo.dlr.de/wiki/TraCI/Interfacing_TraCI_from_Python" rel="nofollow">link</a>. The code is as follows</p>
<pre><code>import os, sys
import subprocess
if 'SUMO_HOME' in os.environ:
tools = os.path.join(os.envi... | -2 | 2016-06-17T12:50:18Z | 38,094,939 | <p>The problem was that my command line used Python 2 whereas the spyder IDE used python 3. Since I wont be needing to pass any more arguments to the stdin, I removed the option and simply tried to open the sumo-gui with <code>subprocess</code> as follows. It works now.</p>
<pre><code>PORT = 8813
sumoBinary = 'C:/Prog... | 0 | 2016-06-29T09:03:55Z | [
"python"
] |
Error: IOStream has no fileno - SUMO | 37,882,022 | <p>I am trying to run SUMO through traci interface. I copy pasted this example from this <a href="http://sumo.dlr.de/wiki/TraCI/Interfacing_TraCI_from_Python" rel="nofollow">link</a>. The code is as follows</p>
<pre><code>import os, sys
import subprocess
if 'SUMO_HOME' in os.environ:
tools = os.path.join(os.envi... | -2 | 2016-06-17T12:50:18Z | 38,262,242 | <p>You could also work around the issue by doing something like:</p>
<pre><code>import sys
import subprocess
p = subprocess.Popen(['ls', '-alh'],
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
p.wait()
sys.stderr.write(p.stderr.read())
sys.stdout.write(p.stdout.read())
</c... | 0 | 2016-07-08T08:33:16Z | [
"python"
] |
NaiveBayes model training with separate training set and data using pyspark | 37,882,201 | <p>So, I am trying to train a naive bayes clasifier. Went into a lot of trouble of preprocessing the data and I have now produced two RDDs:</p>
<ol>
<li>Traininng set: composed of a set of sparse-vectors;</li>
<li>Labels: a <strong>corresponding</strong> list of labels (0,1) for every vector.</li>
</ol>
<p>I need to... | 0 | 2016-06-17T12:59:19Z | 37,884,071 | <p>I was able to solve this by first collecting the SparseVectors RDDs - effectively converting them to a list. Then, I run a function that constructed a list of
labelledpoint objects: </p>
<pre><code>def final_form_4_training(SVs, labels):
"""
:param SVs: List of Sparse vectors.
:param labels: List of la... | 0 | 2016-06-17T14:25:20Z | [
"python",
"classification",
"pyspark",
"naivebayes"
] |
Unable to add PyQt module to Python project | 37,882,202 | <p>I'm struggling to figure out how to include the PyQt module in my Python project. I have tried downloading it from <a href="https://www.riverbankcomputing.com/software/pyqt/download" rel="nofollow">here</a> as a zip file, then including that directory in an environment variable that I called PYTHONPATH. I am runnin... | 0 | 2016-06-17T12:59:19Z | 37,882,662 | <p>This is how i install Python and PyQt</p>
<p>1 - Install python (Create a folder somewhere like D:\python_dist)</p>
<p>2 - Install Qt</p>
<p>3 - Install PyQt5/PyQt4 with Windows installer ( PyQt5-5.6-gpl-Py3.5-Qt5.6.0-x64-2.exe) <a href="https://www.riverbankcomputing.com/software/pyqt/download5" rel="nofollow">h... | 0 | 2016-06-17T13:20:01Z | [
"python",
"pyqt4",
"python-import",
"python-3.5"
] |
Unable to add PyQt module to Python project | 37,882,202 | <p>I'm struggling to figure out how to include the PyQt module in my Python project. I have tried downloading it from <a href="https://www.riverbankcomputing.com/software/pyqt/download" rel="nofollow">here</a> as a zip file, then including that directory in an environment variable that I called PYTHONPATH. I am runnin... | 0 | 2016-06-17T12:59:19Z | 37,883,209 | <p>If you are having trouble installing the PyQt library from binary and from pip you could install PyQt from prepackaged whl files.</p>
<p>navigate to the Unofficial Windows Binaries from the University of California, Irvine and download the whl associated with your installed version of Python:
<a href="http://www.lf... | 0 | 2016-06-17T13:43:34Z | [
"python",
"pyqt4",
"python-import",
"python-3.5"
] |
Get element location relative to viewport with selenium/python | 37,882,208 | <p>I'm using the below code to take a screenshot and crop just the element I want. However, as Chrome only takes a screenshot of the viewport the top number is too large as it is counting from the top of the page. Is there a way to get the location relative to the viewport?</p>
<pre><code>element = browser.find_elemen... | 0 | 2016-06-17T12:59:47Z | 37,882,738 | <p>I was able to make it work by scrolling to the element, scroll slightly up (to get out from under the header), then get the scroll position and subtract it from the top number</p>
<pre><code>element = browser.find_element_by_xpath(locator)
browser.execute_script("return arguments[0].scrollIntoView();", element)
bro... | 0 | 2016-06-17T13:23:22Z | [
"python",
"google-chrome",
"selenium"
] |
Filter query with relative hour range | 37,882,400 | <p>Im trying to write a query to give me all entries starting 24 hours in the past, but not more than 25 hours in the past.</p>
<p>So if the date and time the query is executed is <code>06.17.2016 15:00</code> I want to find every entry with a startdate between <code>06.16.2016 15:00</code> and <code>06.16.2016 15:59<... | 2 | 2016-06-17T13:08:46Z | 37,882,916 | <p>You were calculating the wrong range. Your start is 24 hours ago, end is within 25 hours ago, you should have start as 25 hours ago and end as 24 hours ago.</p>
<pre><code>start = timezone.now().date() - relativedelta(hours=+25)
end = timezone.now().date() - relativedelta(hours=+24)
list = Entry.objects.filter(star... | 2 | 2016-06-17T13:31:10Z | [
"python",
"django",
"django-queryset",
"django-orm"
] |
MATLAB-style terminal output in Python | 37,882,437 | <p>I wasn't able to find this question in a few searches. Consider the following MATLAB struct:</p>
<pre><code>>> s = struct('field_a', 1:10, 'field_b', 1:1000);
>> disp(s)
s =
field_a: [1 2 3 4 5 6 7 8 9 10]
field_b: [1x1000 double]
</code></pre>
<p>In a python dictionary (ignore the +1 differenc... | 2 | 2016-06-17T13:10:03Z | 37,882,613 | <p>Yes, it is possible. All you need to do is to subclass the <code>dict</code> class and provide your custom implementation of the <code>__str__()</code> method.</p>
| 0 | 2016-06-17T13:18:00Z | [
"python",
"matlab"
] |
Replace element in a array in python | 37,882,503 | <p>I want to replace element in a array in python.
like,</p>
<pre><code>minNum=min(arr)
for i in range(0,n):
arr[i]=arr[i]-minNum
</code></pre>
<p>but it is not working properly.Anyone know how fix it?</p>
| -2 | 2016-06-17T13:12:42Z | 37,882,612 | <p>Use len() to find our size of array. Also you have error in code using () instead of []. Example:</p>
<pre><code>arr = [1,2,3,4,5]
minNum = min(arr)
print("before:")
for i in range(0, len(arr)):
print(arr[i])
for i in range(0, len(arr)):
arr[i] = arr[i] - minNum
print("after:")
for i in range(0, len(arr... | 0 | 2016-06-17T13:17:59Z | [
"python"
] |
openpyxl: Formulas read as blanks in some (key use) cases | 37,882,504 | <p>My code downloads a .xlsx file from google drive (using pydrive), finds some blank cells with pandas, and fills in those blank cells with openpyxl. </p>
<p>When I open the openpyxl altered file, everything looks great. However, when I use the pandas read_excel function, all cells that have equations are read as b... | 0 | 2016-06-17T13:12:45Z | 37,884,053 | <p>Using openpyxl 2.4 you might be able to do what you need in a single pass. I've taken your first function and adapted it.</p>
<pre><code>from itertools import islice
from pandas import DataFrame
def save_to_workbook(newval,
date,
header,
rows_to_skip=1... | 1 | 2016-06-17T14:24:35Z | [
"python",
"pandas",
"openpyxl"
] |
openpyxl: Formulas read as blanks in some (key use) cases | 37,882,504 | <p>My code downloads a .xlsx file from google drive (using pydrive), finds some blank cells with pandas, and fills in those blank cells with openpyxl. </p>
<p>When I open the openpyxl altered file, everything looks great. However, when I use the pandas read_excel function, all cells that have equations are read as b... | 0 | 2016-06-17T13:12:45Z | 37,976,568 | <p>Charlie's Answer from the <a href="https://groups.google.com/forum/#!topic/openpyxl-users/0NL45GhxSKc" rel="nofollow">mailing list</a>: </p>
<blockquote>
<p>So, if you want to keep the formulae then you must not use data only mode.<br>
As previously stated, openpyxl never evaluates formulae so if you want to<br... | 0 | 2016-06-22T19:20:30Z | [
"python",
"pandas",
"openpyxl"
] |
Python Bisection Number Guessing Game | 37,882,643 | <p>I am trying to write a simple bisection method question and it works perfectly fine as long as I don't have a certain conditional statement which I have commented out. What is the reason for this? This is not a homework question.</p>
<pre><code>low = 0
high = 100
ans = (low+high)/2
print "Please think of a numbe... | 2 | 2016-06-17T13:19:22Z | 37,882,753 | <p>That condition will always be true because you are comparing for inequality with multiple things. It would be like asking "If this character isn't <code>c</code>, <strong>or</strong> if it isn't <code>h</code>, <strong>or</strong> if it isn't <code>l</code>, <em>do this</em>. It can't be three things at once, so it ... | 6 | 2016-06-17T13:23:55Z | [
"python",
"bisection"
] |
Python Bisection Number Guessing Game | 37,882,643 | <p>I am trying to write a simple bisection method question and it works perfectly fine as long as I don't have a certain conditional statement which I have commented out. What is the reason for this? This is not a homework question.</p>
<pre><code>low = 0
high = 100
ans = (low+high)/2
print "Please think of a numbe... | 2 | 2016-06-17T13:19:22Z | 37,883,467 | <p>I suggest you use a double while loop :</p>
<pre><code>while True:
response = None
print "Is your secret number " + str(ans) + "?"
response = str(raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly."))
while r... | 0 | 2016-06-17T13:55:51Z | [
"python",
"bisection"
] |
scrapy - how to populate item with data from pandas dataframe? | 37,882,663 | <p>Suppose the following CrawlSpider:</p>
<pre><code>import scrapy
from scrapy.loader import ItemLoader
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from tutorial.items import TestItem
from scrapy.http import HtmlResponse
class TestCrawlSpider(CrawlSpider):
name = ... | 1 | 2016-06-17T13:20:02Z | 37,882,849 | <p>I would use <code>start_requests()</code> method to populate the <a href="http://doc.scrapy.org/en/latest/topics/request-response.html?highlight=meta#scrapy.http.Request.meta" rel="nofollow"><code>meta</code></a> information for every city, dumping the dataframe into a dictionary via <a href="http://pandas.pydata.or... | 2 | 2016-06-17T13:28:06Z | [
"python",
"pandas",
"scrapy"
] |
Convert string of dates with 'th' 'st' 'rd' 'nd' into date format via python | 37,882,805 | <p>I am scrapping a website for the dates using beautiful soup. Here is the CSS</p>
<pre><code><div id="listing-details-list">
<h3 class="listing-details-header">
Details:
<span>Posted on: 14th June 2016</span>
</h3>
</div>
</code></pre>
<p>The code I am using for getting the date ... | 2 | 2016-06-17T13:26:09Z | 37,883,076 | <p>To parse the dates I would just let the <a href="https://labix.org/python-dateutil" rel="nofollow"><code>dateutil</code> parser</a> do the job:</p>
<pre><code>>>> from dateutil.parser import parse
>>> l = ["23rd June 2016", "21st July 2016", "20th July 2016", "3rd July 2016"]
>>> for item... | 4 | 2016-06-17T13:38:26Z | [
"python",
"regex",
"string",
"python-2.7",
"beautifulsoup"
] |
Multiple for loops in Python with variable range and variable number of loops | 37,882,838 | <p>With this code:</p>
<pre><code>from itertools import product
for a, b, c, d in product(range(low, high), repeat=4):
print (a, b, c, d)
</code></pre>
<p>I have an output like this:</p>
<pre><code>0 0 0 0
0 0 0 1
0 0 0 2
0 0 1 0
0 0 1 1
0 0 1 2
0 0 2 0
0 0 2 1
0 0 2 2
</code></pre>
<p>but how I can create an ... | -1 | 2016-06-17T13:27:37Z | 37,883,134 | <p>You looking for something like this?</p>
<pre><code># the program would modify these variables below
column1_max = 2
column2_max = 3
column3_max = 4
column4_max = 5
# now generate the list
for a in range(column1_max+1):
for b in range(column2_max+1):
for c in range(column3_max+1):
for d in ... | 2 | 2016-06-17T13:40:17Z | [
"python"
] |
Multiple for loops in Python with variable range and variable number of loops | 37,882,838 | <p>With this code:</p>
<pre><code>from itertools import product
for a, b, c, d in product(range(low, high), repeat=4):
print (a, b, c, d)
</code></pre>
<p>I have an output like this:</p>
<pre><code>0 0 0 0
0 0 0 1
0 0 0 2
0 0 1 0
0 0 1 1
0 0 1 2
0 0 2 0
0 0 2 1
0 0 2 2
</code></pre>
<p>but how I can create an ... | -1 | 2016-06-17T13:27:37Z | 37,883,203 | <p><a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product</code></a> can already do exactly what you are looking for, simply by passing it multiple iterables (in this case the ranges you want). It will collect one element from each iterable passed. For exampl... | 4 | 2016-06-17T13:43:13Z | [
"python"
] |
Trading strategy P&L for holding period - solve rolling_apply bottleneck | 37,882,911 | <p>I am calculating a <code>DataFrame</code> of profit/loss amounts for every row in a <code>DataFrame</code> containing price data.</p>
<p>The logic is as follows:</p>
<ul>
<li>We buy/sell the asset at the current time period.</li>
<li>We hold the asset for <code>holding_period</code>.</li>
<li>If, during the holdin... | 2 | 2016-06-17T13:30:58Z | 37,884,343 | <p>Here's one way to go about this:</p>
<pre><code>from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from pandas_datareader.data import DataReader
</code></pre>
<p>Sample data:</p>
<pre><code>prices = DataReader('IBM', 'yahoo', datetime(2015, 1, 1), datetime.today().utcnow())[... | 1 | 2016-06-17T14:39:01Z | [
"python",
"numpy",
"pandas",
"machine-learning"
] |
Flask project in Visual Studio 2015: how to specify port number? | 37,882,955 | <p>How can I specify the port number in a Flask python project under Visual Studio 2015, so that when it starts it always uses the same port?</p>
<p>My startup file (app.py) looks like this:</p>
<pre><code>from svc.svc import app
wsgi_app = app.wsgi_app
if __name__ == '__main__':
import os
HOST = os.environ.... | 1 | 2016-06-17T13:32:51Z | 37,891,528 | <p>In Visual Studio, right click on the project name and choose "Properties".
Then, click on "Debug" and you will see a "Port Number" and "Environment" section in which you will be able to set the port number and any other environment variables.</p>
<p><a href="http://i.stack.imgur.com/f8Udf.png" rel="nofollow"><img s... | 4 | 2016-06-17T23:05:41Z | [
"python",
"visual-studio",
"flask",
"visual-studio-2015",
"ptvs"
] |
using decorators to persist python objects | 37,883,015 | <p>Code that I got from below link, can persist data to the disk. </p>
<p><a href="http://tohyongcheng.github.io/python/2016/06/07/persisting-a-cache-in-python-to-disk.html">http://tohyongcheng.github.io/python/2016/06/07/persisting-a-cache-in-python-to-disk.html</a></p>
<p>I tried it but the file does not get genera... | 8 | 2016-06-17T13:35:20Z | 37,914,677 | <p>The problem is the example employs <code>atexit</code> which runs the dump routine only when python exits. This modified version will dump each time the cache is updated:</p>
<pre><code>import atexit
import functools
import pickle
# or import cPickle as pickle
def persist_cache_to_disk(filename):
def decorato... | 10 | 2016-06-20T04:34:07Z | [
"python",
"ipython-notebook",
"jupyter-notebook"
] |
using decorators to persist python objects | 37,883,015 | <p>Code that I got from below link, can persist data to the disk. </p>
<p><a href="http://tohyongcheng.github.io/python/2016/06/07/persisting-a-cache-in-python-to-disk.html">http://tohyongcheng.github.io/python/2016/06/07/persisting-a-cache-in-python-to-disk.html</a></p>
<p>I tried it but the file does not get genera... | 8 | 2016-06-17T13:35:20Z | 38,039,701 | <p>The best solution depends on the use case. There is no general way to solve all problems at once.</p>
<h2>Caching data</h2>
<p>If you want to speed up function calls, you probably want to cache results in memory (because disk read/write is slow too). If you are calling a function with the same arguments, only the ... | 5 | 2016-06-26T14:50:43Z | [
"python",
"ipython-notebook",
"jupyter-notebook"
] |
mod_wsgi: Reload Code via Inotify - not every N seconds | 37,883,127 | <p>Up to now I followed this advice to reload the code:</p>
<p><a href="https://code.google.com/archive/p/modwsgi/wikis/ReloadingSourceCode.wiki" rel="nofollow">https://code.google.com/archive/p/modwsgi/wikis/ReloadingSourceCode.wiki</a></p>
<p>This has the drawback, that the code changes get detected only every N se... | 11 | 2016-06-17T13:39:58Z | 37,999,641 | <p>You can use inotify hooktables to run <strong>any command you want</strong> depending on a i-notify signal (here's my source link: <a href="http://terokarvinen.com/2016/when-files-change-take-action-inotify-hookable" rel="nofollow">http://terokarvinen.com/2016/when-files-change-take-action-inotify-hookable</a>). </p... | 3 | 2016-06-23T18:54:00Z | [
"python",
"django",
"mod-wsgi",
"inotify"
] |
mod_wsgi: Reload Code via Inotify - not every N seconds | 37,883,127 | <p>Up to now I followed this advice to reload the code:</p>
<p><a href="https://code.google.com/archive/p/modwsgi/wikis/ReloadingSourceCode.wiki" rel="nofollow">https://code.google.com/archive/p/modwsgi/wikis/ReloadingSourceCode.wiki</a></p>
<p>This has the drawback, that the code changes get detected only every N se... | 11 | 2016-06-17T13:39:58Z | 38,025,844 | <h2>Preliminaries.</h2>
<blockquote>
<p>Developers can use runserver or mod_wsgi. Using runserver has the
benefit that you it easy for debugging, mod_wsgi has the benefit that
you don't need to start the server first.</p>
</blockquote>
<p>But you do, the server needs to be setup first and that takes a lot of ef... | 4 | 2016-06-25T06:50:27Z | [
"python",
"django",
"mod-wsgi",
"inotify"
] |
Use two interpreters in a PyCharm project | 37,883,148 | <p>I am using Pycharm 5.0.1. I want to use two packages that exist in two envs. Scipy is in a Conda env, and Tweepy is in the default env.</p>
<p>How can I use packages of both the interpreters in a single project?</p>
| 3 | 2016-06-17T13:40:49Z | 37,892,956 | <p><em>If</em> both interpreters are the same major version of python--so that they share compatible byte code--you should be able to hack python's <code>sys.path</code> or the <code>PYTHONPATH</code> environment variable to add the <code>site-packages</code> directory of one interpreter to the other.</p>
<p>I think. ... | 2 | 2016-06-18T03:32:28Z | [
"python",
"pycharm",
"conda"
] |
How do I override imports of other files for unit testing | 37,883,222 | <p>I am currently attempting to write unit tests for my Main.py's <code>main()</code> function</p>
<p>Here is a simplified version of my Main.py:</p>
<pre><code>from Configuration import Configuration # Configuration.py is a file in the same dir
def main():
try:
Configuration('settings.ini')
except:
sys.... | 0 | 2016-06-17T13:44:09Z | 37,884,490 | <p>when you use the import</p>
<pre><code>from bar import a
</code></pre>
<p>it import the name directly into the module, so monkeypatching <code>bar</code> won't help, you need to override <code>a</code> directly in the main file:</p>
<pre><code>def fake_a():
print("OVERRIDEN!")
main.a = fake_a
</code></pre>
... | 1 | 2016-06-17T14:46:00Z | [
"python",
"python-unittest"
] |
Machine learning algorithm for mapping a 2d coordinate to a value | 37,883,325 | <p>I'm trying to build a program to map a 2d coordinate (latitude, longitude) to a float value. I have about 1 million rows of training data like</p>
<pre><code>(41.140359, -8.612964) -> 65
... -> ...
</code></pre>
<p>I think this is a regression problem, except all of the regression examples I've found are onl... | 0 | 2016-06-17T13:49:07Z | 37,883,573 | <p>It is a regression problem and you can freely use e.g. <a href="https://en.wikipedia.org/wiki/Linear_regression" rel="nofollow">linear regression</a> to solve it. The examples are often one-dimensional so it is easy to understand, however they work for an arbitrary number of dimensions.</p>
| 0 | 2016-06-17T14:00:51Z | [
"python",
"machine-learning",
"scikit-learn",
"regression"
] |
Machine learning algorithm for mapping a 2d coordinate to a value | 37,883,325 | <p>I'm trying to build a program to map a 2d coordinate (latitude, longitude) to a float value. I have about 1 million rows of training data like</p>
<pre><code>(41.140359, -8.612964) -> 65
... -> ...
</code></pre>
<p>I think this is a regression problem, except all of the regression examples I've found are onl... | 0 | 2016-06-17T13:49:07Z | 37,883,582 | <p>Before trying to find a function, plot your data on an excel of python plot, you may see the kind of function you are looking for.</p>
<p>In addition, excel has a regression computation module.</p>
| 1 | 2016-06-17T14:01:16Z | [
"python",
"machine-learning",
"scikit-learn",
"regression"
] |
Machine learning algorithm for mapping a 2d coordinate to a value | 37,883,325 | <p>I'm trying to build a program to map a 2d coordinate (latitude, longitude) to a float value. I have about 1 million rows of training data like</p>
<pre><code>(41.140359, -8.612964) -> 65
... -> ...
</code></pre>
<p>I think this is a regression problem, except all of the regression examples I've found are onl... | 0 | 2016-06-17T13:49:07Z | 37,883,882 | <p>You can try to use linear regression first.</p>
<p>Lets give an example using <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.linalg.lstsq.html" rel="nofollow"><code>numpy.linalg.lstsq</code></a>:</p>
<pre><code>>>> import numpy as np
>>> x = np.random.rand(10, 2)
>&g... | 0 | 2016-06-17T14:16:27Z | [
"python",
"machine-learning",
"scikit-learn",
"regression"
] |
Count items through documents on mongo query | 37,883,456 | <p>My mongo cursor looks like this :</p>
<pre><code>{
"_id":ObjectId("57558ee01807ce2f774569cc"),
"description": "Lorem Ipnsun ....",
"results":[
{
"name":"Alica James",
"gender":"male"
},
{
"name":"Alica James",
"gender":"female"
},
{
"name... | 0 | 2016-06-17T13:55:22Z | 37,887,501 | <p>You are using the wrong method to do this. You need to use the <a href="https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.aggregate" rel="nofollow"><code>.aggregate()</code></a> method which gives access to the aggregation pipeline.</p>
<pre><code>unwind1 = {"$unwind":... | 0 | 2016-06-17T17:51:39Z | [
"python",
"mongodb",
"pymongo",
"aggregation-framework"
] |
Filter a pandas dataframe based on a derived field | 37,883,476 | <p>I have the below query that I execute and store in a pandas dataframe. </p>
<pre><code>SELECT
mn as MachineName,
dt as DateTime,
REGEXP_EXTRACT(path, 'Name:([\\s\\S\\w\\W]*?)Domain:') AS Name1,
FROM TABLE DataGallery
</code></pre>
<p>Output of the query is:</p>
<pre><code>MachineName DateTime Name... | 2 | 2016-06-17T13:56:09Z | 37,883,515 | <p>IIUC use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> if need filter <code>df</code>:</p>
<pre><code>df = pd.DataFrame({'Name1': {0: 'PI1', 1: 'PI2'},
'DateTime': {0: '2016-12-13 12:14', 1: '2016-12-14 13:12... | 0 | 2016-06-17T13:57:49Z | [
"python",
"pandas",
"filter",
"dataframe",
"ipython"
] |
Filter a pandas dataframe based on a derived field | 37,883,476 | <p>I have the below query that I execute and store in a pandas dataframe. </p>
<pre><code>SELECT
mn as MachineName,
dt as DateTime,
REGEXP_EXTRACT(path, 'Name:([\\s\\S\\w\\W]*?)Domain:') AS Name1,
FROM TABLE DataGallery
</code></pre>
<p>Output of the query is:</p>
<pre><code>MachineName DateTime Name... | 2 | 2016-06-17T13:56:09Z | 37,885,832 | <p>Try this: Make sure its Capital "i" not Lowercase 'L". </p>
<pre><code> df[df["Name1"] == "PI1"] not df[df["Name1"] = "PI1"]
</code></pre>
| 0 | 2016-06-17T15:59:46Z | [
"python",
"pandas",
"filter",
"dataframe",
"ipython"
] |
numpy.insert() invalid slice -- Trying to Insert NaN in Numpy Array | 37,883,681 | <p>I know there are already lots of questions about this, but none of the answers I've seen have solved my problem. I have a pandas DataFrame with 10 columns for data, but on some rows I have just 9 columns-worth of data. For the rows with just 9 datapoints, I need the data to be in the last nine columns. My solution i... | 0 | 2016-06-17T14:06:02Z | 37,883,831 | <p>Your code is currently attempting to insert <code>0</code> at index <code>np.nan</code>. Switch the args around:</p>
<pre><code>a = np.insert(a, 0, np.nan)
</code></pre>
| 1 | 2016-06-17T14:13:37Z | [
"python",
"numpy",
"pandas"
] |
conditional sum over a range python | 37,883,703 | <p>I have created X as folowing</p>
<pre><code>num_locations = 2
X= [ ]
for n in range(num_locations):
X.append([0 for j in range(num_locations)])
</code></pre>
<p>Now I want to sum these X[n][m] values for the case n != m . Such that the result should be like</p>
<pre><code>X[0][1]+X[1][0]
</code></pre>
<p>Is ther... | 2 | 2016-06-17T14:06:50Z | 37,883,794 | <p>You can simply use <code>enumerate</code></p>
<pre><code>>>> sum(o for i, a in enumerate(X) for j, o in enumerate(a) if i!=j)
0
</code></pre>
<p>Where <code>i</code> and <code>j</code> are <em>row</em> (1st dim) and <em>column</em> (2nd dim) indices respectively</p>
| 2 | 2016-06-17T14:11:22Z | [
"python",
"sum",
"conditional"
] |
conditional sum over a range python | 37,883,703 | <p>I have created X as folowing</p>
<pre><code>num_locations = 2
X= [ ]
for n in range(num_locations):
X.append([0 for j in range(num_locations)])
</code></pre>
<p>Now I want to sum these X[n][m] values for the case n != m . Such that the result should be like</p>
<pre><code>X[0][1]+X[1][0]
</code></pre>
<p>Is ther... | 2 | 2016-06-17T14:06:50Z | 37,883,802 | <p>This should work </p>
<pre><code>sum([sum(row) - (row[i] if len(row) < i else 0) for i,row in enumerate(X)])
</code></pre>
<p>It runs over every row in the 2d array, and sums it, then take out the <code>i</code> cell (if exists) so it won't get into sum</p>
| 1 | 2016-06-17T14:11:59Z | [
"python",
"sum",
"conditional"
] |
conditional sum over a range python | 37,883,703 | <p>I have created X as folowing</p>
<pre><code>num_locations = 2
X= [ ]
for n in range(num_locations):
X.append([0 for j in range(num_locations)])
</code></pre>
<p>Now I want to sum these X[n][m] values for the case n != m . Such that the result should be like</p>
<pre><code>X[0][1]+X[1][0]
</code></pre>
<p>Is ther... | 2 | 2016-06-17T14:06:50Z | 37,883,860 | <p>This is effectively taking the sum of the non-diagonal elements of your 2D array. One option using Numpy could simply be to subtract the sum of the main diagonal (<a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.trace.html" rel="nofollow"><code>np.trace</code></a>) from the sum of the entire... | 2 | 2016-06-17T14:15:28Z | [
"python",
"sum",
"conditional"
] |
Python: initialize several names simultaneously without giving them the same id | 37,883,720 | <p>This is what I've tried so far:</p>
<pre><code>a, b, c = ([],)*3
a.append(0)
b.append(1)
c.append(2)
print(a,b,c)
>> [0, 1, 2] [0, 1, 2] [0, 1, 2] # Result
>> [0] [1] [2] # Expected results
</code></pre>
| 1 | 2016-06-17T14:07:45Z | 37,883,805 | <p>The problem is that you are creating only one list and then duplicating it.</p>
<p>So your code is the same as:</p>
<pre><code>def build_lists():
l = []
return l, l, l
a, b, c = build_lists()
</code></pre>
<p>So the following would work as that would be creating new lists for each iteration:</p>
<p><code... | 0 | 2016-06-17T14:12:11Z | [
"python"
] |
Python: initialize several names simultaneously without giving them the same id | 37,883,720 | <p>This is what I've tried so far:</p>
<pre><code>a, b, c = ([],)*3
a.append(0)
b.append(1)
c.append(2)
print(a,b,c)
>> [0, 1, 2] [0, 1, 2] [0, 1, 2] # Result
>> [0] [1] [2] # Expected results
</code></pre>
| 1 | 2016-06-17T14:07:45Z | 37,883,811 | <pre><code>>>> a, b, c = [],[],[]
>>> id(a),id(b),id(c)
(573212632, 635724224, 626682216)
</code></pre>
<p>or</p>
<pre><code> >>> a,b,c = ([] for _ in range(3) )
>>> id(a),id(b),id(c)
(633263648, 197690032, 633261352)
>>> a.append(1)
>>> b.appen... | 2 | 2016-06-17T14:12:22Z | [
"python"
] |
array assignment using slicing | 37,883,776 | <p>When I was using array assignment using slicing, there is some thing strange happened. The source code is below:</p>
<pre><code>import numpy as np
a = np.array([1,2,3,4]).reshape(2,2)
b = np.array([5,6,7,8]).reshape(2,2)
print(id(a))
print(id(b))
b = a[:]
b[1,1] = 10
print(b is a)
print(id(a))
print(id(b))
print(a)... | 0 | 2016-06-17T14:10:14Z | 37,884,442 | <p>I think you might have an issue with referencing (b=a[:]). Here is a previous answer that might help: </p>
<p><a href="http://stackoverflow.com/questions/4588100/python-objects-confusion-a-b-modify-b-and-a-changes">Python objects confusion: a=b, modify b and a changes!</a></p>
| 1 | 2016-06-17T14:43:38Z | [
"python",
"arrays",
"numpy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.