Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
1,700
58,916,783
How to best perform recursion on a pandas dataframe column
<p>I am trying to calculate an index value over a time series within a pandas dataframe. This index depends on the previous row's result to calculate each row after the first iteration. I've attempted to do this recursively, within iteration over the dataframe's rows, but I find that the first two rows of the calculat...
<p>Based on your updated question, you just need to do this:</p> <pre><code># assign a new temp_factor with initial values and prep for cumprod stpassrev['temp_factor'] = np.where(stpassrev['factor'].isna(), 1, stpassrev['factor'].add(100).div(100)) # calculate the cumprod based on the temp_factor (grouped by Sector)...
python|pandas|recursion
1
1,701
52,041,963
Select rows containing a NaN following a specific value in Pandas
<p>I am trying to create a new DataFrame consisting of the rows corresponding to the value 1.0 or NaN in the last column, whereby I only take the Nans under a 1.0 (that is, I'm interested in everything until a 0.0 appears).</p> <pre><code>Timestamp Value Mode 00-00-10 34567 1.0 00-00-20 4542...
<p>You can use <code>.ffill</code> to figure out if it's a <code>NaN</code> below a 1 or a 0.</p> <p>Here are the <code>NaN</code> values below a 1</p> <pre><code>df[(df['Mode'].isnull()) &amp; df['Mode'].ffill() == 1] # Timestamp Value Mode #1 00-00-20 45425 NaN #5 00-00-60 25678 NaN </code></pre> <p>To ...
python|pandas|dataframe
2
1,702
51,926,983
Change CSV name to CSV date time python
<p>I want to change csv name (in this case Example.csv) to a specific name: date time name. I have a library called <code>from datetime import datetime</code></p> <p>This is my sentence to create a cvsFile:</p> <pre><code>with open('Example.csv', 'w') as csvFile: </code></pre> <p>I want that my output to be:</p> <p...
<p>Something like this:</p> <pre><code>import pandas as pd import datetime current_date = datetime.datetime.now() filename = str(current_date.day)+str(current_date.month)+str(current_date.year) df.to_csv(str(filename + '.csv')) </code></pre>
python|csv|datetime
3
1,703
18,837,125
Python select exists SQLite3 with variable
<p>I am to be unable to get the following code to work. I know how to use python variables in queries, but somehow I can't get this right. The query works fine when I hard code the 'icaocode' variable in the query, but not if I try to use a variable. What is wrong with this code?</p> <pre><code>icaocode = input() c.e...
<p>In Python, wrapping an expression in parentheses does not make any difference, <code>(icaocode)</code> is exactly the same as <code>icaocode</code>.</p> <p>The <code>execute</code> method expects some kind of <em>list</em> of parameters, so it sees the string as a sequence of four characters.</p> <p>To tell Python...
variables|python-3.x|sqlite|exists
1
1,704
69,108,624
File in "datas" array from the pyinstaller "spec" file is not found
<p>By creating the following spec file:</p> <pre class="lang-py prettyprint-override"><code># -*- mode: python ; coding: utf-8 -*- block_cipher = None face_models = [ ('face_recognition_models/models/*.dat', 'face_recognition_models/models') ] a = Analysis(['main.py'], pathex=[], binaries=f...
<p>I found an interesting solution that solved the problem, follow the link: <a href="https://github.com/explosion/spaCy/issues/3592" rel="nofollow noreferrer">https://github.com/explosion/spaCy/issues/3592</a></p> <p>I used this script to get the correct PATH from the file that was built by the .spec</p> <pre><code>de...
python|pyinstaller
0
1,705
63,739,327
How to export all the Details in the Div using Beautiful soup python to excel/csv?
<p>i am Newbie to Soup/python and i am trying to find the data. my website Structure look like this. <a href="https://i.stack.imgur.com/kDFSx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kDFSx.jpg" alt="enter image description here" /></a></p> <p>and if i open the Divclass <code>border class</code...
<p>Try the below approach using <a href="https://requests.readthedocs.io/" rel="nofollow noreferrer">requests</a> and <strong>beautiful soup</strong>. I have created the script with the URL which is fetched from website and then creating a dynamic URL to traverse each and every page to get the data.</p> <p>What exactly...
python|excel|web-scraping|beautifulsoup|export-to-csv
1
1,706
36,657,049
TastyPie throttling - by user or by IP?
<p>I can't seem to find any information on what TastyPie throttles based on. Is it by the IP of the request, or by the actual Django user object?</p>
<p>Throttle key is based on <code>authentication.get_identifier</code> function.</p> <p>Default implementation of this function returns a combination of IP address and hostname.</p> <p><strong>Edit</strong></p> <p>Other implementations (i.e. BasicAuthentication, ApiKeyAuthentication) returns username of the currentl...
python|django|tastypie|throttling
2
1,707
19,745,499
Can't get Pygame Collision detection to work
<p>I'm using Pygame and Python 3.2 to make a game. I must find out how to use collision detection so the player (<code>ballpic</code>) can pick up the items.</p> <p>Here is my code:</p> <pre><code>from pygame import * #import pygame bg = image.load('BG.png') ballpic = image.load('PlayerForward1.png') #Set the va...
<p>Why don't you try to use rectangles in pygame and their collision detection. <a href="http://www.pygame.org/docs/ref/rect.html" rel="nofollow">http://www.pygame.org/docs/ref/rect.html</a> You can also try to google a simple pygame game and see what's what.</p>
python|pygame|collision-detection
0
1,708
13,292,970
splitting list and adding values
<p>I have the following list</p> <pre><code>lst = ['Adam,widgets,5769', 'joe,balls,7186', 'greg,tops,1819.999',] </code></pre> <p>I need to be able to take the list and then divide the Adams number by lets say 100, and put that new number back into the list and then add it to gregs total.I started by splitting out th...
<pre><code>In [1]: lst = ['Adam,widgets,5769', 'joe,balls,7186', 'greg,tops,1819.999'] In [2]: lst = [s.split(',') for s in lst] In [4]: for l in lst: l[-1] = float(l[-1]) ...: In [5]: for l in lst: ...: if l[0] == "Adam": ...: l[-1] /= 100 ...: In [6]: lst Out[6]: [['Adam...
python
1
1,709
13,617,366
Python: Listing the duplicates in a list
<p>I am fairly new to Python and I am interested in listing duplicates within a list. I know how to remove the duplicates ( <strong>set()</strong> ) within a list and how to list the duplicates within a list by using <strong>collections.Counter</strong>; however, for the project that I am working on this wouldn't be th...
<p>I really don't think you'll get better than a <code>collections.Counter</code> for this:</p> <pre><code>c = Counter(mylist) duplicates = [ x for x,y in c.items() if y &gt; 1 ] </code></pre> <p>building the Counter should be <code>O(n)</code> (unless you're using keys which are particularly bad for hashing -- But i...
python
5
1,710
21,963,677
Output compiler error to a txt file in python
<p>I'm a beginner using python. I want to create a regular expression to capture error messages from compiler output in python. How would I do this?</p> <p>for example, if the compiler output is the following error message:</p> <pre><code>Traceback (most recent call last): File "sample.py", line 1, in &lt;module&gt...
<pre><code>r'Traceback \(most recent call last\):\n(?:[ ]+.*\n)*(\w+: .*)' </code></pre> <p>should extract your exception; a traceback contains lines that all start with whitespace except for the exception line.</p> <p>The above matches the literal text of the traceback first line, 0 or more lines that start with at ...
python|regex|compiler-construction
1
1,711
43,697,074
nested workspace problems: packages with the same name seem to overwrite?
<p>I am working on a project where I need nested workspaces--our project has a git repository with a submodule, and both need to be able to build and run bazel tests independently.</p> <p>The structure is like this:</p> <pre><code>projectA WORKSPACE tools/ py/ testing.py tests/ s...
<p>This problem resolved itself when I gave projectA a name in the workspace file:</p> <pre><code>workspace(name = "projectA") </code></pre> <p>I already had that line in projectB's WORKSPACE file but it got skipped in projectA.</p>
python|bazel
1
1,712
71,190,359
csv_reader read N lines at a time
<p>I have to read a CSV file N lines at a time.</p> <pre><code>csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: print row </code></pre> <p>I know I can loop N times at a time, build a list of list and process that way.</p> <p>But is there a simpler way of using csv_...
<p>Hi I don't think that you'll be able to do that without a loop with <code>csv</code> package.</p> <p>You should use <code>pandas</code> (<code>pip install --user pandas</code>) instead:</p> <pre class="lang-py prettyprint-override"><code>import pandas df = pandas.read_csv('myfile.csv') start = 0 step = 2 # Your 'N...
python-3.x|csvreader
0
1,713
38,987,427
urlopen for loop with beautifulsoup
<p>New user here. I'm <em>starting</em> to get the hang of Python syntax but keep getting thrown off by for loops. I understand each scenario I've reach on SO thus far (and my previous examples), but can't seem to come up with one for my current scenario.</p> <p>I am playing around with BeautifulSoup to extract featur...
<pre><code>from __future__ import print_function # try: # from urllib import urlopen # Support Python 2 and 3 except ImportError: # from urllib.request import urlopen # from bs4 import BeautifulSoup as bs for line in open('urls.dat'): # Read u...
python|for-loop|beautifulsoup|urlopen
1
1,714
39,210,426
Distributed processing of a PostgreSQL table
<p>I've got a PostgreSQL table with several millions of rows that need to be processed with the same algorithm. I am using Python and SQLAlchemy.Core for this task.</p> <p>This algorithm accepts one or several rows as input and returns the same amount of rows with some updated values.</p> <pre><code>id1, id2, NULL, N...
<p>One option to consider is randomization:</p> <pre><code>SELECT * FROM table WHERE value1 IS NULL ORDER BY random() LIMIT 100; </code></pre> <p>In worst case scenario you will have several workers calculating the same thing in parallel. If it does not bother you this is one of the most simple ways.</p> <p>The othe...
postgresql|python-2.7|sqlalchemy|distributed|dask
1
1,715
47,552,791
BeautifulSoup doesn't find, findAll, or get a div by its ID
<p>I've been on this for the last two days non-stop... I'm trying to get a specific div by its ID using BeautifulSoup as so:</p> <pre><code>import requests from bs4 import BeautifulSoup r = requests.get('www.example.com', cookies=cookies_dict) soup = BeautifulSoup(r.content, 'html.parser') div_text = soup.get('div', ...
<p>Err... Maybe you should check <code>BeautifulSoup</code> documentation again ?-)</p> <blockquote> <p>Help on method get in module bs4.element:</p> <p>get(self, key, default=None) unbound bs4.BeautifulSoup method Returns the value of the 'key' attribute for the tag, or the value given for 'default...
python|python-2.7|beautifulsoup|python-requests
0
1,716
34,288,213
python and mysql connections in a class , DB open and close strange behaviour
<p>I have written a small app that uses mysql to get a list of products that need updating on our magento website.</p> <p>Python then actions these updates and marks the product in the db as complete.</p> <p>My Original code (pseudo to show the overview)</p> <pre><code>class Mysqltools: def get_products(): ...
<p>Ok, the answer to this is as follows:</p> <pre><code>db = pymysql.connect(host=.... user=... ) class MySqlTools: def get_products(): mysqlcursor = db.cursor(pymysql.cursors.DictCursor) sql = select * from x where y = z mysqlcursor.execute(sql % (z)) rows = mysqlcursor.fetchall() ...
python|mysql|magento
1
1,717
34,344,839
Why is my Output 0?
<pre><code>def russian (a,b): x=a y=b z=0 while x&gt;0: if x % 2 == 1: z=z+y y= y *2 x= x/2 return z print russian(24,16) </code></pre> <p>This function uses the russian peasant algorithm to multiply two numbers together. I am expecting to see <code>384</code> as my outp...
<p>You are computing the z value only once and then immediately return it inside the <code>while</code> loop. Lose one level of indentation for <code>return z</code>.</p>
python|algorithm|python-2.7
1
1,718
34,270,328
How to split an equation given as a string into coefficients, variables and powers?
<p>So I have to create a program which takes a string in the following form: <code>2x^3 + x^2 - 4</code> and calculate its derivative i.e. make it like this: <code>6x^2 + 2x</code> </p> <p>So I'm creating a <code>class Monomial</code> that has three member variables: coefficient, variable name and power. In other word...
<p>I would use <a href="https://docs.python.org/2/library/re.html" rel="nofollow" title="regular expressions">regular expressions</a>:</p> <pre><code>pattern = "(\d+)?([a-z])\^(\d+)" result = re.match(pattern, "323x^22") print result.groups() </code></pre> <p>produces:</p> <pre><code>('323', 'x', '22') </code></pre...
python|string|oop
5
1,719
72,704,057
mpi4py getting only one MPI process available
<p>I'm trying to use mpi4py but am getting the following error when trying to initialize it:</p> <p><code>Tried to create an MPI pool, but there was only one MPI process available. Need at least two.</code></p> <p>The value of <code>MPI.COMM_WORLD.Get_size()</code> is <code>1</code>, which confirms the issue.</p> <p>St...
<p>This was a stupid mistake. I just had to call Python with <code>mpiexec -n &lt;# processes&gt; python ...</code>. Problem solved.</p>
python|mpi|hpc|mpi4py
0
1,720
72,578,120
Optimal memory storage, nested lists vs. flat lists
<p>I have a fairly large amount of data that needs to be stored in memory in Python, and i'm trying to work out how to save memory space as i'm continually running out of RAM.</p> <p>I have restricted myself to use only basic Python methods like lists, dicts and tuples as i have found, that these often have a huge adva...
<p>If your data is all of the same type, especially if it is primitive types (int, float, character, <strong>not</strong> str though) try using numpy arrays. Numpy stores data as a flat list but let's you access it like it's nested, and will generally use less memory as it is implemented to be more memory and speed eff...
python|memory
1
1,721
39,488,282
total size of new array must be unchanged
<p>I have two arrays x1 and x2, both are 1*14 arrays i am trying to zip them up and then perform reshape.</p> <p>The code is as below ;</p> <pre><code>x1 </code></pre> <p>Out[122]: array([1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 7, 9])</p> <pre><code>x2 </code></pre> <p>Out[123]: array([1, 3, 2, 2, 8, 6, 7, 6, 7, 1, 2,...
<p>I would assume you're on Python 3, in which the result is an array with a <code>zip</code> object. </p> <p>You should call <code>list</code> on the <em>zipped</em> items:</p> <pre><code>X = np.array(list(zip(x1, x2))).reshape(2, len(x1)) # ^^^^ print(X) # [[1 1 2 3 3 2 1 2 5 8 6 6 5 7] # [5 6 6 7 7 1 8...
python|arrays|numpy|reshape
3
1,722
16,465,014
How should negative time work?
<p>I'm trying to create a <code>Time</code> -class which can handle times of format <code>hh:mm:ss</code>. This is what I have:</p> <pre><code>class Time(object): def __init__(self, h=0, m=0, s=0): #private self.__hours = 0 self.__minutes = 0 self.__seconds = 0 #public ...
<p>There are 2 concepts to time:</p> <ul> <li>a moment in time (instant)</li> <li>a length between two instants (timespan or time delta).</li> </ul> <p>We measure timespan in seconds and multiple of seconds.</p> <p>A moment of time is described using the same unit, understood as a timespan between some reference tim...
python|time|python-3.x|negative-number
1
1,723
16,140,052
What's the difference between class variables of different types?
<p>Firstly, there is class <code>A</code> with two class variables and two instance variables:</p> <pre><code>In [1]: def fun(x, y): return x + y In [2]: class A: ...: cvar = 1 ...: cfun = fun ...: def __init__(self): ...: self.ivar = 100 ...: self.ifun = fun </code></pre> ...
<p>Actually, a function assigned to a class member remains function:</p> <pre><code>def x():pass class A: f = x e = None g = None print(A.__dict__['f']) # &lt;function x at 0x10e0a6e60&gt; </code></pre> <p>It's converted on the fly to a method object when you retrieve it from an instance:</p> <pre><c...
python|class|variables|instance
3
1,724
31,815,013
Using POST for flask url
<p>I've been looking at other stack questions but I am still confused on a concept that I think is very simple to most people on here. Basically, I'm trying to understand how my data from my form will post to my url route when <code>form.validate_on_submit</code>. Apologies in advance for bad terminology with Get/Post ...
<p>In your HTML template, when setting up your form tags, make sure it looks like:</p> <pre><code>&lt;form action="{{ url_for('people') }}" method="post"&gt; &lt;...content of your form here...&gt; &lt;/form&gt; </code></pre>
python|flask|wtforms
1
1,725
32,086,631
Can't install virtualenvwrapper on OSX 10.11 El Capitan
<p>I recently wiped my Mac and reinstalled OSX El Capitan public beta 3. I installed pip with <code>sudo easy_install pip</code> and installed virtualenv with <code>sudo pip install virtualenv</code> and did not have any problems.</p> <p>Now, when I try to <code>sudo pip install virtualenvwrapper</code>, I get the fol...
<p>You can manually install the dependencies that don't exist on a stock 10.11 install, then install the other packages with <code>--no-deps</code> to ignore the dependencies. That way it will skip <code>six</code> (and <code>argparse</code> which is also already installed). This works on my 10.11 beta 6 install:</p> ...
python|macos|virtualenv|virtualenvwrapper|osx-elcapitan
86
1,726
32,104,270
SQL syntax error in absurdly simple sql?
<p>Calling: </p> <pre><code>INSERT IGNORE INTO standard_group (group_name, subject, grade, country, state) VALUES (%(group_name), %(subject), %(grade), %(country), %(state)); </code></pre> <p>With </p> <pre><code>('Arizona Social Studies Standards', 'Social Studies', '1', 'United States', 'AZ') </code></pre> <p>eg:...
<p>It looks like a small typo. You forgot to add <code>s</code> to the params</p> <pre><code>INSERT IGNORE INTO standard_group (group_name, subject, grade, country, state) VALUES (%(group_name)s, %(subject)s, %(grade)s, %(country)s, %(state)s); </code></pre> <p>The relevant code is here:</p> <ul> <li><a href="https:...
python|mysql|prepared-statement|named-parameters
2
1,727
40,505,917
Django string_if_invalid and default
<p>I have <code>string_if_invalid</code> set to 'INVALID' in my django template settings. And there is some template that looks like this:</p> <pre><code>{{ some_nonexisting_value|default:'Default value' }} </code></pre> <p>After rendering result looks like <code>'INVALID'</code>. So, default value is not used. Is th...
<p>No, it's not possible to get the <code>default</code> filter to display the provided default instead of the invalid string.</p> <p>Note that <a href="https://docs.djangoproject.com/en/1.10/ref/templates/api/#how-invalid-variables-are-handled" rel="nofollow noreferrer">the docs</a> warn against using the <code>string...
python|django|templates|django-templates
5
1,728
10,020,676
Passing Commands To Python From PHP
<p>I have a python script on a vps that I run a simple command though.</p> <pre><code>./script.py [ipaddress] [portnumber] </code></pre> <p>example</p> <pre><code>./script.py 127.0.0.1 8080 </code></pre> <hr> <p>What I'd like to do is put a simple php script on my apache server (same vps) with a form on the page t...
<p>popen() is what you want</p> <p><a href="http://www.php.net/manual/en/function.popen.php" rel="nofollow">http://www.php.net/manual/en/function.popen.php</a></p> <p>This allows you to run an arbitrary command and get the stdout result.</p>
php|python|apache
4
1,729
26,185,422
Pulling certain data from an input
<p>Im trying to extract a certain part of my input from the first line and use it to calculate the problem and then put it back together. </p> <p>For example,</p> <pre class="lang-none prettyprint-override"><code>Please enter the starting weight of food in pounds followed by ounces:8:9 Please enter the ending weight...
<pre><code># get input from the user, e.g. '8:9' start_weight= input('Starting weight of food (in lbs:ozs)=') # so start_weight now has the value '8:9' # find the position of the ':' character in the user input, as requested in the assignment: 'Use the “find” command to locate the “:” in the input data' sep= start_wei...
python|python-3.x|input|extract
0
1,730
1,466,732
Testing for cookie existence in Django
<p>Simple stuff here...</p> <p>if I try to reference a cookie in Django via</p> <pre><code>request.COOKIE["key"] </code></pre> <p>if the cookie doesn't exist that will throw a key error.</p> <p>For Django's <code>GET</code> and <code>POST</code>, since they are <code>QueryDict</code> objects, I can just do</p> <pr...
<p><code>request.COOKIES</code> is a standard Python dictionary, so the same syntax works.</p> <p>Another way of doing it is:</p> <pre><code>request.COOKIES.get('key', 'default') </code></pre> <p>which returns the value if the key exists, otherwise 'default' - you can put anything you like in place of 'default'.</p>
python|django|http|cookies
22
1,731
63,276,670
Why can't I use variables (using "%s" or "?") to refer to table and column names in sqlite's "CREATE TABLE IF NOT EXISTS" and "INSERT INTO VALUES"?
<p>I am creating a database class for my application since I'll need database tables at various occasions. I am using sqlite3 and I need my code to be as generic as possible but when I used &quot;%s&quot; and/or &quot;?&quot; for the table name and the column titles I got the above mentioned error.</p> <p>Here's my cod...
<p>You can use <code>%s</code> to refer to the table name or other variables in the string. Notice the <code>%s</code> marker to insert a string, and the <code>%d</code> marker to insert an integer.</p> <p>Alternatively, you can also use the <code>format</code> method to substitute the value of a variable in the string...
python|sql|python-3.x|sqlite|oop
0
1,732
28,261,614
How do I write in a new text file every x lines? [python]
<p>Let's say I have a list with 10,000 entries. The user inputs a number, say 10. What I need to do is write all of the entries in the list to .txt files, but only 10 to each file. So the program would write the first 10, and then create a new file, and write the next 10... etc.</p> <p>Thanks</p> <pre><code>count = 0...
<p>Very easy do with the <a href="https://docs.python.org/2/library/itertools.html#recipes" rel="nofollow">itertools.grouper recipe</a>:</p> <pre><code>from itertools import izip_longest n = 2 l = ["1", "2", "3", "4", "5", "6"] def grouper(iterable, n, fillvalue=""): args = [iter(iterable)] * n return izip_l...
python|text|split
2
1,733
14,202,162
Xpath returning more than desired (python, urllib, lxml)
<p>I am trying to retrieve the first download link from a website, but my code is returning more than that and I'm not sure why.</p> <p>Here is a piece of my code:</p> <pre><code>site_search = "http://mp3skull.com/mp3/tubidy.html" user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0'...
<p>//something[1] returns all values that are the first something of their respective parent. (//something)[1] would return the first of all somethings in the document.</p> <p>So you would have to use:</p> <pre><code>(//a[@style = 'color:green;'])[1]/@href </code></pre>
python|xpath|lxml|urllib
2
1,734
27,341,064
How do I fix 'ImportError: cannot import name IncompleteRead'?
<p>When I try to install anything with <code>pip</code> or <code>pip3</code>, I get:</p> <pre class="lang-none prettyprint-override"><code>$ sudo pip3 install python3-tk Traceback (most recent call last): File "/usr/bin/pip3", line 9, in &lt;module&gt; load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')() ...
<p>While <a href="https://stackoverflow.com/a/27341847/2854723">this previous answer</a> might be the reason, this snipped worked for me as a solution (in <code>Ubuntu 14.04</code>):</p> <p>First remove the package from the package manager:</p> <pre class="lang-none prettyprint-override"><code># apt-get remove python...
python|pip
434
1,735
12,227,084
A way to get the path to the user installed packages on Linux and OS X operating systems? (Usable for Python versions between 2.5 - 2.7)
<pre><code>&gt;&gt;&gt; import distutils.sysconfig &gt;&gt;&gt; distutils.sysconfig.get_python_lib() /usr/lib/python2.7/dist-packages </code></pre> <p>But I want this path: <code>/usr/local/lib/python2.7/dist-packages</code>. I can't use the <code>sysconfig</code> module because it is only supported on python2.7 and t...
<p>If you need the specific functionality of the <code>get_python_lib</code> function, the <a href="http://hg.python.org/cpython/file/2370e331241b/Lib/distutils/sysconfig.py" rel="nofollow">source for that module</a> is fairly straightforward and doesn't use any Python 2.7 specific syntax at all; you could simply backp...
python|linux|macos|path|python-2.x
1
1,736
12,554,422
mapping keys (all occur in the given string) to the position in string
<p>I am trying to get all indexes of the keys in the string and store them in a dict, so that every index has a list of keys mapping to it.</p> <p>Example: </p> <pre><code>string = "loloo and foofoo at the foo bar" keys = "foo", "loo", "bar", "lo" </code></pre> <p>i expect something like</p> <pre><code>{ 0: [lo]...
<p><code>Non-regex</code> approach:</p> <p>using <code>str.find()</code>, <code>str.find()</code> accepts a optional second argument which is the index after which you want to find the word.</p> <pre><code>def indexes(word,strs): ind=0 #base index is 0 res=[] while strs.find(word,ind)!=-1: ...
python
1
1,737
42,065,870
How can i use my own images to train my CNN neural network in tensorFlow
<p>I am currently working on a program that uses a CNN tensorflow neural network and I want to use my own images to train and test it, please I want some advice because I am new in deep learning </p> <p>Thanks.</p>
<p>Download the ronnie package from python.[{pythonpath}\scripts\pip3 ronnie] Construct the training data structure as [label, image pixel] and execute the below code to create the training data.</p> <p>dataFileLoc = os.path.join(dir,"./data/digitalRec/train.csv") orgDF = collector.initial(dataFileLoc)</p> ##########...
tensorflow
0
1,738
47,115,600
Python 3 Bokeh Heatmap Rect simple example not showing anything in plot
<p>I'm trying to color code a simple categorical heatmap using python's Bokeh library. For example, given the following table, I would want to replace each 'A' with a red square and each 'B' with a blue square:</p> <pre><code>AAAABAAAAB BBBAAAABBB </code></pre> <p>To start, I thought the following would produce 2 row...
<p>You need to create specific coordinates <em>for each rect</em>. If there are 2 possible values on the y-axis, and 10 possible values on the x-axis, then there are <strong>20</strong> possible unique pairs of coordinates for all the rects (i.e. the cross product of those two lists). For example:</p> <pre><code>(0, '...
python|heatmap|bokeh|rect
1
1,739
47,419,345
Save rows of a bidimensional numpy array in another array
<p>I have a bidimensional np array V (100000x50). I want to create a new array V_tgt in which I keep just certain rows of V, so the dimension will be (ix50). It may be easy to do it but I tried different things and it seems to save just the first of the 50 elements. My code is the following:</p> <pre><code>V_tgt = np....
<p>From your comments I assume that you have some kind of list of target indices (in my example <code>tgt_idx1</code> and <code>tgt_idx2</code>)that tells you which elements to take from V. You could do something like this:</p> <pre><code>import numpy as np V = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) tgt_...
python|arrays|numpy
0
1,740
12,016,242
Is there any Celeryd or Celery (for Django/Python) type altenative for Symfony 2 framework
<p>I am a big fan of <a href="http://en.wikipedia.org/wiki/Celery_Task_Queue" rel="nofollow">Celery</a> for executing scheduled tasks in Django. I am now using <a href="http://en.wikipedia.org/wiki/Symfony" rel="nofollow">Symfony</a>&nbsp;2 and see that it is almost similar to Django framework.</p> <p>I wonder if ther...
<p>Celery is providing a simple layer to use messaging. It makes the task of building async services easy. Interestingly the concept is not new. It is already available in form of standard protocol like AMQP. Documentation available at </p> <p><a href="http://php.net/manual/en/book.amqp.php" rel="nofollow">http://php....
php|python|django|symfony|celery
0
1,741
11,908,919
Python parsing log file to extract events in real time
<p>I've a process that is logging messages to a file. </p> <p>I want to implement another process (in Python) that parses these logs (as they are written to the file), filters the lines that I'm interested in and then performs certain actions based on the state of the first process.</p> <p>I was wondering before I g...
<p>C programs usually seek to the current position to clear any “end of file” flags. But as <a href="https://stackoverflow.com/a/11909244/1468366">@9000 correctly pointed out</a>, python apparently takes care of this, so you can read from the same file repeatedly even if it has reached end of file.</p> <p>You might ha...
python|linux|logging
19
1,742
33,582,388
Expand a list of dictionaries into a readable format
<p>My description/title may be lacking, as I am new to python, however as an example, I currently have data like below stored in the variable <code>bunnies</code>:</p> <blockquote> <p>[{'rabbithole': {'holenumber': 1, 'family': 'roger', 'status': 'elite'}, 'food': 'steak', 'children': 108, 'job': 'chef', 'etc': 'e...
<p>You can use the <a href="https://docs.python.org/2/library/json.html" rel="nofollow"><code>json</code></a> Python module:</p> <pre><code>import json print json.dumps(your_data, sort_keys=True, indent=4, separators=(',', ': ')) </code></pre> <p>Example:</p> <pre><code>a=json.dumps([{'rabbithole': {'holenumber': 1...
python|python-2.7
1
1,743
46,914,866
why will I get a "TypeError: object of type 'NoneType' has no len()"?
<pre><code>words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes',"don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under'] def requirement(word): onelist = [] if word in words: r...
<p>The function <code>list.append()</code> modifies a list in place and returns <code>None</code>. So the line</p> <pre><code>return(len(onelist.append(word))) </code></pre> <p>is trying to return the length of <code>None</code>, which should obviously throw a TypeError. Try something like </p> <pre><code>onelist.ap...
python|python-3.x
2
1,744
37,630,202
python pandas: passing in dataframe to df.apply
<p>Long time user of this site but first time asking a question! Thanks to all of the benevolent users who have been answering questions for ages :)</p> <p>I have been using <code>df.apply</code> lately and ideally want to pass a dataframe into the <code>args</code> parameter to look something like so: <code> df.appl...
<p>The error is in this line:</p> <pre><code> File "C:\Anaconda3\envs\p2\lib\site-packages\pandas\core\frame.py", line 4017, in apply if kwds or args and not isinstance(func, np.ufunc): </code></pre> <p>Here, <code>if kwds or args</code> is checking whether the length of <code>args</code> passed to <code>apply</...
python|pandas|dataframe
8
1,745
37,837,682
Python class input argument
<p>I am new to OOP. My idea was to implement the following class:</p> <pre><code>class name(object, name): def __init__(self, name): print name </code></pre> <p>Then the idea was to create two instances of that class:</p> <pre><code>person1 = name("jean") person2 = name("dean") </code></pre> <p>I know, ...
<p>The problem in your initial definition of the class is that you've written:</p> <pre><code>class name(object, name): </code></pre> <p>This means that the class inherits the base class called "object", and the base class called "name". However, there is no base class called "name", so it fails. Instead, all you nee...
python|oop
65
1,746
27,579,899
Cannot use im.getcolors
<p>I was trying this code:</p> <pre><code>im = Image.open("myimage") colors = im.getcolors() print colors </code></pre> <p>and it returns "None". So I tried this:</p> <pre><code>im = Image.open("myimage") size = im.size colors = im.getcolors(size[0]*size[1]) </code></pre> <p>and when I "print colors" with this,...
<p>The image has to be in RGB mode in order to use <code>getcolors</code>. So try:</p> <pre><code> im_rgb = im.convert('RGB') colors = im_rgb.getcolors() print colors </code></pre>
python|image|colors|python-imaging-library
4
1,747
27,573,687
Python TypeError: cannot convert dictionary update sequence element #1 to a sequence
<p>doing some data wrangling from an example in O'Reilly's "Python for Data Analysis."</p> <p>We start with data of the following format:</p> <pre><code>In [108]: data.CATEGORY[:5] Out[108]: 0 1. Urgences | Emergency, 3. Public Health, 4 1. Urgences | Emergency, 5 ...
<p>Here is the solution:</p> <ol> <li><p>"cannot convert dictionary update sequence element #1 to a sequence"---because there is null value in the expression "get_english(x) for x in all_cats", so it can't be converted into a dictionary;</p></li> <li><p>Why? </p></li> </ol> <blockquote> <pre><code>def get_english(cat...
python-2.7
3
1,748
27,762,618
python requests: how can I get the "exception code"
<p>I am using "requests (2.5.1)" .now I want to catch the exception and return an dict with some exception message,the dict I will return is as following:</p> <pre><code>{ "status_code": 61, # exception code, "msg": "error msg", } </code></pre> <p>but now I can't get the error status_code and error message,I ...
<pre><code>try: #the codes that you want to catch errors goes here except: print ("an error occured.") </code></pre> <p>This going to catch all errors, but better you define the errors instead of catching all of them and printing special sentences for errors.Like;</p> <pre><code>try: #the codes that you w...
python|exception
0
1,749
43,167,362
R to Python pandas numpy.where conversion
<p>what is the best way to write the following R code in Python (pandas dataframe) using numpy.where syntax.</p> <pre><code>Data$new = ifelse(Data$Diff &gt; 1.652*Data$Diff10, 1, ifelse(Data$Diff &lt; 3.95*Data$Diff10, -1, 0 )) </code></pre>
<p>You can use:</p> <pre><code>Data['new'] = np.where(Data['Diff'] &gt; 1.652*Data['Diff10'], 1, np.where(Data['Diff'] &lt; 3.95*Data['Diff10'], -1, 0 )) </code></pre> <p>EDIT:</p> <p>It seems code above have logic error, because never return <code>0</code>.</p> <p>Maybe need:</p> <pre><code>Data = p...
python|pandas|numpy
0
1,750
37,075,349
How to fix overfitting in Elman neural network?
<p>I'm training elman network with neurolab python library and my net doesn't work properly.</p> <ul> <li>Training input vectors: <a href="http://pastebin.com/urQX2eEA" rel="nofollow">http://pastebin.com/urQX2eEA</a> </li> <li>Training target vector: <a href="http://pastebin.com/1JQh1xZv" rel="nofollow">http://pastebi...
<p>First of all this is <strong>not overfitting</strong>. You are <strong>underfitting</strong>, you do not even converge for training cases. Can't you just increase number of epochs? Let the net converge.</p>
python|neural-network|artificial-intelligence|recurrent-neural-network
1
1,751
48,533,286
Why does my data change into NaN in Task4?
<p>Why does my data change into NaN in task 4? I also tried using .loc[], but that still doesn't work. I need to be able to use the numbers.</p> <pre><code>dec6 = pd.read_csv('coinmarketcap_06122017.csv', header=0) market_cap_raw = dec6[['id', 'market_cap_usd']] print(market_cap_raw.describe()) #print(market_cap_raw) ...
<p>The re_index() method is causing the data to change to NaN. </p>
python|pandas
0
1,752
20,156,497
Reading File in Python and putting column into Array
<p>I am fairly new to Python and am working with the NLTK to produce a sound dynamic Text Analyzer. I have a .csv file with member information, survey response number, and survey response text that I need open and read. </p> <p>I have: </p> <pre><code>import csv import codecs f = open('testresponseFS.csv') raw = f...
<pre><code>import csv # read data with open('testresponseFS.csv', 'rb') as inf: incsv = csv.reader(inf) header = next(incsv) data = [row for row in incsv] # process data header.append('Comments') response_column = 4 for row in data: response = row[response_column] newval = response[:4].lower() ...
python|arrays|file|csv
3
1,753
20,276,338
Itertools to create a list and work out probability
<p>I am trying to work out the probability of 'Susie' winning a match.</p> <p>Probability of 'Susie' winning a game = 0.837<br> Probability of 'Bob' winning a game = 0.163</p> <p>If the first person to win n games wins a match, what is the smallest value of n such that Susie has a better than 0.9 chance of winning th...
<p>You also need to loop over values of <code>n</code>. Also note that 'first to <code>n</code>' is the same as 'best out of <code>2n-1</code>'. So we can say <code>m = 2 * n - 1</code> and see who wins the most games of that set. <code>max(set(product), key=product.count)</code> is a short but opaque way of working ou...
python|probability|itertools
1
1,754
48,156,814
unable to install face_recognition library for python
<p>I'm trying to install dbLib Library for executing python face_recognition as mentioned here </p> <p><a href="https://github.com/ageitgey/face_recognition/issues/175#issuecomment-355899230" rel="nofollow noreferrer">https://github.com/ageitgey/face_recognition/issues/175#issuecomment-355899230</a></p> <p>as I execu...
<p>I was able to install it with pip (through the pip install face_recognition command) after I had Boost and CMake installed.</p> <p>to install face_recognition install Boost from here <a href="http://www.boost.org/users/download/" rel="nofollow noreferrer">here</a> and then install Cmake if both get successful then ...
python
1
1,755
47,989,741
Python - Array becomes scalar variable when passed into function
<p>I am trying to create a simple python script that when given a photo, first converts it to greyscale and then will band it into a number of colors. For example if the number of colours passed in is 2, the greyscale image will be changed so that each pixel is either pitch black (0) or bright white (255). </p> <p>How...
<p>Change:</p> <pre><code>for i in range(1, bandWidthArray.len): </code></pre> <p>to:</p> <pre><code>for i in range(1, len(bandWidthArray)): </code></pre> <p>NumPy arrays don't have a <code>len</code> method.</p> <p>Furthermore, don't vectorize your function. Remove this line:</p> <pre><code>getGreyScaleValue = n...
python|numpy
0
1,756
48,144,206
How can I extract credit card substring from a string using python
<p>I am new to python and I hope someone can help me with this. I need to extract credit card numbers from a string. e.g</p> <p>"My credit card number is 1234-2312-2312-2312" or "My Credict card number is 1234 1234 1832 1234"</p> <p>Anyone knows how I can do it?</p>
<p>Do it like this using regex</p> <pre><code>import re def findCardNumber(string): pattern = r"(^|\s+)(\d{4}[ -]\d{4}[ -]\d{4}[ -]\d{4})(?:\s+|$)" match = re.search(pattern, string) if match: print(match.group(0)) findCardNumber("My Credict card number is 1234 1234 1832 1234") </code></pre> <...
python|credit-card
1
1,757
73,644,154
pandas creates 2 copies of files in a loop
<p>I have a dataframe like as below</p> <pre><code>import numpy as np import pandas as pd from numpy.random import default_rng rng = default_rng(100) cdf = pd.DataFrame({'Id':[1,2,3,4,5], 'customer': rng.choice(list('ACD'),size=(5)), 'region': rng.choice(list('PQRS'),size=(5)), ...
<p>The issue is happening because you are referencing 2 different file names one with the prefix <code>&quot;test_files/&quot;</code> and once without it. Best way to handle it will be to define file name as follows</p> <pre><code>dir_filename = &quot;test_files/&quot; + f&quot;{filename}.xlsx&quot; </code></pre> <p>an...
python|pandas|dataframe|file|group-by
1
1,758
17,475,715
Making sublist indices refer to the original list
<p>I need to check some sublist for a particular property, and then return the bin which satisfies that property, but as an index of the original list. Currently I'm having to do this manually:</p> <pre><code>sublist = mylist[start:end] positive = search(sublist) positive = start + positive posiveList.append(positiv...
<p>I think what you're asking is this:</p> <blockquote> <p>If I search and find an index in a sublist, is there a straightforward way to convert it to its index in the original list?</p> </blockquote> <p>No, the only way is what you're already doing: you need to add the <code>start</code> offset back to the index t...
python
2
1,759
17,210,650
64-bit argument for fcntl.ioctl()
<p>In my Python (2.7.3) code, I'm trying to use an ioctl call, accepting a long int (64 bit) as an argument. I'm on a 64-bit system, so a 64-bit int is the same size as a pointer.</p> <p><strong>My problem is that Python doesn't seem to accept a 64-bit int as the argument for a fcntl.ioctl() call.</strong> It happily ...
<p>Whether or not this is possible using Python's <code>fcntl.ioctl()</code> will be system-dependent. Tracing through the source code, the error message is coming from the following test on <a href="http://hg.python.org/cpython/file/bc6d28e726d8/Python/getargs.c#l658" rel="nofollow">line 658 of <code>getargs.c</code><...
python|ioctl
6
1,760
73,119,036
why my click function not working in python selenium
<h1>Imported all the driver and library</h1> <pre><code> from lib2to3.pgen2.driver import Driver from sqlite3 import Timestamp from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from time import sleep import getpass as gp...
<p>You may want to use explicit waits, rather than implicit. The following code will wait for the elements in page to become available, input your username, and click on Next button. Do not forget to import WebDriverWait and expected_conditions:</p> <pre><code>from selenium.webdriver.support.ui import WebDriverWait fro...
python|selenium-webdriver|web-scraping|xpath
0
1,761
64,929,710
How to make the docker container search the file within the host rather than within the container?
<p>I have a <strong>python script</strong> which takes the input file path from the user processes that file and gives the output file in the location specified by the user in the terminal. Below is my code which takes the files path.</p> <pre><code>inputfilepath = input(&quot;Enter the input file path&quot;) print(inp...
<p>You should mount your files (or the directory containing the files) from the host to the container.</p> <p>Assuming you want the same path in the container as in the host:</p> <pre><code>docker run \ --mount type=bind,source=/path/to/directory,target=/path/to/directory </code></pre> <p>See the <a href="https://doc...
python|docker|containers
0
1,762
64,118,898
pandas: from how to unpack nested JSON as dataframe?
<p>I have an JSON output like this</p> <p><code>json.json</code></p> <pre><code>{&quot;SeriousDlqin2yrs&quot;: {&quot;prediction&quot;: &quot;0&quot;, &quot;prediction_probs&quot;: {&quot;0&quot;: 0.95, &quot;1&quot;: 0.04}}} {&quot;SeriousDlqin2yrs&quot;: {&quot;prediction&quot;: &quot;0&quot;, &quot;prediction_probs&...
<p>Tested in pandas <code>1.1.1</code> - convert values to <code>list</code>s and pass to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.json.json_normalize.html" rel="nofollow noreferrer"><code>json_normalize</code></a>:</p> <pre><code>s = pd.read_json('json.json', lines=True)['SeriousDlq...
python|pandas
3
1,763
68,740,447
How to drop all strings in a column using a wildcard?
<p>I have some data that changes regularly but the column headers need to be consistent (so I cant drop the headers) but I need to clear our the strings in a given column.</p> <p>This is what I have now but this only seems to work for where I know what the string is called and one at a time?</p> <pre><code> df1= pd....
<p>You can use the <code>pd.drop</code> function which removes rows having a specific index from a dataframe.</p> <pre class="lang-py prettyprint-override"><code>for i in df.index: if type(df.loc[i, 'Aborted Reason']) == str: df.drop(i, inplace = True) </code></pre> <p><code>df.drop</code> will remove the ...
python|python-3.x|pandas
2
1,764
60,363,904
How to use the universal POS tags with nltk.pos_tag() function?
<p>I have a text and I want to find number of 'ADJs','PRONs', 'VERBs', 'NOUNs' etc. I know that there is <code>.pos_tag()</code> function but it gives me different results , and I want to have results as 'ADJ','PRON', 'VERB', 'NOUN'. This is my code:</p> <pre><code>import nltk from nltk.corpus import state_union, brow...
<p>From <a href="https://github.com/nltk/nltk/blob/develop/nltk/tag/__init__.py#L135" rel="noreferrer">https://github.com/nltk/nltk/blob/develop/nltk/tag/<strong>init</strong>.py#L135</a> </p> <pre><code>&gt;&gt;&gt; from nltk.tag import pos_tag &gt;&gt;&gt; from nltk.tokenize import word_tokenize # Default Penntreeb...
python|nlp|nltk|pos-tagger|universal-pos-tag
8
1,765
71,241,648
Get max time of grouped by time series dataframe
<p>I have a dataframe as follows:</p> <pre><code>Date User Tag 2-22-2022 09:00:00 u1 a 2-22-2022 10:00:00 u1 b 2-22-2022 11:00:00 u2 c 2-23-2022 09:00:00 u1 a 2-23-2022 10:00:00 u2 b </code></pre> <p>Want to creat, for each user, a column with the time difference be...
<p>First of all, I had to split your calculation of the &quot;diff&quot; column in two steps to reach the same output as you:</p> <pre><code>&gt;&gt;&gt; df[&quot;diff&quot;] = df.groupby(&quot;User&quot;)[&quot;Date&quot;].diff() &gt;&gt;&gt; df[&quot;diff&quot;] = df.groupby(&quot;User&quot;)[&quot;diff&quot;].shift(...
pandas
0
1,766
71,315,413
Create and populate dataframe column simulating (excel) vlookup function
<p>I am trying to create a new column in a dataframe and polulate it with a value from another data frame column which matches a common column from both data frames columns.</p> <pre><code>DF1 DF2 A B W B ——— ——— Y 2 X 2 N 4 F 4 Y 5 T 5 </code></pre> <p>I though the following could do the tick.</p> <pre...
<p>Your question is not clear because why is F associated with N and T with Y? Why not F with Y and T with N?</p> <p>Using <code>merge</code>:</p> <pre><code>&gt;&gt;&gt; df2.merge(df1, on='B', how='left') W B A 0 X 2 Y 1 F 4 N # What you want 2 F 4 Y # Another solution 3 T 4 N # What you want 4 T ...
python|dataframe|vlookup
3
1,767
70,134,730
How to use alt.condition() in alt.color(condition=)?
<p>I'm new to altair so i want to be able to see my code more clearly. that's why i'm trying to use long version coding. my problem is that, i could't find any documentation on how to use a <code>alt.color(condition=)</code> . How can i use <code>condition=</code> preferably with <code>alt.condition()</code>?</p> <pre>...
<p><code>alt.condition</code> is a shorthand for generating the full <code>alt.Color</code> specification for a conditional encoding. If you wish, you can create it more manually like this:</p> <pre class="lang-python prettyprint-override"><code> alt.Color( condition={&quot;selection&quot;: brush.name, &quot...
python|conditional-statements|altair
0
1,768
63,481,133
How to show all categories in legend in pie chart with matplotlib python
<p>Hi I am trying a plot chart and have some difficulties to show the legend. Here's my code below:</p> <pre><code>age = ['below 20', '20-30', '30-40', '40-50'] age_count = [23,0,35,0] labels = age sizes = age_count fig1, ax1 = plt.subplots() ax1.pie(sizes, autopct='%1.1f%%', shadow=True, startangle=90) ...
<p>from matplotlib.pyplot.pie docs:</p> <p>&quot;autopct None or str or callable, default: None</p> <p>If not None, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be fmt % pct. If it is a function, it will be...
python|matplotlib|pie-chart
0
1,769
65,929,177
How can I get "START!" to print after the first line of asterisks when I run it, rather than just the changes of direction?
<p>It will print start and stop, but not on the first line? How can I get &quot;START!&quot; to print after the first line of asterisks when I run it, rather than just the changes of direction?</p> <pre><code>import time, sys while True: try: print(&quot;Enter and integer between 5 and 15: &quot;) userInpu...
<p>How about just adding a print statement before the <code>while</code> loop and initializing <code>indent</code> at 1 instead of 0?</p> <pre><code>indent = 1 indentIncreasing = True try: stars += &quot;*&quot; * userInput print(stars + ' START!') while True: print(' ' * indent, end='') pr...
python
0
1,770
66,160,791
Merging excel sheets using pandas
<p>I have a quick script using python and pandas thats supposed to compare two excel sheets, grab the information that i need and create a new file. However when it creates the new file or if i just print it for testing one of the columns is coming back empty depending on where i merge (left of right)</p> <pre><code> ...
<p>I haven't double checked your merge, but rather than sending your merged data to a string, you should use pd.to_excel()</p> <p>something like:</p> <pre><code>merge_data.to_excel('merged_data.xlsx', sheet_name='merged') </code></pre> <p>If you need to save multiple sheets, looks the documentation - there are directio...
python|excel|pandas
1
1,771
66,030,470
Plotly: How to show other values than counts for marginal histogram?
<p>I am trying to create a linked marginal plot above the original plot, with the same x axis but with a different y axis.</p> <p>I've seen that in <code>plotly.express</code> package there are 4 options in which you can create marginal_x plot on a scatter fig, but they are all based on the same columns as x and y.</p>...
<p>I'm understanding your statement</p> <blockquote> <p>[...] and rate of something on my y-axis</p> </blockquote> <p>... to mean that you'd like to display a value on your histogram that is <em>not</em> count.</p> <p><code>marginal_x='histogram'</code> in <code>px.scatter()</code> seems to be defaulted to show counts ...
python|pandas|plotly|plotly-python|plotly.graph-objects
4
1,772
69,073,297
Pandas: Compare rows within groups in a dataframe and create summary rows to mark / highlight different entries in group
<p>I have a pandas dataframe with approx. 1200 rows, where some of the rows are duplicated multiple times. The df looks like this:</p> <pre><code>ID Serial Age Grade Chem Bio Math Phy M001 2 52 37 1 1 1 1 M001 2 55 37 2 1 0 1 M001 3 51 36,5 1 1 ...
<p>You can create a comparison marking table by grouping on <code>ID</code> and <code>Serial</code> using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>.groupby()</code></a> and get the number of unique entries for each column by <a hr...
python|pandas|dataframe
2
1,773
72,796,183
how to use keras demo code siamese_contrastive.py to use a custom dataset?
<p>I am following this example <a href="https://keras.io/examples/vision/siamese_contrastive/" rel="nofollow noreferrer">Image similarity estimation using a Siamese Network with a contrastive loss</a>.</p> <p>The given code snippet reads directly from <code>keras.datasets.mnist.load_data()</code>.</p> <p>I am trying to...
<p>You can load images like this :</p> <pre><code>anchor_images = sorted([str(anchor_images_path / f) for f in os.listdir(anchor_images_path)]) </code></pre> <p>Same for positives and negatives.</p> <p><strong>Detailed example here:</strong></p> <p><a href="https://keras.io/examples/vision/siamese_network/" rel="nofoll...
python|tensorflow|keras|deep-learning|siamese-network
0
1,774
63,300,715
Django Localization: languages and models connection
<p>The main idea of my project with localisation is show different content on all languages. I'm trying to use Django Internationalization and localization.</p> <p>Everything worked, except for one problem:</p> <p>If I post question (QA project) on polish language, my url is - site.com/pl/questions/question_123/</p> <p...
<p>You can override</p> <pre><code>get_queryset() </code></pre> <p>from the DetailView and control, and filter your queryset by language.</p> <pre><code>return Question.objects.filter(language__code=MY_LANGUAGE_CODE) </code></pre> <p>You can access your language code probably with your URL-slug field. This should be ac...
python|django
0
1,775
63,074,439
Can not uninstall Tensorflow 2.1.0 as conda can't find the package and solving environment fails
<p>The tensorflow 2.1.0 package is shown under <code>conda list</code> as follows:</p> <p><a href="https://i.stack.imgur.com/9Ho54.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9Ho54.png" alt="conda list output" /></a></p> <p>But when I try to uninstall it using <code>conda remove tensorflow</code>...
<p>First obtain the path where your packages are installed in anaconda-spyder using this command. Refer <a href="https://stackoverflow.com/a/49028561/9279666">this link</a> for more information</p> <pre><code>python -c &quot;from distutils.sysconfig import get_python_lib; print(get_python_lib())&quot; </code></pre> <p>...
python|tensorflow|pip|anaconda|conda
0
1,776
58,832,584
Insert Property Value using Py2neo
<p>I have one label say User,and one property say Email.I am trying to insert one property value based on user input like <em>"abcd@gmail.com"</em> . My code is below </p> <pre><code>db=Graph("bolt://localhost:1234", user="", password="") db.evaluate('''Create (u:User) WHERE u.Email=$para1 RETURN u''', ...
<p>I have solved my problem.Posting the answer so it may help others.</p> <pre><code>self.db.evaluate('''Create (u:User) SET u.Email=$para1 RETURN u''', parameters={'para1': arg}) </code></pre>
python|python-3.x|py2neo
0
1,777
58,644,645
ValueError: cannot reshape array of size 7840000 into shape (60000,784)
<p>I am trying to classify greyscale images of hand written digits (28 by 28 pixels) into their 10 categories.</p> <p>I already checked similar questions on this site, but I failed at solving why I am getting the error: </p> <blockquote> <p>ValueError: cannot reshape array of size 7840000 into shape (60000,784)</p...
<p>MNIST dataset consist of 60000 training images and 10000 test images. Reshape as:</p> <pre><code>test_images = test_images.reshape((10000, 28 * 28)) </code></pre>
python|keras|deep-learning
0
1,778
49,237,550
Flask configuration Error
<p>I'm having issues making flask work. I'm a noob and still learning about Linux. I'm getting this (very intimidating looking)error after running:</p> <p><code>flask run</code></p> <pre><code>root@DESKTOP-TV7O885:/mnt/c/Projects/app_1# flask run * Serving Flask app "application" * Running on http://127.0.0.1:5000/...
<p>On the call stack in the exception, you must go from bottom to top, until you find a file in your project. This is the starting point. In your case, it is:</p> <pre><code>File "/mnt/c/Projects/app_1/application.py", line 7, in index return render_template("index.html") </code></pre> <p>You say you have a templat...
python|flask
0
1,779
60,120,792
Performing list of Google Search using Python code
<p>I'm pretty new to programming, and I didn't start to learn python yet. In general I have a long list of codes which I need to search in google for example: <code>123</code>, <code>124</code>, <code>125</code>, <code>126</code> I find code which can do that in python <a href="https://www.geeksforgeeks.org/performing...
<p>I'd recommend just setting up a collection of strings you want to search for. Then iterate through the collection, search for that string, and store the results.</p> <pre><code>from googlesearch import search list_of_queries = ["Geeksforgeeks", "stackoverflow", "GitHub"] results = [] for query in list_of_queries...
python|google-chrome|search
0
1,780
67,144,638
Python - Function not returning y value
<p>I'm essentially making a counter and it counts the number of times a name appears in a list. I'm trying to use a function so I can easily do it for all the names. It works fine when I don't make the code a function but as soon as I do it no longer returns the value of y.</p> <pre><code># animal_types=['Elephant', 'R...
<p>The assignment inside a function does not modify the global variable. To modify a global variable from inside a function, use the global keyword as shown below.</p> <pre><code>def Counter(x,y) : for i in short_animal_list : if i == x : y = y + 1 print(i) print('found',i) print(y) ...
python-3.x|function
0
1,781
45,239,458
pip install numpy error - Unmatched "
<p>I am trying to install numpy in a python3 virtual environment</p> <pre><code>python3 -m venv venv source venv/bin/activate pip install numpy </code></pre> <p>After running the above, the installation fails with an error something like this...</p> <pre><code>error Command "gcc ..." failed with exit status 1 Unmat...
<p>When you install numpy using pip, it runs various shell commands to build the parts of numpy that are written in c. Your environment's <code>$SHELL</code> variable will be used to determine which shell to use. In this case, <code>csh</code> is being used but the command in the installation script expects to be able ...
python-3.x|numpy|virtualenv
0
1,782
61,482,940
Pulling API data into Django Template that has <a></a> tags embedded, is there a way of wrapping the text in an HTML tag?
<p>I'm reading a very large API, one of the fields I need, have "a" tags embedded in the item in the dictionary and when I pull it into my template and display it, it shows the "a" tags as text.</p> <p>exp:</p> <pre><code>"Bitcoin uses the &lt;a href="https://www.coingecko.com/en?hashing_algorithm=SHA-256"&gt;SHA-256...
<p>I figured it out, I used the Humanize function with the |safe tag.</p> <p>Pretty simple answer.</p> <p>In the settings.py add 'django.contrib.humanize' to the INSTALLED_APPS:</p> <p>**INSTALLED_APPS = [</p> <p>'django.contrib.humanize', ]**</p> <p>In the HTML Template add </p> <pre><code>{% load humanize %} </...
html|django|python-3.x
0
1,783
56,154,199
How can I simplify adding columns with certain values to my dataframe?
<p>I have a big dataframe (more than 900000 rows) and want to add some columns depending on the first column (Timestamp with date and time). My code works, but I guess it's far too complicated and slow. I'm a beginner so help would be appreciated! Thanks!</p> <pre><code>df['seconds_midnight'] = 0 df['weekday'] = 0 df[...
<p>If the column is a datetime64/Timestamp column you can use the <a href="https://pandas.pydata.org/pandas-docs/stable/getting_started/basics.html#dt-accessor" rel="nofollow noreferrer">.dt accessor</a>:</p> <pre><code>In [11]: df = pd.DataFrame(pd.date_range('2019-01-23', periods=3), columns=['date']) In [12]: df O...
python|pandas
0
1,784
69,373,811
JavaScript not 'unclicking' button and its affecting Flask
<p>I am trying to create buttons on my webpage that apply a filter to a camera feed using a Python backend.</p> <p>My two javascript buttons, Filter on / Filter off have an execution problem. When a button is pressed for the first time the system works. But when the next button is pressed it does not 'unpress' the firs...
<p>If they are radios, they need the same name</p> <p>Also you wrap in too many load directives</p> <pre class="lang-js prettyprint-override"><code>function filterOn(){ $.get('/video_feed/1'); // normally one needs to do something with that } function filterOff(){ $.get('/video_feed/0'); } $(function(){ $(&qu...
javascript|python-3.x|flask
1
1,785
55,191,193
Show the sum for multiple items
<p>I've a data dictionary, I want to pickup some items for exemple at the 2nd range, from different lists as value of dictionary every key start with 111####, I created this method but how, I can get the sum off all items and insert it at QTableWidget cell?</p> <pre><code>import sys from PyQt5.QtWidgets import (QWidge...
<p>Try it:</p> <pre><code>import sys from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem) from PyQt5.QtGui import QBrush, QColor from PyQt5 import QtCore # vvvvvv data = {'1111':['Title 1','12521', '94565','', ...
python-3.x|dictionary|pyqt5|qtablewidget|qtablewidgetitem
1
1,786
57,389,849
Copying python scripts from local to remote mahcine
<p>I have two computers, both windows 64-bit machines. Call the local computer machine A and the remote computer machine B. I have a <code>script.py</code> file on machine A. Without leaving machine A, I want to:</p> <ol> <li>Copy <code>script.py</code> onto machine B; </li> <li>Run <code>script.py</code> on machine B...
<p>From <a href="https://stackoverflow.com/questions/18344004/is-there-a-scp-alternative-for-powershell">Is there a SCP alternative for PowerShell?</a>: the little tool <code>pscp.py</code>, which comes with Putty can solve your task 1. </p> <p>For an example with PowerShell see <a href="https://stackoverflow.com/a/18...
python-3.x|powershell
0
1,787
42,255,409
Python count element occurrence of list1 in list2
<p>In the following code, I want to count the occurrence of every word in <code>word_list</code> in <code>test</code>, the code below can do this job but it may not be efficient, is there any better way to do it?</p> <pre><code>word_list = ["hello", "wonderful", "good", "flawless", "perfect"] test = ["abc", "hello", "...
<p>Use <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow noreferrer"><code>collections.Counter</code></a> to count all the words in <code>test</code> in one go, then just get that count from the <code>Counter</code> for each word in <code>word_list</code>.</p> <pre><code>&g...
python|list|counting
6
1,788
42,444,312
Tkinter copy to clipboard not working in PyCharm
<p>I just installed PyCharm and opened up a script I had been using in IDLE that did some string manipulation then copied it to the clipboard, but it doesn't work when I run it in PyCharm. </p> <pre><code>from tkinter import Tk r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append("test") r.destroy() </code></p...
<p>There seems to be problem if the clipboard is manipulated and the program closes too quickly soon after. The following program worked for me but was unreliable when the call to <code>root.after</code> only used one millisecond for the delay. Other possibilities were tried, but code down below should work:</p> <pre>...
python-3.x|tkinter|pycharm
2
1,789
41,488,676
Python Data Frame: cumulative sum of column until condition is reached and return the index
<p>I am new in Python and am currently facing an issue I can't solve. I really hope you can help me out. English is not my native languge so I am sorry if I am not able to express myself properly.</p> <p>Say I have a simple data frame with two columns:</p> <pre><code>index Num_Albums Num_authors 0 10 ...
<p><strong><em>Opt - 1:</em></strong></p> <p>You could compute the cumulative sum using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html" rel="noreferrer"><code>cumsum</code></a>. Then use <a href="https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.isclose.html" r...
python|pandas|dataframe|sum
7
1,790
41,260,773
How to set Environment Variable for NLTK in Mac?
<p>I recently downloaded nltk_data in Macintosh HD 2 (Renamed "External") since my main HD is out of memory, can someone help me in setting environment variables for the same? I tried the following in my .bash_profile however it just runs temporarily till bash runs, I need to make the change permanent:</p> <pre><code>...
<p>Setting environment variables on OS X is a bit tricky, and it's a moving target: Stackoverflow is full of good solutions that no longer work.</p> <p>If your goal is to use the nltk from programs or applications that you launch from Terminal, then it's pretty straightforward; in your <code>.bash_profile</code> or <c...
python|macos|nltk
2
1,791
41,564,782
What’s the best way to Convert a list to dict in Python2.7
<p>I have a list like: </p> <pre><code>x = ['user=inci', 'password=1234', 'age=12', 'number=33'] </code></pre> <p>I want to convert x to a dict like:</p> <pre><code>{'user': 'inci', 'password': 1234, 'age': 12, 'number': 33} </code></pre> <p>what's the quickest way?</p>
<p>You can do this with a simple one liner:</p> <pre><code>dict(item.split('=') for item in x) </code></pre> <p>List comprehensions (or generator expressions) are generally faster than using <code>map</code> with <code>lambda</code> and are normally considered more readable, see <a href="https://stackoverflow.com/que...
python|python-2.7|list|dictionary|type-conversion
4
1,792
25,767,411
Making my IDE take a specific Python version
<p>I have Python 2.7.8 installed and when doing the version check in my command line, it shows that I have Python 2.7.8. </p> <p>However, when I run PyCharm it's running it on version 2.6. Is there a way for me to get it to make PyCharm take the 2.7.8 version?</p> <p>Thanks for the help!</p>
<p>By default, PyCharm picks up the Python installed system-wide. </p> <p>Which Python your project should use is configured under <a href="http://www.jetbrains.com/pycharm/webhelp/project-interpreter.html" rel="nofollow">Project Interpreter</a> section of your Project Settings. From <a href="http://www.jetbrains.com/...
python|python-2.7|ide|pycharm
1
1,793
25,451,234
How to call from within Python an application with double quotes around an argument using subprocess?
<p>I'm trying to call <strong>certutil</strong> from inside <strong>python</strong>. However I need to use quotation marks and have been unable to do so. My code is as follows:</p> <pre><code>import subprocess output= subprocess.Popen(("certutil.exe", "-view", '-restrict "NotAfter &lt;= now+30:00, NotAfter &gt;= now+0...
<p>I do not have Python in any version installed. But according to answer on <a href="https://stackoverflow.com/a/16177142/3074564">How do I used 2 quotes in os.system? PYTHON</a> and documentation of <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow noreferrer">subprocess</a>, <strong>subproces...
python-3.x|certutil
0
1,794
44,745,750
failing scipy.minimize for multiple constraints
<p>I would like to minimize the following function using scipy.minimize</p> <pre><code>def lower_bound(x, mu, r, sigma): mu_h = mu_hat(x, mu, r) sigma_h = sigma_hat(x, sigma) gauss = np.polynomial.hermite.hermgauss(10) return (1 + mu_h + math.sqrt(2) * sigma_h * min(gauss[1])) </code></pre> <p>all the...
<p>The error message says:</p> <pre><code>mieq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['ineq']])) TypeError: &lt;lambda&gt;() argument after * must be an iterable, not float </code></pre> <p>So we can infer that <code>c['args']</code> is of type <code>float</code>, because <code>c['args']</c...
python|scipy
1
1,795
20,717,945
Tweepy: simple script with 'Bad Authentication data' error
<p>Is this really an authentication problem or has it to do with something else? What do I have to modify to get rid of the error?</p> <pre><code>#!/usr/bin/env python import tweepy ckey = 'xxx' csecret = 'xxx' atoken = 'xxx' asecret = 'xxx' auth = tweepy.OAuthHandler(ckey, csecret) auth.set_access_token(atoken, as...
<p>Your doing it wrong:</p> <p>It should be-</p> <pre><code>#!/usr/bin/env python import tweepy ckey = 'xxx' csecret = 'xxx' atoken = 'xxx' asecret = 'xxx' auth = tweepy.OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) api = tweepy.API(auth) # here's where you went wrong (tried and tested), shou...
python|twitter|tweepy
2
1,796
53,469,296
Iterating Through a List to create a Stock checker
<p>So to begin I am new to programming in general (3 months or so in) and although learning through books is good I do like to try and apply my knowledge and learn through experience. </p> <p>At my work our warehouse staff often pick orders wrong so I am trying to develop something that will pull an order list from a ...
<p>For each item in the list you want to scan a <em>picked</em> item and compare them; if the comparison fails you want to <em>continually</em> scan picked items until they match. </p> <p>You are really close - in the <code>else</code> suite the comparison with the new scanned item needs to be <em>in</em> the loop, ...
python|list|function
0
1,797
40,887,074
Character @ in a :: literal
<p>I am trying to include in my source .rst file literal producing text like:</p> <pre> :: @reboot myscript </pre> <p>However <code>@reboot</code> appears in boldface. Did not find how to avoid it.</p>
<p>Very easy -- just precede with the following line:</p> <p><code>.. highlight:: none</code></p> <p>Otherwise Sphinx assumes it is Python code (default)!</p>
python-sphinx
0
1,798
27,240,381
python SimpleHTTPServer suspended, how to stop?
<p>I accidentally hit ctrl z instead of ctrl c to stop python SimpleHTTPServer and it came up saying</p> <pre><code>[1] + 35296 suspended python -m SimpleHTTPServer </code></pre> <p>now I cannot restart it on the same port as port 8000 is in use</p> <pre><code>Traceback (most recent call last): File "/System/Libra...
<p>The process is suspended in the background, you'll have to kill it for it to release the port.</p> <p>If you're in the same terminal, running <code>fg</code> will bring it to the front and reactivate it, letting you interrupt it normally with <kbd>CTRL</kbd>+<kbd>C</kbd>.</p> <p>If you're not, you can use that num...
python|macos|networking|port
3
1,799
47,527,747
Pandas: Rolling mean over array of windows
<p>Similar to <a href="https://stackoverflow.com/a/42152692/2327328">this answer</a>, I can calculate multiple rolling means</p> <pre><code>d1 = df.set_index('DateTime').sort_index() ma_1h = d1.groupby('Event').rolling('H').mean() ma_2h = d1.groupby('Event').rolling('2H').mean() </code></pre> <p>But how can I do this...
<p>I believe you need convert offsets and create new <code>DataFrame</code>s in loop by list comprehension, last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>:</p> <pre><code>from pandas.tseries.frequencies import to_offset df1 = p...
python|pandas|time-series|moving-average
1