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
Removing \xa0 from string in a list
38,830,308
<p>I have a list with a bunch of words:</p> <pre><code>lista = ['Jeux Olympiques De Rio\xa02016', 'Sahara Ray', 'Michael Phelps', 'Amber Alert'] </code></pre> <p>I tried to replace the <code>'\xa0'</code>:</p> <pre><code>for element in listor: element = element.replace('\xa0',' ') </code></pre> <p>But it didn't...
1
2016-08-08T13:19:36Z
38,830,660
<p>the easiest way:</p> <pre><code>lista = [el.replace('\xa0',' ') for el in lista] </code></pre>
2
2016-08-08T13:35:14Z
[ "python", "string", "python-3.x" ]
Using py2neo v3 with google app engine
38,830,407
<p>I'm trying to set a backend using py2neo on google app engine. It works just fine when pushed on the dev on app engine, however, unfortunately, it doesn't work when I use it on localhost.</p> <p>First, i've setted the HOME environment variable in python (thanks to that tip, my code works on my dev) but it doesn't f...
0
2016-08-08T13:23:49Z
38,831,353
<p>The 1st traceback could indicate that the py2neo package may be incompatible with <a href="https://cloud.google.com/appengine/docs/python/runtime#Python_The_sandbox" rel="nofollow">GAE's sandbox restrictions</a>. In particular it shows an attempt to open the <code>/Users/Arnaud/.neo4j/known_hosts</code> file in writ...
0
2016-08-08T14:05:23Z
[ "python", "google-app-engine", "ssl", "neo4j", "py2neo" ]
Groupby and any() | all()
38,830,423
<p>I have the following <code>pd.DataFrame</code></p> <pre><code>In [155]: df1 Out[155]: ORDER_ID ACQ DATE UID 2 3 False 2014-01-03 1 3 4 True 2014-01-04 2 4 5 False 2014-01-05 3 6 7 True 2014-01-08 5 7 8 False 2014-01-08 5 9 10 False 2014-0...
2
2016-08-08T13:24:27Z
38,830,719
<p>You need first use condition and then add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.all.html" rel="nofollow"><code>all</code></a>:</p> <pre><code>print (df1.groupby('UID').filter(lambda x: (x.ACQ == False).all())) ORDER_ID ACQ DATE UID 2 3 False 2014-01-03 ...
1
2016-08-08T13:38:07Z
[ "python", "pandas" ]
Non-error message from another script when importing library
38,830,469
<p>I produced a very strange error today, using Python 2.7 on a Windows 10 system. I wrote a Python script, <code>C:\Users\$me\copy.py</code> looking something like this:</p> <pre><code>import subprocess import sys try: out = subprocess.check_output("do_stuff.bat") except subprocess.CalledProcessError as e: p...
4
2016-08-08T13:26:31Z
38,830,626
<p>It's possible that your script is getting imported before (or because Python thinks it is part of) the <code>OpenOPC</code> library. Is your script by chance called <code>OpenOPC.py</code> or similar, or does it reside in a <a href="http://docs.python-guide.org/en/latest/writing/structure/#packages" rel="nofollow">p...
1
2016-08-08T13:33:42Z
[ "python" ]
How to take info from particular amount of elements with the same class name?
38,830,500
<p>I have a lot of tables on the same screen. And i need to take tex from only one of it Simple example: Table:Phone</p> <pre><code>div id="phone_type" type-id="pass" class="panel panel-default sort_table"&gt; &lt;div class="panel-heading"&gt; &lt;h3 class="panel-title"&gt;PHONE&lt;/h3&gt; &lt;...
0
2016-08-08T13:28:16Z
38,830,711
<p>Just make <em>context-specific searches</em>. E.g. If you need this element from a "phone type" table:</p> <pre><code>phone_type = driver.find_element_by_id("phone_type") print(phone_type.find_element_by_css_selector('.col-md-8.col-xs-8.increase_padding').text) </code></pre> <p>Or, in one go:</p> <pre><code>print...
4
2016-08-08T13:37:43Z
[ "python", "selenium-webdriver" ]
To redirect os.system() output to a .txt file
38,830,596
<p>I'm new to Python. I have list of Unix commmands <code>("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")</code> and I want to run them and redirect the entire output to a <code>.txt</code> file. I searched a lot but didn't get a proper solution, or I unders...
2
2016-08-08T13:32:29Z
38,830,757
<p>This answer uses <code>os.popen</code>, which allows you to write the output of the command in your file:</p> <pre><code>import os def commandsoutput(): commands = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev") with open('output.txt','a') as out...
1
2016-08-08T13:39:59Z
[ "python" ]
To redirect os.system() output to a .txt file
38,830,596
<p>I'm new to Python. I have list of Unix commmands <code>("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls -l /dev")</code> and I want to run them and redirect the entire output to a <code>.txt</code> file. I searched a lot but didn't get a proper solution, or I unders...
2
2016-08-08T13:32:29Z
38,830,786
<p><code>os.system</code> returns the exit code of the command, not its output. It is also deprecated. </p> <p>Use <code>subprocess</code> instead:</p> <pre><code>import subprocess def commandsoutput(): command = ("uname -a","uptime","df -h","ifconfig -a","chkconfig --list","netstat -rn","cat /proc/meminfo","ls...
3
2016-08-08T13:41:12Z
[ "python" ]
Access Jupyter notebook running on Docker container
38,830,610
<p>I created a docker image with python libraries and Jupyter. I start the container with the option <code>-p 8888:8888</code>, to link ports between host and container. When I launch a Jupyter kernel inside the container, it is running on <code>localhost:8888</code> (and does not find a browser). I used the command ...
0
2016-08-08T13:33:01Z
38,936,551
<p>You need to run your notebook on <code>0.0.0.0</code>: <code>jupyter notebook -i 0.0.0.0</code>. Running on localhost make it available only from inside the container.</p>
0
2016-08-13T20:07:00Z
[ "python", "docker", "jupyter-notebook" ]
How to represent fractions in python
38,830,869
<p>I am trying to implement a method that takes a matrix from the matrix class i've defined and returns a triagonal matrix using gaussian elimination. Consider the following matrix:</p> <pre><code>m1 = [[2, -3, -4], [-1, 4, 5], [1, -3, -4]] </code></pre> <p>Basically i need to add to each row, a multiple ...
-1
2016-08-08T13:45:24Z
38,830,986
<p>There is a class that does exactly what you want: <a href="https://docs.python.org/3.5/library/fractions.html" rel="nofollow"><code>fractions.Fraction</code></a>:</p> <pre><code>&gt;&gt;&gt; from fractions import Fraction &gt;&gt;&gt; print(Fraction(5, 6)) 5/6 </code></pre> <p>Fractions behave like regular numbers...
1
2016-08-08T13:50:26Z
[ "python", "matrix", "fractions" ]
Django update model entry using form fails
38,830,937
<p>I want to update a model entry using a form. the problem is that instead of updating the entry it creates a new entry.</p> <pre><code>def edit(request, c_id): instance = get_object_or_404(C, id=int(c_id)) if request.POST: form = CForm(request.POST, instance=instance) if form.is_valid(): ...
0
2016-08-08T13:48:12Z
38,831,117
<p>You're checking the request for a <code>POST</code> method incorrectly. <a href="https://docs.djangoproject.com/ja/1.9/ref/request-response/#django.http.HttpRequest.POST" rel="nofollow"><code>request.POST</code></a> isn't a boolean, it contains a dictionary of post variables and is always going to have the CSRF toke...
2
2016-08-08T13:56:22Z
[ "python", "django", "forms" ]
How to make a function determining the winner of Tic-Tac-Toe more concise
38,830,944
<p>I'm writing a Python script which is supposed to allow human and computer players to play Tic Tac Toe. To represent the board, I'm using a 3x3 Numpy array with <code>1</code> and <code>0</code> for the marks of the players (instead of "X" and "O"). I've written the following function to determine the winner:</p> <p...
2
2016-08-08T13:48:32Z
38,831,029
<p>I have made a loop instead, and return only once, to conform with PEP8 and to be honest to my personal coding standards :)</p> <p><code>enumerate</code> in the correct order will yield <code>0,zeromatrix</code> then <code>1,onematrix</code></p> <pre><code>rval = None for i,m in enumerate([np.zeros(3),np.ones(3)]):...
1
2016-08-08T13:52:20Z
[ "python", "numpy" ]
How to make a function determining the winner of Tic-Tac-Toe more concise
38,830,944
<p>I'm writing a Python script which is supposed to allow human and computer players to play Tic Tac Toe. To represent the board, I'm using a 3x3 Numpy array with <code>1</code> and <code>0</code> for the marks of the players (instead of "X" and "O"). I've written the following function to determine the winner:</p> <p...
2
2016-08-08T13:48:32Z
38,831,050
<p>I found out one way, by using a Lambda function:</p> <pre><code>any_lane = lambda x: any([np.array_equal(lane, x) for lane in lanes]) if any_lane(np.ones(3)): return 1 elif any_lane(np.zeros(3)): return 0 </code></pre> <p>This adds an extra line to the code but makes it more legible overall, I reckon.</p>...
0
2016-08-08T13:53:26Z
[ "python", "numpy" ]
How to make a function determining the winner of Tic-Tac-Toe more concise
38,830,944
<p>I'm writing a Python script which is supposed to allow human and computer players to play Tic Tac Toe. To represent the board, I'm using a 3x3 Numpy array with <code>1</code> and <code>0</code> for the marks of the players (instead of "X" and "O"). I've written the following function to determine the winner:</p> <p...
2
2016-08-08T13:48:32Z
38,831,389
<p>Another option is to check the sum of <code>lanes</code>.</p> <pre><code> s = np.sum(lanes, axis=1) if 3 in s: return 1 elif 0 in s: return 0 </code></pre>
2
2016-08-08T14:06:35Z
[ "python", "numpy" ]
How to make a function determining the winner of Tic-Tac-Toe more concise
38,830,944
<p>I'm writing a Python script which is supposed to allow human and computer players to play Tic Tac Toe. To represent the board, I'm using a 3x3 Numpy array with <code>1</code> and <code>0</code> for the marks of the players (instead of "X" and "O"). I've written the following function to determine the winner:</p> <p...
2
2016-08-08T13:48:32Z
38,832,650
<p>This can be done in two lines, starting from the board (<code>grid</code>): simple sums along columns, rows and the two main diagonals gives you a value of 0 or 3 depending on who is winning (or some intermediate values only if nobody is winning). You can thus calculate something like:</p> <pre><code># Score along ...
0
2016-08-08T15:05:14Z
[ "python", "numpy" ]
tkinter populate treeview using threading pool
38,830,958
<p>I'm looking for "best" way to populate treeview using threads. I have multiple mail account which I'm checking for new emails.</p> <p>My plan is to use <code>Queue</code> to store accounts which will be checked using <code>check_mail</code> method. This method will return a list of new mails.</p> <p>Can I use anot...
0
2016-08-08T13:49:17Z
38,832,489
<p>Your question is very broad, so this answer will also be.</p> <p>Generally speaking, <code>tkinter</code> doesn't play well with multi-threading. You can do it, but must make sure only the main thread interacts with the GUI. A common way to do this is to use the <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinte...
0
2016-08-08T14:58:12Z
[ "python", "multithreading", "design-patterns", "tkinter" ]
tkinter populate treeview using threading pool
38,830,958
<p>I'm looking for "best" way to populate treeview using threads. I have multiple mail account which I'm checking for new emails.</p> <p>My plan is to use <code>Queue</code> to store accounts which will be checked using <code>check_mail</code> method. This method will return a list of new mails.</p> <p>Can I use anot...
0
2016-08-08T13:49:17Z
38,868,204
<p>I'm not sure if this is the best idea but it works</p> <pre><code>class Main(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.master = master self.some_service = SomeService() self.some_service.run() self.init_gui() self.after(60...
0
2016-08-10T08:37:24Z
[ "python", "multithreading", "design-patterns", "tkinter" ]
Extract subarray from collection of 2D coordinates?
38,831,006
<p>In Python, I have a large 2D array containing data, and another Mx2 2D array containing a collection of M 2D coordinates of interest, e.g.</p> <pre><code>coords=[[150, 123], [151, 123], [152, 124], [153, 125]] </code></pre> <p>I would like to extract the Mx1 array containing the values of the data array at these c...
2
2016-08-08T13:51:19Z
38,831,291
<p>You could use a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p> <pre><code>In [73]: [data[i][j] for i,j in coords] Out[73]: [2, 23, 40, 5, 20] </code></pre> <p>The result returned by the list comprehension is equivalent to</p> <pre><code...
2
2016-08-08T14:02:59Z
[ "python", "arrays" ]
Twitter Streaming in Python: cp949 codec
38,831,077
<p>I am currently using tweepy to gather data using Streaming API.</p> <p>Here is my code and I ran this on Acaconda command prompt. When streaming starts, it returns tweets and then after giving few tweets it gives the following error:</p> <pre><code>Streaming Started ... RT @ish10040: Crack Dealer Released Early Fr...
0
2016-08-08T13:54:39Z
38,831,233
<p>All text produced and accepted through the twitter API should be encoded as UTF-8, so your code should be using that codec to decode what's coming back.</p> <p>See here: <a href="https://dev.twitter.com/overview/api/counting-characters" rel="nofollow">https://dev.twitter.com/overview/api/counting-characters</a></p>...
0
2016-08-08T14:00:48Z
[ "python", "twitter", "tweepy" ]
Remove cancelling rows from Pandas Dataframe
38,831,088
<p>I have a list of invoices sent out to customers. However, sometimes a bad invoice is sent, which is later cancelled. My Pandas Dataframe looks something like this, except much larger (~3 million rows)</p> <pre><code>index | customer | invoice_nr | amount | date --------------------------------------------------- 0 ...
4
2016-08-08T13:55:02Z
38,832,006
<p>What if you just do a groupby on all 3 fields? The resulting sums would net out any canceled invoices:</p> <pre><code>df2 = df.groupby(['customer','invoice_nr','date']).sum() </code></pre> <p>results in</p> <pre><code>customer invoice_nr date 1 1 2016/01/01 11 2 2016/02/01 ...
0
2016-08-08T14:35:12Z
[ "python", "pandas" ]
Remove cancelling rows from Pandas Dataframe
38,831,088
<p>I have a list of invoices sent out to customers. However, sometimes a bad invoice is sent, which is later cancelled. My Pandas Dataframe looks something like this, except much larger (~3 million rows)</p> <pre><code>index | customer | invoice_nr | amount | date --------------------------------------------------- 0 ...
4
2016-08-08T13:55:02Z
38,832,078
<pre><code>def remove_cancelled_transactions(df): trans_neg = df.amount &lt; 0 return df.loc[~(trans_neg | trans_neg.shift(-1))] groups = [df.customer, df.invoice_nr, df.date, df.amount.abs()] df.groupby(groups, as_index=False, group_keys=False) \ .apply(remove_cancelled_transactions) </code></pre> <p><a hr...
3
2016-08-08T14:38:15Z
[ "python", "pandas" ]
Remove cancelling rows from Pandas Dataframe
38,831,088
<p>I have a list of invoices sent out to customers. However, sometimes a bad invoice is sent, which is later cancelled. My Pandas Dataframe looks something like this, except much larger (~3 million rows)</p> <pre><code>index | customer | invoice_nr | amount | date --------------------------------------------------- 0 ...
4
2016-08-08T13:55:02Z
38,832,926
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow"><code>filter</code></a> all values, where each group has values where sum is <code>0</code> and modulo by <code>2</code> is <code>0</code>:</p> <pre><code>print (df.groupby([df.customer, df.invoic...
2
2016-08-08T15:18:03Z
[ "python", "pandas" ]
Convert Python to Java 8
38,831,101
<p>I’m working in a project that use java 8, this project is about get some geographic information and work with this. I already have done part of this work in python, and now I’m translating this part did in Python to java 8, well in Python I use this lines bellow to convert coordinates in Google format to Postgis...
-4
2016-08-08T13:55:33Z
38,831,186
<p>Java 8 added (among other things) Lambdas, Streams and Functional interfaces.</p> <p>You can use streams to simplify looping over objects. But the syntax like you see in Python isn't the same as in java like that.</p>
-5
2016-08-08T13:58:53Z
[ "java", "python", "postgis" ]
Convert Python to Java 8
38,831,101
<p>I’m working in a project that use java 8, this project is about get some geographic information and work with this. I already have done part of this work in python, and now I’m translating this part did in Python to java 8, well in Python I use this lines bellow to convert coordinates in Google format to Postgis...
-4
2016-08-08T13:55:33Z
38,844,665
<p>Define the following in your class to precompile a Regex pattern</p> <pre><code>private static final Pattern pattern = Pattern.compile("([^ ]++) ([^ ]++)(?: |$)"); </code></pre> <p>Then in your method use</p> <pre><code>if ((new StringTokenizer(str, " ").countTokens() % 2) == 1) { return null; } return patter...
0
2016-08-09T07:31:57Z
[ "java", "python", "postgis" ]
Annotation DB has no 'select' method in rpy2
38,831,169
<p>I have the following code in R:</p> <pre><code>require(hgu133a.db) entrezIDs &lt;- select(hgu133a.db, probeNames, "ENTREZID") </code></pre> <p>where <code>probeNames</code> is a list of strings corresponding to probes found in this database.</p> <p>I am attempting to translate it to Python using rpy2:</p> <pre>...
0
2016-08-08T13:58:20Z
38,832,083
<p>Apparently there are two issues with the above. First, <strong>AnnotationDbi</strong> should be used to resolve the <code>select()</code> method. Second, <code>hgu133a_db</code> is an <strong>InstallSTPackage</strong> object - instead one must use <code>hgu133a_db.hgu133a_db</code>. Putting it together, the trans...
0
2016-08-08T14:38:28Z
[ "python", "rpy2", "bioconductor" ]
Annotation DB has no 'select' method in rpy2
38,831,169
<p>I have the following code in R:</p> <pre><code>require(hgu133a.db) entrezIDs &lt;- select(hgu133a.db, probeNames, "ENTREZID") </code></pre> <p>where <code>probeNames</code> is a list of strings corresponding to probes found in this database.</p> <p>I am attempting to translate it to Python using rpy2:</p> <pre>...
0
2016-08-08T13:58:20Z
38,884,147
<p>[should have been a comment to @merv 's answer, but exceeded the number characters]</p> <p><code>rpy2</code>'s <code>importr()</code> is trying to help a being specific about which package namespace an R object is coming from, while R's common usage is much less so (and can lead to annoyances such as the loading or...
1
2016-08-10T21:50:40Z
[ "python", "rpy2", "bioconductor" ]
Qt/Spyder scaling with 4K display
38,831,239
<p>I've recently made the switch from an old macbook pro to a razer blade stealth laptop. I have many programs that I've written that have pyqt4 GUIs, and I usually do most of my coding in spyder. Upon switching to a computer with a 4K screen spyder has become unusable as it does not scale properly, in addition all the...
0
2016-08-08T14:01:00Z
38,832,329
<p>The next version of Spyder (3.0.0) will natively support high dpi screen and makes use for vector icons.</p> <p>You can try the latest beta (Spyder 3.0.0 beta4) if you want to be an early adopter.</p> <p>Check out the talk on "what's new in Spyder 3.0" at the last Scipy conference: <a href="https://www.youtube.com...
0
2016-08-08T14:50:21Z
[ "python", "qt", "pyqt", "spyder", "pyqtgraph" ]
JWT integration with django
38,831,298
<p>I am new to Django (not DRF) and I have a hard time configuring my authentication requirements. I have an external authentication service that gets a username and password and returns a JWT. After I have the JWT how should I save the token and provide it with every request from the browser. And after that where can ...
0
2016-08-08T14:03:10Z
38,831,519
<p>For every call that your service get there should be header to that call</p> <pre><code>{'Authorization':'Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'} </code></pre> <p>And you can use that in views.py as :</p> <pre><code> if request.user.is_authenticated(): </code></pre> <p>It has to be included i...
0
2016-08-08T14:12:00Z
[ "python", "django", "jwt", "json-web-token" ]
Not getting an output when I call __str__ on a class instance?
38,831,442
<p>I am just a beginner so be easy on me. i was just playing with the <code>__str__</code> method and found that when I try to print the instance it just doesn't work</p> <pre><code>import random brand = ("Samsung","Nokia","Sony","ATAT","Reliance") no_of_sim = ("Dual-sim","Single-sim") color = ("Blue","Violet","Orang...
0
2016-08-08T14:08:46Z
38,831,942
<p>There is a typo in the end of <strong>str</strong> method:</p> <pre><code>self,additional </code></pre> <p>It makes <strong>str</strong> method recursive. Changing "," to "." removes the problem.</p>
1
2016-08-08T14:32:32Z
[ "python" ]
Not getting an output when I call __str__ on a class instance?
38,831,442
<p>I am just a beginner so be easy on me. i was just playing with the <code>__str__</code> method and found that when I try to print the instance it just doesn't work</p> <pre><code>import random brand = ("Samsung","Nokia","Sony","ATAT","Reliance") no_of_sim = ("Dual-sim","Single-sim") color = ("Blue","Violet","Orang...
0
2016-08-08T14:08:46Z
38,832,011
<p>You have a comma where you need a dot:</p> <pre><code>import random brand = ("Samsung","Nokia","Sony","ATAT","Reliance") no_of_sim = ("Dual-sim","Single-sim") color = ("Blue","Violet","Orange","Green") no_of_camera =("Front","Front-Back","Back") no_of_cores = ("Dual Core","Quad Core","Octa Core") additional = ("Bl...
0
2016-08-08T14:35:23Z
[ "python" ]
Am I using virtualenv wrong or is this a limitation of it?
38,831,613
<p>So I used <code>virtualenv</code> to define environments for a number of projects I am working on. I defined the <code>virtualenv</code> python as being version 3.4. Eventually, my global python was upgraded from 3.4.0 to 3.4.3. This proved to be a problem because the <code>virtualenv</code> was dependent on the glo...
1
2016-08-08T14:16:14Z
38,833,295
<p>Virtualenvs were not desiged to be portable, both across machines or across Python versions.</p> <p>This means upgrading Python versions sometimes breaks virtualenvs. You need to recreate them and reinstall everything inside of it (run this in your virtualenv root):</p> <pre><code># Save a list of what you had ins...
2
2016-08-08T15:35:27Z
[ "python", "virtualenv" ]
How does asyncio's event loop know when an awaitable resource is ready?
38,831,687
<p>I'm learning Python asyncio for asynchronous programing. I know that the event loop watch over Future objects until they are ready and then resumes the appropriate coroutines to continue the execution in the point where the await keyword occurred. </p> <p>This is very understandable when you use something like <cod...
0
2016-08-08T14:19:52Z
38,838,700
<blockquote> <p>How does the event loop know when a resource is ready or how many time will take to gather data from some source?</p> </blockquote> <p>The default event loop (based on <a href="https://docs.python.org/3.4/library/asyncio-eventloops.html#asyncio.SelectorEventLoop" rel="nofollow">SelectorEventLoop</a>)...
2
2016-08-08T21:20:26Z
[ "python", "asynchronous", "python-asyncio" ]
Is it possible to overload operators for native datatypes?
38,831,695
<p>For example, if I try to do:</p> <pre><code>a_string + an_int </code></pre> <p>... where a_string is type 'str' and an_int is type 'int', or:</p> <pre><code>an_int + a_string </code></pre> <p>There would be a <code>TypeError</code> because there is no implicit conversion of the types. I understand that if I were...
3
2016-08-08T14:20:15Z
38,832,002
<p>In general, without reverting to the C-level API, you cannot modify attributes of builtin types (see <a href="http://stackoverflow.com/questions/2444680/how-do-i-add-my-own-custom-attributes-to-existing-built-in-python-types-like-a">here</a>). You can, however, subclass builtin types and do what you want on the new ...
2
2016-08-08T14:35:04Z
[ "python", "operator-overloading", "overloading" ]
Is it possible to overload operators for native datatypes?
38,831,695
<p>For example, if I try to do:</p> <pre><code>a_string + an_int </code></pre> <p>... where a_string is type 'str' and an_int is type 'int', or:</p> <pre><code>an_int + a_string </code></pre> <p>There would be a <code>TypeError</code> because there is no implicit conversion of the types. I understand that if I were...
3
2016-08-08T14:20:15Z
38,832,741
<p>As pointed out above, you can't (unless you are up to building your own Python implementation). That is, you cannot change the way <code>'1'+1</code> is handled if encountered in code. But you can mess with builtin <em>functions</em> however you please:</p> <pre><code>&gt;&gt;&gt; int = str &gt;&gt;&gt; type(1) &lt...
2
2016-08-08T15:09:25Z
[ "python", "operator-overloading", "overloading" ]
How to read a line from python currently in console?
38,831,703
<p>I want to use a line of code that can read what I was typing in console, for use with <code>asyncio</code> module in python. My code prints data when it receives it from the server, and after it does that, I want it to read what I was typing and save it to a variable. I am fine with having to use a non-standard modu...
-4
2016-08-08T14:20:53Z
38,926,940
<p>I solved the problem (Windows only) by using <code>msvcrt</code> to catch a single character and some code changes.</p> <p>New Functions/Changes</p> <ol> <li><p>draw_screen:</p> <ul> <li>clear screen using <code>os.system("cls")</code></li> <li><strong>print lines that I save when I print info (Could get laggy)</...
0
2016-08-12T21:50:34Z
[ "python", "console", "python-asyncio" ]
Reading hex to double-precision float python
38,831,808
<p>I am trying to <code>unpack</code> a hex string to a double in Python. </p> <p>When I try to unpack the following: </p> <pre><code>unpack('d', "4081637ef7d0424a"); </code></pre> <p>I get the following error: </p> <pre><code>struct.error: unpack requires a string argument of length 8 </code></pre> <p>This doesn'...
4
2016-08-08T14:25:41Z
38,831,901
<p>Try this:</p> <pre><code>a = "\x40\x81\x63\x7e\xf7\xd0\x42\x4a" unpack('d', a); </code></pre>
0
2016-08-08T14:30:59Z
[ "python", "hex" ]
Reading hex to double-precision float python
38,831,808
<p>I am trying to <code>unpack</code> a hex string to a double in Python. </p> <p>When I try to unpack the following: </p> <pre><code>unpack('d', "4081637ef7d0424a"); </code></pre> <p>I get the following error: </p> <pre><code>struct.error: unpack requires a string argument of length 8 </code></pre> <p>This doesn'...
4
2016-08-08T14:25:41Z
38,831,910
<p>You need to convert the hex digits to a binary string first:</p> <pre><code>struct.unpack('d', "4081637ef7d0424a".decode("hex")) </code></pre> <p>or</p> <pre><code>struct.unpack('d', binascii.unhexlify("4081637ef7d0424a")) </code></pre> <p>The latter version works in both Python 2 and 3, the former only in Pytho...
4
2016-08-08T14:31:14Z
[ "python", "hex" ]
Video Chat feature for Django and possibly Ionic
38,831,929
<p>I developed a website with Django (Python). This website allows users to make 1-to-1 video chat with each others. For the video chat feature I'm currently using WebRTC with quite good results.</p> <p>Now I'm planning to: </p> <ul> <li>upgrade to a paid service for video chat (to improve preformances and fix browse...
-2
2016-08-08T14:31:58Z
38,889,100
<p>You will have to create an API for charging your users and provide us the same according to the below-mentioned steps: </p> <ol> <li>Create a feature on your site which allows users to purchase credits (by making payment)</li> <li>Create a simple API to deduct credits and check number of credits </li> </ol> <p>Onc...
0
2016-08-11T06:45:16Z
[ "android", "python", "django", "video", "ionic-framework" ]
What is the "Python" way to parse through mroutes
38,831,931
<p>I am a network engineer who is trying to script out a specific "mroute" (multicast route) from some exported data. I am trying to figure out the most "pythonic" path to do this. </p> <p>The data looks something like this (nothing specific to my network, just lab exports):</p> <pre> (*,224.0.0.0/4) RPF nbr: 96.34.3...
1
2016-08-08T14:32:03Z
38,833,799
<p>Using a for loop eliminates having to use a variable counter, since it already returns the sequence number while looping.</p> <p>There's probably a simpler or better way still available to do it also, but here's just one way i thought of i hope you get the same results.</p> <pre><code>myarray = output.split("\n") ...
1
2016-08-08T16:02:46Z
[ "python", "networking" ]
What is the "Python" way to parse through mroutes
38,831,931
<p>I am a network engineer who is trying to script out a specific "mroute" (multicast route) from some exported data. I am trying to figure out the most "pythonic" path to do this. </p> <p>The data looks something like this (nothing specific to my network, just lab exports):</p> <pre> (*,224.0.0.0/4) RPF nbr: 96.34.3...
1
2016-08-08T14:32:03Z
38,849,790
<p>Not sure that it is more pythonic, but i prefer to use iterator/generator instead of direct array indexing.</p> <pre><code>import re def print_out_ifaces( group, iterator ): """ function print output interfaces with its group (ip) It uses fact that you have empty line between 2 groups """ ...
0
2016-08-09T11:43:46Z
[ "python", "networking" ]
django auth system 'created'
38,832,122
<p><a href="http://i.stack.imgur.com/PejnM.png" rel="nofollow"><img src="http://i.stack.imgur.com/PejnM.png" alt="enter image description here"></a></p> <p>I'm working with django 1.7.11. I have a preexisting project and I've decided to try to use the built in admin panel (I have not created a superuser). When I opene...
0
2016-08-08T14:40:16Z
38,833,806
<p>Your <code>username</code> field is set to <code>created</code>. Change it to contact_name to use a "name" to log in.</p> <p>However!... You should probably extend the AbstractUser model and not change the USERNAME_FIELD unless you really have to. The way you are doing it now will require you to write custom logi...
1
2016-08-08T16:03:16Z
[ "python", "django" ]
pyqt4: How to change button event without adding a new event?
38,832,143
<p>I have a click button that I want to change events when the button is pressed. A minimal version of the existing code looks like this:</p> <pre><code># Event that happens the first time def first_event(self): button.setText("Second Event") button.clicked.connect(second_event) # Event that happens the secon...
0
2016-08-08T14:41:33Z
38,835,964
<p>I found a way to separate old events from signals using the <code>disconnect()</code> method. Here is an edited version that accomplishes what I originally wanted to do:</p> <pre><code># Event that happens the first time def first_event(self): button.setText("Second Event") button.clicked.disconnect() b...
0
2016-08-08T18:20:01Z
[ "python", "events", "signals", "pyqt4" ]
Traverse through .tar.gz directories and concatenate files (without uncompressing the folders)
38,832,182
<p>I have a folder of about 20000 tar.gz directories, each containing a bunch of files. I want to go in the source folder, traverse through the tar.gz directories (<strong>without decompressing</strong>) and concatenate the files so at the end I will have three big files.</p> <p>For e.g. I have a root folder <code>pno...
3
2016-08-08T14:43:15Z
38,832,277
<p>Using <code>bash</code> <code>find</code> command as below; The <code>cat</code> command in <code>exec</code> is applied to all the files returned by the command. The <code>+</code> option is to ensure no more than one instance of the <code>cat</code> is spawned by the shell.</p> <p>Here <code>{}</code> denotes the...
3
2016-08-08T14:47:56Z
[ "python", "bash", "shell", "find" ]
Regex subbing in Python leads to ASCII characters appearing
38,832,203
<p>I am trying to use regex to replace some issues in some text.</p> <p>Strings look like this:</p> <p><code>a = "Here is a shortString with various issuesWith spacing"</code></p> <p>My regex looks like this right now: <code>new_string = re.sub("[a-z][A-Z]", "\1 \2", a)</code>.</p> <p>This takes those places with m...
1
2016-08-08T14:44:17Z
38,832,261
<pre><code>&gt;&gt;&gt; a = "Here is a shortString with various issuesWith spacing" &gt;&gt;&gt; re.sub("([a-z])([A-Z])", r"\1 \2", a) 'Here is a short String with various issues With spacing' </code></pre> <p>capturing group and backslash escaping was missing.</p> <p>you can go even further:</p> <pre><code>&gt;&gt;...
2
2016-08-08T14:47:12Z
[ "python", "regex", "string" ]
Regex subbing in Python leads to ASCII characters appearing
38,832,203
<p>I am trying to use regex to replace some issues in some text.</p> <p>Strings look like this:</p> <p><code>a = "Here is a shortString with various issuesWith spacing"</code></p> <p>My regex looks like this right now: <code>new_string = re.sub("[a-z][A-Z]", "\1 \2", a)</code>.</p> <p>This takes those places with m...
1
2016-08-08T14:44:17Z
38,832,267
<p>You need to define capturing groups, and use raw string literals:</p> <pre><code>import re a = "Here is a shortString with various issuesWith spacing" new_string = re.sub(r"([a-z])([A-Z])", r"\1 \2", a) print(new_string) </code></pre> <p>See the <a href="https://ideone.com/CoE8xR" rel="nofollow">Python demo</a>.</...
1
2016-08-08T14:47:31Z
[ "python", "regex", "string" ]
Regex subbing in Python leads to ASCII characters appearing
38,832,203
<p>I am trying to use regex to replace some issues in some text.</p> <p>Strings look like this:</p> <p><code>a = "Here is a shortString with various issuesWith spacing"</code></p> <p>My regex looks like this right now: <code>new_string = re.sub("[a-z][A-Z]", "\1 \2", a)</code>.</p> <p>This takes those places with m...
1
2016-08-08T14:44:17Z
38,833,842
<p>You can have a try like this:</p> <pre><code>&gt;&gt;&gt;&gt; import re &gt;&gt;&gt;&gt; a = "Here is a shortString with various issuesWith spacing" &gt;&gt;&gt;&gt; re.sub(r"(?&lt;=[a-z])(?=[A-Z])", " ", a) &gt;&gt;&gt;&gt; Here is a short String with various issues With spacing </code></pre>
0
2016-08-08T16:04:43Z
[ "python", "regex", "string" ]
How to 'unpack' a list or tuple in Python
38,832,218
<p>I'm writing a Python program to play Tic Tac Toe, using Numpy arrays with "X" represented by <code>1</code> and "O" by <code>0</code>. The class includes a function to place a mark on the board:</p> <pre><code>import numpy as np class Board(): def __init__(self, grid = np.ones((3,3))*np.nan): self.grid...
2
2016-08-08T14:45:00Z
38,832,442
<p>As suggested by Lukasz, the input argument should be a tuple. In this example it can be converted to one:</p> <pre><code>def place_mark(self, pos, mark): self.grid[tuple(pos)] = mark </code></pre> <p>My question is not the same <a href="http://stackoverflow.com/questions/2238355/what-is-the-pythonic-way-to-unp...
2
2016-08-08T14:55:46Z
[ "python", "numpy" ]
How to 'unpack' a list or tuple in Python
38,832,218
<p>I'm writing a Python program to play Tic Tac Toe, using Numpy arrays with "X" represented by <code>1</code> and "O" by <code>0</code>. The class includes a function to place a mark on the board:</p> <pre><code>import numpy as np class Board(): def __init__(self, grid = np.ones((3,3))*np.nan): self.grid...
2
2016-08-08T14:45:00Z
38,832,648
<p>With Numpy, there's a difference between indexing with lists and multi-dimensional indexing. <code>self.grid[[0,1]]</code> is equivalent to concatenating <code>self.grid[0]</code> and <code>self.grid[1]</code>, each 3x1 arrays, into a 3x2 array.</p> <p>If you use tuples instead of lists for indexing, then it will b...
3
2016-08-08T15:05:10Z
[ "python", "numpy" ]
How to discretize large dataframe by columns with variable bins in Pandas/Dask
38,832,219
<p>I am able to discretize a Pandas dataframe by columns with this code:</p> <pre><code>import numpy as np import pandas as pd def discretize(X, n_scale=1): for c in X.columns: loc = X[c].median() # median absolute deviation of the column scale = mad(X[c]) bins = [-np.inf, loc -...
2
2016-08-08T14:45:03Z
38,841,341
<p>I've never used <code>dask</code>, but I guess you can define a new function to be used in <code>apply</code>.</p> <pre><code>import dask.dataframe as dd import multiprocessing as mp import numpy as np import pandas as pd def discretize(X, n_scale=1): X_dask = dd.from_pandas(X.T, npartitions=mp.cpu_count()+1)...
1
2016-08-09T02:57:04Z
[ "python", "pandas", "dataframe", "parallel-processing", "dask" ]
Find number of breaks in a sequence
38,832,238
<p>I have a program that is parsing allele sequences. I am trying to write a code that determines if the allele is complete or not. To do so, I need to count the number of breaks in the reference sequence. A break is signified by a string of '-'. If there is more than one break I want the program to say "Incomplete All...
4
2016-08-08T14:46:08Z
38,832,430
<p>I think this should do:</p> <pre><code>def test(sequence): sequence = ''.join(sequence.splitlines()[1:]) # remove first line (header and line breaks) S = [segments for segments in sequence.split('-') if block != ''] if len(S)&gt;2: # len(S) should be the number of remaining segments print "Incom...
0
2016-08-08T14:55:15Z
[ "python", "string", "python-2.7" ]
Find number of breaks in a sequence
38,832,238
<p>I have a program that is parsing allele sequences. I am trying to write a code that determines if the allele is complete or not. To do so, I need to count the number of breaks in the reference sequence. A break is signified by a string of '-'. If there is more than one break I want the program to say "Incomplete All...
4
2016-08-08T14:46:08Z
38,832,440
<p>It seems like you can just count the occurrances of <code>-+</code>, i.e. a sequence of <em>one or more</em> <code>-</code> symbols. The only problem are the line breaks, but you could either incorporate those into the regex, or split and join the string before matching.</p> <pre><code>&gt;&gt;&gt; sequence = """&g...
0
2016-08-08T14:55:45Z
[ "python", "string", "python-2.7" ]
Find number of breaks in a sequence
38,832,238
<p>I have a program that is parsing allele sequences. I am trying to write a code that determines if the allele is complete or not. To do so, I need to count the number of breaks in the reference sequence. A break is signified by a string of '-'. If there is more than one break I want the program to say "Incomplete All...
4
2016-08-08T14:46:08Z
38,832,553
<p>You could just filter out all the '-' characters and based on the number of remaining segments determine number of breaks.</p> <pre><code>str_list = filter(None, sequence.split('-')) if len(str_list) &gt; 2: return "Incomplete Allele" else: return "Complete Allele" </code></pre>
1
2016-08-08T15:00:39Z
[ "python", "string", "python-2.7" ]
How to make the regexp ignore a new line in python?
38,832,239
<p>I use the regex like that</p> <pre><code>return(\s+([^"\n;]+))?; </code></pre> <p>in order to match the return statement in obj-c,but when I use it through python like this:</p> <pre><code>re.sub(r'return(\s+([^"\n;]+))?;',r'{\g&lt;0&gt;}',str(content)) </code></pre> <p>I find that it match like this statement</...
2
2016-08-08T14:46:08Z
38,832,599
<p>I think the issue is that your regex has <code>\s</code> that matches any whitespace.</p> <p>You might want to just match literal spaces or tabs with <code>[ \t]</code>:</p> <pre><code>r'return([ \t]+([^"\n;]+))?;' </code></pre> <p>(<a href="https://regex101.com/r/mM6mK2/2" rel="nofollow">demo</a>) or - better:</...
2
2016-08-08T15:02:51Z
[ "python", "regex" ]
pcapy.PcapError: eth1: You don't have permission to capture on that device
38,832,347
<p>I am trying to run pcapy_sniffer.py but i get this</p> <p>pcapy.PcapError: eth1: You don't have permission to capture on that device (socket: Operation not permitted)</p>
0
2016-08-08T14:50:48Z
38,832,386
<p>If you're running on linux or OS X try running as root or with <code>sudo</code>, otherwise if you're on windows try running as administrator.</p>
0
2016-08-08T14:53:03Z
[ "python", "scapy", "pcap" ]
Change pd datetime object to integer
38,832,486
<p>I have a pandas dataframe with two dates in them. I want to take the difference in days between them. But the resulting difference looks like a string ex ('7 days'). Is there a way to change this to just the integer date difference?</p> <pre><code>y['datePulled'] = pd.to_datetime(y['datePulled']) y['Dates'] = pd...
1
2016-08-08T14:57:50Z
38,832,514
<p>You can use:</p> <pre><code>(y['Datediff'] / np.timedelta64(1, 'D')).astype(int) </code></pre> <p>Or:</p> <pre><code>y['Datediff'].dt.days </code></pre> <p>Sample:</p> <pre><code>import pandas as pd import numpy as np y = pd.DataFrame({ 'datePulled': ['2016-01-05','2016-01-04'], 'Dates': [...
2
2016-08-08T14:59:09Z
[ "python", "date", "pandas" ]
TypeError: get() missing 1 required positional argument: 'self' - NOT USING CLASS - Python 3.5
38,832,494
<p>due to my crude knowledge of Python, I am expecting more mistakes with the following script than just the positional argument error. Hence, I would very much appreciate any and all kind of observations/corrections. Again, I would like, if at all possible, to fix the positional argument error without having to use cl...
0
2016-08-08T14:58:24Z
38,862,779
<p>You're getting the error message because .get() won't work on the class Entry. It will work on an object such as totalEnt that is an instance of Entry.</p> <p>So you need </p> <pre><code>total = totalEnt.get() </code></pre> <p>Also, something like</p> <pre><code>totalEnt=ttk.Entry(root).grid(row=n, column=2) <...
0
2016-08-10T01:16:20Z
[ "python", "python-3.x", "variables", "tkinter", "arguments" ]
Saving print statement to new file
38,832,545
<p>New to python (should be noted). Go easy on me. </p> <p>I have written the following to isolate a very specific part of a file</p> <pre><code>for line in open('120301.KAP'): rec = line.strip() if rec.startswith('PLY'): print line </code></pre> <p>the output appears as such </p> <pre><code>PLY/1,48...
1
2016-08-08T15:00:22Z
38,832,657
<p>you can use csv module</p> <pre><code>import csv with open('120301.csv', 'w', newline='') as file: writer = csv.writer(file) for line in open('120301.KAP'): rec = line.strip() if rec.startswith('PLY'): writer.writerow(rec.split(',')) </code></pre> <p>In the similar way <code>...
1
2016-08-08T15:05:42Z
[ "python", "writing" ]
Saving print statement to new file
38,832,545
<p>New to python (should be noted). Go easy on me. </p> <p>I have written the following to isolate a very specific part of a file</p> <pre><code>for line in open('120301.KAP'): rec = line.strip() if rec.startswith('PLY'): print line </code></pre> <p>the output appears as such </p> <pre><code>PLY/1,48...
1
2016-08-08T15:00:22Z
38,832,783
<p>This is totally doable! Here are a couple links to some docs: <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">https://docs.python.org/2/library/csv.html</a> #for writing/reading CSV. You could also just make your own CSV with the regular file reading/writing functions. </p> <pre><code>file = ope...
1
2016-08-08T15:11:00Z
[ "python", "writing" ]
Saving print statement to new file
38,832,545
<p>New to python (should be noted). Go easy on me. </p> <p>I have written the following to isolate a very specific part of a file</p> <pre><code>for line in open('120301.KAP'): rec = line.strip() if rec.startswith('PLY'): print line </code></pre> <p>the output appears as such </p> <pre><code>PLY/1,48...
1
2016-08-08T15:00:22Z
38,832,918
<p>You could open the file at the beginning of your code and then just add a write statement after the print line. Something like this:</p> <pre><code>target = open(filename, 'w') for line in open('120301.KAP'): rec = line.strip() if rec.startswith('PLY'): print line target.write(line) target.write("\n") #wr...
1
2016-08-08T15:17:45Z
[ "python", "writing" ]
Saving print statement to new file
38,832,545
<p>New to python (should be noted). Go easy on me. </p> <p>I have written the following to isolate a very specific part of a file</p> <pre><code>for line in open('120301.KAP'): rec = line.strip() if rec.startswith('PLY'): print line </code></pre> <p>the output appears as such </p> <pre><code>PLY/1,48...
1
2016-08-08T15:00:22Z
38,833,887
<p>The simplest way is to redirect stdout to a file:</p> <pre><code>for i in range(10): print str(i) + "," + str(i*2) </code></pre> <p>will output:</p> <pre><code>0,0 1,2 2,4 3,6 4,8 5,10 6,12 7,14 8,16 9,18 </code></pre> <p>if you run it as <code>python myprog.py &gt; myout.txt</code> the result go to myout....
0
2016-08-08T16:06:42Z
[ "python", "writing" ]
Dynamic dict value access with dot separated string
38,832,563
<p>I'm using Python 3.5.1</p> <p>So what I am trying to do is pass in a dict a <em>dot separated string</em> representing the path to a key and a default value. I want to check for the keys existence and if it's not there , provide the default value. The problem with this is that the key I want to access could be nes...
1
2016-08-08T15:01:12Z
38,832,961
<p>You could use recursivity:</p> <pre><code>def replace_key(the_dict, dict_keys, default_value): if dict_keys[0] in the_dict: if len(dict_keys)==1: the_dict[dict_keys[0]]=default_value else: replace_key(the_dict[dict_keys[0]], dict_keys[1:],default_value) else: ...
1
2016-08-08T15:19:40Z
[ "python", "python-3.x" ]
Get table name for field in database result in Python (PostgreSQL)
38,832,646
<p>I'm trying to get table name for field in result set that I got from database (Python, Postgres). There is a function in PHP to get table name for field, I used it and it works so I know it can be done (in PHP). I'm looking for similar function in Python.</p> <p><a href="http://php.net/manual/en/function.pg-field-t...
2
2016-08-08T15:05:04Z
38,834,445
<p>It is necessary to query the <a href="https://www.postgresql.org/docs/current/static/catalog-pg-attribute.html" rel="nofollow"><code>pg_attribute</code> catalog</a> for the table qualified column names:</p> <pre><code>query = ''' select string_agg(format( '%%1$s.%%2$s as "%%1$s.%%2$s"', ...
0
2016-08-08T16:39:38Z
[ "python", "postgresql", "psycopg2" ]
Suppress warnings in Hachoir
38,832,691
<p>I'm using <a href="http://hachoir3.readthedocs.io/index.html" rel="nofollow">hachior-parser</a> to grab the duration of a large set of video files. (I'm resetting the "Last modified" date based on the file's timestamp, plus its duration.) I'm using code adapted from <a href="http://stackoverflow.com/questions/171853...
0
2016-08-08T15:06:54Z
38,832,806
<p>You can use the <a href="https://docs.python.org/2/using/cmdline.html#cmdoption-W" rel="nofollow"><code>-W</code></a> option to suppress warnings in python. </p> <pre><code>python -W ignore my_file.py </code></pre> <p>Edit: since you've already tried the above, you could try the following. </p> <pre><code>import ...
0
2016-08-08T15:12:29Z
[ "python", "hachoir-parser" ]
Suppress warnings in Hachoir
38,832,691
<p>I'm using <a href="http://hachoir3.readthedocs.io/index.html" rel="nofollow">hachior-parser</a> to grab the duration of a large set of video files. (I'm resetting the "Last modified" date based on the file's timestamp, plus its duration.) I'm using code adapted from <a href="http://stackoverflow.com/questions/171853...
0
2016-08-08T15:06:54Z
38,851,150
<p>I found the solution by checking the issues page for the project on BitBucket.</p> <p><a href="https://bitbucket.org/haypo/hachoir/issues/54/control-log-level-whith-the-python-api" rel="nofollow">https://bitbucket.org/haypo/hachoir/issues/54/control-log-level-whith-the-python-api</a></p> <pre class="lang-py pretty...
0
2016-08-09T12:45:41Z
[ "python", "hachoir-parser" ]
How to assign months to their numeric equivalents in Python / Pandas?
38,832,968
<p>Currently, I'm using the following for loop based on an if condition for each month to assign months to their numeric equivalents. It seems to be quite efficient in terms of runtime, but is too manual and ugly for my preferences.</p> <p>How could this be better executed? I imagine it's possible to improve on it by ...
1
2016-08-08T15:20:02Z
38,833,040
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.month.html" rel="nofollow"><code>month</code></a>, convert to string and use <a href="h...
4
2016-08-08T15:22:51Z
[ "python", "datetime", "pandas" ]
How to assign months to their numeric equivalents in Python / Pandas?
38,832,968
<p>Currently, I'm using the following for loop based on an if condition for each month to assign months to their numeric equivalents. It seems to be quite efficient in terms of runtime, but is too manual and ugly for my preferences.</p> <p>How could this be better executed? I imagine it's possible to improve on it by ...
1
2016-08-08T15:20:02Z
38,833,202
<p>You can use a map:</p> <pre><code>month2int = {"January":1, "February":2, ...} combined["month_numeric"] = combined["month"].map(month2int) </code></pre>
1
2016-08-08T15:30:36Z
[ "python", "datetime", "pandas" ]
How can I remove all non-alphanumeric characters from a string, except for '#', with regex?
38,833,054
<p>I currently have this line <code>address = re.sub('[^A-Za-z0-9]+', ' ', address).lstrip()</code> which will remove all special characters from my string <code>address</code>. How can I modify this line to keep <code>#</code>?</p>
1
2016-08-08T15:23:26Z
38,833,139
<p>In order to avoid removing the hash symbol, you need to add it into the <a href="http://www.regular-expressions.info/charclass.html#negated" rel="nofollow">negated character class</a>:</p> <pre><code>r'[^A-Za-z0-9#]+' ^ </code></pre> <p>See the <a href="https://regex101.com/r/xP1yL8/1" rel="nofollow">...
4
2016-08-08T15:28:14Z
[ "python", "regex" ]
Ruffus pipeline with internal inputs
38,833,119
<p>I'd like to create a pipeline with the Ruffus package for Python and I am struggling with its simplest concepts. Two tasks should be executed one after the other. The second task depends on output of the first task. In Ruffus documentation everything is designed for import/export from/to external files. I'd like to ...
0
2016-08-08T15:26:56Z
38,849,678
<p>I suggest you only use the Ruffus decorators when there are input/output <em>files</em>. For example, if <code>task1</code> generates <code>file1.txt</code> and this is the input for <code>task2</code>, which generates <code>file2.txt</code> then you could write a pipeline as follows:</p> <pre><code>@originate("fil...
0
2016-08-09T11:38:20Z
[ "python", "cluster-computing", "distributed-computing", "pipeline" ]
Search for a part of a tuple in a list of tuples
38,833,275
<p>I am working on a sudoku solver in python. The coordinates of the boxes are given by this code:</p> <pre><code>for row in range(1, 10): for column in range(1,10): boxes.append((row, column)) </code></pre> <p>Later, I have a list of tuples in the format of (row, column, box, number). I need to organize ...
0
2016-08-08T15:34:30Z
38,833,438
<p>I believe this should work for finding the (row, column) pair:</p> <pre><code>entry = [e for e in tuple_list if (e[0] == row and e[1] == column)][0] </code></pre> <p>You essentially end up with a list of all entries <code>e</code> that match the (1, 1) pattern and then get the first of these using <code>[0]</code>...
0
2016-08-08T15:42:37Z
[ "python", "list", "tuples" ]
RabbitMQ: Consuming only one message at a time from multiple queues
38,833,309
<p>I'm trying to stay connected to multiple queues in RabbitMQ. Each time I pop a new message from one of these queue, I'd like to spawn an external process.</p> <p>This process will take some time to process the message, and I don't want to start processing another message from that specific queue until the one I pop...
0
2016-08-08T15:36:31Z
38,833,846
<p>RabbitMQ can do this.</p> <p>You only want to read from the queue when you're ready - so spin up a thread that can spawn the external process and watch it, then fetch the next message from the queue when the process is done. You can then have mulitiple threads running in parallel to manage multiple queues.</p> <p>...
0
2016-08-08T16:04:44Z
[ "python", "rabbitmq", "amqp", "pika" ]
Merge dataframes on nearest datetime / timestamp
38,833,362
<p>I have two data frames as follows:</p> <pre><code>A = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"], "date":["06/22/2014","07/02/2014","01/01/2015","01/01/1991","08/02/1999"]}) B = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"], "date":["02/15/2015","06/30/2014","07/02/1999","10/05/1990","06/24/2014"], "value": ["3",...
0
2016-08-08T15:39:15Z
38,833,547
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> with <code>method='nearest'</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>:</p> <...
1
2016-08-08T15:48:26Z
[ "python", "pandas" ]
dataframe append not visible out of function scope
38,833,433
<p>According to my understanding of python, mutable references to data can be modified within a function scope and reflect the change outside. However the behavior below confuses me:</p> <p>1) Consider a list:</p> <pre><code>my_list = [] def checklistappend( list ): list.append( 1 ) checklistappend( my_list ) pri...
0
2016-08-08T15:42:32Z
38,833,709
<p>You need to assign the output back to <code>df</code>.</p> <pre><code>df = df.append([1]) </code></pre>
0
2016-08-08T15:57:49Z
[ "python", "pandas", "pass-by-reference" ]
Python Scrapy Spider: Inconsistent results
38,833,506
<p>I would love to know what you guys think about this please. I have researched for a few days now and I can't seem to find where I am going wrong. Any help will be highly appreciated.</p> <p>I want to systematically crawl this url: <a href="https://studyacer.com/latest/" rel="nofollow">Question site</a> using the pa...
0
2016-08-08T15:46:17Z
38,834,852
<p>kevin; I had a similar but slightly different problem earlier today, where my crawlspider was visiting unwanted pages. Someone responded to my question with the suggestion of checking the linkextractor as you suggested here : <a href="http://doc.scrapy.org/en/latest/topics/link-extractors.html" rel="nofollow">http:...
0
2016-08-08T17:04:09Z
[ "python", "css-selectors", "scrapy" ]
Match dictionary with list (Python)
38,833,527
<p>I have a dictionary of words with categories. I want to output the categories if the words match the words in my list. This is what my code looks like at the moment: </p> <pre><code>dictionary = { "object" : 'hat', "animal" : 'cat', "human" : 'steve' } list_of_things = ["steve", "tom", "cat"] for cate...
1
2016-08-08T15:47:25Z
38,833,578
<p>You could use a boolean inside the inner <code>for</code> loop, which changes from False (category not found) to True (category was found), and then only print the <code>categories</code> at the <em>end</em> of the <code>for</code> loop <code>if boolean = False:</code></p> <pre><code>isMatchFound = False for catego...
1
2016-08-08T15:50:49Z
[ "python", "dictionary" ]
Match dictionary with list (Python)
38,833,527
<p>I have a dictionary of words with categories. I want to output the categories if the words match the words in my list. This is what my code looks like at the moment: </p> <pre><code>dictionary = { "object" : 'hat', "animal" : 'cat', "human" : 'steve' } list_of_things = ["steve", "tom", "cat"] for cate...
1
2016-08-08T15:47:25Z
38,833,669
<p>Depending on how much your actual data look like your example, you could do</p> <pre><code>category_thing= { "object" : 'hat', "animal" : 'cat', "human" : 'steve' } list_of_things = ["steve", "tom", "cat"] thingset=set(list_of_things) # just for speedup for category,thing in category_thing.iteritems()...
1
2016-08-08T15:55:47Z
[ "python", "dictionary" ]
Match dictionary with list (Python)
38,833,527
<p>I have a dictionary of words with categories. I want to output the categories if the words match the words in my list. This is what my code looks like at the moment: </p> <pre><code>dictionary = { "object" : 'hat', "animal" : 'cat', "human" : 'steve' } list_of_things = ["steve", "tom", "cat"] for cate...
1
2016-08-08T15:47:25Z
38,833,814
<p>Since you want only 3 lines in output, your for-loops should be re-ordered.</p> <pre><code>for stuff in list_of_things: print_val = None for categories,things in dictionary.iteritems(): if stuff in things: print_val=categories if print_val is None: print_val="dump as usual" print print_val </c...
0
2016-08-08T16:03:30Z
[ "python", "dictionary" ]
Match dictionary with list (Python)
38,833,527
<p>I have a dictionary of words with categories. I want to output the categories if the words match the words in my list. This is what my code looks like at the moment: </p> <pre><code>dictionary = { "object" : 'hat', "animal" : 'cat', "human" : 'steve' } list_of_things = ["steve", "tom", "cat"] for cate...
1
2016-08-08T15:47:25Z
38,834,795
<p>First of all, your dictionary is poorly structured; it seems to have its keys and values swapped. By using the categories as keys, you can only have one object per category, which is probably not what you want. It also means that you have to read every entry in the dictionary in order to look up an item, which is ge...
1
2016-08-08T17:01:01Z
[ "python", "dictionary" ]
OSError: [Errno 8] Exec format error selenium
38,833,589
<p>Trying to learn how to use selenium, I managed to overcome first error which involved chrome driver not being in the path name but it has thrown up another error. </p> <pre><code> from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome('/Users/williamneal/...
1
2016-08-08T15:51:47Z
38,836,361
<p>Looks like this is complaining about the format of chromedriver binary. It might be because of platform and chromedriver format mismatch. For example windows requires chromedriver.exe while there are different formats for linux and mac.</p> <p>If you don't want to install through package manager, just download chro...
0
2016-08-08T18:44:12Z
[ "python", "selenium" ]
Python program to check matching of simple parentheses
38,833,819
<p>I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.</p> <p>I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong?</...
3
2016-08-08T16:03:36Z
38,834,005
<p>A very slightly more elegant way to do this is below. It cleans up the for loop and replaces the lists with a simple counter variable. It also returns false if the counter drops below zero so that <code>matched(")(")</code> will return <code>False</code>.</p> <pre><code>def matched(str): count = 0 for i in ...
5
2016-08-08T16:13:37Z
[ "python" ]
Python program to check matching of simple parentheses
38,833,819
<p>I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.</p> <p>I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong?</...
3
2016-08-08T16:03:36Z
38,834,134
<p>Most blatant error done by you is:</p> <pre><code> if l == ")": clo = clo + [")"] else: return(ope, clo) # here </code></pre> <p>By using return, you exit from function when first char not equal to "(" or ")" is encountered. Also some indentation is off.</p> <p>Minimal change which allows...
3
2016-08-08T16:21:27Z
[ "python" ]
Python program to check matching of simple parentheses
38,833,819
<p>I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.</p> <p>I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong?</...
3
2016-08-08T16:03:36Z
38,834,144
<p>The problem with your approach is that you don't consider the order. Following line would pass: <code>))) (((</code>. I'd suggest to keep the count of open and closed parenthesis:</p> <ul> <li><code>counter</code> starts from 0</li> <li>every <code>(</code> symbol increment counter</li> <li>every <code>)</code> sym...
1
2016-08-08T16:22:06Z
[ "python" ]
Python program to check matching of simple parentheses
38,833,819
<p>I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.</p> <p>I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong?</...
3
2016-08-08T16:03:36Z
38,834,249
<p>This checks whether parentheses are properly matched, not just whether there is an equal number of opening and closing parentheses. We use a <code>list</code> as a stack and push onto it when we encounter opening parentheses and pop from it when we encounter closing parentheses.</p> <p>The main problem with your so...
1
2016-08-08T16:28:34Z
[ "python" ]
Python program to check matching of simple parentheses
38,833,819
<p>I am a Python newbie and I came across this exercise of checking whether or not the simple brackets "(", ")" in a given string are matched evenly.</p> <p>I have seen examples here using the stack command which I havent encountered yet.So I attempted a different approach. Can anyone tell me where I am going wrong?</...
3
2016-08-08T16:03:36Z
38,834,251
<p>this code works fine </p> <pre><code>def matched(s): p_list=[] for i in range(0,len(s)): if s[i] =='(': p_list.append('(') elif s[i] ==')' : if not p_list: return False else: del p_list[-1] if not p_list: return True else: return False </code></pre>
1
2016-08-08T16:28:43Z
[ "python" ]
Python - Pass a range of float (without step) as an argument of a function
38,833,828
<p>I created a function and I would like to be able to call it with a set of keyworded-parameters that I call <code>**criterias</code>:</p> <pre><code>def actionBasedOnParameters(**criterias): # my code </code></pre> <p>Inside this set of parameters one of them will be called 'SumInc' and I would like to pass a r...
0
2016-08-08T16:03:59Z
38,836,398
<p>Something like this?</p> <pre><code>criterias = dict(SumInc=(1,15)) def actionBasedOnParameters(**criterias): if 'SumInc' in criterias: lower, upper = criterias['SumInc'] if lower &lt;= my_variable &lt;= upper: #action1 else: #action2 infinity = float('inf') act...
2
2016-08-08T18:46:19Z
[ "python", "function", "arguments", "range", "keyword-argument" ]
pandas: sum of each column results a NaN value?
38,833,837
<p>I have a dataframe in pandas as below. I am trying to add a row with row-name ="Total", which is the sum of each column. I am using the following code : <strong>df.loc["Total"] = df.sum(axis =1)</strong></p> <p>I am getting NaN as a sum of each column. Any idea why and how to solve it ?</p> <p><a href="http://i.st...
-3
2016-08-08T16:04:29Z
38,833,949
<p>Use:</p> <pre><code>df.loc["Total"] = df.sum() </code></pre> <p>Or if need convert first string values of columns to float:</p> <pre><code>df.loc["Total"] = df.astype(float).sum() </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,...
0
2016-08-08T16:10:55Z
[ "python", "pandas", "sum", "row" ]
How can I add items to Context.data without loosing it once I exit the inner_function
38,833,859
<p>I am having some trouble with Python Closures, hoping someone here could help. Below is my code.</p> <pre><code>import time from multiprocessing import Process class Context(object): def __init__(self, x, y): self.x = x self.y = y self.data = [] context = Context(1, 2) def test(te...
0
2016-08-08T16:05:21Z
38,834,463
<p>Your problem is not about closures but about <a href="https://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes" rel="nofollow">sharing data between processes</a> as in <code>thread</code> everything works as expected but you do not pass back your data to the main process. </p> <p>You c...
1
2016-08-08T16:40:42Z
[ "python", "python-2.7", "closures" ]
How to force Django to delete objects using multiple inheritance
38,833,866
<p>I have an object model as follows:</p> <pre><code>class Corporation(models.Model): corp_id = models.AutoField(primary_key=True) original_name = models.CharField(max_length=1000, blank=True, null=True) address = models.ManyToManyField(Address, related_name='corp_address') class Person(models.Model): ...
1
2016-08-08T16:05:40Z
38,833,974
<p>Check out <a href="https://docs.djangoproject.com/ja/1.9/ref/models/fields/#module-django.db.models.fields.related" rel="nofollow">on_delete</a> set to cascade in django which will delete the associated records also . </p> <p>In your models please add on_delete = models.CASCADE in this fashion:</p> <pre><code> c...
1
2016-08-08T16:12:06Z
[ "python", "django", "multiple-inheritance" ]
Write Custom Python-Based Gradient Function for an Operation? (without C++ Implementation)
38,833,934
<p>I'm trying to write a custom gradient function for 'my_op' which for the sake of the example contains just a call to tf.identity() (ideally, it could be any graph).</p> <pre><code>import tensorflow as tf from tensorflow.python.framework import function def my_op_grad(x): return [tf.sigmoid(x)] @function.Def...
1
2016-08-08T16:10:13Z
38,862,401
<p>Note that python_grad_func needs the same interface as ops.RegisterGradient (<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/function.py#L349" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/function.py#L349</a>). </p> <p>Here...
1
2016-08-10T00:22:52Z
[ "python", "tensorflow", "gradient-descent" ]
Write Custom Python-Based Gradient Function for an Operation? (without C++ Implementation)
38,833,934
<p>I'm trying to write a custom gradient function for 'my_op' which for the sake of the example contains just a call to tf.identity() (ideally, it could be any graph).</p> <pre><code>import tensorflow as tf from tensorflow.python.framework import function def my_op_grad(x): return [tf.sigmoid(x)] @function.Def...
1
2016-08-08T16:10:13Z
39,565,081
<p>The following seems work fine. Do you have any reason prefering python_grad_func instead?</p> <pre><code>@tf.function.Defun(tf.float32, tf.float32) def bprop(x, dy): return tf.sigmoid(x) @tf.function.Defun(tf.float32, grad_func=bprop) def fprop(x): return x # identity a = tf.Variable(tf.constant([-5., 4., -3...
0
2016-09-19T03:50:42Z
[ "python", "tensorflow", "gradient-descent" ]
Compare only part of two of three items in triple
38,833,937
<p>I have a list that goes something like this, and new content is added in a loop.</p> <pre><code>list = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)] </code></pre> <p>In the loop I want to add items like so:</p> <pre><code>list.append(("strawberry", "b", 4)) </code></pre> <p>however, this cannot o...
1
2016-08-08T16:10:21Z
38,834,137
<p>A time-efficient solution would be to keep a <code>set</code> with added items</p> <pre><code>li = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)] se= set(t[:2] for t in li) add=[ ("banana", "a", 5), # Should NOT be appended ("banana", "c", 6), # SHOULD be appended ("strawberry", "a", 7) # SHOULD be ...
0
2016-08-08T16:21:34Z
[ "python", "list", "duplicates", "append" ]
Compare only part of two of three items in triple
38,833,937
<p>I have a list that goes something like this, and new content is added in a loop.</p> <pre><code>list = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)] </code></pre> <p>In the loop I want to add items like so:</p> <pre><code>list.append(("strawberry", "b", 4)) </code></pre> <p>however, this cannot o...
1
2016-08-08T16:10:21Z
38,834,141
<p>you may check the presence of an new item with</p> <pre><code>#check for every item if newItem matches an Item in the list if not any( True for item in list if newItem[:2]==item[:2] ): # add your newItem </code></pre>
1
2016-08-08T16:21:48Z
[ "python", "list", "duplicates", "append" ]
Compare only part of two of three items in triple
38,833,937
<p>I have a list that goes something like this, and new content is added in a loop.</p> <pre><code>list = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)] </code></pre> <p>In the loop I want to add items like so:</p> <pre><code>list.append(("strawberry", "b", 4)) </code></pre> <p>however, this cannot o...
1
2016-08-08T16:10:21Z
38,834,175
<p>You can use tuples as keys in a dictionary:</p> <pre><code>fruits = { ('banana', 'a'): 0, ('banana', 'b'): 1, ('coconut', 'a'): 2, } </code></pre> <p>Then, you can just check if <code>(item[0], item[1])</code> is already in the dictionary:</p> <pre><code>item = ('strawberry', 'b', 4) if (item[0], item...
1
2016-08-08T16:23:55Z
[ "python", "list", "duplicates", "append" ]
Compare only part of two of three items in triple
38,833,937
<p>I have a list that goes something like this, and new content is added in a loop.</p> <pre><code>list = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)] </code></pre> <p>In the loop I want to add items like so:</p> <pre><code>list.append(("strawberry", "b", 4)) </code></pre> <p>however, this cannot o...
1
2016-08-08T16:10:21Z
38,834,306
<pre><code>data = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)] items = [("banana", "a", 5), ("banana", "c", 6), ("strawberry", "a", 7)] for item in items: if item[:2] not in map(lambda x: x[:2], data): data.append(item) </code></pre> <p>Output:</p> <pre><code> [('banana', 'a', 0), ...
1
2016-08-08T16:31:20Z
[ "python", "list", "duplicates", "append" ]
Compare only part of two of three items in triple
38,833,937
<p>I have a list that goes something like this, and new content is added in a loop.</p> <pre><code>list = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)] </code></pre> <p>In the loop I want to add items like so:</p> <pre><code>list.append(("strawberry", "b", 4)) </code></pre> <p>however, this cannot o...
1
2016-08-08T16:10:21Z
38,834,467
<p>I would highly recommend using a <em>dictionary</em> for this type of data coupling structure, along with <strong>O(1)</strong> look-up times, you'll also be implementing better design. However, you could do this with your current data structure using the following:</p> <p><strong>Sample output:</strong></p> <p><e...
1
2016-08-08T16:40:59Z
[ "python", "list", "duplicates", "append" ]
Using Python to manipulate 31-bits
38,833,978
<p>I have a specification which outlines how instructions should be sent over serial.</p> <p>Currently I am crafting the packets that will go over the connection.</p> <p>One segment of the packet, requires a 32-bit (4 byte) binary number. The first 31-bits are 'data' and the last bit is merely a flag.</p> <p>So, Th...
2
2016-08-08T16:12:16Z
38,834,214
<p>The only thing which comes to my mind is operation on strings</p> <p>Say we have two variables:</p> <pre><code>&gt;&gt;&gt; data = '7AAAAAAA' &gt;&gt;&gt; flag = '1' </code></pre> <p>Convert the data hex to number</p> <pre><code>&gt;&gt;&gt; num = int(data, 16) &gt;&gt;&gt; num 2058005162 </code></pre> <p>Conve...
1
2016-08-08T16:26:28Z
[ "python", "binary", "hex", "python-3.4", "pyserial" ]
Using Python to manipulate 31-bits
38,833,978
<p>I have a specification which outlines how instructions should be sent over serial.</p> <p>Currently I am crafting the packets that will go over the connection.</p> <p>One segment of the packet, requires a 32-bit (4 byte) binary number. The first 31-bits are 'data' and the last bit is merely a flag.</p> <p>So, Th...
2
2016-08-08T16:12:16Z
38,834,450
<p>I think you can use binary shift to add your flag to a number:</p> <pre><code>a = 0x7AAAAAAA # 2058005162 = 0b1111010101010101010101010101010 f = 1 # 1 = 0b1 packet = a + (f &lt;&lt; 31) # a + 0b10000000000000000000000000000000 bin(packet) # 0b1111101...
2
2016-08-08T16:39:53Z
[ "python", "binary", "hex", "python-3.4", "pyserial" ]
Using Python to manipulate 31-bits
38,833,978
<p>I have a specification which outlines how instructions should be sent over serial.</p> <p>Currently I am crafting the packets that will go over the connection.</p> <p>One segment of the packet, requires a 32-bit (4 byte) binary number. The first 31-bits are 'data' and the last bit is merely a flag.</p> <p>So, Th...
2
2016-08-08T16:12:16Z
38,834,714
<p>See if this works, similar to other answers but accounts for original bit length.</p> <p>Define the final number of bits</p> <pre><code>&gt;&gt;&gt; bits = 16 </code></pre> <p>Start with a bytes literal</p> <pre><code>&gt;&gt;&gt; a = b'10' </code></pre> <p>Convert to an <code>int</code></p> <pre><code>&gt;&gt...
0
2016-08-08T16:55:46Z
[ "python", "binary", "hex", "python-3.4", "pyserial" ]
Use a.empty, a.bool(), a.item(), a.any() or a.all()
38,834,028
<pre><code>import random import pandas as pd heart_rate = [random.randrange(45,125) for _ in range(500)] blood_pressure_systolic = [random.randrange(140,230) for _ in range(500)] blood_pressure_dyastolic = [random.randrange(90,140) for _ in range(500)] temperature = [random.randrange(34,42) for _ in range(500)] respir...
0
2016-08-08T16:14:54Z
38,834,238
<p>solution is easy:</p> <p>replace</p> <pre><code> mask = (50 &lt; df['heart rate'] &lt; 101 &amp; 140 &lt; df['systolic blood pressure'] &lt; 160 &amp; 90 &lt; df['dyastolic blood pressure'] &lt; 100 &amp; 35 &lt; df['temperature'] &lt; 39 &amp; 11 &lt; df['respir...
0
2016-08-08T16:28:00Z
[ "python", "pandas" ]
Use a.empty, a.bool(), a.item(), a.any() or a.all()
38,834,028
<pre><code>import random import pandas as pd heart_rate = [random.randrange(45,125) for _ in range(500)] blood_pressure_systolic = [random.randrange(140,230) for _ in range(500)] blood_pressure_dyastolic = [random.randrange(90,140) for _ in range(500)] temperature = [random.randrange(34,42) for _ in range(500)] respir...
0
2016-08-08T16:14:54Z
38,834,618
<p>As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use <code>&amp;</code>. That also requires using parentheses so that <code>&amp;</code> wouldn't take precedence. </p> <p>It would go something like this:</p> <pre><code>mask = ((50 &lt; df['h...
2
2016-08-08T16:49:38Z
[ "python", "pandas" ]
Calculating mean value in DataFrame using a mask
38,834,031
<p>I have the following DataFrame:</p> <pre><code> DATA Price1 Price2 Price3 sys dis 27 0.8 43.89 83.06 33.75 0.9 2.56 12.19 2.48 1.0 42.28 1.87 1.93 1.2 22.70 ...
1
2016-08-08T16:15:02Z
38,834,158
<p>easiest solution is</p> <pre><code>df['price_low']=df.ix[df.reset_index()['dis'] &lt; 1,'price'] df['price_high']=df.ix[df.reset_index()['dis'] &gt; 1, 'price'] df.price_low.mean() df.price_high.mean() </code></pre>
0
2016-08-08T16:22:53Z
[ "python", "pandas", "dataframe" ]
Calculating mean value in DataFrame using a mask
38,834,031
<p>I have the following DataFrame:</p> <pre><code> DATA Price1 Price2 Price3 sys dis 27 0.8 43.89 83.06 33.75 0.9 2.56 12.19 2.48 1.0 42.28 1.87 1.93 1.2 22.70 ...
1
2016-08-08T16:15:02Z
38,834,889
<p>You could use boolean comparators:</p> <pre><code>mean_low = df.loc[(df.index.get_level_values('dis') &lt; 1.0), 'Price1'].mean() mean_high = df.loc[(df.index.get_level_values('dis') &gt; 1.0), 'Price1'].mean() </code></pre>
2
2016-08-08T17:06:52Z
[ "python", "pandas", "dataframe" ]