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,089,538
7,585,973
How to crosstab distance in pandas
<p>Here's my Input</p> <pre><code>City Logitude Latitude A 2 2 B 5 6 C 8 10 </code></pre> <p>Here's my Output, calculation using Pythagoras formula</p> <pre><code> A B C A 0 5 10 B 5 0 5 C 10 5 ...
<python><pandas>
2023-01-11 22:10:39
1
7,445
Nabih Bawazir
75,089,386
20,107,918
DataFrame cleanup: join/concatenate non-NaN values when there is NaN in-between rows (spin-off from row with 'unique' record))
<p>I created a data-capturing template. When imported into Python (as DataFrame), I noticed that some of the records spanned multiple rows.<br /> I need to clean up the spanned record (see expected representation).</p> <p>The 'Entity' column is the anchor column. Currently, it is not the definitive column, as one can s...
<python><dataframe><join><vectorization><nan>
2023-01-11 21:53:14
0
399
semmyk-research
75,089,175
154,154
Accessing Minio with a self signed certificate and the Python client library
<p>We have an instance of minio running with a certificate that is signed by our corporate CA. Accessing it with S3 Browser works perfect. Now I try to write a python script to upload files. I try to use the windows cert store to get my CA certs</p> <pre><code>myssl = ssl.create_default_context() myhttpclient = urllib...
<python><python-3.x><minio><urllib3>
2023-01-11 21:27:27
0
753
nojetlag
75,088,921
7,875,444
VS CODE and python import path confusion
<p>I'm trying to understand the appropriate settings for vs code so that I can import local .py files from different sub directories in my vs code project. I ended up solving my problem by adding sub directories I need to import from to <code>PYTHONPATH</code> in my <code>.env</code> file like so: <code>PYTHONPATH = &q...
<python><visual-studio-code>
2023-01-11 20:56:11
1
338
ablanch5
75,088,743
4,150,078
How to enumerate keys from list and get values without hardcoding keys?
<p>How to enumerate keys from list and get values without hard coding keys? <code>my_list</code> contains tuples and I am trying to generate dictionary based on the position of the tuple in list. <code>num</code> in <code>enumerate</code> gives number like 0, 1,2, ...etc.</p> <pre><code>my_list = [(1,2),(2,3),(4,5),(8,...
<python><python-3.x><dictionary>
2023-01-11 20:35:05
2
2,158
sharp
75,088,724
10,401,171
Managing optional dependencies in __init__.py
<p>I am developing a python package K (so it has an <code>__init__.py</code>).</p> <p>Such package contains different sub-packages, each about a different part of my work, Let us call one of these M (so it also has its own <code>__init__.py</code>).</p> <p>Now M has 2 modules A and B containing one or more functions ea...
<python><python-3.x><import><dependency-management>
2023-01-11 20:33:18
1
446
Michele Peresano
75,088,655
12,764,795
How to calculate the areas under the spikes (interference) of a curve in Python
<p><strong>What I'm trying to do</strong></p> <p>I got an <code>np.array</code> with frequencies (x) and an <code>np.array</code> with the signal strength / power spectral density (y). The signal without any noise looks similar to a logarithmic curve, but might have a slightly different form, depending on the data.</p>...
<python><numpy><scipy><filtering><curve-fitting>
2023-01-11 20:25:05
1
1,624
Marco Boerner
75,088,637
5,992,641
Do PySpark window functions affect the write operation?
<p>I am having trouble writing a PySpark dataframe (~50 columns and ~9 million rows) to an S3 bucket, and I have isolated the problem, though I am not sure why the problem occurs.</p> <p>The following runs quite quickly (&lt; 1 minute):</p> <pre><code># Runs &lt; 1 minute df.write.format('parquet') \ .option(&quot;...
<python><apache-spark><amazon-s3><pyspark>
2023-01-11 20:22:55
0
303
gm1991
75,088,415
20,589,275
How to make graph matplotlib
<p>I have got an a frames in numpy:</p> <pre><code>php = np.array([282, 804, 1209, 1558, 1368, 1208, 594, 224]) js = np.array([273, 902, 1355, 1647, 1501, 1424, 678, 186]) html = np.array([229, 626, 865, 1275, 1134, 959, 446, 138]) html5 = np.array([227, 596, 764, 879, 715, 610, 264, 67]) my_sql = np.array([218, 620, 9...
<python><matplotlib>
2023-01-11 19:58:56
2
650
Proger228
75,088,245
15,229,310
decrease mandatory parameters (change method signature) on overriden method best practices (i.e. to avoid pylint errors)
<p>I have a generic parent class with mymethod and specific child class, where some parameters required for mymethod are known - user of child don't even need to know about them. I want to override mymethod so it only require param1, however pylint complains about inherited method changed signature - W0221: Number of ...
<python><pylint>
2023-01-11 19:42:32
1
349
stam
75,088,079
11,194,619
Rolling window groupby on panel data
<p>The goal is to perform a grouped rolling-window calculation on panel data. If possible, avoiding the use of <code>apply</code> and similar functions that perform slowly when there are many observation groups. Consider the following longitudinal data frame of customers with monthly sales:</p> <pre><code>customers = p...
<python><pandas><time-series>
2023-01-11 19:25:24
1
454
Raisin
75,087,691
5,058,757
Solve Stable Marriages Problem using constraint programming - BoundedLinearExpression object is not iterable
<p>I'm taking a course on <a href="https://www.coursera.org/learn/discrete-optimization" rel="nofollow noreferrer">Discrete Optimization</a>, and we're working through constraint programming. In a topic about reification, we're working through the <a href="https://en.wikipedia.org/wiki/Stable_marriage_problem" rel="nof...
<python><or-tools><constraint-programming>
2023-01-11 18:44:21
1
3,817
azizj
75,087,550
5,036,928
Request proxies to access PyPI
<p>I am trying to screenscrape PyPI packages using the requests library and beautiful soup - but am met with an indefinite hang. I am able to retrieve html from a number of sites with:</p> <pre><code>session = requests.Session() session.trust_env = False response = session.get(&quot;http://google.com&quot;) print(respo...
<python><http><https><python-requests><http-headers>
2023-01-11 18:28:32
4
1,195
Sterling Butters
75,087,483
1,294,072
How to detect colored blocks in a PDF file with python (pdfminer, minecart, tabula...)
<p>I am trying to extract quite a few tables from a PDF file. These tables are sort of conveniently &quot;highlighted&quot; with different colors, which makes it easy for eyes to catch (see the example screenshot).</p> <p>I think it would be good to detect the position/coordinates of those colored blocks, and use the c...
<python><pdf><shapes><pdfminer>
2023-01-11 18:21:56
2
746
xyliu00
75,087,444
3,788,557
Unable to import python package in vs-code but, no issues in terminal
<p>I'm trying to use <a href="https://github.com/uber/orbit" rel="nofollow noreferrer">https://github.com/uber/orbit</a>. I have the package installed without errors as far as I can see.</p> <p>I can run everything just fine in my terminal on my mac. However, I load up vs-code and try and run there and I receive the ...
<python><visual-studio-code>
2023-01-11 18:18:35
0
6,665
runningbirds
75,087,401
7,506,883
How to encase the value of a yaml in single quotes after a dictionary <> yaml serialization
<p>I'd like to convert my dictionary to a YAML document, where the keys are rendered without quotes, but the values are encased in single quotes.</p> <p>I found several solutions to encase both the key and value in a single quote, but that's not what I'd like. Below you can see an example script:</p> <pre><code>import...
<python><yaml><pyyaml>
2023-01-11 18:14:21
1
1,791
Dom DaFonte
75,087,363
11,883,900
Delete item from a list of Dictionaries
<p>I have a quick one.</p> <p>I do have a long list of dictionaries that looks like this:</p> <pre><code>mydict = [{'id': '450118', 'redcap_event_name': 'preliminary_arm_1', 'redcap_repeat_instrument': '', 'redcap_repeat_instance': '', 'date_today': '2022-11-04', 'timestamp': '2022-11-04 10:49', 'doc_source...
<python><dictionary>
2023-01-11 18:10:35
2
1,098
LivingstoneM
75,087,330
20,589,275
How to make graph in matplotlib
<p>I'm not good at matplotlib, I need your help, I have an upload of this format by year from 2015-2022:</p> <pre><code>PHP:282 JavaScript:273 HTML:229 HTML5:227 MySQL:218 CSS:217 CSS3:203 PHP5:184 jQuery:168 1С:168 </code></pre> <p>I need to do something like a visual graph - from the bottom - the year, on the left - ...
<python><matplotlib>
2023-01-11 18:07:55
1
650
Proger228
75,087,105
10,309,712
Computing the Fourier-transform of each column for each array in a multidimensional array
<p>In the following <code>4D</code> array, each column represents an attribute for machine learning model development.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from scipy.fft import fft, fftfreq, fftshift A = np.array([ [[[0, 1, 2, 3], [3, 0, 1, 2], ...
<python><arrays><numpy><multidimensional-array><fft>
2023-01-11 17:47:42
1
4,093
arilwan
75,087,029
9,494,140
ModuleNotFoundError: No module named 'requests.adapters' when using pyfcm
<p>I'm trying to use <code>pyfcm</code> library in my django project , by adding it to <code>requiements.txt</code> but I noticed that it is getting an error that mainly comes because of trying to import from <code>requests</code> library .. here is the error :</p> <pre><code>rolla_django | from pyfcm import ...
<python><django><python-requests><pyfcm>
2023-01-11 17:41:32
1
4,483
Ahmed Wagdi
75,086,562
10,710,625
Filter rows from a grouped data frame based on string columns
<p>I have a data frame grouped by multiple columns but in this example it would be grouped only by <code>Year</code>.</p> <pre><code> Year Animal1 Animal2 0 2002 Dog Mouse,Lion 1 2002 Mouse 2 2002 Lion 3 2002 Duck 4 2010 Dog Cat 5 2010 Cat 6 20...
<python><pandas><dataframe><filter><data-manipulation>
2023-01-11 16:58:57
2
739
the phoenix
75,086,526
2,377,957
Can only use .dt accessor with datetimelike values pandas
<p>This seems to be a new error for previously well running code. Probably user error...</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from io import StringIO df = pd.read_csv(StringIO(&quot;&quot;&quot; transactionDate 2022-08-01T00:00:00.000-04:00 2021-09-01T00:00:00.000-04:00 2022-08-01T00...
<python><pandas><datetime><timezone>
2023-01-11 16:55:29
1
4,105
Francis Smart
75,086,422
3,165,683
AUC 1, but accuracy <100%
<p>When testing a binary classifier I get an accuracy of 83% (when the threshold is set to 0.5) however when I workout the ROC and AUC I get an AUC value of 1, which I believe is incorrect as in this case I should be getting an accuracy of 100?</p> <p>I have the following data (first 5 points for example):</p> <p>True ...
<python><machine-learning><scikit-learn><roc><auc>
2023-01-11 16:47:36
1
377
user3165683
75,086,387
705,113
How to filter a dataframe by the mean of each group using a on-liner pandas code
<p>I'm trying to filter my dataset so that only the rows that, for a given column, have values larger than the mean (or any other function) of that column.</p> <p>For instance, suppose we have the following data frame:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ &quo...
<python><pandas><group-by><filtering>
2023-01-11 16:44:46
1
693
an_drade
75,086,370
5,920,187
Custom Python Azure IoT Edge Module "No such file or directory: ''"
<p>I'm trying to debug my custom Azure IoT Edge module in Python using Visual Studio Code, however when I run</p> <p><code>client = IoTHubModuleClient.create_from_edge_environment()</code></p> <p>I get the following error:</p> <pre><code>Exception has occurred: FileNotFoundError [Errno 2] No such file or directory: '' ...
<python><visual-studio-code><azure-iot-hub><azure-iot-edge>
2023-01-11 16:43:11
2
331
jcbrowni
75,086,308
7,475,193
Function returns None- Python
<p>I call an exchange API. When I try to put it as a function, it returns <code>None</code>:</p> <pre><code>def getCurrentExchange(source, target): &quot;&quot;&quot;The function takes the source - source and target currency - target and extract the rate as of now&quot;&quot;&quot; url = 'https://api.exchangera...
<python>
2023-01-11 16:38:02
1
477
eponkratova
75,086,302
979,099
Navigating JSON with variable keys in Python?
<p>Lets say I have some json like so store in a variable called <code>data</code></p> <pre class="lang-json prettyprint-override"><code>{ &quot;print&quot;: { &quot;ams&quot;: { &quot;exists&quot;: 1}, &quot;fan_speed&quot;: 29, &quot;reports&quot;: [ {&quot;name&quot;: &quot;foo&quot;}, {&quo...
<python><json><python-3.x>
2023-01-11 16:37:15
1
6,315
K20GH
75,086,141
5,889,169
Django - how to remove INFO logs of "channels" package
<p>I recently started using the <a href="https://channels.readthedocs.io/en/stable/" rel="nofollow noreferrer">channels</a> package in Django (versions: <code>channels==3.0.4</code> and <code>channels-redis==3.3.1</code>)</p> <p>The application is sending massive amount of unwanted logs for each request i make to Djang...
<python><django><logging><redis><channel>
2023-01-11 16:24:26
0
781
shayms8
75,086,138
4,865,723
Combine two sort conditions one ascending the other descending
<p>I would like to combine two sort conditions but one is ascending the other descending.</p> <p>The input data are this list of tuples:</p> <pre><code>data = [ ('Apple', 4), ('Cherry', 5), ('Ananas', 4), ('Blueberry', 3), ('Banana', 3) ] </code></pre> <p>The sorting conditions:</p> <ol> <li>2nd tup...
<python><sorting>
2023-01-11 16:23:47
1
12,450
buhtz
75,085,943
19,633,374
Generate holiday data using python holidays library
<p>I want to create a datafarme with the holidays using the python holiday library.</p> <pre><code>from datetime import date import holidays us_holidays = holidays.US() date(2015, 1, 1) in us_holidays # True date(2015, 1, 2) in us_holidays # False </code></pre> <p>I want to create a dataframe with dates and holiday ...
<python><dataframe><python-holidays>
2023-01-11 16:09:04
2
642
Bella_18
75,085,847
11,729,210
Install local package through a Dockerfile
<p>I have started learning Docker and I have developed a Python package (not published anywhere, it is just used internally) that installs and works fine locally (here I will call it <code>mypackage</code>). However, when trying to install it in a Docker container, Python in the container fails to recognise it even tho...
<python><docker><pip><dockerfile><virtualenv>
2023-01-11 16:01:37
0
375
André Lourenço
75,085,758
1,127,776
function from_dict() failing for unknown reason in python
<p>I converted below JSON using <a href="https://json2csharp.com/code-converters/json-to-python" rel="nofollow noreferrer">https://json2csharp.com/code-converters/json-to-python</a> to a dataclass:</p> <pre><code>{ &quot;bypassCd&quot;: [ &quot;Duis sint ipsum in&quot;, &quot;consequat&quot; ...
<python><json><python-dataclasses>
2023-01-11 15:54:32
2
1,092
jimsweb
75,085,734
9,212,995
What is the best way to raise an exception in case of BadHeaderError in django unit testing?
<p>Tests fail with an error response meaning that it is likely to be allowing email with wrong data and yet it should throw an HttpResponse as expected, I have tried to figure it out why my test is failing and returning 200 http status code but not as expected = 400.</p> <h1>reset password</h1> <pre><code>class ResetPa...
<python><django><django-rest-framework><django-views><django-forms>
2023-01-11 15:52:52
1
372
Namwanza Ronald
75,085,728
13,494,917
How to further specify an exception when there are two different errors under the same exception class
<p>I have two different errors under the same exception class that I want to handle differently.</p> <p>1.</p> <blockquote> <p>Exception: ProgrammingError: (pyodbc.ProgrammingError) ('42S22', &quot;[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'newCol'. (207) (SQLExecDirectW); [42S22...
<python><exception>
2023-01-11 15:52:32
0
687
BlakeB9
75,085,724
1,792,858
How to enforce microseconds with datetime()?
<p>I'd like <code>date2</code> to output <code>2023-01-11 14:00:00.000000</code> to have a predictable format.</p> <pre><code>from datetime import datetime date1 = datetime(2023, 1, 11, 14, 0, 0, 123456) date2 = datetime(2023, 1, 11, 14, 0, 0) print(date1) # 2023-01-11 14:00:00.123456 print(date2) # 2023-01-11 14:00...
<python><python-3.x><datetime>
2023-01-11 15:51:58
0
8,825
Mr. B.
75,085,591
891,919
Gensim ensemblelda multiprocessing: index -1 is out of bounds for axis 0 with size 0
<p>I'm using the <a href="https://radimrehurek.com/gensim/" rel="nofollow noreferrer">gensim library</a> for topic modelling, more precisely the <a href="https://radimrehurek.com/gensim/models/ensemblelda.html" rel="nofollow noreferrer">Ensemble LDA</a> method. My code is fairly standard (I follow the documentation), t...
<python><nlp><multiprocessing><gensim>
2023-01-11 15:43:08
1
1,185
Erwan
75,085,016
5,869,076
Run Celery tasks on Railway
<p>I deployed a Django project in Railway, and it uses Celery and Redis to perform an scheduled task. The project is successfully online, but the Celery tasks are not performed.</p> <p>If I execute the Celery worker from my computer's terminal using the Railway CLI, the tasks are performed as expected, and the results ...
<python><django><celery><django-deployment>
2023-01-11 14:58:27
1
611
Jim
75,085,009
1,921,666
How to type hint a function, added to class by class decorator in Python
<p>I have a class decorator, which adds a few functions and fields to decorated class.</p> <pre class="lang-py prettyprint-override"><code>@mydecorator @dataclass class A: a: str = &quot;&quot; </code></pre> <p>Added (via <code>setattr()</code>) is a <code>.save()</code> function and a set of info for dataclass fie...
<python><python-decorators><python-typing>
2023-01-11 14:57:54
1
412
chersun
75,084,859
6,304,433
How can I disallow mypy `type: ignore` comments?
<p>I would like for <code>mypy</code> to ignore or disallow any <code># type: ignore</code> comments.</p> <p>Is this possible, short of modifying source files to remove the comments?</p> <p>Looking for the equivalent of <a href="https://flake8.pycqa.org/en/latest/user/options.html#cmdoption-flake8-disable-noqa" rel="no...
<python><python-typing><mypy>
2023-01-11 14:46:40
0
618
Gabriel G.
75,084,852
7,556,397
How can I transform columnar hierarchy into parent child list in Pandas?
<p>I am trying to transform a hierarchy that use a columnar format with a fixed number of columns (many of them being null) into an adjacency list, with child and parent, using the Pandas library.</p> <h2>example hierarchy</h2> <p>Here is a fictitious example with 5 hierarchical levels:</p> <pre><code> ...
<python><pandas>
2023-01-11 14:46:23
3
1,420
Lionel Hamayon
75,084,839
5,502,306
Finding python on Apple Silicon
<p>I have installed Python on my Apple Silicon (ARM64) machine, but it installs it as <code>python3</code> and not <code>python</code>.</p> <p>The problem is that I have a <code>node.js</code> project with dependencies which need python (and pip). They fail to build because they are unable to find <code>python</code>.<...
<python><macos>
2023-01-11 14:44:47
1
4,776
chughts
75,084,737
8,869,570
Is copy() still needed for extracting a subset of a pandas dataframe?
<p>In the codebase I'm working in, I see the following</p> <pre><code>df1 = some pandas dataframe (one of the columns is quantity) df1_subset = df1[df1.quantity == input_quantity].copy() </code></pre> <p>I am wondering why the <code>.copy()</code> is needed here? Doesn't <code>df1_subset = df1[df1.quantity == input_qua...
<python><pandas><dataframe>
2023-01-11 14:37:22
0
2,328
24n8
75,084,713
7,048,760
How to use docker secrets in docker-compose and python app?
<p>I'm trying to use <code>docker secret</code> to store username and password. I did the following:</p> <p><strong>Step 1: Initiate docker swarm</strong></p> <p><code>docker swarm init</code></p> <p><strong>Step 2: Create docker secrets</strong></p> <p><code>echo &quot;username&quot; | docker secret create app_usernam...
<python><docker-compose><docker-secrets>
2023-01-11 14:35:26
0
865
Kuni
75,084,692
3,623,723
export pyplot figure to PNG without antialias
<p>I'd like to generate high-resolution raster images from pyplot figures, <strong>without antialias</strong> (why? See below)</p> <p>Some time ago, on Python 2.7 and Matplotlib 1.5, I worked out two processes for this:</p> <ol> <li><code>plt.savefig()</code> to PDF, and then manually import into GIMP at 1200dpi or hig...
<python><matplotlib>
2023-01-11 14:34:08
0
3,363
Zak
75,084,665
13,950,870
'Application not responding' when running opencv imshow() in Jupyter notebook extension inside VSCode
<p>Very simple code</p> <pre><code>import cv2 cap = cv2.VideoCapture('../data/videos/cat.mp4') ret, frame = cap.read() cv2.imshow('Hi', frame) cv2.waitKey(0) cv2.destroyAllWindows() </code></pre> <p>It opens the first frame as expected and shows it. When I press a key however, python refuses to respond and I get <code...
<python><opencv><visual-studio-code><jupyter-notebook>
2023-01-11 14:32:38
0
672
RogerKint
75,084,637
1,999,585
How can I draw bars close to each other in matplotlib's bar function?
<p>I have this bar chart, obtained in Seaborn, using <code>barplot</code>:</p> <p><a href="https://i.sstatic.net/WVTmZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/WVTmZ.png" alt="Seaborn picture" /></a></p> <p>I have the bar chart for the same dataset, obtained by Matplotlib's <code>bar</code>: <a hr...
<python><matplotlib><seaborn>
2023-01-11 14:30:24
1
2,424
Bogdan Doicin
75,084,605
4,380,853
PyFlink: What's the best way to provide reference data and keep them uptated
<p>I have a use case where I want to do comparisons between incoming data and some reference data provided by another service.</p> <p>What's the best way in <code>pyflink</code> to fetch those data and update them regularly (in intervals of 1-2 hours)</p> <p>Other considerations:</p> <ul> <li>The reference data may con...
<python><apache-flink><pyflink>
2023-01-11 14:28:56
0
2,827
Amir Afianian
75,084,586
15,279,420
Is there a way to import variables and connections to MWAA?
<p>I have a MWAA environment and I have to create another one by Terraform. The environment creation is not an issue, but the 'metadata' of my old enviroment. I want to import all variables and connections, programatically, but I haven't figured out so far.</p> <p>I tried to change a few things in this <a href="https:/...
<python><amazon-web-services><airflow><mwaa>
2023-01-11 14:26:44
2
343
Luis Felipe
75,084,570
11,269,090
Python pandas dict to csv with one header only
<p>I have some data in a dict that I would like to save as an csv file with pandas:</p> <pre><code>data = { &quot;a&quot;: 1, &quot;c&quot;: 2, &quot;d&quot;: 3, } </code></pre> <p>Which I am trying to save it in this format:</p> <p><a href="https://i.sstatic.net/ojOCl.png" rel="nofollow ...
<python><pandas>
2023-01-11 14:25:55
3
1,010
Chen
75,084,549
6,694,814
Python folium - Markercluster not iterable with GroupedLayerControl
<p>I would like to group my 2 marker cluster layers, where one is reliant on the other by providing a separate styling. Hence the second one is set as control=False. Nevertheless, I want to have it disappear when the first one is switched off.</p> <p>Along with the new Python folium issue v.0.14 I found, that the new f...
<python><folium>
2023-01-11 14:24:27
2
1,556
Geographos
75,084,508
14,269,252
Filter different data frame and merge the results
<p>I have different DataFrames, they have a common column (id), as the data is huge, I want to filter all DataFrames on a list of values defined in (lis) and then merge all the newly built DataFrames on a common column. I implemented it, as follows, it is slow and have many duplicate.I am not sure if my answer is corre...
<python><pandas><dataframe>
2023-01-11 14:21:31
1
450
user14269252
75,084,453
702,846
populate SQL database with dask dataframe and dump into a file
<p>reproduce the error and the use case on <a href="https://colab.research.google.com/drive/1ynvOxOm3Kbf_qW7xJa-_glp_iMFi9Plc?usp=sharing" rel="nofollow noreferrer">this colab</a></p> <p>I have multiple large tables that I read and analyze through Dask (dataframe). After doing analysis, I would like to push them into a...
<python><sqlite><sqlalchemy><dask><dask-dataframe>
2023-01-11 14:17:09
1
6,172
Areza
75,084,390
7,626,198
Python. Read QDateTime from file with QDataStream
<p>I have a binary file created with <code>QDataStream</code>.</p> <p>QDataStream has functions to read int, float, QString, etc. But I don't find the function to read <code>QDatatime</code></p> <p>My file includes <code>QDatatime</code>. But I don't find the function to read <code>QDatatime</code> How can I read the <...
<python><pyqt5>
2023-01-11 14:12:25
1
442
Juan
75,084,328
5,510,540
Python: Venn diagram from score data
<p>I have the following data:</p> <pre><code>df = id testA testB 1 3 NA 1 1 3 2 2 NA 2 NA 1 2 0 0 3 NA NA 3 1 1 </code></pre> <p>I would like to create a Venn diagram of the number of times that testA and testB appear, testA but not testB, and testB but not testA.</p> <p>The expected ou...
<python><venn>
2023-01-11 14:07:15
2
1,642
Economist_Ayahuasca
75,084,322
2,897,989
List all files/modules imported but nothing else in Python?
<p>I'm working with some code that's been handed off to me by someone else. I need to reuse some parts of the project, but not all. I'm basically adding a Flask server that hosts a single function from all the project.</p> <p>I'm packaging it into a docker image, and I want to keep it as lightweight as possible. For th...
<python><module>
2023-01-11 14:06:37
0
7,601
lte__
75,084,238
4,838,024
Python XGBoost Month Variables - One Hot Encoding versus Numeric
<p>I'm training a model using XGBoost in Python. One of my variables is month (Jan, Feb, Mar, ...)</p> <p>What is the correct way to do this, and would there be any difference in performance/evaluation metrics between the methods of:</p> <ol> <li>One hot encoding of the 12 months, so 12 new variables taking on either 0...
<python><tree><xgboost>
2023-01-11 14:00:50
1
361
tpoh
75,084,205
13,184,183
How to add file to docker container?
<p>I work with the airflow operators and mlproject. So the pipeline looks like the following : I define airflow operator, in which I specify entry point of MLProject and parameters for the program, then it turns to MLProject file where running command is specified, so it has the following form:</p> <pre class="lang-py ...
<python><docker><airflow>
2023-01-11 13:58:10
1
956
Nourless
75,084,163
9,715,816
Use PostGIS geometry types in SQLModel
<p>Is it possible to use PostGIS geometry types in models created in SQLModel? If yes, how can it be done?</p>
<python><postgis><sqlmodel><geoalchemy2>
2023-01-11 13:55:54
1
2,019
Charalamm
75,084,155
3,025,981
Use npt.NDArray[np.uint64] to query pd.DataFrame
<p>I'm trying to understand how to properly use type annotations with pandas and numpy. I have a DataFrame indexed with an index of dtype <code>np.uint64</code>. I want to write a function that returns a subset of this DataFrame in the following way:</p> <pre class="lang-py prettyprint-override"><code>import numpy as n...
<python><pandas><numpy><python-typing>
2023-01-11 13:55:15
1
8,187
Ilya V. Schurov
75,084,082
536,262
openldap noopsrch overlay with pythons ldap3 search
<p>We use the <a href="https://ltb-project.org/documentation/openldap-noopsrch.html" rel="nofollow noreferrer">https://ltb-project.org/documentation/openldap-noopsrch.html</a> overlay on openldap.</p> <p>It gives you the number of entries in each catalog without having to browse all.</p> <p>example show <code>-e '!1.3....
<python><ldap><openldap>
2023-01-11 13:49:57
1
3,731
MortenB
75,084,013
2,248,271
concat result of apply in python
<p>I am trying to apply a function on a column of a dataframe. After getting multiple results as dataframes, I want to concat them all in one.</p> <p>Why does the first option work and the second not?</p> <pre><code>import numpy as np import pandas as pd def testdf(n): test = pd.DataFrame(np.random.randint(0,n*100...
<python><concatenation>
2023-01-11 13:44:35
1
6,020
Wietze314
75,083,999
16,591,917
How do I find GEKKO application success status?
<p>I am running <code>m.solve()</code> in a <code>try .. except</code> construct to elegantly handle any exceptions raised by the solver due to maximum iterations or convergence to an infeasibility but want to interrogate APPINFO and APPSTATUS to determine if a solution was found. I was surprised to see that I always...
<python><gekko>
2023-01-11 13:43:52
1
319
JacquesStrydom
75,083,901
14,082,385
How can I count the number of times I call a loss function?
<p>I personalized my own Huber loss function in the way (<a href="https://goodboychan.github.io/python/coursera/tensorflow/deeplearning.ai/2022/02/08/01-Tensorflow2-Custom-Loss-Function.html" rel="nofollow noreferrer">https://goodboychan.github.io/python/coursera/tensorflow/deeplearning.ai/2022/02/08/01-Tensorflow2-Cus...
<python><tensorflow><keras><counter><loss-function>
2023-01-11 13:36:03
1
786
Theo Deep
75,083,737
11,479,825
How to save custom dataset in local folder
<p>I have created a custom huggingface dataset, containing images and ground truth data coming from json lines file. I want to save it to a local folder and be able to use it as is by loading it after to other notebooks. I did not find out how this can happen.</p> <pre><code>DatasetDict({ train: Dataset({ f...
<python><huggingface><huggingface-datasets>
2023-01-11 13:21:50
2
985
Yana
75,083,706
8,839,068
pandas: find maximum across column range; use second column range for tie breaks
<p>I have a data frame with two corresponding sets of columns, e.g. like this sample containing people and their rating of three fruits as well as their ability to detect a fruit ('corresponding' means that <code>banana_rati</code> corresponds to <code>banana_reco</code> etc.).</p> <pre><code>import pandas as pd df...
<python><pandas><random><max>
2023-01-11 13:20:00
2
4,240
Ivo
75,083,556
3,433,875
Parse XML to pandas using elementTree and python
<p>I have the following xml structure:</p> <pre><code>&lt;GL_MarketDocument xmlns=&quot;urn:iec62325.351:tc57wg16:451-6:generationloaddocument:3:0&quot;&gt; &lt;mRID&gt;352539b33d6245f88c0cea8c70c86e76&lt;/mRID&gt; &lt;revisionNumber&gt;1&lt;/revisionNumber&gt; &lt;type&gt;A75&lt;/type&gt; &lt;proce...
<python><python-3.x><pandas><xml><elementtree>
2023-01-11 13:07:23
2
363
ruthpozuelo
75,083,550
859,227
Nested loop over dataframe rows
<p>I would like to perform a nested loop over a dataframe rows, considering the fact the inner loop starts from <code>outer_row + 1</code>. If I use</p> <pre><code>for o_index, o_row in df.iterrows(): L1 = o_row['Home'] L2 = o_row['Block'] for i_index, i_row in df.iterrows(): L3 = i_row['Home'] ...
<python><pandas>
2023-01-11 13:07:04
2
25,175
mahmood
75,083,527
12,236,313
Complex Django query involving an ArrayField & coefficients
<p>On the one hand, let's consider this Django model:</p> <pre><code>from django.db import models from uuid import UUID class Entry(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) value = models.DecimalField(decimal_places=12, max_digits=22) items = ArrayField(base_fie...
<python><django><django-models><django-queryset><django-orm>
2023-01-11 13:05:12
1
1,030
scūriolus
75,083,505
18,018,869
How to add a new "comment" or "flag" field to every model field of existing model?
<p>Disclaimer: I can wipe out the database anytime. So while answering this, please don't care about migrations and stuff.</p> <p>Imagine me having a model with multiple values:</p> <pre class="lang-py prettyprint-override"><code>class Compound(models.Model): color = models.CharField(max_length=20, blank=True, defa...
<python><django><django-models><django-forms>
2023-01-11 13:03:22
6
1,976
Tarquinius
75,083,359
8,628,566
Error when importing torch_geometric in Python 3.9.7
<p>I'm trying to install torch_geometric in a conda environment but I'm getting the following werror whenever I try to:</p> <pre><code>import torch_geometric </code></pre> <p>Error:</p> <pre><code>OSError: dlopen(/Users/psanchez/miniconda3/envs/playbook/lib/python3.9/site-packages/libpyg.so, 0x0006): Library not loaded...
<python><python-3.x><pytorch><pytorch-geometric>
2023-01-11 12:52:59
3
333
Pablo Sanchez
75,083,356
8,978,116
Tensorflow / CUDA: GPU not detected
<p>I have two Windows 11 laptops with NVIDIA GeForce RTX 3060 GPUs, which I want to run Tensorflow on.</p> <p>If that matters, both laptops are Lenovo Legion 5 laptops with &quot;GPU Working Mode&quot; set to &quot;Hybrid-Auto Mode&quot;.</p> <p>The first laptop has the following setup:</p> <pre><code>Python 3.10.7...
<python><tensorflow><tensorflow2.0>
2023-01-11 12:52:49
1
368
Chris Rahmé
75,083,293
7,540,393
Parse raw rst string using nested_parse
<p>I'm writing a sphinx extension that transforms a custom directive into a <code>flat-table</code>.</p> <p>From inside the <code>.run(self)</code> method, I build a complete <code>flat-table</code> declaration in pure <code>.rst</code>, and I'd like to feed that string into the internal parser, so it is transformed in...
<python><python-sphinx><docutils>
2023-01-11 12:47:40
1
2,994
Arthur Attout
75,083,276
8,354,581
Percentage of groupby in Pandas
<p>I have a dataframe that has columns 'team','home_or_away','result' to store the results ('W': win or 'L': loose) for teams 'X','Y','Z' in sporting events at home ('H') or away ('A'):</p> <pre><code>df = pd.DataFrame({'team': ['X', 'X', 'X', 'X', 'Y', 'Y', 'Z', 'Z', 'Z', 'Z'],'home_or_away':['H', 'A', 'A', 'A', 'H', ...
<python><pandas><group-by>
2023-01-11 12:46:15
2
379
korppu73
75,083,251
9,635,884
Calculate max along one dimension in tensorflow tensor
<p>I have tf tensor in the form of <em>[number_of_image, width, height, channel]</em>. The <em>channel</em> dim is optional and can be removed. I would like to calulate max value for each image. It should be as fast as possible and should work in graphic mode of tensorflow execution.</p> <p>Max calculation is for max n...
<python><tensorflow>
2023-01-11 12:43:57
1
363
Slawomir Orlowski
75,083,237
79,111
Is it possible to validate `argparse` default argument values?
<p>Is it possible to tell <code>argparse</code> to give the same errors on default argument values as it would on user-specified argument values?</p> <p>For example, the following will not result in any error:</p> <pre class="lang-py prettyprint-override"><code>parser = argparse.ArgumentParser() parser.add_argument('--...
<python>
2023-01-11 12:42:42
3
10,598
Ton van den Heuvel
75,083,216
7,797,210
Most computational-time efficient/fastest way to compute rolling (linear) regression in Python (Numpy or Pandas)
<p>I have a need to do very very fast and efficient way of rolling linear regression. I looked through these two threads :</p> <p><a href="https://stackoverflow.com/questions/15636796/efficient-way-to-do-a-rolling-linear-regression">Efficient way to do a rolling linear regression</a> <a href="https://stackoverflow.com/...
<python><pandas><numpy><time><linear-regression>
2023-01-11 12:40:30
3
571
Kiann
75,083,047
5,102,237
How to add decorator to dynamically create class
<p>I want to convert this code to be dynamic:</p> <pre><code>@external_decorator class Robot: counter = 0 def __init__(self, name): self.name = name def sayHello(self): return &quot;Hi, I am &quot; + self.name </code></pre> <p>I can create the class dynamically, this way:</p> <pre><code>de...
<python><dynamic><python-decorators>
2023-01-11 12:27:26
1
1,018
Grigory Ilizirov
75,083,037
981,831
Python.net "GIL" lifetime and multiple instances
<p>My desktop app uses IronPython to perform various scripting functions, but we're under pressure to support Numpy (which isn't possible with IP), so I'm currently looking into Python.Net instead, but I'm a bit unclear on how to manage the lifetimes of objects such as the GIL. Python.Net C# examples typically look lik...
<python><c#><python.net>
2023-01-11 12:26:46
1
10,315
Andrew Stephens
75,082,748
4,445,920
How to distribute parameterized pytest for testing in azure pieplines as different jobs
<p>I have a pytest file that has 1 test and and it is parameterized such that in total there are 100 different tests.</p> <p>I created a pipeline with 2 parallel jobs but when I start the jobs, both the jobs run all the 100 tests individually.</p> <p>What happens:</p> <pre><code>**Job 1 ----Test 1 ----Test 2 ... ...
<python><azure-pipelines><pytest>
2023-01-11 12:03:48
1
544
Manish
75,082,442
4,614,675
How to clear lru_cache across different processes - Python2.7
<p>I'm working on a Django project (version 1.11 - Python 2.7) and I need to create a new endpoint to clear all the methods cached using lru_cache decorator.</p> <p>In this project I have several cached functions like this one:</p> <pre class="lang-py prettyprint-override"><code>try: from functools import lru_cache...
<python><multithreading><python-2.7><caching><functools>
2023-01-11 11:38:24
1
5,618
Giordano
75,082,217
8,832,008
Crop function that slices triangles instead of removing them (open3d)
<p>I have a TriangleMesh in open3d and I would like to crop it using a bounding box.</p> <p>Open3d has the <a href="http://www.open3d.org/docs/latest/python_api/open3d.geometry.TriangleMesh.html#open3d.geometry.TriangleMesh.crop" rel="nofollow noreferrer">crop function</a>, which removes triangles if they are fully or ...
<python><open3d>
2023-01-11 11:20:25
1
1,334
cmosig
75,082,085
8,916,408
Error using bar_label to insert value labels on plot from dataframe, on Python with pandas and matplotlib
<p>I am trying to add value labels to a plot with matplotlib using bar_label. My data is from a DataFrame. I am getting the error <code>AttributeError: 'AxesSubplot' object has no attribute 'datavalues' </code>. I tried looking at different answers to similar problems here in StackOverflow and elsewhere, but I still do...
<python><pandas><matplotlib>
2023-01-11 11:08:55
2
423
Rafael Pinheiro
75,081,962
3,758,912
How to run Flask inside a Jupyter notebook block for easy testing?
<p>I want to Run a Flask Server inside a jupyter notebook for specific test and QA scenarios. I do understand that it is not wise to run a server inside notebook(As mentioned in the comments of this <a href="https://stackoverflow.com/questions/52457582/flask-application-inside-jupyter-notebook">question</a>).</p> <p>Ho...
<python><flask><jupyter-notebook>
2023-01-11 10:58:04
1
776
Mudassir
75,081,931
5,023,667
How to properly align text in an Excel cell using OpenPyXL so that it doesn't repeat or overflow
<p>I'm creating an Excel from scratch using openpyxl. Some of the cells are populated with long strings, if the string is too long, I want it to cut at the cell border and not overflow to the neighboring cell.</p> <p>This can be achieved using <code>Alignment(horizontal='fill')</code>, but then if the string is too sho...
<python><openpyxl>
2023-01-11 10:55:37
1
623
Shlomo Gottlieb
75,081,910
3,164,492
How to change a particular section of code at a mass scale?
<p>I want to scan a code base with approximately 150k python + java files and want to find a specific kind of hardcoding. For ex:</p> <pre><code># some code above if get_city() == 'Delhi': # they way of checking can be different like city = get_city() and then checking city == 'Delhi' country = 'India' else: co...
<python><java><parsing><code-generation>
2023-01-11 10:54:10
0
1,805
Devavrata
75,081,741
4,903,479
pandas dataframe subsetting showing NaN values
<p>I have two pandas dataframes df1 and df2 where age, Start_Time, End_Time are datetime64[ns] dtypes. I want to extract data points in df1 which are falling within any of Start_Time End_Time in df2</p> <pre><code>df1 age LAeq LSeq Doss LSeq Gliss LZeq 0 2019-05-14 15:40...
<python><python-3.x><pandas><numpy><datetime>
2023-01-11 10:40:35
1
583
shan
75,081,737
12,014,637
Tensorflow layer working outside of model but not inside
<p>I have a custom tensorflow layer which works fine by generating an output but it throws an error when used with the Keras functional model API. Here is the code:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.ke...
<python><tensorflow><keras><deep-learning>
2023-01-11 10:40:12
1
618
Amin Shn
75,081,705
4,432,671
Is there a right-left (foldr) reduction in NumPy?
<p>NumPy's <code>.reduce()</code> is a <code>foldl</code>, reducing left to right:</p> <pre><code>&gt;&gt;&gt; np.subtract.reduce(np.array([1, 2, 3])) -4 </code></pre> <p>So <code>(1-2)-3</code>. Is there a standard numpy way of doing <code>foldr</code> instead (right to left), that is to get <code>1-(2-3)</code> in th...
<python><numpy>
2023-01-11 10:37:51
1
3,737
xpqz
75,081,678
20,740,043
Plot-save-close a histogram in Python
<p>I have a data frame and wish to plot-save-close the histogram.</p> <p>These are the codes:</p> <pre><code>#Load the required libraries import pandas as pd import matplotlib.pyplot as plt #Create data data = {'Marks': [22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27]} ...
<python><python-3.x><pandas><matplotlib><plot>
2023-01-11 10:35:27
1
439
NN_Developer
75,081,504
2,713,740
flask pass variables from template to python
<p>I have the following code in my template HTML page:</p> <pre><code>&lt;form class=&quot;ui form&quot; action=&quot;{{ url_for('download_pdf', text=original_text) }}&quot; method=&quot;get&quot;&gt; &lt;button class=&quot;ui left floated submit button&quot; type=&quot;submit&quot;&gt;Export&lt;/button&gt; &lt;/fo...
<python><flask>
2023-01-11 10:22:14
1
11,086
Luca
75,081,499
4,094,231
Scrapy CSS Selectors not extracting all content inside
<p>Using Scrapy 2.5.1, I want to extract main article content from <a href="https://www.upi.com/Top_News/World-News/2023/01/01/N-Koerean-leader-calls-exponential-increase-nuclear-arsenal/4171672578401/" rel="nofollow noreferrer">https://www.upi.com/Top_News/World-News/2023/01/01/N-Koerean-leader-calls-exponential-incre...
<python><python-3.x><scrapy>
2023-01-11 10:21:56
1
21,655
Umair Ayub
75,081,331
16,173,560
Fill contours with OpenCV
<p>I have an image with a black background and some red outlines of polygons, like this:</p> <p><a href="https://i.sstatic.net/v6vNl.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/v6vNl.jpg" alt="enter image description here" /></a></p> <p>I want now to fill those polygons with the same colour, so they ...
<python><opencv><shapes><fill>
2023-01-11 10:08:48
1
323
OlegRuskiy
75,081,293
571,941
Downsize image when training yolov5 model
<p>I am looking into making my custom YoloV5 model faster, based on my current results where I have trained a on ~20k (1280 × 960) images with a configuration based on yolov5l6.yaml (A P6 model I assume)</p> <p>This gives me a very well performing model, and I would now like to explore smaller/simpler models.</p> <p>Op...
<python><yolo><yolov5>
2023-01-11 10:05:47
1
448
Jakob Halskov
75,081,128
12,260,268
Gcloud CLI using what APIs
<p>I've been thinking that how the <code>gcloud</code> work for a long time.</p> <p>Because I saw a bunch of python files in <code>./google-cloud-sdk</code> after I installed the <a href="https://cloud.google.com/sdk/docs/install#installation_instructions" rel="nofollow noreferrer">Google CLI</a> and used the tree comm...
<python><google-cloud-platform><gcloud>
2023-01-11 09:52:22
1
394
Tim Chiang
75,081,043
11,574,636
How to promote (Copy) a Docker image from one repository to another with JFrog Rest API
<p>I have a repository with all Docker Images. I want to copy all docker images from there to another repository that were used in the last 7 days. I must be a python script and I cannot use curl.</p> <p>I have figured out everything except the way to copy the image.</p> <pre><code>URL = &quot;https://repo.url/artifact...
<python><rest><post><artifactory>
2023-01-11 09:46:29
1
326
Fabian
75,080,993
14,098,117
DBusErrorResponse while running poetry install
<p>I tried to upgrade my poetry from 1.1.x version to 1.3 but as an official manual (<a href="https://python-poetry.org/docs/" rel="noreferrer">https://python-poetry.org/docs/</a>) recommends I removed the old version manually. Unfortunately I probably deleted wrong files because after installing 1.3 version I was stil...
<python><python-poetry>
2023-01-11 09:43:12
2
844
Emil Haas
75,080,992
2,425,753
Sum list of dicts of lists
<p>I have a list of dicts, every value in a dict is a four-element list:</p> <pre class="lang-py prettyprint-override"><code>my_dict=[ { 'prop1': [1, 2, 3, 4], 'prop2': [1, 1, 0, 0] }, { 'prop1': [2, 3, 3, 1], 'prop3': [1, 1, 0, 0] } ] </code></pre> <p>Is it possible to sum it up...
<python><list><loops><dictionary>
2023-01-11 09:43:10
3
1,636
rfg
75,080,918
1,974,918
Possible to calculate counts and percentage in one chain using polars?
<p>From seeing some of the other polars answers it seems most things can be complete in a single chain. Is that possible with the below example? Any simplifications possible?</p> <pre class="lang-py prettyprint-override"><code>import polars as pl scores = pl.DataFrame({ 'zone': ['North', 'North', 'North', 'South', ...
<python><dataframe><python-polars>
2023-01-11 09:36:03
1
5,289
Vincent
75,080,750
16,727,671
how to run .sql (mssql or sql server) file in python?
<p>Is there any ways to run .sql(sql server) file in python?</p> <p><strong>Python Code:</strong></p> <pre><code>import pyodbc,tempfile,os server_name = &quot;localhost&quot; db_name = &quot;abc&quot; password = &quot;1234&quot; local_path = tempfile.gettempdir() sqlfile = &quot;test.sql&quot; filepath = os.path.join(l...
<python><sql-server><pyodbc>
2023-01-11 09:22:54
1
448
microset
75,080,713
849,076
How do I make Babel use minus signs?
<p>Why is it that Babel does not use the minus sign used by my locale, in functions like <code>format_decimal()</code>? It seems to me like this would be the very job of a library like Babel.</p> <p>Is there a way I can enforce the usage of locale specific minus signs?</p> <pre><code>&gt;&gt;&gt; import babel &gt;&gt;&...
<python><python-babel>
2023-01-11 09:19:50
1
8,641
leo