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
Is there an one-line python code to replace this nested loop?
38,225,181
<p>variables:</p> <pre><code>rs = { 'results': [ {'addresses': [{'State': 'NY'}, {'State': 'IL'}]}, {'addresses': [{'State': 'NJ'}, {'State': 'IL'}]} ] } </code></pre> <p>I want to get a list of states for each member of results. Currently I used the following code:</p> <pre><code>for y in rs...
2
2016-07-06T13:23:54Z
38,225,216
<p>You almost got it, you just got it the other way around:</p> <pre><code>phy_states = [x['State'] for y in rs['results'] for x in y['addresses']] </code></pre>
9
2016-07-06T13:25:57Z
[ "python", "for-loop", "dictionary" ]
Retrieving variable from tuples in dataframe and code discrepancies
38,225,206
<p>So here is a code I made for extracting the n-th element of tuples contained in a df "dataframe" :</p> <pre><code>df=pd.DataFrame([[(1,2),(3,4)],[(5,6),(7,8)]]) splitframe1=df.copy() splitframe2=df.copy() splitframe1.applymap(lambda x: x[0]) splitframe2.applymap(lambda x: x[1]) </code></pre> <h1>This won't work.....
0
2016-07-06T13:25:06Z
38,228,092
<p>The difference between <code>splitframe1.applymap(lambda x: x[0])</code> and <code>splitframe1=dataframe.copy().applymap(lambda x: x[0])</code> is that in the former you don't assign back the result. applymap returns a new dataframe; it doesn't change the original dataframe. You can assign this new dataframe back to...
1
2016-07-06T15:40:40Z
[ "python", "pandas" ]
Seasonal data selection in python pandas
38,225,232
<p>I have a dataframe with time series data in one column and index as a date. The data looks like below: It's from 2000 to 2015.</p> <pre><code>2000-02-24 NaN 2000-02-25 NaN 2000-02-26 0.272 2000-02-27 0.417 2000-02-28 0.837 2000-02-29 1.082 2000-03-01 0.613 2000-03-02 0.709 2000-03-03 ...
1
2016-07-06T13:26:50Z
38,225,357
<p>You can filter using the <code>DatetimeIndex</code> attribute <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.month.html" rel="nofollow"><code>month</code></a>:</p> <pre><code>df[(df.index.month &gt;=2) &amp; (df.index.month&lt;=6)] </code></pre> <p>months are zero based so <cod...
1
2016-07-06T13:34:17Z
[ "python", "pandas" ]
Multiprocess a function in python that got multiple parameters
38,225,289
<p>I'm trying to use the multiprocessing library in python but I met some difficulties:</p> <pre><code>def request_solr(limit=10, offset=10): # build my facets here using limit and offset # request solr return response.json() def get_list_event_per_user_per_mpm(limit=100): nb_unique_user = get_unique_...
0
2016-07-06T13:30:45Z
38,225,342
<p>You need to use a lambda for this. The way you're doing it right now, it's trying to map the result of <code>request_solr</code> as a function with <code>offset</code> as the argument.</p> <p>This should do the trick.</p> <pre><code>processor_pool.map(lambda x: request_solr(limit, x), offset) </code></pre> <p>Not...
1
2016-07-06T13:33:25Z
[ "python", "multiprocessing", "python-2.x", "python-multiprocessing" ]
Multiprocess a function in python that got multiple parameters
38,225,289
<p>I'm trying to use the multiprocessing library in python but I met some difficulties:</p> <pre><code>def request_solr(limit=10, offset=10): # build my facets here using limit and offset # request solr return response.json() def get_list_event_per_user_per_mpm(limit=100): nb_unique_user = get_unique_...
0
2016-07-06T13:30:45Z
38,225,382
<p>you see that error because you are calling the function <em>before</em> passing it to multiprocessing.</p> <p>I suggest you use <a href="https://docs.python.org/3.6/library/multiprocessing.html#multiprocessing.pool.Pool.starmap" rel="nofollow"><code>starmap</code></a> in combination with <a href="https://docs.pytho...
2
2016-07-06T13:35:24Z
[ "python", "multiprocessing", "python-2.x", "python-multiprocessing" ]
Multiprocess a function in python that got multiple parameters
38,225,289
<p>I'm trying to use the multiprocessing library in python but I met some difficulties:</p> <pre><code>def request_solr(limit=10, offset=10): # build my facets here using limit and offset # request solr return response.json() def get_list_event_per_user_per_mpm(limit=100): nb_unique_user = get_unique_...
0
2016-07-06T13:30:45Z
38,227,389
<p>I used to use a generator to produce the keywords. This is the content a my simple_multiproc.py. </p> <p><strong>Note the important of having request_solr at level module.</strong> </p> <pre><code>import multiprocessing MAX=5 def _get_pool_args(**kw): for _ in range(MAX): r = {"limit": 10, "offset": ...
1
2016-07-06T15:05:11Z
[ "python", "multiprocessing", "python-2.x", "python-multiprocessing" ]
I want to display the names and profile pic of my followers in a template..i am only able to display the names of followers.please suggest
38,225,305
<p>Here is my UserProfile models.py file</p> <pre><code>from django.db import models from django.contrib.auth.models import User import question from question.models import Tag # Create your models here. class UserProfile(models.Model): GENDER_CHOICES=( ('M','Male'), ('F','Female'), ) user...
-2
2016-07-06T13:31:28Z
38,229,560
<p>Given a User, you can get to the UserProfile via the <code>userprofile</code> accessor.</p> <pre><code> {{ c.userprofile.age }} </code></pre>
0
2016-07-06T16:57:41Z
[ "python", "django", "django-templates", "django-views" ]
Is it possible to place a circle that I have created in a Tkitnter window that already has few labels and entry boxes placed using the place method?
38,225,496
<p>I have a need whereby I have already designed a GUI windows with few textboxes and labels for user input. I did this using the .place(x=..., y=...) method.</p> <p>Now, I want to place a circle at a specific position using the same place(x=..., y=...) method in the same window with the already contained labels and t...
0
2016-07-06T13:40:13Z
38,231,709
<p>You got most of the way to an <a href="https://stackoverflow.com/help/mcve">mcve</a> but your code does not run as posted.</p> <p>You missed two things: 1) you only need a convas slightly bigger than the circle you want to display -- see revised Canvas statement; 2) you need your container big enough to show everyt...
0
2016-07-06T18:54:47Z
[ "python", "user-interface", "tkinter" ]
How to parse only a specific category of a website using the newspaper library?
38,225,554
<p>I use <code>Python3</code> and the <code>newspaper</code> library. It is said that this library can create a <code>Source</code> object that is an abstraction of a news website. But what if I need only the abstraction of a certain category.</p> <p>For example, when I use <a href="http://www.kyivpost.com/technology/...
6
2016-07-06T13:42:45Z
38,883,809
<p><code>newspaper</code> will use a site's rss feed when available; KyivPost only has one rss feed and posts articles mainly on politics, which is why your result set is mostly politics. </p> <p>You may have more luck using <code>BeautifulSoup</code> to draw article URLs specifically from the technology page and feed...
0
2016-08-10T21:24:23Z
[ "python", "python-3.x", "parsing", "web-scraping", "newspaper" ]
Alternative way to return HTML as a read only field on the Django Admin
38,225,578
<p>I have a Django admin class that contains a read only field which returns a table in HTML with 2 different links. The first link loads the page of all payments the user has sent, the second loads the page of all payments the user has received. In order to create this functionality, there is a need to return a lot of...
0
2016-07-06T13:44:00Z
38,227,460
<p>How about using render_to_string? <a href="https://docs.djangoproject.com/en/1.9/topics/templates/#django.template.loader.render_to_string" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/templates/#django.template.loader.render_to_string</a></p> <p>templates/myapp/payment_history.html:</p> <pre><code>...
1
2016-07-06T15:09:27Z
[ "python", "html", "django", "django-forms", "django-admin" ]
Using *arg and optional argument in one function
38,225,583
<p>how can i use *arg and variables with defaull values together?</p> <pre><code>def my_fun(a, b = True, *arg): print (a) print (b) print (arg) my_fun(1,2,3) </code></pre> <p>What I want to get is</p> <pre><code>1 True (2,3,) </code></pre> <p>What I get is</p> <pre><code>1 2 (3) </code></pre>
0
2016-07-06T13:44:08Z
38,225,669
<p>If you catch all the args before the keyword arguments:</p> <pre><code>&gt;&gt;&gt; def my_fun(*arg, a=1, b=2): ... print (a) ... print (b) ... print (arg) ... &gt;&gt;&gt; my_fun(3,4,5) 1 2 (3, 4, 5) </code></pre> <p>And <code>a</code> and <code>b</code> can be modified by passing them as named parame...
6
2016-07-06T13:47:51Z
[ "python", "arguments" ]
Using *arg and optional argument in one function
38,225,583
<p>how can i use *arg and variables with defaull values together?</p> <pre><code>def my_fun(a, b = True, *arg): print (a) print (b) print (arg) my_fun(1,2,3) </code></pre> <p>What I want to get is</p> <pre><code>1 True (2,3,) </code></pre> <p>What I get is</p> <pre><code>1 2 (3) </code></pre>
0
2016-07-06T13:44:08Z
38,225,680
<p>What you ask for doesn't make sense.</p> <p>If I follow your logic, no matter how you call your function, <code>a</code> and <code>b</code> always will be <code>1</code> and <code>2</code>.</p>
1
2016-07-06T13:48:17Z
[ "python", "arguments" ]
How to interpret the results of profiling?
38,225,615
<p>I am not a computer scientist and I have been having a hard time trying to make my agent-based model reasonably fast (<a href="http://stackoverflow.com/questions/38212265/implementing-pool-on-a-for-loop-with-a-lot-of-inputs">Implementing Pool on a for loop with a lot of inputs</a>, <a href="http://stackoverflow.com/...
0
2016-07-06T13:45:27Z
38,226,635
<p>You might want to use some of the tools available to analyze/visualize the cProfile output like <a href="https://docs.python.org/2/library/profile.html" rel="nofollow">pstats</a> or <a href="https://pypi.python.org/pypi/RunSnakeRun" rel="nofollow">RunShakeRun</a></p>
0
2016-07-06T14:31:13Z
[ "python", "performance", "profile" ]
Look for a string object from a list in another list
38,225,718
<p>I am doing a little project in which my program unscrambles a string and finds every possible combination of it.</p> <p>I have two lists; <code>comboList</code> and <code>wordList</code>. <code>comboList</code> holds EVERY combination of the word; for example, the <code>comboList</code> for <code>'ABC'</code> is:</...
1
2016-07-06T13:49:51Z
38,226,083
<p>I think the problem here is that you compare two strings with the same letters but with mixed <strong>lower/upper cases</strong>. <br> To see if i'm correct try to convert all word in <code>wordList</code> to upper-case and then in <code>isRealWord</code> compare with upper-case word (just to be sure) as follows:</p...
1
2016-07-06T14:07:23Z
[ "python", "python-2.7", "if-statement", "for-loop" ]
Look for a string object from a list in another list
38,225,718
<p>I am doing a little project in which my program unscrambles a string and finds every possible combination of it.</p> <p>I have two lists; <code>comboList</code> and <code>wordList</code>. <code>comboList</code> holds EVERY combination of the word; for example, the <code>comboList</code> for <code>'ABC'</code> is:</...
1
2016-07-06T13:49:51Z
38,226,502
<p>I'd suggest using <code>set</code> because it would be much faster due to its implementation. There is <code>set.intersection</code> method. Here is a case insensitive solution:</p> <pre><code>listOfActualWords = set.intersection(set(word.upper() for word in comboList), set(word.upper() for word in wordList)) </cod...
2
2016-07-06T14:25:05Z
[ "python", "python-2.7", "if-statement", "for-loop" ]
how to read batches in one hdf5 data file for training?
38,225,770
<p>I have a hdf5 training dataset with size <code>(21760, 1, 33, 33)</code>. <code>21760</code> is the whole number of training samples. I want to use the mini-batch training data with the size <code>128</code> to train the network. </p> <p>I want to ask:</p> <p>How to feed <code>128</code> mini-batch training data f...
-1
2016-07-06T13:52:03Z
38,226,653
<p>You can read the hdf5 dataset into a numpy array, and feed slices of the numpy array to the TensorFlow model. Pseudo code like the following would work :</p> <pre><code>import numpy, h5py f = h5py.File('somefile.h5','r') data = f.get('path/to/my/dataset') data_as_array = numpy.array(data) for i in range(0, 21760, 1...
1
2016-07-06T14:31:48Z
[ "python", "tensorflow", "deep-learning" ]
Gspread - Change Listener?
38,225,812
<p>I currently run a daemon thread that grabs all cell values, calculates if there's a change, and then writes out dependent cells in a loop, ie:</p> <pre><code>def f(): while not event.is_set(): update() event.wait(15) Thread(target=f).start() </code></pre> <p>This works, but the looped get-all c...
1
2016-07-06T13:54:50Z
38,283,194
<p>I rephrased <a href="https://github.com/burnash/gspread/issues/398#issuecomment-231537695" rel="nofollow">my comment</a> on gspread GitHub's Issues:</p> <p>Getting a change notification from Google Sheets is possible with help of <a href="https://developers.google.com/apps-script/guides/triggers/installable" rel="n...
1
2016-07-09T15:10:46Z
[ "python", "gspread" ]
Gspread - Change Listener?
38,225,812
<p>I currently run a daemon thread that grabs all cell values, calculates if there's a change, and then writes out dependent cells in a loop, ie:</p> <pre><code>def f(): while not event.is_set(): update() event.wait(15) Thread(target=f).start() </code></pre> <p>This works, but the looped get-all c...
1
2016-07-06T13:54:50Z
38,283,575
<p>I was able to get this working by triggering an HTTP request whenever Google Sheets detected a change.</p> <p>On Google Sheets:</p> <pre><code>function onEdit (e) { UrlFetchApp.fetch("http://myaddress.com"); } </code></pre> <p>Python-side (w/ Tornado)</p> <pre class="lang-py prettyprint-override"><code>import ...
0
2016-07-09T15:50:07Z
[ "python", "gspread" ]
How to get a value from a string that's between two delimiters, then set another value to what comes after the delimiters?
38,225,828
<p>So lets say I have a string come in like this:</p> <pre><code>newData = "[Fruit]Apple" </code></pre> <p>How would I set set these variables from the string that was sent in?</p> <pre><code>type = "Fruit" food = "Apple" </code></pre>
0
2016-07-06T13:55:46Z
38,225,985
<p>You can use <code>.split()</code></p> <pre><code>food = newData.split(']')[-1] type = newData.split(']')[0].split('[')[-1] </code></pre>
0
2016-07-06T14:02:56Z
[ "python" ]
How to get a value from a string that's between two delimiters, then set another value to what comes after the delimiters?
38,225,828
<p>So lets say I have a string come in like this:</p> <pre><code>newData = "[Fruit]Apple" </code></pre> <p>How would I set set these variables from the string that was sent in?</p> <pre><code>type = "Fruit" food = "Apple" </code></pre>
0
2016-07-06T13:55:46Z
38,225,990
<p><code>replace</code> and <code>split</code>: </p> <pre><code>type, food = newData.replace('[','').split(']') </code></pre> <p>Or without <code>replace</code> (credit @Bakuriu), with <em>slicing</em>:</p> <pre><code>type, food = newData[1:].split(']') </code></pre>
2
2016-07-06T14:03:14Z
[ "python" ]
How to get the plot of clusters in this python code? ValueError: x and y must have same first dimension
38,225,948
<pre><code>Error: Traceback (most recent call last): File "/Users/ankitchaudhari/PycharmProjects/Learn/datascience/gg.py", line 33, in &lt;module&gt; plt.plot(a, k) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib/pyplot.py", line 3154, in plot ret = ax.plot(*args, **kwar...
-2
2016-07-06T14:01:21Z
38,226,627
<p>Your indentation is broken</p> <pre><code>sse = 0 for i in k: label = kmeans(data, i) cluster_mean = df.mean() d = np.zeros([], dtype=float) # for i in k has finished here # label, cluster_mean and d frozen in their last state for j in range(len(label)): sse += sum(pow((data[j]) - cluster_mean, 2)) a = np...
1
2016-07-06T14:30:45Z
[ "python", "python-3.x", "matplotlib", "scikit-learn", "scatter-plot" ]
pysnmp - get output from NET-SNMP-EXTEND-MIB extend script?
38,226,100
<p>How can I properly invoke an SNMP extend script by MIB with pysnmp 4.3?</p> <p>I have this entry in the remote server's snmpd.conf file:</p> <pre><code>extend check_fd_wap /app/users/nagios_checks/check_fd_wap.sh </code></pre> <p>which in turn can be invoked by:</p> <pre><code>snmpwalk -t 60 -v2c -c greendale re...
0
2016-07-06T14:08:07Z
38,340,638
<p>This failure:</p> <pre><code>'DisplayString' failed to cast value OctetString </code></pre> <p>happens when pysnmp receives a response from SNMP Agent for requested OID</p> <pre><code>1.3.6.1.4.1.8072.1.3.2.3.1.1.12.99.104.101.99.107.95.102.100.95.119.97.112 </code></pre> <p>(which corresponds to <em>NET-SNMP-EX...
1
2016-07-13T00:00:46Z
[ "python", "snmp", "mib", "pysnmp" ]
Related models update on model field change
38,226,116
<p>What is the most proper way to trigger update of related models, when one of the fields of parent model is changed? I have this set of models: </p> <pre><code>class ActivityObject(models.Model): is_deleted = models.BooleanField(default=False) class ActivityJob(models.Model): activity_object = models.Forei...
0
2016-07-06T14:08:40Z
38,226,231
<p>Overriding save() will work:</p> <pre><code>class ActivityObject(models.Model): is_deleted = models.BooleanField(default=False) def save(self, *args, **kwargs): super(ActivityObject, self).save(args, kwargs) if self.is_deleted: for job in self.activity_jobs: job....
1
2016-07-06T14:13:44Z
[ "python", "django" ]
Related models update on model field change
38,226,116
<p>What is the most proper way to trigger update of related models, when one of the fields of parent model is changed? I have this set of models: </p> <pre><code>class ActivityObject(models.Model): is_deleted = models.BooleanField(default=False) class ActivityJob(models.Model): activity_object = models.Forei...
0
2016-07-06T14:08:40Z
38,226,463
<p>You can use Django signals' <code>pre_delete</code> or <code>post_delete</code>. More details and examples are available in the Django Signals <a href="https://docs.djangoproject.com/en/1.9/ref/signals/#post-delete" rel="nofollow">documentation</a>.</p>
0
2016-07-06T14:23:38Z
[ "python", "django" ]
Position QWidgets in toolbar with PyQt
38,226,120
<p>I am trying to position some buttons in a toolbar, on my application. As you can see in these images, I need to put one of them in the right side, opposing the others. Something, like this:</p> <p>This is the toolbar that I have: <a href="http://i.stack.imgur.com/VPHoU.png" rel="nofollow"><img src="http://i.stack.i...
0
2016-07-06T14:08:52Z
38,229,704
<p>Add an expanding spacer widget before the label:</p> <pre><code>spacer = QtGui.QWidget(self) spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) toolbar.addWidget(spacer) toolbar.addWidget(label) </code></pre>
1
2016-07-06T17:05:55Z
[ "python", "pyqt", "position", "toolbar" ]
Worker connecting to server but executing on client with multiprocessing package (python 2.7)
38,226,181
<p>First post here, hello everyone.</p> <p>I have a problem with the multiprocessing package with python 2.7. I wish to have some processes run in parallel on a server; they do connect but they are executed locally instead.</p> <p>This is the code I use on the server (Ubuntu 14.04):</p> <pre><code>from multiprocessi...
1
2016-07-06T14:11:28Z
38,226,330
<p>You are starting your <code>Process</code> locally on your client. <code>p</code> and <code>for each in p: each.start()</code> is executed on your client, where it is run and starts the workers.</p> <p>While each <code>Process</code> "connects" to the <code>Manager</code> via <code>mgr.connect()</code> it never int...
0
2016-07-06T14:17:59Z
[ "python", "python-2.7", "multiprocessing", "python-multiprocessing" ]
How to show spline-functions (k=3)
38,226,188
<p>I have some data of x and y-coordinates where x-coordinate is increasing. I used a spline (k=3) to get a smooth curve of those points and plotted it. Now I would like to know the functions f(x) between those points but I don't know how to show or emit it so that I can use it later on.</p> <p>This is the code I used...
-1
2016-07-06T14:11:41Z
38,233,262
<p>You constructed the spline, now you can evaluate it, <code>spl(x)</code>, on any values of x.</p> <pre><code>&gt;&gt;&gt; from scipy.interpolate import InterpolatedUnivariateSpline as IUS &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x = np.arange(8) &gt;&gt;&gt; y = x**4 &gt;&gt;&gt; spl = IUS(x, y) &gt;&gt;&gt; sp...
0
2016-07-06T20:32:21Z
[ "python", "python-3.x", "scipy", "spline" ]
Conditional Constraint Linear Program in Python's Pulp Module
38,226,246
<p>Is there a way to add a constraint within pulp in python that would count all the variables above 5 and require that count to be greater than lets say 10? I currently have the following code but it only calls the function once;</p> <pre><code>def min_qty_constraint(vars): count = 0 for v in vars: if...
0
2016-07-06T14:14:32Z
38,229,868
<p>This is not linear. There is a way doing this with additional binary variables <code>y(i)</code>:</p> <pre><code>x(i) &gt;= 5 y(i) sum(i, y(i)) &gt;= 10 </code></pre> <p>(Note: I assumed <code>x(i)</code> are non-negative variables).</p>
1
2016-07-06T17:13:55Z
[ "python", "constraints", "linear-programming", "pulp" ]
Disable python chrome driver extensions without lose driver path
38,226,305
<p>I started having issues running a python script which uses selenium and chrome driver, so I want to disable extensions of chrome driver using python without losing the path where the driver is located.</p> <p>Currently I have the below:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.k...
0
2016-07-06T14:16:57Z
38,226,409
<p>Just provide multiple keyword arguments:</p> <pre><code>chrome_options = Options() chrome_options.add_argument("--disable-extensions") browser = webdriver.Chrome(executable_path=path_to_Ie, chrome_options=chrome_options) </code></pre>
0
2016-07-06T14:21:35Z
[ "python", "selenium" ]
Global variable not recognized in functions
38,226,310
<p>I know that this question looks exactly like so many other on here, because I just read them all and they all say to do what I already tried, and it hasn't worked (or I'm missing a subtle difference with my situation). Here is my situation:</p> <p>I am writing a scraper using Scrapy and Python 2.7.11, and my code l...
0
2016-07-06T14:17:11Z
38,226,519
<p>In your case the variable you want to access is not global, it is in the scope of the class.</p> <pre><code>global_var = "global" class Example: class_var = "class" def __init__(self): self.instance_var = "instance" def check(self): print(instance_var) # error print(self.ins...
6
2016-07-06T14:25:54Z
[ "python", "python-2.7", "scrapy", "global-variables" ]
Global variable not recognized in functions
38,226,310
<p>I know that this question looks exactly like so many other on here, because I just read them all and they all say to do what I already tried, and it hasn't worked (or I'm missing a subtle difference with my situation). Here is my situation:</p> <p>I am writing a scraper using Scrapy and Python 2.7.11, and my code l...
0
2016-07-06T14:17:11Z
38,226,531
<p>if you want to use variable in class, you can use self.xxx</p> <pre><code>class A: ... var = [] ... def test(self): ... self.var.append(10) ... print self.var </code></pre>
0
2016-07-06T14:26:07Z
[ "python", "python-2.7", "scrapy", "global-variables" ]
extraction of data from oracle into python pandas dataframe very slow
38,226,321
<p>I'm trying to use the cx_Oracle module to extract data from an Oracle database and into a Pandas dataframe.</p> <p>When using the fetchall() function as below</p> <pre><code>cursor = con.cursor() cursor.arraysize = 1000 results = cursor.execute("select * from TABLE1") rows = results.fetchall() </code></pre> <p>th...
1
2016-07-06T14:17:37Z
38,226,512
<p>Try this: </p> <pre><code>df_list = [] for chunk in pd.read_sql_query(sql , conn, chunksize=10): df_list.append(chunk) frames=pd.concat(df_list, ignore_index=True) </code></pre> <p>Also use <code>pandas.io.sql.read_sql</code></p>
0
2016-07-06T14:25:33Z
[ "python", "oracle", "pandas" ]
Boost.Python create handle from type
38,226,401
<p>In some places in exposing C++ code to python, I need to use a <code>PyObject*</code>. If I have an instance of a <code>boost::python::class_</code> object, I can invoke <code>ptr()</code> on it. But what if I just have the type? </p> <p>Basically, given the type list <code>boost::python::bases&lt;A, B, C&gt;</code...
2
2016-07-06T14:21:13Z
38,229,411
<p>Given a C++ type <code>T</code>, one can create a <a href="http://www.boost.org/doc/libs/1_61_0/libs/python/doc/html/reference/utility_and_infrastructure/boost_python_type_id_hpp.html#utility_and_infrastructure.boost_python_type_id_hpp.class_template_type_info" rel="nofollow"><code>boost::python::type_id</code></a> ...
1
2016-07-06T16:49:15Z
[ "python", "c++", "boost-python" ]
Handling error when no data exists to insert
38,226,527
<p>How do I make my code skip an empty variable when no data exists to insert?</p>
-2
2016-07-06T14:26:02Z
38,226,959
<p>Another option, and one I believe to be more correct in this situation, is to use a try except block. See <a href="http://stackoverflow.com/questions/1835756/using-try-vs-if-in-python">this question</a> on when to use <code>try-except</code> blocks vs <code>if</code> statements in these types of situations.</p> <pr...
0
2016-07-06T14:45:23Z
[ "python", "error-handling" ]
Python Flask SQLalchemy query filter by boolean values ignore False
38,226,607
<p>In my database I have rooms, these rooms have multiple boolean values like <code>has_tv</code>.</p> <p>A user can search for a room in a city, he will be redirected to the result page, where he finds all rooms in the searched city.</p> <p>Now there is a filter function which filters the current result set, by room...
0
2016-07-06T14:29:48Z
38,228,336
<p>First if you want to avoid hardcoding you need some way to get programatically which attributes you want to use to filter and what the appropriate field in the form is called. I guess you could scan the <code>Zimmer</code> class and get the name of all boolean attributes, but for now I simply asume a list of strings...
2
2016-07-06T15:52:50Z
[ "python", "python-2.7", "filter", "flask", "sqlalchemy" ]
SQLAlchemy hybrid property expression datetime conversion
38,226,645
<p>I'm using flask-sqlalchemy with python 2.7.</p> <p>I'm trying to create a property which I can use in a query to order by. I already learned I should use a <code>hybrid_property</code> for this with the according expression but I'm having trouble getting a <code>timedelta</code> object in the expression. </p> <p>T...
1
2016-07-06T14:31:36Z
38,794,536
<p>I've learned it really depends on the database backend you're using for this and which functions it provides. For example sqlite would not work as the database itself just doesn't have the capabilities to answer the query, but mysql does. Then it's really just about looking how the function would look like as an ori...
0
2016-08-05T17:10:06Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
Elasticsearch update document in python
38,226,801
<p>I am trying to update document in elasticsearch python, </p> <pre><code>from elasticsearch import Elasticsearch from datetime import datetime from scapy.all import * import json # es = Elasticsearch() es = Elasticsearch(['http://localhost:9200']) doc = getDoc("1") print doc if doc != None: doc['_op_t...
0
2016-07-06T14:38:45Z
38,227,718
<p>Since the second argument in helpers.bulk() method is should be an <strong>iterable</strong>, try enclosing it in a list.</p> <p>Also looking at your code, it seems you are expecting only one document from the getDoc() function. So it would be better if you use simple es.update() method instead of using helpers.bul...
0
2016-07-06T15:22:43Z
[ "python", "elasticsearch", "updates" ]
Elasticsearch update document in python
38,226,801
<p>I am trying to update document in elasticsearch python, </p> <pre><code>from elasticsearch import Elasticsearch from datetime import datetime from scapy.all import * import json # es = Elasticsearch() es = Elasticsearch(['http://localhost:9200']) doc = getDoc("1") print doc if doc != None: doc['_op_t...
0
2016-07-06T14:38:45Z
38,231,447
<p><a href="http://stackoverflow.com/questions/30598152/how-to-update-a-document-using-elasticsearch-py">This</a> solution did work for me.</p> <pre><code>doc= ess.get(...) # modify my doc and ... coll = Elasticsearch() coll.update(index='stories-test',doc_type='news',id=hit.meta.id, body= {"do...
0
2016-07-06T18:40:28Z
[ "python", "elasticsearch", "updates" ]
How to extract special characters using NLTK RegexpParser Chunk for POS_tagged words in Python
38,226,864
<p>I have some text for example say: <code>80% of $300,000 Each Human Resource/IT Department.</code></p> <p>I would need to extract <code>$300,000</code> along with the words <code>Each Human Resource/IT Department</code></p> <p>I have used pos tagging to tag the words after tokenizing. I was able to extract 300,000 ...
0
2016-07-06T14:41:38Z
38,292,371
<p>You need to add &lt;\$>? in your grammar.</p> <pre><code>chunkGram = r"""chunk: {&lt;DT&gt;+&lt;NN.*&gt;+&lt;NN.*&gt;?|&lt;\$&gt;?&lt;CD&gt;+&lt;NN&gt;?|&lt;NNP&gt;?}""" </code></pre> <p><strong>Code :</strong></p> <pre><code>import nltk from nltk.tokenize import PunktSentenceTokenizer text = '80% of $300,000 Ea...
0
2016-07-10T13:26:16Z
[ "python", "nlp", "nltk", "pos-tagging", "text-chunking" ]
What is the right way to use NLTK stopwords?
38,226,917
<p>I'm working on a bag of words project and I want to remove stop words from the NLTK list of stop words. At moment, I'm doing this:</p> <p><code>words.difference_update(set(stopwords.words("english")))</code></p> <p>(words is a set containing all the words in the corpus)</p> <p>However, when I look at the contents...
0
2016-07-06T14:43:48Z
38,227,978
<p>There's no right way for using stopwords. It depends on what task you want to accomplish. However, based on the information you provided, it seems like NLTK is making an assumption that you're splitting your document by whitespace and punctuations. However, I can make a guess that the stopword list will also contain...
0
2016-07-06T15:35:36Z
[ "python", "nltk", "stop-words" ]
PySpark: retrieve mean and the count of values around the mean for groups within a dataframe
38,227,007
<p>My raw data comes in a tabular format. It contains observations from different variables. Each observation with the variable name, the timestamp and the value at that time.</p> <blockquote> <p>Variable [string], Time [datetime], Value [float]</p> </blockquote> <p>The data is stored as Parquet in HDFS and loaded ...
3
2016-07-06T14:47:37Z
38,246,827
<p>In general there is no need for aggregation with join. Instead you can compute statistics without collapsing the rows using window functions. Assuming your data looks like this:</p> <pre><code>import numpy as np import pandas as pd from pyspark.sql.functions import mean n = 10000 k = 20 np.random.seed(100) df = ...
2
2016-07-07T13:31:08Z
[ "python", "python-2.7", "hadoop", "apache-spark", "spark-dataframe" ]
How to do a GroupBy without any mean for other features?
38,227,049
<p>I'm working with python pandas DataFrames and I want to group my Data by category and I don't want any mean or median for other features (PriceBucket, success_rate and products_by_number). My DataFrame look like this :</p> <pre><code> PriceBucket success_rate products_by_number category 0 0 6.890...
1
2016-07-06T14:49:49Z
38,227,190
<p>Assuming you dataframe is <code>df</code> then you want:</p> <pre><code>print df.set_index(['category', 'PriceBucket']) success_rate products_by_number category PriceBucket 10 0 6.890 149837 1 7...
2
2016-07-06T14:56:18Z
[ "python", "pandas", "dataframe", "group-by" ]
Replacing a string in a file in python
38,227,125
<p>What my text is</p> <blockquote> <p>$TITLE = XXXX YYYY<br> 1 $SUBTITLE= XXXX YYYY ANSA<br> 2 $LABEL = first label<br> 3 $DISPLACEMENTS<br> 4 $MAGNITUDE-PHASE OUTPUT<br> 5 $SUBCASE ID = 30411</p> </blockquote> <p>What i want</p> <blockquote> <p>$TITLE = XXXX YYYY<br> 1 $SUBTITLE= XXXX Y...
1
2016-07-06T14:52:56Z
38,227,558
<p>Apart from many blood-curdling but noncritical problems, you are calling <code>readlines()</code> in the middle of an iteration using <code>readline()</code>, causing you to read lines not from the beginning of the file but from the current position of the <code>fo</code> handle, i.e. after the line containing 3041...
1
2016-07-06T15:14:57Z
[ "python", "python-2.7" ]
How do I input filepath by sys.stdin in python?
38,227,131
<p>I wrote a simple py by using sys.stdin</p> <pre><code>import sys for line in sys.stdin: print "hello" + line </code></pre> <p>While I need to import filepath as import to execute in my function. When I use sys.stdin and run it into command line.</p> <pre><code> ~$ python metrics.py /Users/glange/graphs/B...
0
2016-07-06T14:53:08Z
38,227,270
<p>You can use .rstrip() to remove the new line character</p> <pre><code>print "hello" + line.rstrip() </code></pre>
2
2016-07-06T14:59:40Z
[ "python", "apache-spark", "pyspark" ]
Python+Selenium Scrape Error: ElementNotVisibleException
38,227,167
<p>I'm currently trying to use Selenium/Python/PhantomJS to scrape the results of the form below:</p> <p><a href="http://gis.vgsi.com/newhavenct/Sales.aspx" rel="nofollow">http://gis.vgsi.com/newhavenct/Sales.aspx</a></p> <p>It looks like when I try to click on the search button, I get an ElementNotVisibleException e...
0
2016-07-06T14:54:58Z
38,227,338
<p>A portion of the screen is not visible by Selenium. It may be that another element lies on top of the one you are trying to click.</p> <p>For me what always works without spending hours searching for the cause is to click using Javascript:</p> <pre><code>self.driver.execute_script("arguments[0].click();", elt) </c...
1
2016-07-06T15:02:38Z
[ "python", "selenium", "web-scraping", "phantomjs" ]
Python+Selenium Scrape Error: ElementNotVisibleException
38,227,167
<p>I'm currently trying to use Selenium/Python/PhantomJS to scrape the results of the form below:</p> <p><a href="http://gis.vgsi.com/newhavenct/Sales.aspx" rel="nofollow">http://gis.vgsi.com/newhavenct/Sales.aspx</a></p> <p>It looks like when I try to click on the search button, I get an ElementNotVisibleException e...
0
2016-07-06T14:54:58Z
38,227,377
<p>Requested element has attribute <code>style="display:none;"</code>, so you need to make it visible</p> <p>Try to use following code:</p> <pre><code>self.driver.execute_script('document.getElementById("MainContent_btnSearch").style.display="block";') self.driver.find_element_by_id("MainContent_btnSearch").click() <...
1
2016-07-06T15:04:34Z
[ "python", "selenium", "web-scraping", "phantomjs" ]
Code for finding Pisano Period showing wrong output
38,227,229
<p>I want to calculate Pisano Period for any integer <code>2 &lt;= m &lt;= 100000</code>.</p> <p>This code is currently not working for <code>m&gt;4</code>, for <code>m&gt;4</code> output showing is <code>9</code>.What am I doing wrong in the below code.</p> <pre><code>def fib(n): i=0 f=[] while(i&lt;=n):...
0
2016-07-06T14:57:50Z
38,227,737
<p>Your stopping condition is <code>p[::-1] != p[0:]</code>, which checks if the list is palindromic. Your stopping condition should be if the list repeats.</p> <p>One way to do it would be to use the recurrence relation representing the <em>n</em>-th Fibonacci number, which still holds modulo <em>m</em>. There are on...
0
2016-07-06T15:23:34Z
[ "python", "python-3.x", "fibonacci", "mod" ]
Append a range of numbers in a List in Python, as 1 Line of Code
38,227,277
<p>I am looking for a list of months in Python. The result will be, not surprisingly (with syntax error)</p> <pre><code>months = [1, 2, 3, 4, 5, 6, ..., 12] </code></pre> <p>To obtain it, I write a piece of Python code:</p> <pre><code>months = [] for x in range(1, 12): months.append(x) </code></pre> <p>Can I do...
-5
2016-07-06T14:59:55Z
38,227,306
<p>yes</p> <pre><code>months = range(1, 13) </code></pre> <p>if it's python3 then:</p> <pre><code>months = list(range(1,13)) </code></pre>
3
2016-07-06T15:01:06Z
[ "python", "list" ]
Append a range of numbers in a List in Python, as 1 Line of Code
38,227,277
<p>I am looking for a list of months in Python. The result will be, not surprisingly (with syntax error)</p> <pre><code>months = [1, 2, 3, 4, 5, 6, ..., 12] </code></pre> <p>To obtain it, I write a piece of Python code:</p> <pre><code>months = [] for x in range(1, 12): months.append(x) </code></pre> <p>Can I do...
-5
2016-07-06T14:59:55Z
38,227,409
<p>You can also use a list comprehension if you're feeling groovy.</p> <pre><code>months = [x for x in range(1,13)] </code></pre>
0
2016-07-06T15:06:25Z
[ "python", "list" ]
Selenium with Marionette on Windows: "Permission Denied"
38,227,399
<p>After updating to Firefox 47 and installing Marionette (instructions here: <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver</a>) my code is throwing the following error:</p> <pre><code>from sel...
1
2016-07-06T15:05:43Z
38,227,436
<p>You can just simply downgrade your Firefox to version 45 as Firefox 47 is not compatible yet.</p> <p>Or</p> <p>You may refer to this link. <a href="http://stackoverflow.com/questions/37693106/selenium-2-53-not-working-on-firefox-47">Selenium 2.53 not working on Firefox 47</a></p> <p>You can find a solution to you...
1
2016-07-06T15:08:21Z
[ "python", "selenium", "firefox", "firefox-marionette" ]
Python No module named
38,227,410
<p>I have a custom module that I am trying to read from a folder under a hierarchy:</p> <pre><code>&gt; project-source /tests /provider my_provider.py settings_mock.py __init__.py </code></pre> <p>I am trying to call, from my_provider.py </p> <pre><code>import tests...
1
2016-07-06T15:06:25Z
38,227,494
<p>You only have one small mistake. To use subfolders, you need <code>__init__.py</code>, not <code>init.py</code> as you stated in the question. The difference is that <code>__init__</code> is a builtin function of python, whereas <code>init</code> is not. Having this file in each subfolder tells the pyhon interpreter...
1
2016-07-06T15:11:31Z
[ "python", "python-2.7" ]
Django Rest framework: passing request object around makes it lose POST data in newer version
38,227,476
<p>I'm upgrading a site from Django 1.4 to Django 1.9</p> <p>I have a view passing control to another view like this:</p> <pre><code>@csrf_protect @api_view(['POST']) @authentication_classes((SessionAuthentication,)) def preview(request, project_id, channel_type, format=None): return build(request, projec...
3
2016-07-06T15:10:13Z
38,339,312
<p>You could just separate out the logic you're storing in the <code>build</code> view into a common function used by both endpoints without any decorators e.g. <code>_build</code> – this way whatever is happening within the decorators shouldn't occur in the case of the call within <code>preview</code>.</p> <pre><co...
8
2016-07-12T21:39:43Z
[ "python", "django", "django-rest-framework" ]
Problems with installation of Pillow
38,227,515
<p>I am running Python 2.7.1.1 with Anaconda2 4.0.0 64-bit on a Windows 7 machine. I'm trying to install Pillow for imaging, and after having read through every thread I could find, I am still unable to reach a solution. I have installed and uninstalled Pillow through various means including: </p> <pre><code>pip insta...
0
2016-07-06T15:12:42Z
38,227,755
<p>It sounds like Anaconda isn't playing nice with your system due to the fact that you have two interpreters installed (Anaconda's and Python 2.7.1.1). I would remove everything (Python, Anaconda, etc) and either reinstall Anaconda fresh, or the get the newest version of Python from python.org (2.7.12). </p> <p>Perso...
0
2016-07-06T15:24:26Z
[ "python", "python-2.x", "pillow" ]
Problems with installation of Pillow
38,227,515
<p>I am running Python 2.7.1.1 with Anaconda2 4.0.0 64-bit on a Windows 7 machine. I'm trying to install Pillow for imaging, and after having read through every thread I could find, I am still unable to reach a solution. I have installed and uninstalled Pillow through various means including: </p> <pre><code>pip insta...
0
2016-07-06T15:12:42Z
38,233,918
<p>If you can't <code>import</code> a package into Python but it is <em>definitely</em> there in the <code>site-packages</code> folder, then you are more than likely running the <em>wrong</em> Python interpreter.</p> <p>You can check this by running <code>python</code> from the command line and then entering:</p> <pr...
0
2016-07-06T21:17:46Z
[ "python", "python-2.x", "pillow" ]
python function to generate a timestamp in a range of timestamps
38,227,591
<p>What is the most efficient or most readable or shortest way to generate a timestamp in a range on timestamps. Basically a function that will return a timestamp.</p> <p>Lets say timestamp has to be later than <code>1999-04-01T07:00:00Z</code> and earlier than <code>2016-06-03T15:18:07Z</code> in this exact format. <...
2
2016-07-06T15:16:37Z
38,227,894
<blockquote> <p>as a url param to GET some entities</p> </blockquote> <p>It seems that you need a <em>string</em> of a certain format.</p> <blockquote> <p>is this some certain standard of a format? Does it have name?</p> </blockquote> <p>Take a look at <a href="https://en.wikipedia.org/wiki/ISO_8601" rel="nofoll...
1
2016-07-06T15:31:30Z
[ "python" ]
How to find the difference, mean, sum between all pairs of rows in pandas dataframe?
38,227,593
<p>I have the following pandas DataFrame.</p> <pre><code>import pandas as pd df = pd.read_csv('filename.csv') print(df) dog A B C 0 dog1 0.787575 0.159330 0.053095 1 dog10 0.770698 0.169487 0.059815 2 dog11 0.792689 0.152043 0.055268 3 dog12 0.785066 ...
1
2016-07-06T15:16:47Z
38,227,877
<p>Consider the following dataframe:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'Dog': list('ABCDEFG'), 'A': range(7)})[['Dog', 'A']] df </code></pre> <p><a href="http://i.stack.imgur.com/audgV.png" rel="nofollow"><img src="http://i.stack.imgur.com/audgV.png" alt="enter image descriptio...
3
2016-07-06T15:30:40Z
[ "python", "numpy", "pandas", "dataframe" ]
Numpy find number of occurrences in a 2D array
38,227,751
<p>Is there a numpy function to count the number of occurrences of a certain value in a 2D numpy array. E.g.</p> <pre><code>np.random.random((3,3)) array([[ 0.68878371, 0.2511641 , 0.05677177], [ 0.97784099, 0.96051717, 0.83723156], [ 0.49460617, 0.24623311, 0.86396798]]) </code></pre> <p>How do ...
1
2016-07-06T15:24:12Z
38,227,897
<pre><code>arr = np.random.random((3,3)) # find the number of elements that get really close to 1.0 condition = arr == 0.83723156 # count the elements np.count_nonzero(condition) </code></pre> <p>The value of <code>condition</code> is a list of booleans representing whether each element of the array satisfied the cond...
3
2016-07-06T15:31:36Z
[ "python", "numpy" ]
Numpy find number of occurrences in a 2D array
38,227,751
<p>Is there a numpy function to count the number of occurrences of a certain value in a 2D numpy array. E.g.</p> <pre><code>np.random.random((3,3)) array([[ 0.68878371, 0.2511641 , 0.05677177], [ 0.97784099, 0.96051717, 0.83723156], [ 0.49460617, 0.24623311, 0.86396798]]) </code></pre> <p>How do ...
1
2016-07-06T15:24:12Z
38,227,905
<p>To count the number of times <code>x</code> appears in any array, you can simply sum the boolean array that results from <code>a == x</code>:</p> <pre><code>&gt;&gt;&gt; col = numpy.arange(3) &gt;&gt;&gt; cols = numpy.tile(col, 3) &gt;&gt;&gt; (cols == 1).sum() 3 </code></pre> <p>It should go without saying, but I...
0
2016-07-06T15:31:54Z
[ "python", "numpy" ]
Numpy find number of occurrences in a 2D array
38,227,751
<p>Is there a numpy function to count the number of occurrences of a certain value in a 2D numpy array. E.g.</p> <pre><code>np.random.random((3,3)) array([[ 0.68878371, 0.2511641 , 0.05677177], [ 0.97784099, 0.96051717, 0.83723156], [ 0.49460617, 0.24623311, 0.86396798]]) </code></pre> <p>How do ...
1
2016-07-06T15:24:12Z
38,228,464
<p>For floating point arrays <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isclose.html" rel="nofollow"><code>np.isclose</code></a> is much better option than either comparing with the exactly same element or defining a custom range.</p> <pre><code>&gt;&gt;&gt; a = np.array([[ 0.68878371, 0.2...
1
2016-07-06T15:59:12Z
[ "python", "numpy" ]
Merging nested lists with overlap
38,227,798
<p>I have to merge nested lists which have an overlap. I keep thinking that there has to be an intelligent solution using list comprehensions and probably difflib, but I can't figure out how it should work. My lists look like this:</p> <pre><code>[['C', 'x', 'F'], ['A', 'D', 'E']] </code></pre> <p>and</p> <pre><code...
1
2016-07-06T15:26:24Z
38,228,050
<p>You can try something like this.</p> <pre><code>list1 = [['C', 'x', 'F'], ['A', 'D', 'E']] list2 = [['x', 'F', 'G', 'x'], ['D', 'E', 'H', 'J']] for x in range(len(list1)): for element in list2[x]: if element not in list1[x]: list1[x].append(element) print list1[x] </code></pre> <p>Outp...
0
2016-07-06T15:38:48Z
[ "python", "list", "merge", "nested", "difflib" ]
Which port is used for updating Anaconda?
38,227,824
<p>I have an old version of Anaconda setup on a machine without (virtually) access to Internet and I would like to update its version as follows :</p> <pre><code> conda update conda conda update anaconda </code></pre> <p>I would be able to setup a port forwarding through another machine connected to the Internet, bu...
0
2016-07-06T15:27:47Z
38,236,125
<p><code>conda</code> usually relies on HTTPS (443), though it's also possible to specify a channel that relies on HTTP (80). You can see this for yourself by running Conda in <code>debug</code> mode and examining its output. For instance, here's a snippet of the output of <code>conda --debug update conda</code>:</p> ...
0
2016-07-07T01:00:53Z
[ "python", "ide", "port", "updates", "anaconda" ]
Sending Sparse Files
38,227,854
<p>I've been messing around with sockets in Python and I'd like to be able to send a sparse image file from one machine to another. As expected, sending a sparse file over a python socket doesn't preserve the sparseness of the file. I'd like to do a sparse tar and send it that way, but I just can't figure it out.</p> ...
0
2016-07-06T15:29:49Z
38,232,276
<p>Holes in files are normally created if you write to the beginning of a file, seek to the end and write there. If you read the file you are reading zeros even if there are holes in the file. When you send the files the literal bytes are sent and of course also read. When you then write the bytes all bytes will be wri...
1
2016-07-06T19:29:40Z
[ "python", "linux", "python-2.7", "sockets" ]
Pandas hierarchical columns
38,227,855
<p>Say I have two dataframes, is it possible to concatenate them by columns, but with the second one appearing as a single column in the concatenated dataframe?</p> <p>Pictorially, I'm looking for:</p> <pre><code>df_A: C1 C2 C3 1 2 3 11 22 33 df_B: D1 D2 D3 3 4 5 33 44 55 Concatenated: C1 C2 C3 df_B D1...
1
2016-07-06T15:29:49Z
38,228,325
<p>You can contruct a <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html" rel="nofollow">MultiIndex</a> to created a DataFrame with the desired appearance:</p> <pre><code>import pandas as pd df_A = pd.DataFrame([(1,2,3), (11,22,33)], columns=['C1', 'C2', 'C3']) df_B = pd.DataFrame([(3,4,5), (33,44,55)]...
2
2016-07-06T15:52:05Z
[ "python", "pandas", "dataframe" ]
How to stop Python from executing script on import?
38,227,926
<p>I have a Tkinter-based GUI with a series of buttons. I want one of these buttons to execute a command from another script - <code>testExecute.py</code> - when pressed (code for both scripts included below). </p> <p>Right now, when I start the GUI, the external script function appears to be executing on <code>impor...
0
2016-07-06T15:33:02Z
38,227,965
<p>When you create the button you are executing the function directly. Instead you should bind to the function itself. So</p> <pre><code> abtn = Button(self, text="Activate", command = testEx.testFunc()) </code></pre> <p>should be</p> <pre><code> abtn = Button(self, text="Activate", command = testEx.testFunc) </...
4
2016-07-06T15:35:15Z
[ "python", "python-3.x", "tkinter" ]
How to stop Python from executing script on import?
38,227,926
<p>I have a Tkinter-based GUI with a series of buttons. I want one of these buttons to execute a command from another script - <code>testExecute.py</code> - when pressed (code for both scripts included below). </p> <p>Right now, when I start the GUI, the external script function appears to be executing on <code>impor...
0
2016-07-06T15:33:02Z
38,228,086
<p>Check out <a href="http://effbot.org/tkinterbook/button.htm" rel="nofollow">http://effbot.org/tkinterbook/button.htm</a>. </p> <p>The problem is that you are <em>calling</em> the command callback during initialization. Change, </p> <pre><code>abtn = Button(self, text="Activate", command = testEx.testFunc()) </code...
3
2016-07-06T15:40:23Z
[ "python", "python-3.x", "tkinter" ]
Copy a django project in another PC (postgreSQL)
38,227,941
<p>I have a project in my notebook and I want copy it in my desktop. I use windows 7 in both</p> <p>I installed python 3.5 (a different version, to be honest, in my notebook was 3.4) and postgreSQL. <em>Of course</em> the directory structure is different. In my notebook is:</p> <p>C:/Python34/scripts/myproject1 </p> ...
0
2016-07-06T15:34:04Z
38,231,997
<p>Python 3.5 is not currently supported by the python Postgres driver <a href="http://initd.org/psycopg/docs/install.html" rel="nofollow"><code>psycopg2</code></a>:</p> <blockquote> <p>The current psycopg2 implementation supports:</p> <ul> <li>Python 2 versions from 2.5 to 2.7</li> <li>Python 3 versions fr...
1
2016-07-06T19:11:59Z
[ "python", "django", "postgresql" ]
Copy a django project in another PC (postgreSQL)
38,227,941
<p>I have a project in my notebook and I want copy it in my desktop. I use windows 7 in both</p> <p>I installed python 3.5 (a different version, to be honest, in my notebook was 3.4) and postgreSQL. <em>Of course</em> the directory structure is different. In my notebook is:</p> <p>C:/Python34/scripts/myproject1 </p> ...
0
2016-07-06T15:34:04Z
38,283,709
<p>I think Python 3.5 require <code>MS Visual C++ 2015</code> (look <a href="http://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat">here</a>) so I installed it. I'm not sure that is a good thing because it installed something like 17 (!) more <code>MS .NET Framework</code> 16 (!) <code>MS SQL Se...
0
2016-07-09T16:05:50Z
[ "python", "django", "postgresql" ]
Optimization of this Python code - webscraping and output results to CSV file
38,227,971
<p>I am trying to scrape data from a few thousands pages. The code I have works fine for about a 100 pages, but then slows down dramatically. I am pretty sure that my Tarzan-like code could be improved, so that the speed of the webscrapping process increases. Any help would be appreciated. TIA!</p> <p>Here is the simp...
0
2016-07-06T15:35:26Z
38,228,062
<p>The main bottleneck is that <em>your code is synchronous</em> (blocking). You don't proceed to the next URL until you finish processing the current one.</p> <p>You need to make things asynchronously either by switching to <a href="http://scrapy.org/" rel="nofollow"><code>Scrapy</code></a> which solves this problem ...
0
2016-07-06T15:39:20Z
[ "python", "csv", "web-scraping", "beautifulsoup" ]
Optimization of this Python code - webscraping and output results to CSV file
38,227,971
<p>I am trying to scrape data from a few thousands pages. The code I have works fine for about a 100 pages, but then slows down dramatically. I am pretty sure that my Tarzan-like code could be improved, so that the speed of the webscrapping process increases. Any help would be appreciated. TIA!</p> <p>Here is the simp...
0
2016-07-06T15:35:26Z
38,275,597
<p>If you want to go really fast without a lot of complex code, you need to A) Segregate the requests from the parsing (because the parsing is blocking the thread you'd otherwise use to make the request), and B) Make requests concurrently and parse them concurrently. So, I'd do a couple things:</p> <ol> <li>Request a...
0
2016-07-08T21:24:00Z
[ "python", "csv", "web-scraping", "beautifulsoup" ]
Optimization of this Python code - webscraping and output results to CSV file
38,227,971
<p>I am trying to scrape data from a few thousands pages. The code I have works fine for about a 100 pages, but then slows down dramatically. I am pretty sure that my Tarzan-like code could be improved, so that the speed of the webscrapping process increases. Any help would be appreciated. TIA!</p> <p>Here is the simp...
0
2016-07-06T15:35:26Z
38,275,994
<p>Perhaps this is just a bug in simplification, but looks like you are opening 'test.csv' multiple times, but closing it only once. Not sure if that's the cause for unexpected slowdown when number of URLs grows above 100, but if you want all data to go in one csv file, you should probably stick to opening the file an...
0
2016-07-08T22:03:35Z
[ "python", "csv", "web-scraping", "beautifulsoup" ]
How to simulate Orbits
38,227,995
<p>When I run my code the earth seems to tend towards a limit instead of orbiting round the sun, am I missing equations or is there something wrong with my code?</p> <p>Here is the error I get:</p> <pre><code>Warning (from warnings module): File "C:\Python32\lib\site-packages\visual\visual_all.py", line 52 retu...
2
2016-07-06T15:36:27Z
38,228,111
<p>I notice your gravity equation is wrong. You are supposed to divide by the radius squared, not twice the radius. Instead of <code>mag(Distance)*2</code>, try <code>Distance * Distance</code>, or <code>Distance**2</code></p>
0
2016-07-06T15:41:53Z
[ "python", "vpython" ]
Conditionally set pandas dataframe column values
38,228,082
<p>This question is exactly as the following request, with one more twist, </p> <ul> <li><a href="http://stackoverflow.com/questions/23307301/pandas-replacing-column-values-in-dataframe">Pandas: Replacing column values in dataframe</a></li> <li><a href="http://stackoverflow.com/questions/33283579/conditional-substitut...
2
2016-07-06T15:40:11Z
38,232,996
<p>You can use square brackets to access a column name using the string rather than as an attribute, I also strongly recommend that you ditch this habit of accessing columns by attribute as this can lead to confusing behaviour such as if you have a column name <code>sum</code> and you do <code>df.sum</code> will return...
1
2016-07-06T20:16:35Z
[ "python", "python-3.x", "pandas", "dataframe" ]
Same Python code, same data, different results on different machines
38,228,088
<p>I have a very strange problem that I get different results on the same code and same data on different machines.</p> <p>I have a python code based on <code>numpy/scipy/sklearn</code> and I use <code>anaconda</code> as my base python distribution. Even when I copy the entire project directory (which includes all the...
3
2016-07-06T15:40:30Z
38,233,222
<p>If your code uses linear algebra, check it. Generally, roundoff errors are not deterministic, and if you have badly conditioned matrices, it can be it.</p>
0
2016-07-06T20:29:59Z
[ "python", "numpy", "scipy", "scikit-learn", "anaconda" ]
Line plot in pandas series generates extra indices
38,228,090
<p>I have a Pandas series as follows:</p> <pre><code>2014 5668 2015 6024 2016 3903 Name: year, dtype: int64 </code></pre> <p>I try to plot a line graph where x axis labels are years, and y axis labels are corresponding values. I do this:</p> <pre><code>ax = year_counts.plot(kind='line', figsize=[10, 5], mar...
0
2016-07-06T15:40:35Z
38,231,023
<p>Why don't you simply specify the columns you like to plot in your <code>year_counts.plot()</code>? For example:</p> <pre><code>import pandas as pd data = [[2014, 5668], [2015, 6024], [2016, 3903]] df = pd.DataFrame(data, columns=['years','value']) df.plot('years', 'value') </code></pre>
0
2016-07-06T18:18:01Z
[ "python", "pandas", "matplotlib" ]
How to scrape for specific HTML span elements that get loaded with JQuery
38,228,091
<p>I am writing a python app that scrapes sensor data from a web-app that I made. I want to use lxml to gather certain span elements from the HTML that get updated periodically with a JQuery script. It seems as though lxml does not grab the text that gets updated with JQuery because I only retrieve the empty string tha...
0
2016-07-06T15:40:36Z
38,228,319
<blockquote> <p>JQuery makes an ajax request to get the value from an XML document.</p> </blockquote> <p>You need to <em>simulate</em> that AJAX request with <code>requests</code>. You can either do it manually, or copy the request as cURL (from the browser developer tools->network tab) and use this <a href="http://...
1
2016-07-06T15:51:49Z
[ "jquery", "python", "html", "lxml" ]
Pandas: No column names in data file
38,228,098
<p>I am trying to process a dataset to play with for DataScience but it does not have column names. The output of <code>df.head()</code> as shown below:</p> <pre><code> 1 73 Not in universe 0 0.1 0.2 Not in universe.1 0 2 58 Self-employed-not incorporated 4 34 0 Not in universe...
0
2016-07-06T15:41:12Z
38,228,227
<p>You loaded the file without specifying whether it had a header row or not, by default it infers it from the first row, if it's missing then pass <code>header=None</code>:</p> <pre><code>df = pd.read_csv(file_path, header=None) </code></pre>
1
2016-07-06T15:47:35Z
[ "python", "python-2.7", "numpy", "pandas" ]
Django runs with wrong python version
38,228,129
<p>I run the django on my ubuntu server. On the server, there are two different versions of python, which are python 2.x and 3.x. I use the request module of 3.x, but the server default uses the python of 2.x that occurs the error. How can that be solved? Thanks</p> <p>I run the django with apache server, and here is ...
0
2016-07-06T15:43:04Z
38,228,761
<p>You will point your server to the correct python interpreter. How that is done will depend on the server software you are using. This tutorial shows the apache configuration, close to the bottom of the page. Note the "python-path" being designated. </p> <p><a href="https://www.digitalocean.com/community/tutorials/h...
1
2016-07-06T16:14:22Z
[ "python", "django", "django-models" ]
Pandas: how to make algorithm faster
38,228,150
<p>I have the task: I should find some data in big file and add this data to some file. File, where I search data is <code>22 million string</code> and I divide it using <code>chunksize</code>. In other file I have column with <code>600 id of users</code> and I find info about every users in big file. The first I divi...
0
2016-07-06T15:44:05Z
38,232,533
<p>There are some issues in your code</p> <ol> <li><p><code>zip</code> takes arguments that may be of different length</p></li> <li><p><code>dateutil.relativedelta</code> may not be compatible with pandas Timestamp. With pandas 0.18.1 and python 3.5, I'm getting this:</p> <pre><code>now = pd.Timestamp.now() now Out[4...
1
2016-07-06T19:46:13Z
[ "python", "pandas" ]
Complicated Nested Dictionary
38,228,153
<p>I have Data as below</p> <pre><code>Value(City) Key1 Key3 Key4 Baltimore 111111 111 122 Towson 111111 111 122 Columbia 111111 111 122 SilverSpring 111111 222 ...
-2
2016-07-06T15:44:20Z
38,228,351
<p>Here is a short example done at the python prompt - a great way to experiment with code before creating a module to test concepts that you're learning.</p> <pre><code>&gt;&gt;&gt; dict1 = {'a':0,'b':1} &gt;&gt;&gt; dict2 = {'c':2,'d':3} &gt;&gt;&gt; nestedDict = {'key0':dict1, 'key1':dict2} &gt;&gt;&gt; dict1 {'a':...
0
2016-07-06T15:53:18Z
[ "python", "dictionary" ]
Do something on every Celery Task run
38,228,155
<p>Assume I have some Celery tasks which are based on one abstract task.</p> <pre><code>class BaseTask(Task): abstract = True def on_failure(self, exc, task_id, args, kwargs, einfo): logging.info('Task failed') def on_success(self, retval, task_id, args, kwargs): logging.info('Task succes...
0
2016-07-06T15:44:23Z
38,229,216
<p>You can override the <code>__call__</code> method. This will work both if you call the task synchronously with <code>task1(1)</code> or call it asynchronously, with <code>task1.delay(1)</code>. In the following example, you'll get "CALLED!" on the console or in the logs depending on how you call the task and how you...
3
2016-07-06T16:37:41Z
[ "python", "celery" ]
Do something on every Celery Task run
38,228,155
<p>Assume I have some Celery tasks which are based on one abstract task.</p> <pre><code>class BaseTask(Task): abstract = True def on_failure(self, exc, task_id, args, kwargs, einfo): logging.info('Task failed') def on_success(self, retval, task_id, args, kwargs): logging.info('Task succes...
0
2016-07-06T15:44:23Z
38,371,648
<p>If need 'semantically beautiful' method, you can try signals.</p> <p><a href="http://use%20celery%20signals%20-%20http://docs.celeryproject.org/en/latest/userguide/signals.html" rel="nofollow">http://docs.celeryproject.org/en/latest/userguide/signals.html</a></p> <p>Here is another useful post on pre/post task cal...
0
2016-07-14T10:21:08Z
[ "python", "celery" ]
How to select values in between strings and place in column of dataframe using regex in python
38,228,163
<p>I have a large dataframe containing a column titled "Comment" </p> <p>within the comment section I need to pull out 3 values and place into separate columns i.e. (Duty cycle, gas, and pressure) </p> <p>"Data collection START for Duty Cycle: <strong>0</strong>, Gas: <strong>Vacuum</strong> Pressure: <strong>0.00002...
4
2016-07-06T15:44:44Z
38,229,158
<p>use <code>str.extract</code> with a regex.</p> <pre><code>regex = r'Duty Cycle: (?P&lt;Duty_Cycle&gt;\d+), Gas: (?P&lt;Gas&gt;\w+) Pressure: (?P&lt;Pressure&gt;\S+) Torr' df1 = eventsDf.comment.str.extract(regex, expand=True) df1 </code></pre> <p><a href="http://i.stack.imgur.com/MEI1S.png" rel="nofollow"><img src...
2
2016-07-06T16:34:22Z
[ "python", "regex", "pandas", "dataframe" ]
C++ destructor calling of boost::python wrapped objects
38,228,170
<p>Does boost::python provide any guarantee when the C++ destructor of a wrapped object is called considering the moment of reaching the zero reference count of the corresponding python object? </p> <p>I am concerned about a C++ object that opens a file for writing and performs the file closing in its destructor. Is i...
1
2016-07-06T15:45:05Z
38,238,013
<p>Boost.Python makes the guarantee that if the Python object has ownership of the wrapped C++ object, then when the Python object is deleted, the wrapped C++ object will be deleted. The Python object's lifetime is dictated by Python, wherein when an object’s reference count reaches zero, the object <em>may</em> be ...
1
2016-07-07T05:21:35Z
[ "python", "c++", "boost-python" ]
Split string with parenthesis within parenthesis in Python
38,228,223
<p>I have two strings types; each type can have one of the following exemplary forms:</p> <pre><code>str = ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) </code></pre> <p>or</p> <pre><code>str = ((0, 1, 2), (3, 4, 5, 6, 7), (8, 9)) </code></pre> <p>The number of substrings within parentheses in the second form can range from 1 t...
0
2016-07-06T15:47:23Z
38,228,407
<p>If these are the only two options you can use:</p> <pre><code>if type(str[0]) == int: print 'TYPE1' else if type(str[0]) == tuple: print 'TYPE2' else: print 'unknown' </code></pre> <p>and for your second question, in case you're in form 2, use:</p> <pre><code>list(sum(str, ())) </code></pre> <p>to flatt...
0
2016-07-06T15:56:06Z
[ "python", "regex", "string", "substring" ]
Extract a diagonal cross profile from a 2D Numpy array
38,228,277
<p>If I have a 100x100 2D Numpy array and I want to extract the cross profile that is centred at (50,50) at an angle of 25 degrees (to the horizontal). How can this be achieved?</p> <p>I have attempted using numpy.diagonal to no avail.</p>
0
2016-07-06T15:49:50Z
38,228,824
<p>This is what I would do. Assuming your mat is mymat.</p> <pre><code>import numpy as np ang = 25 extract = [] for i in range(100): j = int(50 + (50 - i) * np.tan(ang * np.pi /180)) if j&lt;=99 and j&gt;=0: extract.append(mymat[i,j]) </code></pre> <p>Numbers should be adjusted for other sizes.</p>
1
2016-07-06T16:17:03Z
[ "python", "numpy" ]
How to name each instance of a nested dictionary in Python?
38,228,301
<p>I wrote this code to create a nested dictionary, but I am unable to name each instance. </p> <pre><code>def genvlandict(num,attrs): val=num vlans = [] for i in range(val): vlans.append(dict([("Vlan_Attr"+str(i)+'.'+str(x), "val"+str(i)+'.'+str(x)) for x in range(0, attrs, +1)])) return vlans ...
-5
2016-07-06T15:50:49Z
38,228,347
<p>Change <code>vlans</code> to a dictionary? With some minimal changes, your code would be something like:</p> <pre><code>import json def genvlandict(num,attrs): val=num vlans = {} for i in range(val): vlans['dict%d' % i] = dict([("Vlan_Attr"+str(i)+'.'+str(x), "val"+str(i)+'.'+str(x)) for x in ra...
0
2016-07-06T15:53:06Z
[ "python", "json", "dictionary" ]
for loop for all possible combinations of letters+numbers within range
38,228,409
<p>I need a for loop that can take an input, say of 5, and iterate through all possible 5 length combinations of uppercase/lowercase/numbers/specials and do something with each one, is this possible? I don't want to store them in memory, just iterate over them and then get rid of it.</p> <p>Also how would I do just ea...
-5
2016-07-06T15:56:13Z
38,228,605
<blockquote> <p>I need a for loop that can take an input, say of 5, and iterate through all possible 5 length combinations of uppercase/lowercase/numbers/specials and do something with each one</p> </blockquote> <p>For this, you might want to use <code>itertools.product()</code></p> <pre><code>import string import ...
1
2016-07-06T16:04:48Z
[ "python" ]
Python .split() on a string on every splittable token bar whitespace, but ignore some specific strings
38,228,461
<p>I am looking to split a sentence into tokens, but ignore 2 specific strings and also ignore spaces.</p> <p>For example:</p> <p><code>GNI per capita ; PPP -LRB- US dollar -RRB- in LOCATION_SLOT was last measured at NUMBER_SLOT in 2011 , according to the World Bank .</code></p> <p>Should be split into <code>[GNI,pe...
1
2016-07-06T15:59:03Z
38,228,656
<p>You can simply use split</p> <pre><code>&gt;&gt;&gt; x = "GNI per capita ; PPP -LRB- US dollar -RRB- in LOCATION_SLOT was last measured at NUMBER_SLOT in 2011 , according to the World Bank ." &gt;&gt;&gt; &gt;&gt;&gt; x.split() ['GNI', 'per', 'capita', ';', 'PPP', '-LRB-', 'US', 'dollar', '-RRB-', 'in', 'LOCATION_S...
1
2016-07-06T16:07:41Z
[ "python", "regex", "string", "split" ]
Python .split() on a string on every splittable token bar whitespace, but ignore some specific strings
38,228,461
<p>I am looking to split a sentence into tokens, but ignore 2 specific strings and also ignore spaces.</p> <p>For example:</p> <p><code>GNI per capita ; PPP -LRB- US dollar -RRB- in LOCATION_SLOT was last measured at NUMBER_SLOT in 2011 , according to the World Bank .</code></p> <p>Should be split into <code>[GNI,pe...
1
2016-07-06T15:59:03Z
38,228,891
<p>You can use <code>re.findall</code> and strip the spaces from starting and ending</p> <pre><code>&gt;&gt;&gt; [x.strip() for x in re.findall('\s*(\w+|\W+)', line)] #['GNI', 'per', 'capita', ';', 'PPP', '-', 'LRB', '-', 'US', 'dollar', '-', 'RRB', '-', 'in', 'LOCATION_SLOT', 'was', 'last', 'measured', 'at', 'NUMBER_...
1
2016-07-06T16:19:44Z
[ "python", "regex", "string", "split" ]
How to switch between python and java using eclipse
38,228,568
<p>I have just installed pydev on eclipse to write a simple python project. Now I would like to switch back to using java in eclipse. In my project explorer window I do not see any of my java projects. When I go to file-> import -> Existing Projects into Workspace, all of the java projects are greyed out (not selectabl...
0
2016-07-06T16:03:41Z
38,228,868
<p>You need to switch to java environment in eclipse then only you would be able to import java project ! </p> <p>refer this : <a href="http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Ftasks%2Ftasks-9f.htm" rel="nofollow">http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.platfo...
0
2016-07-06T16:18:56Z
[ "java", "python", "eclipse" ]
Django template -- render a list of dictionaries with incrementing values
38,228,642
<p>Without incrementing a template variable, which would be a hacky way to do it, how can I "remember" which level my subskill variable is at and correctly "increment" the level counter in a Django template? </p> <p>I have a list of dictionaries that looks like this: <code>[{'level': 0, 'skill': 'style a page using CS...
0
2016-07-06T16:06:41Z
38,231,763
<p>As suggested in the comments, by changing the structure of my list to look like</p> <p><code>subskills = {0:[{'skill': 'style a page using CSS'}, {'skill': 'download JSFiddle'}], 1: [{'skill': 'learn django'}], 2: [{'skill: 'customize a template'}]}</code></p> <p>pass to the view with</p> <p><code>return render(r...
0
2016-07-06T18:57:23Z
[ "python", "django", "django-templates" ]
How to optimize loading of batch on tensorflow?
38,228,703
<p>I have a problem with the very slow batch loading in tensorflow. Each step in the training is reasonably fast but my function to load data is extremely slow.</p> <p>I was wondering if there were any ways to make this faster or run it in the background when train operation is running so that the batch can be ready b...
0
2016-07-06T16:10:43Z
38,228,960
<p>Input data preparation and training a model using the prepared data can be decoupled in TensorFlow using <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/io_ops.html#queues" rel="nofollow">queues</a>. You can create a queue with <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/io_op...
0
2016-07-06T16:22:58Z
[ "python", "numpy", "optimization", "tensorflow" ]
In BeautifulSoup how to iterate the append function?
38,228,734
<p>From <a href="http://stackoverflow.com/questions/22496401/iterating-through-a-dom-with-beautifulsoup-python#">this question</a>, the following code iterates over the tags between two of <code>h2</code>:</p> <pre><code>from bs4 import BeautifulSoup, Tag data = """&lt;h2&gt;&lt;name&gt;Main Section&lt;/name&gt;&lt;...
-1
2016-07-06T16:13:04Z
38,485,754
<p>Appending the tag to a new list solved my problem.</p> <pre><code>soup = BeautifulSoup(data) for main_section in soup.find_all('h2'): x = [] for sibling in main_section.next_siblings: if not isinstance(sibling, Tag): continue if sibling.name == 'h2': break x.a...
0
2016-07-20T16:17:06Z
[ "python", "html", "beautifulsoup" ]
Django “The view didn't return an HttpResponse object on the line 151”
38,228,751
<p>I have this problem to HttpResponse on the line 151, i dont know what happen, i need your help. I think the error is on views.py but i dont know where is the error if i type the same code on the tutorial-book.</p> <p>when i start this project only for lisen how work django, i read a tutorial and i type the same cod...
-4
2016-07-06T16:13:59Z
38,229,459
<p>The condition when the form is invalid is not handled. Can you try this, I have moved last two lines out of else block.</p> <pre><code>def registro_usuario_view(request): if request.method == 'POST': form = RegistroUserForm(request.POST,request.FILES) if form.is_valid(): cleaned_data...
1
2016-07-06T16:52:13Z
[ "python", "django" ]
NLP nltk using the custom grammar
38,228,880
<p>Hi let's imagine i have a grammar like this S-> NNP VBZ NNP . However the number of NNPs are huge and its in a file. How can I load that directly into grammar or how can I make sure that the grammar fetches the words from the corpus instead of specifying all the words ?</p>
0
2016-07-06T16:19:25Z
38,251,732
<p>Assuming each POS has its own text file consisting of every possible word with that tag on a separate line, you just want to make a dictionary by reading in the lines:</p> <pre><code>lexicon = {} with open('path/to/the/files/NNP.txt', 'r') as NNP_File: # 'with' automatically closes the file once you're done ...
1
2016-07-07T17:27:55Z
[ "python", "nlp", "nltk", "grammar" ]
Python - Tkinter Label Output?
38,228,932
<p>How would I take my entries from Tkinter, concatenate them, and display them in the Label below (next to 'Input Excepted: ')? I have only been able to display them input in the python console running behind the GUI. Is there a way my InputExcept variable can be shown in the Label widget? </p> <pre><code>from Tkinte...
1
2016-07-06T16:21:46Z
38,229,464
<p>Two main steps to do:</p> <ul> <li>You need to declare <code>usrE</code>, <code>usrE</code> and <code>lbl</code> as global variables inside your callback method.</li> <li>You need to use <a href="http://effbot.org/tkinterbook/tkinter-widget-configuration.htm" rel="nofollow"><code>config()</code></a> method to updat...
1
2016-07-06T16:52:29Z
[ "python", "python-2.7", "user-interface", "tkinter" ]
Find line in one csv in another csv
38,228,937
<p>I have been using this code below to find exact matches of strings from one csv to another:</p> <pre><code>with open(filename1, 'rb') as file1: file1reader = csv.reader(file1) for line1 in file1reader: with open(filename2, 'rb') as file2: file2reader = csv.reader(file2) for linenum, line2 in e...
0
2016-07-06T16:22:05Z
38,229,001
<p>You're trying to <code>check if a substring is present in a string</code>.</p> <p>For this you can use the <a href="https://docs.python.org/3/reference/expressions.html#membership-test-details" rel="nofollow">in</a> operator:</p> <p>Example:</p> <pre><code>if "humpty" in "humptydumpty": print "Ok" </code></p...
0
2016-07-06T16:25:56Z
[ "python", "string", "csv", "match" ]
Find line in one csv in another csv
38,228,937
<p>I have been using this code below to find exact matches of strings from one csv to another:</p> <pre><code>with open(filename1, 'rb') as file1: file1reader = csv.reader(file1) for line1 in file1reader: with open(filename2, 'rb') as file2: file2reader = csv.reader(file2) for linenum, line2 in e...
0
2016-07-06T16:22:05Z
38,229,004
<p>Try checking both directions:</p> <pre><code>if (str(line1) in str(line2)) or (str(line2) in str(line1)): </code></pre> <p>I don't think the parentheses are strictly necessary but they make the meaning clearer.</p>
1
2016-07-06T16:26:23Z
[ "python", "string", "csv", "match" ]
How can I draw the histogram of date values group by month in each year in Python?
38,228,995
<p>I wrote this code to draw the histogram of date values in each month. It shows the number of dates for each month in the whole dataset. But I want the histogram to be for each month in each year.That is, for example, I should have January through December for year1, and then January through December for year2 and so...
0
2016-07-06T16:25:34Z
38,229,371
<p>According to the docstring <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">the <code>groupby</code> docstring</a>, the <code>by</code> parameter is:</p> <blockquote> <p>list of column names. Called on each element of the object index to determine the gr...
1
2016-07-06T16:46:41Z
[ "python", "pandas", "dataframe" ]
Anaconda ignoring "extra_paths" in Sublime Text settings
38,229,009
<p>I'm trying to configure Sublime Text 3 to act as my IDE for Python development, and while I've read the documentation, I'm still having problems importing extra libraries using the Anaconda.sublime-settings file. From what I've read, it should be as simple as having this text in the Anaconda.sublime-settings file:</...
0
2016-07-06T16:26:35Z
38,274,658
<p>As <a href="http://stackoverflow.com/questions/38229009/anaconda-ignoring-extra-paths-in-sublime-text-settings#comment63910722_38229009">r-stein indicated</a>, the <code>"extra_paths"</code> setting in Anaconda is for its auto-completing and linting features, not for building. If you need to change your <code>PYTHON...
0
2016-07-08T20:10:11Z
[ "python", "sublimetext3", "sublime-text-plugin", "sublime-anaconda" ]