QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
75,150,031
13,359,498
ValueError: Shapes (None, 1) and (None, 4) are incompatible
<p>I am trying to implement StratifiedKFold. I am using resnet50 for classification. I have 4 classes so I used softmax activation function in the last layer. code snippets:</p> <pre><code>from sklearn.model_selection import StratifiedKFold # create the stratified k-fold cross-validator skf = StratifiedKFold(n_splits=5...
<python><tensorflow><keras><cross-validation>
2023-01-17 17:21:11
0
578
Rezuana Haque
75,149,926
4,822,772
Pandas merge by interval with missing intervals
<p>The question can be summarized in this image</p> <ul> <li>I have a table (df1) with ID column, and dates</li> <li>Another table (df2) with date intervals</li> <li>I want a final table to indicate if each date is in one of the intervals.</li> </ul> <p><a href="https://i.sstatic.net/7X5UY.png" rel="nofollow noreferrer...
<python><pandas><merge>
2023-01-17 17:09:37
1
1,718
John Smith
75,149,830
10,710,625
KeyError(key) in get_loc_level after using .transform() or apply()
<p>I have a large grouped data frame with multiple groups where I'm trying to filter rows within each group. To simplify it, I will share a simplified data frame with one group where I'm getting the error. df5 is grouped by <code>&quot;Detail&quot;, &quot;ID&quot;, &quot;Year&quot;</code></p> <pre><code>data2 = {&quot;...
<python><pandas><apply>
2023-01-17 17:02:48
1
739
the phoenix
75,149,732
12,140,406
color seaborn swarmplot points with additional metadata beyond hue in boxplot
<p>Say I have data that I want to box plot and overlay with a swarm plot in seaborn, whose colors of the points add additional information on the data.</p> <p>Question: <strong>How can I get box plots to be close to each other for a given x axis value (as is done in hue) without refactorizing x to the hue value and the...
<python><seaborn><visualization><boxplot><swarmplot>
2023-01-17 16:54:02
1
365
wiscoYogi
75,149,654
17,653,423
How to get data from nested list in response.json()
<p>There is a json response from an API request in the following schema:</p> <pre><code>[ { &quot;id&quot;: &quot;1&quot;, &quot;variable&quot;: &quot;x&quot;, &quot;unt&quot;: &quot;%&quot;, &quot;results&quot;: [ { &quot;classification&quot;: [ { &quot;id&quot;: &...
<python><pandas><python-requests>
2023-01-17 16:48:00
1
391
Luiz
75,149,539
20,054,635
How to check if file exists before reading the data into data frame using Pyspark?
<p>My requirement is to check if the specific file pattern exists in the data lake storage directory and if the file exists then read the file into pyspark dataframe if not exit the notebook execution.</p> <p>I have following working code below just to read the file into dataframe.</p> <pre><code>kaka_adls_path = &quot...
<python><dataframe><pyspark><azure-databricks><azure-data-lake>
2023-01-17 16:38:53
1
369
Anonymous
75,149,469
2,546,099
Processing numpy array in parallel significantly slows down process
<p>For my work I have to process rather large numpy arrays (&gt; 2e6 entries) by cutting them into small windows, and then calculating several features for each of those windows. To speed up this process I intended to take advantage of the multiprocessing-module. To test my approach, I wrote the following test code (ap...
<python><numpy><parallel-processing><python-multiprocessing>
2023-01-17 16:32:59
0
4,156
arc_lupus
75,149,460
6,903,605
Setting xtick labels in of an sns.heatmap subplot
<p>I am trying to put 3 subplots of <code>sns.heatmap</code> with custom <code>xticklabels</code> and <code>yticklabels</code>. You can see that the labels I enter overlaps with some default labels. How to avoid this?</p> <pre><code>glue = sns.load_dataset(&quot;glue&quot;).pivot(&quot;Model&quot;, &quot;Task&quot;, &q...
<python><matplotlib><heatmap><subplot><yticks>
2023-01-17 16:32:18
1
306
volkan g
75,149,389
14,598,633
matplotlib legend not showing correctly
<p>I am trying to plot some data from a csv file. I used the Pandas to load the csv file. I am using <code>sns.lineplot()</code> to plot the lines. But one of the legend is always faulty. It shows a square around one of the legend.</p> <pre class="lang-py prettyprint-override"><code>plt.figure(dpi=150) lin1 = sns.linep...
<python><matplotlib><seaborn><legend>
2023-01-17 16:26:21
2
866
Prakhar Sharma
75,149,281
3,130,926
Pandas apply returns function instead of value
<p>Puzzling pandas apply behavior</p> <pre class="lang-py prettyprint-override"><code>data = {'date_col_1': ['2020-01-24', '2020-03-24' ], 'date_col_2': ['2017-03-08', '2020-01-24']} testdf = pd.DataFrame(data) </code></pre> <p>Then try to convert the columns ...
<python><pandas><datetime>
2023-01-17 16:18:01
1
14,217
muon
75,149,191
7,437,143
Ignoring mypy attr-defined with triple quotes
<p>The following code:</p> <pre class="lang-py prettyprint-override"><code># type: ignore[attr-defined] timeit.template = &quot;&quot;&quot; # type: ignore[attr-defined] def inner(_it, _timer{init}): {setup} _t0 = _timer() for _i in _it: retval = {stmt} _t1 = _timer() return _t1 - _t0, retv...
<python><mypy>
2023-01-17 16:10:02
1
2,887
a.t.
75,149,181
5,195,209
Expanding a Scribunto module that doesn't have a function
<p>I want to get the return value of this Wikimedia <a href="https://cs.wiktionary.org/wiki/Modul:Languages" rel="nofollow noreferrer">Scribunto module</a> in Python. Its source code is roughly like this:</p> <pre class="lang-lua prettyprint-override"><code>local Languages = {} Languages = { [&quot;aa&quot;] = { ...
<python><lua><wikitext><scribunto>
2023-01-17 16:08:59
1
587
Pux
75,149,145
11,622,712
Filter rows conditionally in PySpark: Aggregate/Window/Generate expressions are not valid in where clause of the query
<p>I have the following dataframe in PySpark:</p> <pre><code>from pyspark.sql import SparkSession # Create a SparkSession spark = SparkSession.builder.appName(&quot;myApp&quot;).getOrCreate() # Create a list of rows for the DataFrame rows = [(&quot;2011-11-13 11:00&quot;, 1, &quot;2011-11-13 11:06&quot;, &quot;2011-1...
<python><apache-spark><pyspark><apache-spark-sql>
2023-01-17 16:06:29
1
2,998
Fluxy
75,149,094
1,709,475
Display the output of datatypes from two dataframes
<p>I would like to display the output of datatypes from two dataframes.</p> <p><code>column_name, dbf datatype, df datatype</code> should be displayed.</p> <p>Working code</p> <pre><code>import csv import pandas as pd from dbfread import DBF csv_file = &quot;bridges.csv&quot; dbf_file = &quot;bridges.dbf&quot; def db...
<python><pandas><dataframe>
2023-01-17 16:02:20
1
326
Tommy Gibbons
75,149,076
7,800,760
Select rows of dataframe whose column values amount to a given sum
<p>I need to find out how many of the first N rows of a dataframe make up (just over) 50% of the sum of values for that column.</p> <p>Here's an example:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(10, 1), columns=list(&quot;A&quot;)) 0 0.681991 1 0.304026 2 0.552589 3 0....
<python><pandas><dataframe>
2023-01-17 16:01:00
1
1,231
Robert Alexander
75,148,953
5,947,182
mouse.up() not working after mouse.move()
<p>I'm writing a test in Playwright Python and pytest to see if the auto mouse movements can be simulated to look more like of a real user's. I use a local html canvas written from html and javascript, the code is from <a href="https://www.onlywebpro.com/2013/01/10/create-html5-canvas-drawing-board-within-5-minutes/" r...
<python><mouseevent><playwright><mouseup>
2023-01-17 15:51:09
2
388
Andrea
75,148,949
20,700,631
IfxPy connection to Informix DB problem - user with added hostname
<p>I am currently trying to establish connection from server (64b windows) to Avaya CMS DB - which is Informix engine - using IfxPy. IfxPy 3.0.5 comes with HCL ONEDB ODBC DRIVER (version 1.0.0.0), which is copied into site-packages. I think I've properly installed the IfxPy module, pointed ODBC registers to iclit09b.dl...
<python><odbc><informix><avaya>
2023-01-17 15:50:49
1
372
bracko
75,148,938
9,944,937
tensorflow map_fn with a list of list of strings
<p>I'm trying to pass a list of arguments to a function using <code>tensorflow</code> function: <code>tf.map_fn</code>. Here is my code:</p> <pre class="lang-py prettyprint-override"><code>def my_func(a,v,c,d): print(a,v,c,d) if __name__ == '__main__': tf.config.set_visible_devices(tf.config.list_physical_devi...
<python><python-3.x><tensorflow><tensor>
2023-01-17 15:50:05
1
1,101
Fabio Magarelli
75,148,936
1,551,974
Cancel repeating thread in python if it takes longer than 15 seconds
<p>I have a function that calls itself again after completion with a delay. They goal is that the function <code>doSomething</code> runs roughly every 5 seconds. However if the function needs more than 15 seconds the thread should be cancelled. How can I add the condition that the thread gets killed if it takes to long...
<python><python-3.x><multithreading>
2023-01-17 15:49:47
0
2,278
Silve2611
75,148,921
2,290,763
Merging multiple dataframes with applying different operation on each column
<p>I have several daily CSV files with structure similar to this:</p> <pre><code>| resource | start_date | end_date | total_usage | usage_per_hour | last_read | |----------|------------|------------|-------------|----------------|------------| | s3 | 2023-01-01 | 2023-01-01 | 22333 | 930,54 | 202...
<python><pandas>
2023-01-17 15:48:41
0
1,649
Forin
75,148,810
5,197,034
Create custom sized bins of datetime Series in Pandas
<p>I have multiple Pandas Series of datetime64 values that I want to bin into groups using arbitrary bin sizes.</p> <p>I've found the <code>Series.to_period()</code> function which does exactly what I want except that I need more control over the chosen bin size. <code>to_period</code> allows me to bin by full years, m...
<python><pandas><datetime><binning>
2023-01-17 15:39:57
1
2,603
pietz
75,148,665
19,826,650
Insert list into MySQL database using Python
<p>I am doing a classification using k-nearest neighbor with python. The data I am using is float type, <code>latitude</code> and <code>longitude</code> and get the output from it like this:</p> <p>prediction</p> <pre><code>preds2 = model.predict(new_list) print(type(preds2)) print(preds2) print(&quot;-----------&quot;...
<python><mysql-python>
2023-01-17 15:27:08
1
377
Jessen Jie
75,148,659
4,056,181
Using SeedSequence to convert any random seed into a good seed
<p>In NumPy 1.17, the <code>random</code> module was given an overhaul. Among the new additions were <a href="https://numpy.org/doc/stable/reference/random/bit_generators/generated/numpy.random.SeedSequence.html#numpy.random.SeedSequence" rel="nofollow noreferrer"><code>SeedSequence</code></a>. In the section about <a ...
<python><python-3.x><numpy><random><random-seed>
2023-01-17 15:26:44
1
13,201
jmd_dk
75,148,585
98,080
Union of dict with typed keys not compatible with an empty dict
<p>I'd like to type a dict as either a dictionary where the all the keys are integers or a dictionary where all the keys are strings.</p> <p>However, when I read mypy (v0.991) on the following code:</p> <pre class="lang-py prettyprint-override"><code>from typing import Union, Any special_dict: Union[dict[int, Any], di...
<python><mypy><python-typing>
2023-01-17 15:20:56
1
3,241
fgregg
75,148,551
6,067,741
http 1.1 with requests and proxy
<p>I cant seem to find a way to send http connect 1.1 using python requests with proxy. it sends 1.0 and I dont want my infra to be able to accept http 1.0 connections.</p> <pre class="lang-py prettyprint-override"><code>proxy = { 'https': f'http://{xyz}:10000' } requests.get( f'https://{url}/health', timeout =...
<python><python-3.x><python-requests><proxy><request>
2023-01-17 15:18:36
0
71,429
4c74356b41
75,148,449
12,883,297
Remove the rows of dataframe based on date and flag condition in pandas
<p>I have a dataframe</p> <pre><code>df = pd.DataFrame([[&quot;A&quot;,&quot;13-02-2022&quot;,&quot;B&quot;,&quot;FALSE&quot;],[&quot;A&quot;,&quot;13-02-2022&quot;,&quot;C&quot;,&quot;FALSE&quot;],[&quot;A&quot;,&quot;14-02-2022&quot;,&quot;D&quot;,&quot;FALSE&quot;], [&quot;A&quot;,&quot;14-02-2022...
<python><python-3.x><pandas><dataframe><datetime>
2023-01-17 15:11:15
2
611
Chethan
75,148,441
5,371,102
Sqlalchemy creating group to group relationship
<p>I have the following models, where my two models share an outside_id to some table I don't have access to, but it is via that table they are connected. So they are not in a traditional many to many relationship. The only solution I have found is to create a table with primary key outside_id and use that to bridge th...
<python><sql><postgresql><sqlalchemy>
2023-01-17 15:10:35
1
1,989
Peter Mølgaard Pallesen
75,148,235
4,040,743
Why aren't identical datetimes equal?
<p>I'm working on a simple Python3 script that considers data in five-minute increments. <a href="https://stackoverflow.com/questions/75112399/how-to-round-down-a-datetime-to-the-nearest-5-minutes">Thanks to this post</a>, I have code which takes any Python datetime object and then rounds it down to the nearest five m...
<python><python-3.x><datetime><equality>
2023-01-17 14:52:57
1
1,599
Pete
75,148,114
275,002
Python: How to efficiently fetch the latest record from multiple tables in MySQL?
<p>Let me give you some background.</p> <p>The earlier version of the Python script was fetching data from an API after every second and then will create MySQL tables on the fly based on the value of a JSON field returns from API and then insert data into it. I was returning the list of tuples of the API data in this f...
<python><mysql>
2023-01-17 14:43:57
0
15,089
Volatil3
75,148,057
11,645,617
django set image delete old reference and prevent delete default
<p>despite of many mordern website employ an OSS for serving image, I still want to build a backend to manage small thumbnails locally.</p> <p>however, django image field is a bit tricky.</p> <p>there are three views I may change image reference:</p> <ul> <li><code>models.py</code></li> <li><code>views.py</code></li> <...
<python><django><django-models><imagefield>
2023-01-17 14:39:04
1
3,177
Weilory
75,148,018
2,998,077
To count in how many list, certain elements appeared
<p>Several names that I want to count, in how many lists they appeared.</p> <pre><code>four_in_one = [['David','Ellen','Ken'],['Peter','Ellen','Joe'],['Palow','Ellen','Jack'],['Lily','Elain','Ken']] for name in ['David','Ken','Kate']: for each_list in four_in_one: i = 0 if name in each_list: ...
<python><list><loops>
2023-01-17 14:36:00
2
9,496
Mark K
75,148,002
1,176,573
Populate pods CPU limits using Kubernetes Python Client for Azure AKS cluster
<p>I need to use <a href="https://github.com/Azure/azure-sdk-for-python" rel="nofollow noreferrer">Azure Python SDK</a> and <a href="https://github.com/kubernetes-client/python" rel="nofollow noreferrer">Kubernetes Python Client</a> to list the Pods CPU limits for a cluster running in AKS.</p> <p>Although its straight ...
<python><azure><kubernetes><kubectl><azure-aks>
2023-01-17 14:34:42
3
1,536
RSW
75,147,819
1,141,818
Extract text before two underscores with regex
<p>I feel I am not far from a solution but I still struggle to extract some text from variables with Regex. The conditions are:</p> <ul> <li>The text can only contain upper case characters or integers</li> <li>The text can contain underscores BUT not two consecutive ones</li> </ul> <p>Examples:</p> <pre><code>test_TEST...
<python><regex>
2023-01-17 14:18:56
2
3,575
GuillaumeA
75,147,699
10,590,609
Multiprocessing queue closing signal
<p>Suppose I have a number of items that I put in a queue for other processes to deal with. The items are rather large in memory, therefore I limit the queue size. At some point I will have no more things to put in the queue. How can I signal the other processes that the queue is closed?</p> <p>One option would be to c...
<python><multiprocessing><queue>
2023-01-17 14:09:26
3
332
Izaak Cornelis
75,147,684
12,193,952
Check if variable exists and if exists whether is not a nan using Python
<p>I would like to improve my coding skill and I struggle with finding a proper solution. I have a variable named <code>foo</code>. If <code>foo</code> has a numeric value, I need to do some action. However <code>foo</code> can be either:</p> <ul> <li>not set (<code>NoneType</code>)</li> <li>float with value nan (<code...
<python><validation><variables><types>
2023-01-17 14:08:27
0
873
FN_
75,147,682
9,422,346
How to interpret HAF sensor data?
<p>My sensor i2c - (flow sensor) on raspberry pi gives a reading <code>b'\x06g'</code>. How can |I possibly interpret this? Code snippet used (this code is based on - <a href="https://github.com/stripemsu/HoneywellFlow" rel="nofollow noreferrer">https://github.com/stripemsu/HoneywellFlow</a>)</p> <pre><code>import io, ...
<python><raspberry-pi><sensors><i2c>
2023-01-17 14:08:21
1
407
mrin9san
75,147,507
7,074,969
Validating adb2c jwt is throwing Invalid authorization token: InvalidSignatureError in Python
<p>I have been trying to validate a jwt received from adb2c in Python in the latest days. For that case, I use the <code>azure_ad_verify_token</code> library and have followed a tutorial on their docs page. As they say, I define</p> <pre><code>azure_ad_app_id = &quot;app_id&quot; azure_ad_issuer = f&quot;https://login....
<python><jwt><azure-ad-b2c>
2023-01-17 13:54:40
1
1,013
anthino12
75,147,455
1,818,713
Running dash app in azure functions python model v2 but only getting default site up page
<p>I'm using the v2 python programming model and trying to launch a dash app similar to the example of a Flask app <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python?tabs=wsgi%2Capplication-level&amp;pivots=python-mode-decorators#alternative-entry-point" rel="nofollow noreferrer...
<python><azure-functions><wsgi>
2023-01-17 13:51:11
1
19,938
Dean MacGregor
75,147,385
4,913,660
Running __main__.py script with python . (dot)
<p>I am trying to understand why a <code> __main__.py</code> file could be run from shell issuing <code> python .</code> within the folder where said file is located.</p> <p>How does this work? What does the <code>.</code> stand for, and why is not the file name needed?</p> <p>Where is the dot coming from?. Given a b...
<python><bash>
2023-01-17 13:46:36
0
414
user37292
75,147,334
6,372,859
Evaluate scalar function on numpy array with conditionals
<p>I have a numpy array <code>r</code> and I need to evaluate a scalar function, let's say <code>np.sqrt(1-x**2)</code> on each element <code>x</code> of this array. However, I want to return the value of the function as zero, whenever <code>x&gt;1</code>, and the value of the function on <code>x</code> otherwise. The ...
<python><arrays><numpy><if-statement>
2023-01-17 13:43:14
3
583
Ernesto Lopez Fune
75,147,116
14,353,779
conditional flagging in pandas
<p>I have a dataframe <code>df</code> :-</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">ID</th> <th style="text-align: center;">1F_col</th> <th style="text-align: center;">2F_col</th> <th style="text-align: center;">3F_col</th> <th style="text-align: center;">4G...
<python><pandas><numpy>
2023-01-17 13:26:03
3
789
Scope
75,146,906
6,494,707
ValueError: Length of values (586) does not match length of index (521)
<p>I have two data frames that I am comparing two columns <code>df_luad['Tumor_Sample_Barcode']</code> and <code>df_tmb['Patient ID']</code> of them, if the two columns values from two dataframes are equal, then it adds a column from the second dataframe <code>df_tmb['TMB (nonsynonymous)']</code>to a new third datafram...
<python><pandas><dataframe>
2023-01-17 13:07:39
1
2,236
S.EB
75,146,792
1,542,093
Get all required fields of a nested Pydantic model
<p>My nested Pydantic model is defined as follows:</p> <pre class="lang-py prettyprint-override"><code>from typing import Optional from pydantic import BaseModel class Location(BaseModel): city: Optional[str] state: str country: str class User(BaseModel): id: int name: str = &quot;Gandalf&quot; ...
<python><python-3.6><pydantic>
2023-01-17 12:57:17
1
1,213
lordlabakdas
75,146,595
19,580,067
Unable to install pypiwin32 library
<p>Tried to install the <code>pip install pypiwin32</code> in Google Colab for reading outlook emails. But the installation keeps on getting failed.</p> <p><a href="https://i.sstatic.net/wIXxI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wIXxI.png" alt="enter image description here" /></a></p> <p>Trie...
<python><machine-learning><pywin32>
2023-01-17 12:43:03
2
359
Pravin
75,146,476
20,281,672
Using Scipy's LowLevelCallable and numba cfunc to optimise a time based ode that takes multiple arrays as input
<p>I want to optimise the solving of a system of time based ODE's by combining Numba's <code>cfunc</code> and scipy's <code>LowLevelCallable</code> functionality to greatly speed up <code>odeint()</code>. However, i am having trouble finding out what the exact syntax is for the correct solution.</p> <p>My (non-optimise...
<python><optimization><scipy><numba><ode>
2023-01-17 12:33:48
1
312
Rafnus
75,146,416
10,065,556
Impact of idle connections on max_connections in postgres
<p>I've been getting <code>'M': 'sorry, too many clients already'</code> lately when my FastAPI endpoint is called, throwing 500.</p> <p>I tried running this script:</p> <pre><code>select pid as process_id, usename as username, datname as database_name, client_addr as client_address, app...
<python><postgresql><fastapi>
2023-01-17 12:28:24
1
994
ScriptKiddieOnAComputer
75,146,250
7,714,681
E1101 (no-member) for code that works well
<p>I have a structure similar to below, in my code:</p> <pre><code>class A(): def __init__( self, &lt;SOME_VARIABLES&gt; ) self.matrix = self._get_matrix() class B(A): def __init__( self, &lt;SOME_VARIABLES&gt; ) super(...
<python><object><oop><constructor><pylint>
2023-01-17 12:13:08
1
1,752
Emil
75,146,221
19,633,374
compare python list with a string array column in Pyspark
<p>I have a python list</p> <pre><code>my_list = [&quot;AAA&quot;,&quot;BBB&quot;, &quot;CCC&quot;] </code></pre> <p>I have to compare this list with the array column in df</p> <pre><code># dataframe dummy df = spark.createDataFrame([('1A', '3412asd','value-1', ['XXX', 'YYY', 'AAA']), ('2B', '2345tyu','value-2',...
<python><arrays><list><dataframe><pyspark>
2023-01-17 12:10:19
0
642
Bella_18
75,146,100
913,098
Execute a Python script post install using setuptools
<p>This is exactly the same as <a href="https://stackoverflow.com/q/17806485/913098">this question</a>.</p> <p>The <a href="https://stackoverflow.com/a/18159969/913098">accepted (and only) answer</a> uses <code>distutils</code> <a href="https://stackoverflow.com/a/14753678/913098">which is deprecated</a>.</p> <p>Simply...
<python><installation><pip><setuptools><distutils>
2023-01-17 11:59:36
0
28,697
Gulzar
75,146,086
860,233
My access to Google Sheets API is being blocked to a URI Redirect Mismatch
<p>I am unable to access my Google sheet, here is the error I get:</p> <pre><code>Error 400: redirect_uri_mismatch You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy. If you're the app developer, register the redirect URI in the Google Cloud Console. Request details: redirect_uri=h...
<python><django><google-sheets><google-cloud-platform>
2023-01-17 11:58:34
1
930
Glenncito
75,145,735
9,778,828
PyMongo - get 20% (random or not) of the collection
<p>I have a big MongoDB collection - 16 GB, 130M rows.</p> <p>I need to query the DB and get only 20% of the data.</p> <p>The best option would be to only get every 5th row, but also a random 20% choosing could work.</p> <p><a href="https://www.mongodb.com/docs/upcoming/reference/operator/aggregation/sample/#pipe._S_sa...
<python><pandas><mongodb><pymongo>
2023-01-17 11:27:07
1
505
AlonBA
75,145,428
14,353,779
How to achieve this concatenation in Pandas?
<p>I have a dataframe <code>df</code> :-</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">tray</th> <th style="text-align: center;">bag</th> <th style="text-align: center;">ball</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">0</td> <td style="tex...
<python><pandas>
2023-01-17 11:02:57
1
789
Scope
75,145,424
9,947,412
FastAPI/Starlette: How to handle exceptions inside background tasks?
<p>I developed some API endpoints using FastAPI. These endpoints are allowed to run <code>BackgroundTasks</code>. Unfortunately, I do not know how to handle unpredictable issues from theses tasks.</p> <p>An example of my API is shown below:</p> <pre class="lang-py prettyprint-override"><code># main.py from fastapi imp...
<python><exception><fastapi><background-task><starlette>
2023-01-17 11:02:34
1
907
PicxyB
75,145,410
4,451,315
Dispaly DataFrame in Jupyter Notebook along with other attributes
<p>If I just construct a pandas DataFrame in a Jupyter notebook, then the output looks nice:</p> <pre class="lang-py prettyprint-override"><code>frame = pd.DataFrame({'a': [1,2,3]}) frame </code></pre> <p><a href="https://i.sstatic.net/6l9Bz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6l9Bz.png" alt=...
<python><pandas><jupyter-notebook>
2023-01-17 11:01:26
1
11,062
ignoring_gravity
75,145,244
9,770,831
How to add extra data to pydantic schemas in FastAPI response?
<p>This is my Response model -</p> <pre><code>class BillBase(BaseModel): bill_no: int amount: int about: str class ShowSalesBill(BillBase): id: int left_amount: int class Config: orm_mode = True </code></pre> <p>so this <code>left_amount</code> int field is not in the Bills model I wan...
<python><fastapi><pydantic>
2023-01-17 10:44:39
0
657
mdhv_kothari
75,145,058
12,752,172
Why tkinter filedialog not opening file dialog box when the code is inside the function in python?
<p>I'm creating a python console menu app. I want to select a CSV file from the user file location and need to ask the user to select the file location. I'm trying it with tkinter filedialog. But it working fine when it is outside of the function. But when I put the code lines into a function it is not opening the file...
<python><tkinter>
2023-01-17 10:27:34
1
469
Sidath
75,145,023
4,056,181
Advancing PRNGs in NumPy and general distributions
<p>I would like to use the <a href="https://numpy.org/doc/stable/reference/random/generator.html" rel="nofollow noreferrer">random number generation of NumPy</a> to draw numbers from different distributions. For a given generator, seed and distribution, I would like to be able to draw the <code>i</code>'th number in th...
<python><python-3.x><numpy><random>
2023-01-17 10:24:35
1
13,201
jmd_dk
75,144,956
3,605,534
How to delete icons from comments in csv files using pandas
<p>I am try to delete an icons which appears in many rows of my csv file. When I create a dataframe object using pd.read_csv it shows a green squared check icon, but if I open the csv using Excel I see ✅ instead. I tried to delete using split function because the verification status is separated by | to the comment:<...
<python><pandas><csv>
2023-01-17 10:19:12
2
945
GSandro_Strongs
75,144,935
1,186,624
How to simulate a heat diffusion on a rectangular ring with FiPy?
<p>I am new to solving a PDE and experimenting with a heat diffusion on a copper body of a rectangular ring shape using FiPy.</p> <p>And this is a plot of simulation result at some times. <a href="https://i.sstatic.net/kAlJS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kAlJS.png" alt="enter image desc...
<python><simulation><fipy>
2023-01-17 10:17:08
2
5,019
relent95
75,144,910
11,586,653
Python multiple substring index in string
<p>Given the following list of sub-strings:</p> <pre><code>sub = ['ABC', 'VC', 'KI'] </code></pre> <p>is there a way to get the index of these sub-string in the following string if they exist?</p> <pre><code>s = 'ABDDDABCTYYYYVCIIII' </code></pre> <p>so far I have tried:</p> <pre><code>for i in re.finditer('VC', s): ...
<python><string><loops>
2023-01-17 10:15:38
6
471
Chip
75,144,827
10,829,044
Pandas filter list of list values in a dataframe column
<p>I have a dataframe like as below</p> <pre><code>sample_df = pd.DataFrame({'single_proj_name': [['jsfk'],['fhjk'],['ERRW'],['SJBAK']], 'single_item_list': [['ABC_123'],['DEF123'],['FAS324'],['HSJD123']], 'single_id':[[1234],[5678],[91011],[121314]], ...
<python><pandas><list><dataframe><transformation>
2023-01-17 10:08:09
2
7,793
The Great
75,144,814
3,062,781
Generate SSH ed25519 private key with embedded comment
<p>So I've been looking at modifying some existing code to make it compatible with Windows as well as Linux/MacOS. There is a generator which currently shells out to <code>ssh-keygen</code> via subprocess to produce an SSH private key, and there is also an encoder for a public key which also leverages <code>ssh-keygen<...
<python><ssh><cryptography><ssh-keys>
2023-01-17 10:07:24
0
765
264nm
75,144,722
2,081,152
AWS Glue Pyspark Python UDFRunner timing info total/boot/init/finish
<p>I am running a Pyspark AWS Glue Job that includes a Python UDF. In the logs I see this line repeated.</p> <pre><code>INFO [Executor task launch worker for task 15765] python.PythonUDFRunner (Logging.scala:logInfo(54)): Times: total = 268103, boot = 21, init = 2187, finish = 265895 </code></pre> <p>Does anyone know ...
<python><apache-spark><pyspark><user-defined-functions><aws-glue>
2023-01-17 10:00:50
1
703
mamonu
75,144,634
16,852,041
Python | Redis Connects but Stuck on Set or Get
<p>Goal: Successfully <code>set()</code> and <code>get()</code> key-value pairs to local <strong>Redis</strong> via. <strong>Python</strong>.</p> <p>I can connect to Redis. A possible issue is a firewall has closed port <code>6379</code>. However, it is open.</p> <p>Connection works with or without parameters: <code>re...
<python><redis><get><set><port>
2023-01-17 09:53:39
1
2,045
DanielBell99
75,144,592
13,238,456
Extracting tables from PDF using tabula-py fails to properly detect rows
<h4>Problem</h4> <p>I want to extract a 70-page vocabulary table from a PDF and turn it into a CSV to use in [any vocabulary learning app]. Tabula-py and its read_pdf function is a popular solution to extract the tables, and it did detect the columns ideally without any fine-tuning. But, it only detected the columns we...
<python><pandas><pdf><tabula-py>
2023-01-17 09:50:37
2
493
Dustin
75,144,422
6,670,900
Handle multiple request from Flask with Python Selenium
<p>I have used Flask to receive request and then run the desired actions with Selenium.</p> <p>My problem is <code>driver = webdriver.Chrome(executable_path=&quot;chromedriver&quot;)</code> takes more time to run my request, is that a way to keep the chrome window open?</p> <p>The results are as below:</p> <p><a href="...
<python><selenium><flask>
2023-01-17 09:37:02
1
443
Dave Cruise
75,144,399
4,974,431
Split string in Python using two conditions (one delimiter and one "contain")
<p>Considering the following string:</p> <pre><code>my_text = &quot;&quot;&quot; My favorites books of all time are: Harry potter by JK Rowling, Dune (first book) by Frank Herbert; and Le Petit Prince by Antoine de Saint Exupery (I read it many times). &quot;&quot;&quot; </code></pre> <p>I want to extra...
<python><string><split>
2023-01-17 09:35:28
6
1,624
Vincent
75,144,389
859,141
Reverse Inlines in Django Admin for Many to Many
<p>Apologies if this has been asked before and my searches have not uncovered the solution. I'm looking to include admin inlines for two models. Django version is 4.1.4</p> <pre><code>class Book(models.Model): title = models.CharField(max_length=100) author_series = models.CharField(max_length=100, blank=Tr...
<python><django><django-models><django-admin>
2023-01-17 09:34:38
1
1,184
Byte Insight
75,144,145
1,530,405
Python Client/Server hangs
<p>I have an Android app, written in Javascript (source not available) that allows the creation of Buttons and sending Button presses.</p> <p>The Server is running on a Win10 desktop, and the code is as follows:</p> <pre><code># Try.py import socket CRLF = '\r\n' count = 0 port = 6666 print('Server Waiting on ' + ...
<python><sockets>
2023-01-17 09:12:15
0
455
user1530405
75,144,127
14,065,992
ROC Curve area is nan CNN model
<p>I have implemented a CNN based Classification of image datasets but the problem is it provides a nan value of the ROC_Curve's area. Here is the coding part,</p> <pre><code>#Package Initilize import numpy as np from sklearn import metrics import matplotlib.pyplot as plt import tensorflow as tf import keras from keras...
<python><scikit-learn><deep-learning><conv-neural-network><roc>
2023-01-17 09:10:18
1
1,855
Imdadul Haque
75,144,064
10,829,044
Pandas pick an item from list column and search in other list column
<p>I have a dataframe like as shown below</p> <pre><code>sample_df = pd.DataFrame({'single_proj_name': [['jsfk'],['fhjk'],['ERRW'],['SJBAK']], 'single_item_list': [['ABC_123'],['DEF123'],['FAS324'],['HSJD123']], 'single_id':[[1234],[5678],[91011],[121314]], ...
<python><pandas><list><dataframe><transformation>
2023-01-17 09:04:09
1
7,793
The Great
75,144,059
12,215,366
Python Playwright start maximized window
<p>I have a problem starting Playwright in Python maximized. I found some articles for other languages but doesn't work in Python, also nothing is written about maximizing window in Python in the official documentation.</p> <p>I tried <code>browser = p.chromium.launch(headless=False, args=[&quot;--start-maximized&quot;...
<python><playwright><playwright-python>
2023-01-17 09:03:34
4
375
bbfl
75,143,895
14,632,651
Cyrillic Encoding in Urllib Python with lower cases
<p>My goal is to encode this dict with <code>cyrilic</code> text:</p> <pre><code>target_dict = {&quot;Animal&quot;: &quot;Cat&quot;, &quot;city&quot;: &quot;Москва&quot;} </code></pre> <p>To this (<code>cyrilic lettesrs with lower case</code> encoded):</p> <pre><code>Animal=Cat&amp;city=%d0%9c%d0%be%d1%81%d0%ba%d0%b2%d...
<python><url><urllib><urlencode>
2023-01-17 08:51:42
1
1,303
oruchkin
75,143,826
10,311,377
What is the best way to wrap Thread/Process in magic method __await__ to create awaitable class?
<p>I would like to create &quot;awaitable&quot; class instances. It will be useful when I have to use some db connectors which do not have <code>asyncio</code> wrappers. Also it is just interesting for me to better understand <code>asyncio</code> and <code>generators</code>.</p> <p>I came to the following solutions:</p...
<python><python-3.x><multithreading><multiprocessing><python-asyncio>
2023-01-17 08:45:15
0
3,906
Artiom Kozyrev
75,143,677
12,275,675
Reindexing Pandas based on daterange
<p>I am trying to reindex the dates in pandas. This is because there are dates which are missing, such as weekends or national hollidays.</p> <p>To do this I am using the following code:</p> <pre><code>import pandas as pd import yfinance as yf import datetime start = datetime.date(2015,1,1) end = datetime.date.today...
<python><pandas><datetime><reindex>
2023-01-17 08:31:11
2
1,220
Slartibartfast
75,143,537
997,832
Tensorflow text classification with subject for each text
<p>I want to classify texts with additional input 'text' subject. I acquire these subjects from wikidata 'instance of' properties. I designed a neural net model as below. Network takes texts and subjects as input. Texts are encoded into vectors and than these vectors get pooled. Other input 'subjects', are taken as int...
<python><tensorflow><deep-learning><neural-network><text-classification>
2023-01-17 08:17:55
0
1,395
cuneyttyler
75,143,522
1,581,090
How to read data from a serial port in Windows using python?
<p>In windows 10 I am trying to read the output of an attached serial device.</p> <p>Using <code>hterm</code> I am able to see the data on serial port <code>COM5</code>. So the serial port works fine.</p> <p>Now using WSL2 (Ubuntu 20.04.3) I am running the following python script</p> <pre><code>import serial ser = se...
<python><windows><serial-port><windows-subsystem-for-linux>
2023-01-17 08:15:55
4
45,023
Alex
75,143,435
14,194,418
Web Driver Wait is not working when page load strategy is set to none
<p><strong>Selenium Version: 4.7.2</strong></p> <p>I only want to wait for specific page to load so I want to disable the default behavior of driver page load strategy.</p> <p>I disable it with the following code.</p> <pre><code>options = webdriver.ChromeOptions() options.page_load_strategy = &quot;none&quot; </code></...
<python><selenium><selenium-webdriver><selenium-chromedriver><pageloadstrategy>
2023-01-17 08:05:23
2
2,551
Ibrahim Ali
75,143,190
15,416,614
Is it possible to close a window in macOS with Python?
<p>Actually, I wanna do some automated operations on macOS, like closing a specific window.</p> <p>I have read some threads, and I got know about <code>Appkit</code> and <code>Quartz</code> from <a href="https://stackoverflow.com/questions/53237266/how-can-i-minimize-maximize-windows-in-macos-with-the-cocoa-api-from-a-...
<python><python-3.x><macos>
2023-01-17 07:37:30
0
387
Gordon Hui
75,143,185
997,832
Tensorflow Data cardinality is ambigous with multiple inputs
<p>I have a model with two inputs for text classification with additional input 'subject' of text. One of my inputs is for text - it gets vectorized by a vectorization layer. The other is 'subject' as int. These are concatenated later. In my code below, <code>x_train_text</code> is simply a list of texts. <code>x_train...
<python><tensorflow><deep-learning>
2023-01-17 07:36:44
1
1,395
cuneyttyler
75,143,062
5,521,699
Performing realtime Google Cloud speech recognition with PyAudio + VB-Audio virtual cable
<p>I am trying to perform streaming speech recognition with the realtime Google Cloud Speech API. I have used the second code snippet from here (<a href="https://cloud.google.com/speech-to-text/docs/transcribe-streaming-audio" rel="nofollow noreferrer">https://cloud.google.com/speech-to-text/docs/transcribe-streaming-a...
<python><python-3.x><virtual><pyaudio><google-cloud-speech>
2023-01-17 07:23:02
0
710
Polb
75,142,908
8,723,790
eval vs string.split when getting values from .env (environment variable)
<p>In Python project I have a list of values stored in a .env file as environment variables. I wonder if it is better to use eval or string.split to get the values.</p> <ol> <li>eval</li> </ol> <p><em>.env</em></p> <pre><code>ANIMALS=[&quot;Cat&quot;,&quot;Dog&quot;] </code></pre> <p><em>code.py</em></p> <pre><code>ani...
<python><config><eval><strsplit><.env>
2023-01-17 07:02:18
0
301
Paul Chuang
75,142,751
7,177,478
sqlalchemy check foreign key refer data exist before insert?
<p>I'm new to the sqlalchemy and fastAPI. I wonder there is any way to check refer data automatically before inserting it. For example, I want to make sure that profile.user_id exists before adding a new profile, but I don't want to do it by myself. Is that possible? Below are my table settings.</p> <pre><code>class Us...
<python><sql><sqlite><sqlalchemy><fastapi>
2023-01-17 06:38:55
1
420
Ian
75,142,692
9,377,382
Boto 3 AWS data quality unable to get data_quality result?
<p>I am running a AWS Glue job with data quality check. Using boto3 I am trying to the data quality result by following snippet. But I am unable to get the result. Result ID I am referring to seem to be correct, and I am using current credentials as I can invoke jobs from my code.</p> <pre><code>import boto3 client = b...
<python><amazon-web-services><boto3><aws-glue>
2023-01-17 06:30:11
0
385
Dhivakhar Venkatachalam
75,142,623
5,278,594
Using preorder traversal go binary tree to store elements in a list
<p>I am trying to write a code to implement pre-order traversal of a binary tree and store element in a list. I am using a helper function called <code>pre_util</code> as defined below;</p> <pre><code>def pre_util(root, L): if root is None: return L.append(root) pre_util(root.left, L) pr...
<python><recursion><tree>
2023-01-17 06:21:49
1
1,483
jay
75,142,546
4,321,525
plotting a boolean array as a translucent overlay over a graph with matplotlib
<p>I want to plot the <code>True</code> parts of a boolean array as translucent boxes over another plot.</p> <p>This sketch illustrates what I envision. I know I could do that with Asymptote, but I (among other reasons) need to verify that the data I work with is concise. I can supply example code of a graph and a bool...
<python><matplotlib>
2023-01-17 06:11:29
1
405
Andreas Schuldei
75,142,308
10,844,937
How to merge dataframe and series?
<p>I have a <code>dataframe</code> and a <code>series</code> which are as following.</p> <pre><code>_df = pd.DataFrame({'a': [1, '', '', 4], 'b': ['apple', 'banana', 'orange', 'pear']}, columns=['a', 'b']) _series = pd.Series(['', 2, 3, ''], name=&quot;a&quot;) </code></pre> <p>Here I would like to merge the <code>data...
<python><pandas>
2023-01-17 05:38:50
2
783
haojie
75,142,270
5,901,318
how to call form method from template for dynamic form in django
<p>I have a model that one of it's field is CharField, use to store a JSON (list of dictionary) called 'schema'</p> <pre><code>SCHEMA_DATA_TYPES=( (1, 'Integer'), (2, 'String'), (3, 'Date'), ) class MailTemplate(models.Model): name = models.CharField(max_length=20) tfile = models.FileField(upload_to='up...
<python><django>
2023-01-17 05:31:35
0
615
Bino Oetomo
75,142,234
10,829,044
pandas merge using list columns and contains operation
<p>I have two dataframes that are given below</p> <pre><code>multi_df = pd.DataFrame({'multi_project_ID': [&quot;Combo_1&quot;,&quot;Combo_2&quot;,&quot;Combo_3&quot;,&quot;Combo_4&quot;], 'multi_items':[['Chips','Biscuits','Chocolates'],['Alcoholic Drinks','Juices','Fruits'],['Plants','Veggies','Chips']...
<python><pandas><list><dataframe><merge>
2023-01-17 05:25:57
1
7,793
The Great
75,142,154
2,079,764
Refrehing the Django model after save and 5 second sleep get me old state, what's wrong?
<p>I was able to save the data to a Django model without any errors, but data not reflected in db. But after a sleep time I was able to save the data again with same method. What might be causing this ?</p> <p>I suspect use of the Google API, but was able to print the data before performing the save operation.</p> <pre...
<python><django><google-api>
2023-01-17 05:05:41
1
1,226
Rashi
75,142,131
17,696,880
Identify and replace using regex some strings, stored within a list, within a string that may or may not contain them
<pre class="lang-py prettyprint-override"><code>import re #list of names to identify in input strings result_list = ['Thomas Edd', 'Melissa Clark', 'Ada White', 'Louis Pasteur', 'Edd Thomas', 'Clark Melissa', 'White Eda', 'Pasteur Louis', 'Thomas', 'Melissa', 'Ada', 'Louis', 'Edd', 'Clark', 'White', 'Pasteur'] result...
<python><python-3.x><regex><replace><regex-group>
2023-01-17 04:59:59
1
875
Matt095
75,141,938
4,095,108
Spacy incorrectly identifying pronouns
<p>When I try this code using Spacy, I get the desired result:</p> <pre><code>import spacy nlp = spacy.load(&quot;en_core_web_sm&quot;) # example 1 test = &quot;All my stuff is at to MyBOQ&quot; doc = nlp(test) for word in doc: if word.pos_ == 'PRON': print(word.text) </code></pre> <p>The output shows <c...
<python><nlp><spacy>
2023-01-17 04:15:14
1
1,685
jmich738
75,141,898
4,309,170
HTTP Apis for MT4
<p>I'm exploring options to create RESTful APIs for MT4 without setting up EA. As an example, <a href="http://mt4.mtapi.be/index.html" rel="nofollow noreferrer">http://mt4.mtapi.be/index.html</a> - is just what I want to create.</p> <p>However, the problem is that I'm not entirely sure if its possible to do so without ...
<python><zeromq><metatrader4><mt4>
2023-01-17 04:04:37
1
628
Han
75,141,825
10,200,497
Groupby streak of numbers and a mask
<p>This is my pandas dataframe:</p> <pre><code>df = pd.DataFrame({'a': [10, 20, 1, 55, 66, 333, 444, 1, 2, 10], 'b': [1,1, 1, -1, -1, -1, -1, 1, 1, -1]}) </code></pre> <p>And this is the way that I need it after using <code>groupby</code>. I want all of 1s in b and two -1 after the streak of 1s. For example the first g...
<python><pandas><group-by>
2023-01-17 03:48:44
1
2,679
AmirX
75,141,805
15,298,943
Python - having trouble selecting single value from json data
<p>I have the following code from which I want to select a singular piece of data from the JSON.</p> <p>I have the following code from which I want to select a singular piece of data from the JSON.</p> <pre><code> j = { &quot;data&quot;: [ { &quot;astronomicalDawn&quot;: &quot;2023-01-16T04:5...
<python><json><python-requests>
2023-01-17 03:44:56
1
475
uncrayon
75,141,692
1,715,153
How to get all fish shell commands from a python script?
<p>When I run <code>complete -C</code> from my regular terminal fish shell I get a list of ~4k commands, which is great. I want this to happen from my python script. I have the following but it doesn't work:</p> <pre class="lang-py prettyprint-override"><code>command = &quot;fish -c 'complete -C'&quot; output = ( ...
<python><command><command-line-interface><fish><completion>
2023-01-17 03:20:34
2
1,622
Ariel Frischer
75,141,642
10,200,497
Groupby streak of numbers and a mask to groupby two rows after each group
<p>This is my dataframe:</p> <pre><code>df = pd.DataFrame({'a': [20, 1, 55, 333, 444, 1, 2, 10], 'b': [20, 20, 21, 21, 21, 22, 22, 22]}) </code></pre> <p>I want to group them by column <code>b</code> and two rows after each group. This is the output that I need:</p> <pre><code> a b 0 20 20 1 1 20 2 55 21...
<python><pandas><group-by>
2023-01-17 03:07:01
1
2,679
AmirX
75,141,639
143,397
Python: how to manage a variable's lifetime beyond a single function?
<p>I'm looking to better understand how Python can be used to guarantee resource release when the lifetime of the resource extends beyond a single function.</p> <p>The go-to answer for the general problem of ensuring a resource is released, is to use a <code>with</code> statement, and sometimes to create a context mana...
<python><resources><lifetime><with-statement><raii>
2023-01-17 03:06:33
0
13,932
davidA
75,141,589
19,009,577
Why does multiprocessing not speed up my code
<p>I was trying to test the extent to which multiprocessing could speed up code, so I did this:</p> <pre><code>rom pathos.multiprocessing import Pool def wm(): l = [] for i in range(1000): for j in range(1000): l.append(i+j) return l def m(): with Pool() as pool: return pool...
<python><optimization><multiprocessing>
2023-01-17 02:55:56
0
397
TheRavenSpectre
75,141,543
10,829,044
Pandas filter a list of items present in a column
<p>I have a dataframe like as below</p> <pre><code>df = pd.DataFrame({'text': [&quot;Hi how&quot;,&quot;I am fine&quot;,&quot;Ila say Hi&quot;], 'tokens':[['Hi','how'],['I','am','fine'],['Ila','say','Hi']], 'labels':[['A','B'],['C','B','A'],['D','B','A']]}) </code></pre> <p>I woul...
<python><pandas><list><dataframe><filter>
2023-01-17 02:46:57
1
7,793
The Great