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
7,300
67,276,055
How to make a normalizated series from pandas dataframe?
<p>I have the following code:</p> <pre><code>df = pd.DataFrame({ 'FR': [4.0405, 4.0963, 4.3149, 4.500], 'GR': [1.7246, 1.7482, 1.8519, 4.100], 'IT': [804.74, 810.01, 860.13, 872.01]}, index=['1980-04-01', '1980-03-01', '1980-02-01', '1980-01-01']) df = df.iloc[::-1] df2 = df.pct_change() df2 = df2.il...
<p>Try with <code>cumprod</code>:</p> <pre><code>df.iloc[::-1].pct_change().add(1).fillna(1).cumprod() </code></pre> <p>Output:</p> <pre><code> FR GR IT 1980-01-01 1.000000 1.000000 1.000000 1980-02-01 0.958867 0.451683 0.986376 1980-03-01 0.910289 0.426390 0.928900 1980-04-01 0...
pandas|dataframe|normalization
1
7,301
63,632,755
Plot density histogram of Bernoulli sample and a Bernoulli pmf together
<p><strong>Summary of Question:</strong></p> <p>Why is my density from my sample so different to the pmf and how can I perform this simulation so that the pmf and the sample estimates are similar.</p> <p><strong>Question:</strong></p> <p>I have simulated a sample of independent Bernoulli trials using <code>scipy</code>...
<p>The reason is that <code>plt.hist</code> is primarily meant to work with continuous distributions. If you don't provide explicit bin boundaries, <code>plt.hist</code> just creates 10 equally spaced bins between the minimum and maximum value. Most of these bins will be empty. With only two possible data values, there...
python|matplotlib|scipy|statistics|bernoulli-probability
1
7,302
66,263,765
Changing pandas index to column headings
<p>I have a dataframe with my index as years, and one column of integer entries. I want to change my index into column headings. I have this structure for several small dataframes, which I will attach to a larger dataframe.</p> <pre><code> 1 0 2021 4365 2020 5812 2019 6773 2018 6681 2017 6809 2016...
<p>I have your <code>df</code>:</p> <pre><code>print(df) 1 0 2021 4365 2020 5812 2019 6773 2018 6681 2017 6809 2016 6776 2015 6587 2014 5978 </code></pre> <p>And used <code>T</code> to transpose, and <code>pandas.DataFrame.rename</code> the index.</p> <pre><code>res = df.T res.rename(index={1...
python|pandas|dataframe
2
7,303
72,703,489
Handling a TypeError: unhashable type: 'list' when switching from fetching a single item to fetching a list
<p>I am trying to fetch data from a JSON endpoint. It doesn't work anymore now that I have switched from fetching just one data value <code>coin['id']</code> to fetching multiple ones. I have this code:</p> <pre><code>class Checker: def __init__(self, urls, wait_time): self.wait_time = wait_time sel...
<p><code>get_data()</code> returns a <code>list</code>, and <code>coins.update(Checker.get_data(url))</code> tries to put that <code>list</code> in a <code>set</code>. But <code>set</code> items need to be <em>hashable</em>, and <code>list</code>s are not. If you return a <code>tuple</code> instead of a <code>list</cod...
python|json|list|error-handling|typeerror
1
7,304
68,052,773
How to retrieve the image output from tensorflowlite interpreter
<p>I have retrained pretrained neural network ssd_mobilenet_v2_320x320_coco17_tpu-8 with tfrecords of custom images.</p> <p>The colab notebook link is <a href="https://colab.research.google.com/drive/1zTGsWaeAM3yOdQ5kJ7Z47jNCs-GSo02Q?usp=sharing" rel="nofollow noreferrer">https://colab.research.google.com/drive/1zTGsWa...
<p>Instead of depending on tensor names, consider using signature concept.</p> <pre><code># Load the TFLite model in TFLite Interpreter interpreter = tf.lite.Interpreter(TFLITE_FILE_PATH) # Print signature information to find out the input/output names. signature_defs = interpreter.get_signature_list() print(signature...
tensorflow-lite
0
7,305
58,868,665
Is there any kind of package that includes a function to smooth out, or even out distribution in array by deleting samples?
<p>I have an array of values that range from 0 to 1 that relates to the output truth values for a neural network I'm building. However the distribution is very wide and uneven, so I was curious if there was a package for Python that could remove samples so that the distribution is more even across the array.</p> <p>He...
<p>If this can help anyone in the future, here's what I came up with:</p> <pre><code>def reject_outliers(x_t, y_t, m): mean = np.mean(y_t) std = np.std(y_t) x_t, y_t = zip(*[[x, y] for x, y in zip(x_t, y_t) if abs(y - mean) &lt; (m * std)]) return list(x_t), np.array(y_t) def even_out_distribution(x_...
python|data-science
0
7,306
59,882,104
How to set up a new user in a linux server to work with Python?
<p>I have added a new user in a linux server.</p> <p>While I can run simple python script, the new user get errors to import package that I can upload.</p> <p>For instance</p> <pre><code>import matplotlib as plt </code></pre> <p>returns</p> <pre><code>no module named 'matplotlib' </code></pre>
<p>That is because you probably did :</p> <pre><code>pip install --user matplotlib </code></pre> <p>to install matplotlib on your side.</p> <p>You have multiple solutions, here a non-exhaustive one (docker would be probably overkilled for that purpose imo) ordered from the worse to the best :</p> <ul> <li><p>Instal...
python|ubuntu
0
7,307
25,249,033
Week of a month pandas
<p>I'm trying to get week on a month, some months might have four weeks some might have five. For each date i would like to know to which week does it belongs to. I'm mostly interested in the last week of the month.</p> <pre><code>data = pd.DataFrame(pd.date_range(' 1/ 1/ 2000', periods = 100, freq ='D')) 0 2000-01...
<p>See this <a href="https://stackoverflow.com/questions/7029261/python-number-of-the-week-in-a-month">answer</a> and decide which week of month you want.</p> <p>There's nothing built-in, so you'll need to calculate it with apply. For example, for an easy 'how many 7 day periods have passed' measure.</p> <pre><code>...
python|pandas
18
7,308
70,998,935
Output list elements one per line
<p>This is my code so far:</p> <pre><code>a_string = 'abcd' final_list = [[]] length = len(a_string) groups =[list(a_string)] * 3 for i in groups: final_list = [x+[y] for x in final_list for y in i] permutations = [''.join(item) for item in final_list] print(permutations) </code></pre> <p>It does what i want it to ...
<p>You basically want to <code>print</code> each item in the <code>permutations</code> instead of printing <code>permutations</code> itself which is a list -</p> <pre><code>a_string = 'abcd' final_list = [[]] length = len(a_string) groups =[list(a_string)] * 3 for i in groups: final_list = [x+[y] for x in final_lis...
python
0
7,309
30,685,162
Is the following the correct way to obtain unique id in app engine datastore
<p>I have a legacy Google App engine code, which is having the following entity classes in Python</p> <pre><code>class AffiliateParent(db.Model): name = db.StringProperty(required = True) class Affiliate(db.Model): email = db.StringProperty(required = True) point_gain = db.IntegerProperty() point_used...
<p>yes, if you don't supply <code>id</code> or <code>key</code> when instantiating the model, then datastore will generate a unique ID and assign it to your entity when you <code>.put()</code> it... thus <code>affiliate.key.id()</code> will be unique</p> <p>you can also generate unique IDs using <code>allocate_ids(cou...
python|google-app-engine
1
7,310
50,889,514
Pandas Resampling based on Value exceeding threshold
<p>I have a database with 2 columns. </p> <pre><code>import pandas as pd data = pd.DataFrame({'a':[1,2,1,4,1,1,3,1,4,1,1,1],'b':[5,2,8,3,10,3,5,15,45,41,23,9]}) a b 0 1 5 1 2 2 2 1 8 3 4 3 4 1 10 5 1 3 6 3 5 7 1 15 8 4 45 9 1 41 10 1 23 11 1 9 </code></pre> <p>Is ...
<p>Until someone invented some <code>pandas</code> one-liner (if possible), you could try the following approach:</p> <p>From <em>IPython</em> session:</p> <pre><code>In [393]: get_a_cumsum_lim = lambda df, col, threshold: df[col][df[col].cumsum() &gt;= threshold] In [394]: s, result = get_a_cumsum_lim(data, 'a', 5)...
python|pandas|dataframe
1
7,311
50,512,797
Efficient and concise GroupBy nuisance column pass through
<p><strong>I'm wondering about efficient and concise ways of passing nuisance columns through to the result of a <code>pandas.DataFrame.groupby</code>.</strong> I often have columns which I do not want to apply the <code>groupby</code> operation to, but I do want the values to propagate through to the result. An exampl...
<p>I think you're overly complicating things. You can just <code>groupby</code> and <code>rank</code> to the <code>vals</code> columns. This returns a <code>pandas.Series</code> of the same length of your original <code>df</code> so you can just set the column to this.</p> <pre><code>df['vals'] = df.groupby(['date', '...
python|pandas|pandas-groupby
2
7,312
50,551,069
Python for loop iterating with same variable names throws error
<p>I am learning Python. I came across the following abnormal result, while using Python 3.6.0 REPL.</p> <pre><code>a = [1, 2, 3] for a in a : print(a) </code></pre> <p>output:</p> <pre><code>1 2 3 </code></pre> <p>Again.</p> <p>output:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", ...
<p>In Python when you do</p> <pre><code>for x in y: pass#your code here </code></pre> <p><code>x</code> is defined outside the for loop, and you can use it like a normal variable after the loop ended.</p> <p>If you do something like</p> <pre><code>for a in range(10): pass print(a) </code></pre> <p>it will print...
python-3.x|for-loop
2
7,313
57,881,548
Find all occurrences where value in one column is the same as another other than NULL values
<p>I have imported a CSV file including graduate data like grad_year, grad_major, grad_gender, gpa, etc...</p> <p>The objective is to find all instances in which the originally declared major of the graduate and the major of the graduate upon completion of the program are the same (original_major and grad_major, respe...
<p>You can use nansum instead of sum (<a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.nansum.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.nansum.html</a>)</p> <pre><code>import pandas as pd import numpy as np grads_df = pd.read_csv('User...
python|pandas
0
7,314
55,165,594
keras traindata shape is different from testdata shape but i use full conv network
<p>I'm using keras. When I train my network, I used 256*256*9 shape of the image, but I don't fix the height and weight. And my network is full conv network. But I test with a 512*512*9, I fail to test it because of shape. The function of keras seems cant be changed. I really don't know how to solve it, here is error l...
<p>That is very normal that it is not working. Your model's input shape should be 256*256*9 but you are pushing a 512*512*9 in predict. When you create your model in <code>model = unet(input_size = (h,w,d))</code> , you are setting the shape of the input being h,w,d. So any training examples in <em>fit</em> and validat...
python|machine-learning|keras|conv-neural-network
0
7,315
57,509,948
Downloading a FileField with a View
<p>I have a table which presents order information - attached to each order is a file. This file's file path displays as a link in the table already, but I am unable to download by clicking it. I would like to be able to click this link and have the proper .docx download.</p> <p>I am referencing: <a href="https://st...
<p>This is a bit complex stuff at first, but let me break it down for you.</p> <p>First of all, the files you upload thorough <em>Django</em> are stored somewhere in the <em>Filesystem</em> (in case of default settings). This usually means your uploaded files go to your <code>/media</code> folder which is in the same ...
python|django
-1
7,316
58,572,427
display a list of items in a select box in my html template in django 2.2
<p>I have a list of departments I want to be shown in a select drop-down but its not shown? </p> <p>It's a duty-log app and want the user to be able to select the department from the drop-down.</p> <p>Here's my views.py</p> <pre><code>def index(request): # the index view logs = Dutylog.objects.all() # querying...
<p>You are passing department as a key in your dictionary but you are iterating with departments in your template</p> <p>so change this </p> <pre><code>return render(request, "index.html", {"logs": logs, "department": departments </code></pre> <p>to</p> <pre><code>return render(request, "index.html", {"logs": logs,...
python|django|templates
1
7,317
41,515,278
How do I make an exit button in npyscreen?
<p>What I want is basically a regular npyscreen.Form, but I want the "OK" button to say "Exit".</p> <p>It appears that you can't change the name of the button in the regular npyscreen.Form, so I tried subclassing npyscreen.ButtonPress:</p> <pre><code>import npyscreen class ExitButton(npyscreen.ButtonPress): def ...
<p>Edwin's right, use <code>self.parent.parentApp</code> not <code>self.parentApp</code>. </p> <p>To exit the app use <code>switchForm(None)</code> instead of <code>setNextForm(None)</code>. </p> <pre><code>def whenPressed(self): self.parent.parentApp.switchForm(None) </code></pre> <p>reference: a <a href="h...
python|npyscreen
4
7,318
56,869,278
How to access all registered models when deploying a machine learning model in an Azure Container Instance?
<p>I have built a continuous integration/deployment pipeline in Azure DevOps to train and deploy a machine learning model into a production environment. It uses Azure Machine Learning Services in Python to set everything up i.e. train the model, register it in a machine learning workspace and deploy it as a webservice....
<p>My current approach is to navigate the directory structure provided by Azure in the Docker image create by the release pipeline.</p> <pre><code> root_dir = './azureml-models' for model_name in os.listdir(root_dir): for model_version in os.listdir(os.path.join(root_dir, model_name) ): mode...
python|azure-devops|azure-machine-learning-service
3
7,319
23,643,986
App engine -- when to use memcache vs search index (and search API)?
<p>I am interested in adding a spell checker to my app -- I'm planning on using difflib with a custom word list that's ~147kB large (13,025 words). </p> <p>When testing user queries against this list, would it make more sense to:</p> <ol> <li>load the dictionary into memcache (I guess from the datastore?) and keep it...
<p>Memcache is definitely faster.</p> <p>Another important consideration is cost. Memcache API calls are free, while Search API calls have their own <a href="https://developers.google.com/appengine/pricing" rel="nofollow">quota and pricing</a>.</p> <p>By the way, you may store your library as a static file, because i...
python|google-app-engine
1
7,320
46,204,841
call a specific module using the module name as an argument to the main program
<p>What I would like achieve is this. Have a series of small modules in there own module directory. Each module supplies the same function. Import all the modules in the main program. The have the main program called with a module name and have this return the value from the module.</p> <pre><code>import worker_module...
<p>You can look at imported modules using <code>sys.modules</code></p> <pre><code>import sys # parser code... module = args.module result = sys.modules[module].command() </code></pre> <p>This allows you to import all the modules needed at the beginning without dynamically importing them. When a module is imported i...
python|module|arguments
0
7,321
52,309,471
Handle specific exception from python package
<p>I would like to handle the following Exception from py_vollib/py_lets_be_rational in specific way.</p> <pre><code>py_lets_be_rational.exceptions.BelowIntrinsicException: The volatility is below the intrinsic value. </code></pre> <p>Tried this without success:</p> <pre><code>from py_vollib.black.implied_volatility...
<p>Looking at <a href="https://github.com/vollib/py_lets_be_rational/blob/master/py_lets_be_rational/exceptions.py#L43" rel="nofollow noreferrer">the implementation</a>, you're missing the period at the end of the sentence:</p> <pre><code>if str(e) != 'The volatility is below the intrinsic value.': </code></pre> <p>I...
python|exception|exception-handling|python-3.7
1
7,322
52,563,860
Scraping all links and link content with Scrapy
<p>I am trying to scrape every internal link from IMDB and then scrape the title from each links' page. However, when I run the code below, nothing is returned. </p> <pre><code>import scrapy from urllib.parse import urljoin from FirstSpider.items import MovieItem class ProductsSpider(scrapy.Spider): name = "movi...
<p>You should use <code>//body//a/@href</code> instead of <code>//body/a/@href</code> to get all links. I think you only want the links for movies (there are other links in the page), so change <code>//body//a/@href</code> to <code>'//body//td[@class=&quot;titleColumn&quot;]/a/@href'</code>.</p> <p>I made an IMDB <stro...
python|xpath|scrapy
1
7,323
32,719,652
Sum of values in list of dictionaries
<p>I want to get the sum values for each key in all dictionaries of a list, and if a key is not present in one of the dictionaries, then its value is considered 0. </p> <p>Suppose I have two dictionaries as such:</p> <pre><code>d1 = {'a' : 2, 'b' : 1, 'c' : 1} d2 = {'a' : 3, 'b' : 1.1, 'd' : 2} mylist = [d1, d2] </co...
<p>First get all keys and set up a new dictionary from your list of dictionaries:</p> <pre><code>d1 = {'a' : 2, 'b' : 1, 'c' : 1} d2 = {'a' : 3, 'b' : 1.1, 'd' : 2} mylist = [d1, d2] sum_dict = dict.fromkeys(set().union(*mylist), 0) </code></pre> <p>After that that is simple to just iterate over the list of dictionar...
list|python-2.7|dictionary|sum
2
7,324
46,964,246
I would like to plot specific elements from a list, that are indicated by another list
<p><code>x</code> and <code>y</code> are lists of 50 elements. <code>SV</code> is a list with 4 elements.</p> <p>I would like to plot only the elements of x,y that are in positions SV. For example if <code>SV=[3,7,10,15]</code> I would like to plot only <code>x[3],x[7],x[10],x[15]</code> and <code>y[3],y[7],y[10],y[15...
<p>Use this:</p> <pre><code>x, y = [x[i] for i in SV], [y[i] for i in SV] </code></pre>
python|numpy|matplotlib
1
7,325
70,466,242
Pandas if else condition on a timestamp type
<p>the date column is a timestamp. I am looking to write a if-else condition to manipulate sold to 0 if the date is less than '2021-01-15' and keep as is if the date is greater than or equal to '2021-01-15'. but I keep getting this error: TypeError: unsupported operand type(s) for &amp;: 'str' and 'Timestamp'</p> <pre>...
<p>Try this:</p> <pre><code>df.loc[df['date'] &lt; '2021-01-15', 'sold'] = 0 </code></pre>
python|dataframe|pandas
1
7,326
55,944,470
How can I output to display $00.00 to the second decimal. Code currently generate $00.0 or/and $00.000000000000000
<p>I can't get code to round to the second decimal</p> <p>Ive tried changing from str to int and even float? print(round(GrossPay,2))</p> <pre><code>#SHORT TERM CALCULATOR rate_of_pay = (input("what is the partners rate of pay? $")) #SALARY CALCULATIONS 100% 5 DAY WORK WEEK salary_weekly = float(rate_of_pay)*40 sa...
<pre><code>print("{:.2f}".format(number)) </code></pre>
python|python-3.x
1
7,327
49,905,818
I have pandas dataframe which i would like to be sliced after every 4 columns
<p>I have pandas dataframe which i would like to be sliced after every 4 columns and then vertically stacked on top of each other which includes the date as index.Is this possible by using np.vstack()? Thanks in advance!</p> <p><a href="https://i.stack.imgur.com/uOqll.png" rel="nofollow noreferrer">ORIGINAL DATAFRAME...
<p>Until you provide a <a href="https://stackoverflow.com/help/mcve">Minimal, Complete, and Verifiable example</a>, I will not test this answer but the following should work:</p> <p>given that we have the data stored in a <code>Pandas DataFrame</code> called <code>df</code>, we can use <code>pd.melt</code></p> <pre><...
python|pandas|dataframe
0
7,328
66,598,215
How to select row before and after NaN in pandas?
<p>I have a dataframe which looks like this :</p> <pre><code> Name Age Job 0 Alex 20 Student 1 Sara 21 Doctor 2 john 23 NaN 3 kevin 22 Teacher 4 Rosa 20 senior manager 5 johanes 25 Dentist 6 lina 23 Stud...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with rows before, after and match by condition:</p> <pre><code>m = df.Job.isna() df = pd.concat([df[m.shift(fill_value=False)], df[m.shift(-1, fill_value=False...
python|pandas|duplicates|nan|shift
1
7,329
66,729,796
How to get the for loop output of Python script to Email with Outlook
<p>How to get the for loop consolidated output in the email body?</p> <pre><code>import win32com.client as client j=range(1,9) for i in j: print(i) outlook=client.Dispatch(&quot;Outlook.Application&quot;) message=outlook.CreateItem(0) message.Display() message.To =&quot;xxxxx&quot; message.CC = &quot;xxxxx&quot; mess...
<p>Just move <code>mail sent</code> out of the for loop</p> <pre><code>import win32com.client as client num = &quot;&quot; j = range(1, 9) for i in j: print(i) num += str(i) + &quot;/n&quot; outlook = client.Dispatch(&quot;Outlook.Application&quot;) message = outlook.CreateItem(0) message.Display(...
python
2
7,330
66,528,468
python-telegram-bot error when in Channel
<p>I just finished creating my first bot and it works perfectly in groups and when I message it, however, when I add it to a Channel and give it all permissions it does not work. The echo message function gives an error of <code>caused error 'NoneType' object has no attribute 'text'</code>.</p> <pre><code>from telegram...
<p>For channel posts it's <code>update.channel_post</code> not <code>update.message.text</code>. Alternatively, update.effective_message can be used if you don't want to differentiate between channel posts, messages and edited messages/channel posts.</p> <pre><code>def echo(update, context): context.bot.send_messag...
python-3.x|python-telegram-bot
0
7,331
66,681,887
Module functions with default arguments and namespaces?
<p>I want to collect a few generally useful function into a module my_module. These functions must have default arguments that are variables in the workspace. When I move these functions out from the main code to the module, and then import them into the main code, then I get an error since these default arguments cann...
<p>my_module.py:</p> <pre><code>y = 1 def f(x, y = None): if y is None: y = globals()['y'] sum = x+y return sum </code></pre> <p>test.py</p> <pre><code>import my_module my_module.y = 2 f = my_module.f print(f(1)) </code></pre>
python|module|namespaces
2
7,332
10,565,282
pandas, python - how to select specific times in timeseries
<p>I worked now for quite some time using python and pandas for analysing a set of hourly data and find it quite nice (Coming from Matlab.)</p> <p>Now I am kind of stuck. I created my <code>DataFrame</code> like that:</p> <pre><code>SamplingRateMinutes=60 index = DateRange(initialTime,finalTime, offset=datetools.Minu...
<p>In upcoming pandas 0.8.0, you'll be able to write</p> <pre><code>hour = ts.index.hour selector = ((10 &lt;= hour) &amp; (hour &lt;= 13)) | ((20 &lt;= hour) &amp; (hour &lt;= 23)) data = ts[selector] </code></pre>
python|indexing|time-series|pandas
26
7,333
5,578,032
On Ubuntu, how to install pygtk for python 2.7 through apt-get?
<p>I'm using Ubuntu 10.10, which comes with Python 2.6. I would like to test a PyGTK app I'm writing with Python 2.7.</p> <p>After installing the <code>python2.7</code> package, if I try to run my app like this: <code>python2.7 &lt;my_app&gt;</code>, I get the error: <code>ImportError: No module named pygtk</code></p...
<p>The version that will work for you is <a href="http://packages.ubuntu.com/natty/python-apt" rel="nofollow">in 11.04</a> (depends on <strong><code>python2.7</code></strong>). The one <a href="http://packages.ubuntu.com/maverick-updates/python-apt" rel="nofollow">in 10.10</a> won't work since it depends on <strong><co...
ubuntu|pygtk|apt-get|python-2.7
2
7,334
62,638,041
My django didnt work(I'm studying in tutorial)
<p>I'm very new to django. So I'm studying using tutorial site. I think type perfectly same on site, but it's not work. so plz give me advice.</p> <p>mysite/urls.py</p> <pre><code>from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path(...
<pre><code>&lt;form action=&quot;{% url '***polls***:vote' question.id %}&quot; method=&quot;post&quot;&gt; </code></pre> <p>polls was a string and your urls.py in a <code>path('**&lt;int:question_id&gt;**/vote/', views.vote, name='vote')</code> <code>&lt;int:question_id&gt;</code> is a <code>int</code>. i think that's...
python|django|django-views|django-urls|django-reversion
0
7,335
61,806,383
How to add constrain to One2many field in Odoo?
<p>If have two entities "payment" and "bill". With each payment the user must be able to pay one or more "biils" That is done by adding a One2Many field (of type bill) in the payment model. How can I add a constrain to ensure that a payment should have at least one bill ? (ensure that the One2Many list is not empty). I...
<p><code>@constrains</code> will be triggered only if the declared fields in the decorated method are included in the <code>create</code> or <code>write</code> call. It implies that fields not present in a view will not trigger a call during record creation.<br> A override of <code>create</code> is necessary to make su...
python|odoo
1
7,336
61,610,394
Sorting a list of tuples made up of two numbers by consecutive numbers
<p>The list of tuples is the output from a capacitated vehicle-routing optimization and represents the arcs from one stop to another, where <code>0</code> represents the depot of the vehicle (start and end point of vehicle). As the vehicle must drive several laps it may return to the depot before all stops were made. T...
<p>You are trying to solve the problem of finding cycles in a directed graph. The problem itself is not a difficult one to solve, and Python has a very good package for solving such problems - <a href="https://pypi.org/project/networkx/" rel="nofollow noreferrer">networkx</a>. It would be a good idea to learn a bit abo...
python|list|sorting|tuples|vehicle-routing
0
7,337
61,696,950
How to sort the data wrt final output?
<p>I want to group my dataframe by two columns and then sort the aggregated results within the groups.</p> <p><code>In [167]:df</code></p> <pre><code>count job source 0 2 sales A 1 4 sales B 2 6 sales C 3 3 sales D 4 7 sales E 5 5 market A 6 3 market B 7 2 market C 8 4...
<p>IIUC, we can do a further <code>groupby</code> and use <code>nlargest(3)</code> to get the top n values.</p> <p>then we can create an ordered list to sort your top values to sort and create a categorical column.</p> <pre><code>s = df.groupby(['job','source']).agg({'count':sum}).groupby(level=0)['count']\ .nlargest...
python|pandas|dataframe|sorting|pandas-groupby
2
7,338
60,436,119
Randomize value of given key of Dictionary in Python
<p>So I am practicing python and I'm using a tutorial where you create a terminal based game using python. I'm trying to not follow it letter for letter so I can learn it better. In it I have 2 dictionaries, one for the 'Monster' and 'Player'</p> <pre><code> player = {'name': 'Kevin', 'attack': 10, 'heal': 16, 'health...
<p>You can use <strong>random</strong> to generate random numbers or choices.<br/></p> <pre><code>import random r_num = random.randint(a,b) </code></pre> <p><em>Return a random integer N such that a &lt;= N &lt;= b</em>.</p>
python|dictionary|random
1
7,339
60,706,977
filtering rows after a groupby and apply a function
<p>I'm using python and pandas to work on some data. My data looks like the following:</p> <pre><code>df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar'], 'B' : [1, 2, 3, 4, 5, 6], 'C' : [True, False, True, True, False, True]}) print(df) ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> with <code>mean</code>s of filtered rows, <code>==True</code> should be omitted:</p> <pre><code>df['D'] = df['A'].map(df.loc[df.C, 'B'].groupby(df["A"]).mean()) print(...
python|pandas|pandas-groupby
3
7,340
71,118,331
downloading yahoofinance data for date ranges
<p>I have a dataframe with 900 tickers in it, and I'm trying to download adjusted close prices -15 business days before said date through 30 business days after said date, for a total of ~9 weeks of data.</p> <pre><code> date symbol date_start date_end 0 2020-03-20 USAU 2020-02-28 2020-05-01 1 2020...
<p>You can use <code>iterrows</code>:</p> <pre><code>data_stocks = {} for _, row in data_shortened.iterrows(): placeholder = yf.download(row['symbol'], row['date_start'], row['date_end']) data_stocks[row['symbol']] = placeholder stocks = pd.concat(data_stocks) </code></pre> <p>Output:</p> <pre><code>&...
python-3.x|pandas|finance|yahoo-finance|yfinance
1
7,341
70,221,377
How to use groupby on a dataframe
<p>I have a dataframe (survey) in which i need to groupby 2 columns. One of the 2 columns is a ranking (5 options : Very Poor, Poor, Average, Good and Excellent) and the second one is a list of times. I need to groupby both of those columns like that :</p> <pre><code>raking | Time | Count of how many times the ...
<p>Setup a <a href="https://stackoverflow.com/help/minimal-reproducible-example">MRE</a>:</p> <pre><code>rank = ['Very Poor', 'Poor', 'Average', 'Good', 'Excellent'] df = pd.DataFrame({'Ranking': np.random.choice(rank, 100), 'Time': np.random.randint(1, 50, 100)}) print(df) # Output: Ranking ...
python|pandas|dataframe|graph
0
7,342
63,445,826
How to run multile device under same paho-mqtt script
<p>I am writing a script which will log more than one device with different credentials using paho-mqtt. All the client is running in the same address and with the same port. If I change the username and pass then I get the different feeds depending upon the credentials. It's working fine if I write for different devic...
<p>Your problem lies here:</p> <pre><code>while run: client.loop_forever() </code></pre> <p><code>loop_forever()</code> is a blocking call which will only return when the associated client is disconnected:</p> <blockquote> <p>This is a blocking form of the network loop and will not return until the client calls dis...
python|mqtt|paho
2
7,343
55,721,022
Compare two file then replace the value
<p>File1.csv</p> <pre><code>column1,column2,column3 hello,halo,20A hello2,halo2,50A hello3,halo3,50A </code></pre> <p>File2.csv</p> <pre><code>book1,book2 20A,10 50A,20 </code></pre> <p>Output.csv</p> <pre><code>column1, column2, column3 hello,halo,10 hello2,halo2,20 hello23,halo3,20 </code></pre> <p>I'm comparin...
<p>Since you are new to python I would also suggest learning how to use pandas which makes dealing with csv files very easy and intuitive. This answer is just a suggestion for an alternative method. You can achieve your desired results in pandas as well as follows:</p> <pre class="lang-py prettyprint-override"><code>i...
python|python-3.x|csv
1
7,344
56,664,240
Trouble with KNN on OpenCV, new_samples.type() == CV_32F when training
<p>I am trying to set a simple KNN problem implementation with a three class dataset but whenever I try to execute the train function I keep the said <code>(-215:Assertion failed) new_samples.type() == CV_32F in function 'cv::ml::Impl::train error.</code> </p> <p>I have tried reshaping the responses array into many di...
<p>As indicated in the assertion, the data type for samples must be <code>CV_32F</code>, which stands for 32 bit float. </p> <pre><code>points_np = np.asarray(points).astype(np.float32) responses_np = np.asarray(responses).reshape((30,1)).astype(np.float32) </code></pre>
numpy|opencv|python-3.7
0
7,345
56,636,584
(Rock, paper and Scissors)How to ask player play again function by Python
<p>Here is my code. I already finish the win function call gameplay(Rock beats scissors. Scissors beats paper. Paper beats rock) and asking the player to play again function call replay. However, I didn't know how to complete the replay function into the main class.</p> <pre><code> def gameplay(userinput1,userinput...
<p>Your questions is a little unclear but from what I understood, you should make a loop that calls gameplay and replay. (like @Daniel said) Kind of like this:</p> <pre class="lang-py prettyprint-override"><code>while True: userinput1 = input('Your are player1, Enter Rock, Scissors or Paper :') userinput2 = input(...
python
1
7,346
69,807,950
How to deal with nested serializer fields in Django Rest Framework?
<p>I have nested serializer (AmountSerializer). I need a field meal_name in one ViewSet. But when this field is nested, I don't need it to be seen in endpoint(in MealSerializer). How to exclude field from nested serializer when is it actually nested? models.py:</p> <pre><code>class MealType(models.Model): name = mo...
<p>I'd rather use a trick to exclude some of the fields that are not needed in certain situations. You can inherit your serializer from <code>ExcludeFieldsModelSerializer</code>, and exclude any fields that you want so that the serializer will not serialize that field.</p> <pre><code>class ExcludeFieldsModelSerializer(...
python|django|rest|serialization|django-rest-framework
0
7,347
17,709,813
compiling .py into windows AND mac executables on Ubuntu
<p>I have been trying for hours to figure out how to do this going through pyinstaller's docs, but I haven't had any luck.</p> <p>I have a single .py file, and I need that made into a .exe file executable in windows 7, and a .app (or what ever works) executable in OS X Lion. The problem is that when ever I use</p> <p...
<p>Pyinstaller doesn't build executables for cross-platform targets, only for the platform on which Pyinstaller is run "natively". However, WINE allows running the native Windows Pyinstaller under Linux, so it can be used to build Python scripts developed on Linux into native Windows .exe executables using only the sin...
python|pyinstaller
5
7,348
17,951,820
Convert hh:mm:ss to minutes using python pandas
<p>I have a dataframe column, <code>data['time taken']</code> ;</p> <pre><code>02:08:00 02:05:00 02:55:00 03:42:00 01:12:00 01:46:00 03:22:00 03:36:00 </code></pre> <p>How do I get the output in the form of minutes like below?</p> <pre><code>128 125 175 222 72 106 202 216 </code></pre>
<p>Assuming this is a string column you can use the <a href="http://pandas.pydata.org/pandas-docs/dev/basics.html#vectorized-string-methods" rel="noreferrer"><code>str.split</code></a> method:</p> <pre><code>In [11]: df['time taken'].str.split(':') Out[11]: 0 [02, 08, 00] 1 [02, 05, 00] 2 [02, 55, 00] 3 [0...
python|pandas
16
7,349
66,140,788
Reading one column of data and creating a log graph from a csv
<p>I have data from a spectrometer from Ocean Optics and am trying to extract the right hand column of data to create a log intensity time graph. I'm currently having issues extracting the intensity data from the csv. This is what the data looks like:</p> <p><img src="https://i.stack.imgur.com/w2di7.png" alt="1" /></p>...
<p>you are trying to use <code>csv.reader</code> on a file that is not a csv. instead try something like this:</p> <pre><code>with open('TEST000.csv') as csv_file: for row in list(csv_file)[18:3665]: print(row) </code></pre> <p>This will give you each row and you can split the values of each entry in the li...
python|csv|logging
0
7,350
66,069,902
In Django how to convert an uploaded pdf file to an image file and save to the corresponding column in database?
<p>I am creating an HTML template to show the cover of a pdf file(first page or user can choose one). I want Django to create the cover image automatically without extra upload.</p> <p>The pdf file is uploaded using Django Modelform. Here is the structure of my code</p> <p>models.py</p> <pre><code>class Pdffile(models....
<p>In the <code>pdf2image</code> package there is a function called <code>convert_from_path</code>.</p> <p>This is the description inside the package of what each of the parameters of the function does.</p> <pre class="lang-none prettyprint-override"><code>Parameters: pdf_path -&gt; Path to the PDF that you...
python|django
2
7,351
69,080,045
Replace underscore from all html href with regex and python
<p>So I'm currently using python.</p> <p>How can I go through a HTML file and replace all occurrences of:</p> <p><code>&lt;a href=&quot;#some_snake_case_text&quot;&gt;</code></p> <p>and transform it into:</p> <p><code>&lt;a href=&quot;#somesnakecasetext&quot;&gt;</code></p> <p>independent of the text there is inside th...
<p>You can use <code>re.sub</code>:</p> <pre><code>import re s = '&lt;a href=&quot;#some_snake_case_text&quot;&gt;' new_s = re.sub('(?&lt;=href\=&quot;)[^&quot;]+', lambda x:''.join(x.group().split('_')), s) </code></pre> <p>Output:</p> <pre><code>'&lt;a href=&quot;#somesnakecasetext&quot;&gt;' </code></pre>
python|regex
0
7,352
69,075,272
Extract nodes coordinates according to local Csys_Abaqus Python scripting
<p><a href="https://i.stack.imgur.com/iTZep.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iTZep.png" alt="enter image description here" /></a></p> <p>I wrote a script that will extract nodes coordinates according to a local System. Because coordinates are generated by default according to the globa...
<p>From <a href="http://194.167.201.93/English/SIMACAECMDRefMap/simacmd-c-odbintrotranscpp.htm" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>If the system is model based, you must supply a displacement field that determines the instantaneous location and orientation of the coordinate system</p> </bl...
python|scripting|abaqus
1
7,353
59,418,638
Scaling multiple features with StandardScaler, before or after concatenation?
<p>I have an image data set (with pixel values from 0 to 255), from which I want to extract different features, e.g. HOG features, Gabor filter feature, LBP and color histogram. I would like to concatenate these features into a single feature vector </p> <pre><code>feature_overall = np.concatenate((feat1, feat2, feat3...
<p>The <code>StandardScaler</code> scales each column to have mean 0 and standard deviation 1. In that sense, it does not matter if you scale the features before or after concatenation.</p> <p>However, if you were using <code>sklern.preprocessing.Normalizer()</code> then it would matter. <code>Normalizer()</code> make...
python-3.x|svm|scale|feature-extraction|scikit-image
2
7,354
59,116,690
Combine list of dictionaries with a common key without merging values
<p>I have multiple list of dictionaries as follow:</p> <pre><code>data_aus = [{'name': '2018,7', 'aus_ct': 13}, {'name': '2018,8', 'aus_ct': 3}, {'name': '2018,9', 'aus_ct': 3}] data_asia = [{'name': '2018,7', 'asia_ct': 10}, {'name': '2018,8', 'asia_ct': 11}, {'name': '2018,9', 'asia_ct': 6}] data_us = [{'name': '...
<p>Attempt #2.</p> <p>Figured this should work:</p> <pre><code>import itertools from collections import defaultdict def merge_dicts(shared_key, *dicts): # Remove empty dicts (if any) dicts = list(filter(None, dicts)) # Merging dicts based on shared keys result = defaultdict(dict) for dictionary ...
python-3.x
0
7,355
59,401,943
Threading ping in mininet
<p>I want to launch two or many hosts simultaneously for pinging two others hosts with python in mininet, i do that and doesn't work </p> <pre><code>def simpleTest(h1,h2): print (h1.cmd('ping -c5 %s' h2.IP())) </code></pre> <p>and main :</p> <pre><code>if __name__ == '__main__': net = Mininet(...) thre...
<p>It worked by adding args in this line ...</p> <pre><code> thread = threading.Thread(target=simpleTest, args=(hostsrc,hostdest,)) </code></pre>
python|multithreading|ping|sdn|mininet
1
7,356
62,071,765
No executable found for solver 'glpk' on pyomo
<p>I have an optimization model written on pyomo (Python 3.7/Ubuntu 18.04) and using</p> <pre><code>from pyomo.opt import SolverFactory opt = SolverFactory("gurobi") results = opt.solve(model) </code></pre> <p>It works exactly as it should. However, when I try to use glpk as the solver, I get the following error:</p>...
<p>On terminal, trying running <code>which glpsol</code>.</p> <p>This ought to return a path to your glpsol executable. I am guessing you won't get a result. If that's the case you need to add the location of 'glpsol' to your PATH variable. You should be able to find it by seaching for where the 'glpk' package was ins...
python|pyomo
0
7,357
62,281,326
Flask Dynamic User Input Without Redirecting or Reloading
<p>I want to set user input as a variable on the same page without reloading. Is this possible?</p> <p>I made this simple example to explain my problem. The page dynamically counts up every second. The user should type in a new multiplier so for example if he types in 3 the page should add 3 every second etc. This sho...
<p>POST the multiplier to the Webserver, by using POST instead of GET</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;jQuery Example&lt;/title&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt; &lt;/scr...
javascript|python|html|flask|server
1
7,358
35,372,415
How do I select from a subquery using the Django ORM?
<p>I have a table that is meant to be insert only. It has columns for <code>id</code>, <code>object_id</code>, and <code>user_id</code>. When you update a record, instead of updating the row, you create a new record with a matching <code>object_id</code>.</p> <p>I'm trying to pull all records that match a given <code...
<p>If I got you right the table structure is:</p> <pre><code>---------------------------- | Table | ---------------------------- | id | user_id | object_id | ---------------------------- | 1 | 100 | 10 | ---------------------------- | 2 | 100 | 20 | --------------------------...
python|mysql|django|django-models
1
7,359
31,308,631
search a word in a file using python
<p>In shell, cat filename | grep -i error would return content from the file having the string 'error' .</p> <p>What is the Python equivalent of this ?</p>
<p>Open the file, iterate over all the lines and print the lines only if it contains <code>error</code>.</p> <pre><code>with open(file) as f: for line in f: if 'error' in line: print(line) </code></pre> <p>for case-insensitive match,</p> <pre><code>with open(file) as f: for line in f: ...
python|search
2
7,360
15,645,345
Read Specific line and ignore others using python
<p>I have a text file like this:</p> <pre><code>input file yuorvsdsd dfdsfsd ?dsfsdfsd sdfsdfs ?dfd ds </code></pre> <p>I am trying to make it so that it only reads the lines start with <code>?</code>. The <code>readlines</code> function reads all lines, so I put a condition on it, but I am not satisfied with it, as ...
<p>I would use something like the following:</p> <pre><code>with open("file.txt") as fp: for line in fp: if line.startswith('?'): print line </code></pre> <p>By using a context manager (<code>with ... as</code>) the closing of the file will happen automatically after you are done with it.</p>
python|python-2.7
4
7,361
49,174,658
Index error while using Sieve of Eratosthenes in Python
<p>When trying to find prime numbers using Sieve of Eratosthenes algorithm, following code is used. It gives index error when executed.</p> <p>I cannot find why the index is out of range. I am using Python 2.7</p> <pre><code>""" This program will find all the prime numbers up to the entered number using Sieve of Erat...
<p>You're deleting elements from the list, which is making the list shorter (hence, elements that were initially fine to check will be out of range. That is, once you delete 4, you'll find an error when you look for the 5th element. A way to verify this is to throw an </p> <pre><code>import pdb; pdb.set_trace() </code...
python|algorithm|python-2.7|primes|sieve-of-eratosthenes
1
7,362
48,985,466
pandas calculate row values as function of previous values in same and previous row
<p>If I have a table like this</p> <pre><code> A B C D E row1 1 2 3 4 5 row2 5 6 7 8 9 </code></pre> <p>I would like to calculte row3 as row1 shifted(1, axis=1) + row2 - value in row3 shifted(1, axis=1) [this is the previous calculated price, the cell at the left] It would be the same than apply...
<p>As Arpit mentioned in the comments you can use a <code>for</code> loop and <code>iloc</code> to achieve what you need:</p> <pre><code>df = pd.read_csv(pd.compat.StringIO('''A B C D E 1 2 3 4 5 5 6 7 8 9'''),sep='\s+') df.loc[2,'A'] = 5 for i in range(1,len(df.columns)): df.iloc[2,i] = df.iloc[0,i-...
python|pandas
1
7,363
25,118,553
Python Error in syntax with MySQL
<p>This is my script</p> <pre><code> cur.execute("CREATE TABLE +dnes+ (Id INT PRIMARY KEY AUTO_INCREMENT, \ Name VARCHAR(25))") </code></pre> <p>I'm trying put the variable dnes into the this query. The variable is string. It's not working. It says:</p> <pre><code>_mysql_exceptions.ProgrammingError:...
<p>You are not using string concatenation; the <code>+</code> is part of the string, not Python syntax.</p> <p>You probably meant to do this:</p> <pre><code>cur.execute("CREATE TABLE " + dnes + " (Id INT PRIMARY KEY AUTO_INCREMENT, " "Name VARCHAR(25))") </code></pre> <p>You could use string formatting i...
python|mysql
0
7,364
70,885,698
Redis and channels with Windows
<p>I'm trying to get a var to my consumers.py to send data to the client in real time as a function does API calls and returns that to the browser.</p> <p>I know channels needs Redis to function, but why? Why can we not just pass a list as it's built to the consumers class or any variable for that matter? From another ...
<p>I ended up using server side events (SSE), specifically <a href="https://github.com/fanout/django-eventstream" rel="nofollow noreferrer">django-eventstream</a>, and so far it's worked great as I didn't need the client to interact with the server, for a chat application this would not work.</p> <p>Eventstream creates...
python|django|django-channels
-1
7,365
70,814,847
Backup files/folders on flash drive to Google Drive in Python
<p>I am new to Python. I want to write a script that will backup all the files on a flash drive and upload them to Google Drive, retaining the file structure I have on the flash drive. How would I go about this in Python? I was looking at using something like <code>pydrive</code> to connect to Google Drive, but am unsu...
<p><a href="https://rclone.org/drive/" rel="nofollow noreferrer">Use rclone</a>. One would normally do what you want directly from the command line, but there is <a href="https://pypi.org/project/python-rclone/" rel="nofollow noreferrer">a Python wrapper</a>.</p>
python|google-drive-api
1
7,366
6,299,943
How do I animate the ticks on the x-axis?
<p>I have a <code>matplotlib</code> <code>axes</code> instance inside which I'm animating an <code>AxesImage</code> via <code>blit</code>ting.</p> <p>What I'd like to do is animate the ticks on the x-axis as well. I am updating the data on the AxesImage (and subsequently) drawing its artist quite frequently, and on ea...
<p>The axes bbox doesn't include anything outside of the "inside" of the axes (e.g. it doesn't include the tick labels, title, etc.)</p> <p>One quick way around this is to just grab the entire region of the figure when you're blitting. (E.g. <code>background = canvas.copy_from_bbox(fig.bbox)</code>)</p> <p>This can c...
python|matplotlib
4
7,367
5,655,314
Problem Importing Pylab in Python 2.6
<p>I'm using Python 2.6 in Ubuntu 10.10. I've run <code>help("modules")</code> in the Python interpreter and pylab and matplotlib are installed.</p> <p>However, when I run <code>import pylab</code>, I get the following error message.</p> <pre><code>&gt;&gt;&gt; import pylab Traceback (most recent call last): File "...
<p><a href="http://old.nabble.com/scipy,-matplotlib-import-errors-td16343711.html" rel="nofollow">http://old.nabble.com/scipy,-matplotlib-import-errors-td16343711.html</a></p> <p>You have a new.py somewhere?</p>
python|ubuntu|matplotlib
4
7,368
30,625,986
Python: Tkinter root window not reappearing
<p>I am currently experiencing some trouble getting the root window for tkinter to hide when a <code>Toplevel</code> window appears and then become visible when it is closed. The toplevel window is suppose to be a configuration window and upon completing, it will configure the root window. </p> <p>In my main tkinter ...
<p>Generally speaking, you should never have code after <code>mainloop</code>. That is because <code>mainloop</code> won't return until the root window is destroyed. Since it is destroyed, any windows created as children of the root window will also be destroyed. At that point there's really nothing left for your GUI t...
python|tkinter
2
7,369
66,787,279
tcmalloc: large alloc python in Google Colab
<p>I was trying to apply a deep learning algorithm(CNN) in python but after separating training-testing data and transforming time series to image step my <strong>Colab Notebook</strong> crashed and restarted itself again.</p> <p>It gives an error like <strong>&quot;Your session crashed after using all RAM&quot;</stron...
<p>Your session ran out of all available RAM. You can purchase <code>Colab Pro</code> to get extra RAM or you can use a Higher RAM machine and use the Neural Network there</p>
python|tensorflow|memory-management|google-colaboratory|tcmalloc
3
7,370
72,191,828
Integrity error (FOREIGN KEY constraint field) raised when I try to save request.POST from a model form
<p>I am working on a commerce app, (with django but very new to it) where a user can create a listing through a <code>ModelForm</code> called <code>ListingForm</code> that inherits from a Model called <code>Listing</code>.Here is the code for the the Listing model and ListingForm:</p> <pre><code> from django.contrib.au...
<p>First, in your models.py, you can change the <strong>date_made</strong> from DateField to a DateTimeField so you can save the time that your listing have been created on without need to import the <em>datetime</em> library and to override iton your views when the form is submitted by adding an attribute which is the...
python|django
0
7,371
65,496,294
"Pymongo" query for the field when array length greater than 0
<p>For a collection nameed 'duplicate', we can execute <code>db.duplicate.find( { $where: &quot;this.all_dups.length &gt; 0&quot; } );</code> but what would be the <code>Python</code> version of this query? I tried using</p> <pre><code>db.duplicate.find( { &quot;$where&quot;: {&quot;$gt&quot;:{&quot;all_dups.length&quo...
<p>You could try a search that excludes an empty list or a blank list:</p> <pre><code>db.duplicate.find({&quot;all_dups&quot;: {'$nin': [[], None]}}) </code></pre>
python|mongodb|mongodb-query|pymongo
1
7,372
65,712,365
Building two packages with different requirements from same source code using conda-build
<p>I am working on a project that uses Tensorflow. The requirement is to package my code as conda package using <code>conda-build</code>.</p> <p>Tesnorflow is yet to have one package on conda that supports both cpu and gpu see this <a href="https://stackoverflow.com/questions/64997291/why-anaconda-has-separate-packages...
<p>Assuming your recipe will be <em>almost</em> identical in the CPU and GPU cases, the intended solution for this use-case is to create a recipe with <a href="https://docs.conda.io/projects/conda-build/en/latest/resources/variants.html" rel="nofollow noreferrer">build variants</a>.</p> <p>For your use-case, you probab...
python|tensorflow|anaconda|conda|conda-build
2
7,373
65,569,420
Tensorflow's while loop slower than conventional while loop
<p>Here is a conventional while loop doing a basic add operation -</p> <pre><code>import time def check(a,b): while(a&lt;b): a += 1 return [a,b] a = 1 b = 1500000 start = time.time() check(a,b) print(&quot;Time = &quot;,time.time() - start) Time = 0.07060480117797852 </code></pre> <p>Here is the optimized code...
<p>You can't expect that tf.while_loop would be faster than a simple python loop such as</p> <pre><code>for( int i=0; i&lt;1500000; i++) j=j+1; </code></pre> <p>Will always perform better in python, javaScript, c, etc.</p> <p>tensorflow is highly optimized for matrices operation, not for a simple loop.</p> <p>I know...
python|python-3.x|tensorflow|time
1
7,374
50,765,131
How to efficiently convert a list into probability distribution?
<p>I am trying to convert a list into probability distribution.</p> <pre><code>x = [2, 4] </code></pre> <p>I want it the following array in that order.</p> <pre><code>probability_array = [1-(2+4)/10, 2/10, 4/10] </code></pre> <p>So I did the following...</p> <pre><code>y = 1 - (2 + 4)/10 new_x = [2/10, 4/10] proba...
<p>I think you can do this easily with numpy. Here is an example of <strong>correctness</strong></p> <pre><code>x=[[1, 2], [3,4]] x=np.array(x) sum1 = np.sum(x, axis=1).reshape(2,1) prob = x/sum1 </code></pre> <p>I think it would be pretty fast even if size of x&gt;10000. Let's take <strong>100 features</strong> for <s...
python|arrays|performance
1
7,375
4,005,521
Fast python tutorial for Django beginners?
<p>Is there a FAST python tutorial for Django beginners?</p>
<p><a href="https://developers.google.com/edu/python/" rel="nofollow">Google Python Class</a>. It's a 2-day class providing written matrial, lecture videos and exercises.</p>
python|django
4
7,376
50,563,646
Remove first occurence of a word in a 2d list?
<p>I have a list like this</p> <pre><code>[['a', 'word'], ['University', 'org'], ['of', 'org'], ['Michigan', 'org'], ['Michigan', 'country']] </code></pre> <p>What I wanna do is If I find the word michigan at first iteration I will return the label and I will replace that word with something like "deleted" and when ...
<p>Use a generator expression to find the position of first <code>"Michigan"</code>. Replace it with required word:</p> <pre><code>lst = [['a', 'word'], ['University', 'org'], ['of', 'org'], ['Michigan', 'org'], ['Michigan', 'country']] try: pos = next((i, x.index('Michigan')) for i, x in enumerate(lst) if 'Michi...
python|python-3.x|list
3
7,377
26,712,961
Use of rstdocument widget make kivy crash on android
<p>Recently I tried kivy, and I am trying to compile the demo in kivy source code to my android phone. But some demo didn't work. After some experiment I found the widget RstDocument make it crash. The code is:</p> <p>main.py:</p> <pre><code>from kivy.app import App from kivy.uix.floatlayout import FloatLayout from k...
<p>Haha I'm answering the question from myself :-) I hope my answer is right and it's useful for others</p> <p>The ddms output is filtered by "kivycatalog". Today I restudied it and looked at the full ddms output, and found error: no module named pygment. I don't know why it's filtered out. (I'm not familiar with andr...
android|python|kivy
1
7,378
45,120,506
Could'nt import Django
<p>I started my django project without activating my virtualenv django-admin startproject my_project and django-admin startapp my_app. Everythiing went fine, till i closed my terminal, and stopped the serveer. I wanted to restart my server, but this message is still coming up. i tried to install the virtualenv still th...
<p>You should run <code>pip install django</code> at terminal after active the virtualenv.</p>
python|django|pip|virtualenv
0
7,379
61,545,217
next(iter()) is throwing error while creating dataset using tensorflow in python
<p>I am trying run the below lines of code to create dataset using tensorflow in python. I am using a tensorflow version '2.2.0-rc3'.</p> <pre><code>data = [[[2107, 1037, 3376, 2154, 1012, 1012, 1012, 10166], 1], [[3819, 2305, 2000, 2022, 2012, 1996, 3608, 2380], 1]] all_dataset = tf.data.Dataset.from_generato...
<p>You said your goal is to create dataset using tensorflow in python, then instead of using <code>from_generator</code> why not use <code>from_tensor_slices</code>, check if this works for you</p> <pre><code>data = [[[2107, 1037, 3376, 2154, 1012, 1012, 1012, 10166], 1], [[3819, 2305, 2000, 2022, 2012, 1996, 3...
python|tensorflow2.0
0
7,380
61,329,734
Containerizing a Flask microservice in Kubernetes
<p>I've been working on a <code>Kubernetes</code> cluster with microservices written in <code>Flask</code> for some time now and I'm not sure if my current method for containerizing them is correct. </p> <p>I've been using <a href="https://github.com/tiangolo/uwsgi-nginx-flask-docker" rel="nofollow noreferrer">this</a...
<p>I got your point you are thinking you docker image creation method may be wrong. </p> <p>The main idea while building docker image. The image should have only your dependencies. As you told to find an answer is hard because we don't know your requirement maybe your dockerfile is only way. </p> <p>I recommend you t...
python|docker|flask|kubernetes|microservices
1
7,381
61,492,453
How to change this program to use random.shuffle instead of random.sample?
<p>I was wondering if there was anyone who was willing to help me out, when it came to this program. Backstory is to create a card game that when you draw 6 random cards, if one card is an ace, the player wins a dollar if not they lose a dollar. This goes on till the player either doubles their money or loses it all. T...
<p>The sanest ;-) change would be to replace</p> <pre><code> table = random.sample(shuffledDeck(),6) </code></pre> <p>with</p> <pre><code> table = random.sample(d, 6) </code></pre> <p>There's no need to keep rebuilding the deck. If you're determined to use the more expensive <code>.shuffle()</code> instead, ...
python|python-3.x|function|random|shuffle
0
7,382
60,509,344
Keras validation accuracy is increasing
<p><em>Updated : increased rotate range to 180, added GaussianNoise. see codes</em></p> <p>I am using CNN for image classification. I have 2 class 3500 gray scaled photo of each in training dataset and 1000 of each in validation data set. The problem is first 5-10 epochs train acc and valid acc is increasing but then ...
<p>I would suggest starting with an image augmentation process. Add blur, rotate, noise, clipping, etc to your images such that the model isn't seeing the same set of images over and over. As counter intuitive as it may feel, you need to make it harder on your model by adding variety. This will allow it to generaliz...
python|tensorflow|machine-learning|keras|deep-learning
0
7,383
57,966,928
Unable to get the pagination crawler to work Python3
<p>I m trying to use the scrapy module in python to scrape the details, but I am currently stuck on trying to get the pagination crawler to work. I'm getting the output partially right, but as I said previously, it is not scraping from the following pages on the <a href="https://www.sunwaymedical.com/find-a-doctor/sear...
<p>You are not creating the structure of pagination properly. It is not advised to implement pagination and the yielding of items in a single method. Take a look at the sample code below:</p> <pre><code>class AnswersMicrosoft(CrawlSpider): name = 'answersmicrosoft' allowed_domains = ['answers.microsoft.com'] start_url...
python-3.x|scrapy
0
7,384
58,148,888
I need to pick the cube values between 1 and 100
<pre><code>cubos = [valor**3 for valor in range(1,101)]#creates a list the cubes from 1 to 100 for cubo in cubos:#loop and create the internal values if cubo &gt;= 100:#pick the values bigger then 100 del cubo #delete them print (cubos)#print the values lower then 100 </code></pre> <p>why is not working I ...
<p>Generate <em>all</em> the cubes, then pick the ones that are less than 100.</p> <pre><code>from itertools import takewhile, count cubes1to100 = list(takewhile(lambda x: x &lt;= 100, map(lambda x: x**3, count()))) </code></pre> <p>Breaking it down:</p> <ol> <li><code>count()</code> produces the infinite stream of...
python|math
1
7,385
57,932,089
Is there a way to schedule Jupyter Notebook to run automatically every 2 minutes?
<p>I am working on a project where I need to push a data into an api using Jupyter notebook every 2 minutes. Is there a way to schedule a notebook automatically to run every 2 minutes? I have a notebook with a working code but i just need to run everything in it every 2 minutes. </p> <p>I am using Windows 10 and Anaco...
<p>I think a good way would to take all the code from your <code>Jupyter notebook</code> and make a python file out of it. Let's say the function you make is called <code>run</code>.</p> <p>You can then do something like </p> <pre><code>import if __name__ == "__main__": while True: run() time.sle...
python|python-3.x|automation|jupyter-notebook|jupyter
1
7,386
56,119,971
How to change color of line of an arrow in bokeh?
<p>I want to draw an arrow between two points on a map using bokeh. I was able to do that with following code. I am able to change the color of arrow but not the color of line or the type of line dash. Looks like the properties exist only for the head. Is there a property to change color of the line and the line dash t...
<p>You have passed a <code>line_color</code> to <code>OpenHead</code>. If you want to change the color of the arrow shaft, you also need to pass <code>line_color</code> to <code>Arrow</code> as well. They are distinct components, each with their own separate configuration. Same comment applies to <code>line_dash</code>...
python|bokeh
1
7,387
56,394,362
Problems creating Docker container with python code
<p>I'm very new to both python and docker, but nevertheless I'm trying to create a Docker container for password-generator app I wrote. But after building the app, I am getting error messages that I don't know if they are related to the python code or to the way I built the Docker.</p> <p>I expected the app to run nor...
<p>Please run your Docker container using the -i flag (interactive).</p> <p>Example:</p> <pre><code>docker run -i -t &lt;your-options&gt; </code></pre> <p>This, of course, will leave the biggest problem on the table, as correctly pointed out in a comment from @MisterMiyagi:</p> <blockquote> <p>input asks for inpu...
python|docker
3
7,388
18,657,926
python pg module error messages
<p>pg module in python for interacting with postgres is not giving any error message for DML queries.</p> <p>Is there any alternative to pg module which gives meaningful error messages.</p> <pre><code>&gt;&gt;&gt;import pg &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt;conn = pg.connect(dbname="db", user="postgres", host="lo...
<p>Why are you expecting an error message? I delete does not raise an error in the server if no records were found. So why do you expect a generally applicable database driver to raise an error?</p> <p>I can't think of any database driver that would issue an error in that case because there may be perfectly legitima...
python|postgresql|python-2.7|pygresql
2
7,389
69,364,073
What is a drop-in replacement for Python's `open()` function to read/write a file on S3?
<p>What is a good way to replace Python's built-in <code>open()</code> function when working with Amazon S3 buckets in an AWS Lambda function?</p> <h2>Summary</h2> <ul> <li>I am looking for a method to download a file from or upload a file to Amazon S3 in an AWS Lambda function.</li> <li>The syntax/API should similar t...
<p>There is a Python library called <a href="https://pypi.org/project/smart-open/" rel="nofollow noreferrer">smart-open · PyPI</a>.</p> <p>It's really good, because you can use all the file-handling commands you're familiar with, and it works with S3 objects! It can also read from compressed files.</p> <pre class="lang...
python|amazon-web-services|amazon-s3|aws-lambda
1
7,390
55,225,682
How do I view a specific table from a SQlite3 databse using python?
<p>I use the below code to read a table called 'movies' from the database saved as 'ga2.db'</p> <pre><code>conn = sqlite3.connect('ga2.db') cur = conn.cursor() pd.read_sql_table('movies', con=conn) </code></pre> <p>But I get this error <strong>"NotImplementedError: read_sql_table only supported for SQLAlchemy connect...
<p>Use <code>pd.read_sql_query</code> instead:</p> <pre><code>conn = sqlite3.connect('ga2.db') qry = '''SELECT * FROM movies''' df = pd.read_sql_query(qry, con=conn) </code></pre>
python|database|pandas|sqlite|datatables
0
7,391
55,382,185
Pandas - Extract Specific Values between Parenthesis
<p>I have a pandas series that contains various timezones and the unique values are as follows:</p> <pre><code>{0: '(GMT-05:00) Eastern Time (US &amp; Canada)', 1: '(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London', 2: '(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna', 3: '(GMT) UTC - Coor...
<p>To extract everything between two parenthesis use <code>\((.*?)\)</code></p> <pre><code>import re import pandas as pd data = {} # data dictionary pattern = "\((.*?)\)" df = pd.Series(data) new_data = {} key = 0 for item in df.items(): new_data[key] = re.match(pattern, item[1])[1] key += 1 print(new_data...
regex|python-3.x|pandas
1
7,392
42,467,690
How to Query DBpedia file dumps?
<p>How can I get information about entities from DBpedia data dumps using Python?</p> <p>Most of post currently on stackoverflow are working with an endpoint and not wuth a data dump file (like <a href="https://datascience.stackexchange.com/questions/4873/querying-dbpedia-from-python">https://datascience.stackexchange...
<p>Normally, you would load this data into an RDF store (install one if you don't already have it) and query it using SPARQL.</p> <p>By doing that you would create a local DBPedia mirror. Considering that DBPedia already provides a SPARQL endpoint is there any reason why you can't just use it?</p> <blockquote> <p>T...
python|semantic-web|dbpedia
1
7,393
42,188,061
Remove parenthesis and numbers from names?
<p>There is a list containing the names of several countries but some have numbers and/or parenthesis in their name. I want to get a clean list with only the country names without the parenthesis or number part. Is there a good pythonic way to do it quickly?</p> <p><strong>Example:</strong></p> <p><strong>Input:</str...
<p>You may use regular-expression for the same. Here is an approach to do the same</p> <pre><code>import re pattern = '[a-zA-Z]+' country = ['India12','Bolivia (SA)', 'Australia17 (A)'] country_names = map(lambda x:re.search(pattern,x).group(),country) </code></pre>
python
0
7,394
53,962,040
Converting Python Class Object To A DataFrame
<p>How do I convert a Python class object that has fields that instantiate other classes to a DataFrame? I tried the following code below but it does not work. </p> <p>I can get it to work when I take out <code>self.address = Address()</code> and <code>self.agency_contact_info = ContactInfo()</code> </p> <pre class="...
<p>Quoting <a href="https://stackoverflow.com/a/48750921/5858851">myself</a> again:</p> <blockquote> <p>I find it's useful to think of the argument to createDataFrame() as a list of [iterables] where each entry in the list corresponds to a row in the DataFrame and each element of the [iterable] corresponds to a colu...
python|apache-spark|pyspark|apache-spark-sql
0
7,395
58,248,767
How to get the text in the p tags using bs4
<p>I'm trying to scrape a news site for data and i now need the text in the p tags.</p> <p>i have googled a lot but all the solutions either return "None" or raise this error:</p> <pre><code>Traceback (most recent call last): File "E:/Python/News Uploader to Google Driver/venv/Scripts/main.py", line 41, in &lt;modu...
<p>Add child p to the parent defined by class</p> <pre><code>import requests from bs4 import BeautifulSoup as bs headers = {'User-Agent':'Mozilla/5.0'} r = requests.get('https://gadgets.ndtv.com/mobiles/news/samsung-galaxy-a-series-56-percent-q2-smartphone-sales-share-counterpoint-2112319', headers = headers) soup = ...
python|web-scraping|beautifulsoup
0
7,396
58,428,376
Seaborn scatterplot legend showing true values and normalized continuous color
<p>I have a dataframe that I'd like to use to build a scatterplot where different points have different colors:</p> <pre><code>import numpy as np import seaborn as sns import matplotlib.pyplot as plt import pandas as pd dat=pd.DataFrame(np.random.rand(20, 2), columns=['x','y']) dat['c']=np.random.randint(0,100,20) da...
<p>Partial answer. Do you actually need to determine your marker colors based on the normed values? See the output of the snippet below.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd dat = pd.DataFrame(np.random.rand(20, 2), columns=['x', 'y']) dat['c'] = np.random.randint(0, 1...
python|pandas|matplotlib|seaborn
1
7,397
65,306,871
place tkinter buttons in a row
<p>i want to place my buttons in a raw beside each other but when i set row same and change columns they place too far of each other.i tried to remove grid and add <code>pack()</code> but again i failed.changing <code>pady</code> didn't help me too.what should i do</p> <pre><code>import tkinter as tk from tkinter impor...
<p>What you are looking for is the <code>columnspan</code> option of <code>grid()</code>. First start off by removing custom geometry to your window. After that place the widgets all in same row but different column, like:</p> <pre><code>btnRead=tk.Button(root, height=1, width=20, text=&quot;ثبت&quot;,relief='flat',ove...
python-3.x|tkinter|button
1
7,398
65,255,201
How to combine multiple lists into 1 list without using zip()
<p>I want to combine multiple lists into 1 list without using <code>zip()</code> since <code>zip()</code> will convert <code>expected_list</code> to a list of tuples. I want <code>expected_result</code> is a list of lists.</p> <pre><code>list1 = [ &quot;a&quot; &quot;b&quot; &quot;c&quot; ] list2 ...
<p>Try this:</p> <pre><code>[[i, j] for i, j in zip(list1, list2)] </code></pre> <p>Or as <a href="https://stackoverflow.com/questions/65255201/how-to-combine-multiple-lists-into-1-list-without-using-zip#comment115365561_65255259">ekhumoro</a> wrote below:</p> <pre><code>list(map(lambda *x: list(x), a, b)). </code></pr...
python|list
2
7,399
14,430,331
Correct way of listening for a specific key with pygobject?
<p>I am very new to programming with python and gtk. After a day of googling and trying to find documentation i came up with the following solution for reacting on a press of a given button:</p> <pre><code>from gi.repository import Gtk,Gdk class BNWrestling(Gtk.Window): def __init__(self, bnt): self.conn...
<p>You could use the keyval name (same as the GDK_KEY_XXX constants without the prefix):</p> <pre><code>def on_key_press_event(self, widget, event, user_data=None): key = Gdk.keyval_name(event.keyval) if key == "Left": do_something() return True return False </code></pre>
python|gtk|pygobject
1