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
79,280,318
2,451,542
Skip rows with pandas.read_csv(..., comment="#") but allow hash in the data?
<p>Is there any way in pandas to ignore #-commented lines in their entirety, but leave the # symbol alone in the CSV body?</p> <pre><code>import pandas as pd from io import StringIO csv_content = &quot;&quot;&quot;\ # title: Sample CSV # description: This dataset id,name,favourite_hashtag 1,John,#python 2,Jane,#rstats...
<python><pandas>
2024-12-14 08:29:58
3
357
matentzn
79,280,126
3,358,488
Torchscript failure: 'RecursiveScriptModule' object has no attribute
<p>I am trying to use PyTorch's Torchscript to script a module defined in a third-party library.</p> <p>The example below is an abstract version of the problem. Suppose some library I cannot modify defines <code>SomeClass</code> and <code>LibraryModule</code> classes, where the latter is a PyTorch module.</p> <p><code>...
<python><pytorch><torchscript>
2024-12-14 05:37:41
1
5,872
user118967
79,280,099
11,953,868
The best way to reduce the calculation time of formulas in nested loops?
<p>Could you tell me what is the best way to reduce the calculation time of formulas in nested loops? I have code like this:</p> <pre><code>for k in range(0, 130): for i in range(0, 1600): array2[i,k] = 0 for j in range(0, 1600): array2[i,k] = array2[i,k] + constant_value * (array1[j,k] ...
<python><for-loop><nested><nested-loops>
2024-12-14 05:10:59
3
2,179
James Jacques
79,280,091
5,942,779
Behavior of df.map() inside another df.apply()
<p>I find this <a href="https://stackoverflow.com/questions/55929264/using-a-dataframe-to-format-the-style-of-another-dataframe">code</a> very interesting. I modified the code a little to improve the question. Essentially, the code uses a DataFrame to format the style of another DataFrame using <code>pd.style</code>.</...
<python><pandas>
2024-12-14 05:05:49
1
689
Scoodood
79,280,060
1,625,455
Can Python 3 copy files without overwriting?
<p>In a 2016 blogpost, <a href="https://moltenform.com/articles/avoiding-race-conditions-copying/" rel="nofollow noreferrer">it is claimed</a>:</p> <pre><code>def notActuallySafeCopy(srcfile, destfile): if os.path.exists(destfile): raise IOError('destination already exists') shutil.copy(srcfile, de...
<python><python-3.x><file><copy><race-condition>
2024-12-14 04:25:49
1
346
Atomic Tripod
79,279,979
968,132
GCP pub-sub errors
<p>I am building a simple webapp that accepts HTTP POSTs and should trigger a Cloud Pub-Sub event. Without pub-sub, the app deploys fine and I can reach the endpoint.</p> <p>I've created a sample functions. I've done this both through Cloud Run Functions (console.cloud.google.com/functions/). This shows Deployed By as ...
<python><google-cloud-platform><google-cloud-pubsub><google-cloud-run>
2024-12-14 02:54:05
0
1,148
Peter
79,279,969
654,019
Finding the last unique string in a list
<p>I was doing some coding on CodeSignal to refresh my knowledge.</p> <p>I was asked this question:</p> <blockquote> <p>Suppose you've got a list of words, let's say ['apple', 'banana', 'apple', 'mango', 'banana']. Each word could be repeated an arbitrary number of times. Think of this list as a conveyor belt in a spac...
<python><algorithm>
2024-12-14 02:39:02
9
18,400
mans
79,279,962
4,211,297
can't get doit task to accept parameters from command line
<p>the command:</p> <p><code>doit -f ./srvapp/doit-build.py build --stype $argc_type --zone $argc_zone</code></p> <p>the DAG</p> <pre><code>def task_build(): &quot;&quot;&quot;build&quot;&quot;&quot; def python_build(stype, zone): print(f&quot;TYPE: {stype}, ZONE: {zone}&quot;) return { 'a...
<python><doit>
2024-12-14 02:32:48
0
2,351
Pompey Magnus
79,279,909
8,191,023
Python type hinter function matching Protocol with kwargs
<p>I am having trouble with the PyCharm python type hinter when defining a function that matches a Protocol. It is giving me a warning and I am not sure why.</p> <pre><code>from typing import Protocol, List, Any class MyProtocol(Protocol): def __call__(self, docs: List[str], **kwargs: Any) -&gt; str: pass ...
<python><pycharm><python-typing>
2024-12-14 01:21:40
0
374
MarkRx
79,279,855
1,316,365
Have numpy.concatenate return proper subclass rather than plain ndarray
<p>I have a numpy array subclass, and I'd like to be able to concatenate them.</p> <pre><code>import numpy as np class BreakfastArray(np.ndarray): def __new__(cls, n=1): dtypes=[(&quot;waffles&quot;, int), (&quot;eggs&quot;, int)] obj = np.zeros(n, dtype=dtypes).view(cls) return obj ...
<python><numpy><numpy-ndarray>
2024-12-14 00:17:22
3
995
I.P. Freeley
79,279,854
1,629,904
How to Enable Premove in InputHandler
<p>I am using cm-chessboard and I am trying to allow the player to drag his own pieces even though is not his turn. I am trying to accomplish this so I can allow premove. Premove means I am allowed to &quot;premove&quot; the next move in my opponents time. The issue is I cannot understand how to allow the user to drag ...
<javascript><python><reactjs><chess><chessboard.js>
2024-12-14 00:17:17
0
332
dianesis
79,279,831
5,404,620
Meaning of _* in python (in reserved classes of identifiers)
<p>The python documentation writes about <code>_*</code></p> <p>&quot;Not imported by <code>from module import *</code>.&quot;</p> <p>What do they mean with that?</p> <p><a href="https://docs.python.org/3/reference/lexical_analysis.html#:%7E:text=_*,import%20*." rel="nofollow noreferrer">https://docs.python.org/3/refer...
<python>
2024-12-13 23:58:34
1
2,887
Adler
79,279,737
1,689,179
PIL cannot identify specific JPG file
<p>It works with other JPGs but not this one specifically, I'm wondering what's wrong and how it could be improved.</p> <pre class="lang-py prettyprint-override"><code>import io from aiohttp import ClientSession from PIL import Image session = ClientSession async with session.get(f'https://rocket-league.com/content/m...
<python><python-3.x><python-imaging-library>
2024-12-13 22:39:38
0
3,519
dan
79,279,731
9,415,280
Why Is There No Change Using The pyspark.ml Feature VectorAssembler?
<p>The following is an example from Databricks with my own data, I can't get the <code>VectorAssembler</code> transformation working.</p> <pre><code>string_indexer = StringIndexer(inputCol='ptype', outputCol='index_ptype', handleInvalid=&quot;skip&quot;) string_indexer_model = string_indexer.fit(sample_df) indexed_df =...
<python><apache-spark-mllib><one-hot-encoding><apache-spark-ml>
2024-12-13 22:35:11
1
451
Jonathan Roy
79,279,531
276,363
When are Jinja2 {% set %} operations actually run?
<p>Is it safe to assume that if a portion of a template is not included due to conditional operations, {% set %} operations within it are not evaluated? For example:</p> <pre><code>{% if var = 1 %} {% set thing = function_with_side_effects() %} {% endif </code></pre> <p>Is it safe to assume that if <code>var != 1</c...
<python><jinja2>
2024-12-13 20:39:34
1
2,078
Christophe
79,279,510
3,071,582
Docker Flask Service: ModuleNotFoundError: No module named 'flask' When Running Container, but Works Manually
<p>I am trying to build and run a <code>Flask</code>-based Python service (<code>task_manager</code>) using Docker and Docker Compose, but I'm encountering a persistent issue. When I run the container via <code>docker-compose up --build</code>, the service fails to find the Flask module:</p> <pre class="lang-none prett...
<python><docker><flask><docker-compose><virtualenv>
2024-12-13 20:32:21
0
737
Paul-Jason
79,279,391
4,966,886
Predecessors from scipy depth_first_order
<p>I use scipy version 1.14.1 to traverse the minimum spanning tree in depth-first order, but I do not understand some results, namely the predecessors returned by scipy are not correct.</p> <p>Here is an illustration for the following graph:</p> <p><a href="https://i.sstatic.net/rUVhBQMkm.png" rel="nofollow noreferrer...
<python><scipy><tree><networkx><depth-first-search>
2024-12-13 19:22:22
2
306
user11634
79,279,376
4,200,859
Pytest import issue with VSCode
<p>I literally just had Pytest working fine, I have the correct conda env selected in VSCode. I tried to run a test just then, and it can't find my folder 'modules' which is in my project directory. The import for modules is in my tests/test_function.py file, as:</p> <p><code>from modules.my_module import my_func</code...
<python><visual-studio-code><pytest>
2024-12-13 19:14:54
0
639
Max
79,279,317
13,132,640
Can you serialize a class instance within class method?
<p>I have a class which has a method which performs various calculations. Prior to beginning the calculations, I want the class instance to be saved in a format where I can easily load it again. Since the actual class contains various data types, I am using dill to accomplish this. However, I was wondering if the follo...
<python><serialization>
2024-12-13 18:53:57
0
379
user13132640
79,279,195
10,750,537
subprocess.Popen fails to set the name of executable
<p>According to the documentation of <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen" rel="nofollow noreferrer">Popen</a>, it seems possible, in POSIX systems, to set the name of the process as it is returned by <code>ps</code>:</p> <blockquote> <p>The <em>executable</em> argument specifies ...
<python><ubuntu><popen>
2024-12-13 17:56:08
1
381
JtTest
79,279,193
13,190,759
How to convert from extendedSRGB color to standard sRGB outside of Swift or Objective-C
<p>I am trying to write some code in Python to display a color taken from a Swift program. However, that color is in the <code>extendedSRGB</code> format. <code>extendedSRGB</code> is similar to standard sRGB except RGB values can be outside of the typical 0 to 1 range. Upon further research, it seems that this is an A...
<python><swift><objective-c><colors><srgb>
2024-12-13 17:55:23
0
351
Evan93
79,279,191
13,598,320
Web3.py AsyncWeb3 WebSocket Connection Fails for Infura Sepolia
<p>I’m working on an Ethereum project that connects to the Sepolia network using Infura's WebSocket endpoint <code>(wss://sepolia.infura.io/ws/v3/&lt;PROJECT_ID&gt;)</code>. While the connection works fine in Postman, my Python implementation using Web3.py fails with the following error:</p> <pre><code>ERROR:Blockchain...
<python><websocket><ethereum><web3py><infura>
2024-12-13 17:54:39
1
548
seddouguim
79,279,190
12,466,687
How to conditionally format data in Great Tables?
<p>I am trying to conditionally format table data using Great Tables but not sure how to do it.</p> <p>To highlight the color of all those cells (sort of heatmap) whose values is higher than Upper Range column.</p> <p>Data:</p> <pre><code>import polars as pl gt_sample_df = pl.DataFrame({'Test': ['Test A','Test B','Tes...
<python><dataframe><python-polars><great-tables>
2024-12-13 17:53:52
1
2,357
ViSa
79,279,124
2,475,195
Does pytorch CNN care about image size?
<p>I am playing with CNNs these days, and I have code like pasted below. My question is, would this work on any image size? It is not clear to me what parameter or channel, if any, cares about the image size? And if that's the case, how does the model know how many neurons it needs, isn't that a function of image size?...
<python><machine-learning><deep-learning><pytorch><conv-neural-network>
2024-12-13 17:24:14
1
4,355
Baron Yugovich
79,279,060
17,658,327
How to use numpy.where in a pipe function for pandas dataframe groupby?
<p>Here is a script to simulate the issue I am facing:</p> <pre><code>import pandas as pd import numpy as np data = { 'a':[1,2,1,1,2,1,1], 'b':[10,40,20,10,40,10,20], 'c':[0.3, 0.2, 0.6, 0.4, 0.5, 0.2, 0.8], 'd':[3, 1, 5, 1, 7, 2., 2.], } df = pd.DataFrame.from_dict(data) # I ...
<python><pandas><dataframe><group-by><pipe>
2024-12-13 16:56:50
2
626
learner
79,278,987
405,017
Stop Plotly dash.dcc.Store() triggering an update on page load
<p>Summary: my Dash app is triggering a callback on initial page load from a dcc.Store, with sometimes-old data in it. How do I prevent this? Note: I am using <code>prevent_initial_call=True</code>.</p> <p>The layout for my Dash app contains these:</p> <pre class="lang-py prettyprint-override"><code>dcc.Location(id=sel...
<python><plotly-dash>
2024-12-13 16:34:47
0
304,256
Phrogz
79,278,878
1,406,168
Deploying files from GitHub to Azure
<p>I am having a GitHub action where everything looks like a success, however it seems like the application is not deployed.</p> <p>yaml:</p> <pre><code>name: Build and deploy Python app to Azure Web App - fast-api-port on: push: branches: - main workflow_dispatch: jobs: build: runs-on: ubuntu-lat...
<python><azure><github><azure-web-app-service><github-actions>
2024-12-13 15:49:57
1
5,363
Thomas Segato
79,278,850
11,999,452
openCV: video does not get saved correctly
<p>The output video has only 1kB and can not be opened. What is wrong? This is my code:</p> <pre><code>import cv2 import numpy as np file_name = &quot;Touhou - Bad Apple.mp4&quot; output_file_name = &quot;Touhou - Bad Apple difference flip.mp4&quot; # Open the video file video = cv2.VideoCapture(file_name) # Get the...
<python><opencv><video>
2024-12-13 15:40:40
1
400
Akut Luna
79,278,835
120,440
How do I update a matplotlib plot in realtime and also have a REPL?
<p>I am in a situation where I have a primitive REPL with some simple commands. These commands generate data and put the data into a threadsafe queue. I then have a function that takes the data from the queue and plots it on a matplotlib plot.</p> <p>What I would ultimately like to do is to be able to have a REPL comma...
<python><matplotlib><python-multithreading>
2024-12-13 15:34:41
1
3,155
Angelo
79,278,749
520,275
Is there any way to optimize disk usage for virtualenv environments?
<p>I have several <strong>virtualenvs</strong> for the same Python version, each with a physical copy of each dependency file. Some AI-related dependencies (tensorflow, torch, nvidia, etc) tend to be immense. As a consequence, a lot of disk space is consumed with a lot of duplicate files.</p> <p><strong>I'm looking for...
<python><virtualenv>
2024-12-13 15:05:38
0
10,232
Gonzalo Matheu
79,278,735
2,386,113
Horizontal and vertical colorbars on a single plot in python
<p>I have KDE plot generated using seaborn on which I overlay some scattered points with some size. I need to have two colorbars to represent the data of KDE and the scattered values's size (as shown below).</p> <p>I tried to use the answer provided <a href="https://stackoverflow.com/a/33505522/2386113">here</a> at Sta...
<python><matplotlib><seaborn><colorbar>
2024-12-13 14:59:43
1
5,777
skm
79,278,733
19,556,055
Initializing a local cluster in Dask takes forever
<p>I'm trying out some things with Dask for the first time, and while I had it running a few weeks ago, I now find that I can't get the LocalCluster initiated. I've cut if off after running 30 minutes at some point, and am unable to get it initiated. Does anybody know what the issue may be? The code I'm trying to run i...
<python><dask><dask-distributed>
2024-12-13 14:59:22
0
338
MKJ
79,278,724
11,357,695
Monkeypatching pandas series to_csv with pytest
<p>I am testing a function, <code>write_query()</code>, in <strong>module.py</strong>. My test is in <strong>test_module.py</strong>, which is carried out using pytest. I am using the <a href="https://docs.pytest.org/en/4.6.x/monkeypatch.html" rel="nofollow noreferrer">pytest monkeypatch fixture</a> to monkeypatch <c...
<python><pandas><unit-testing><pytest><monkeypatching>
2024-12-13 14:55:04
0
756
Tim Kirkwood
79,278,659
19,556,055
Can't load numpy when installed through Anaconda
<p>I am trying to run the vaex module which requires Python 3.6 and, apparently, a conda install rather than a pip install. I don't <em>really</em> know what I'm doing here, but I went ahead and installed Anaconda and created a new conda environment through the Anaconda prompt using <code>conda create -n research_proje...
<python><numpy><anaconda>
2024-12-13 14:31:44
0
338
MKJ
79,278,599
3,895,259
How to properly set up django channels and websocket
<p>I'm trying to implement websocket and django channels. On frontend I have react and on backend django.</p> <p>I've installed <code>channels</code> and added it to <code>INSTALLED_APPS</code> in settings and I also added to settings.py</p> <pre><code>ASGI_APPLICATION = 'VideoScreen.routing.application' CHANNEL_LAYERS...
<python><django><websocket><django-channels>
2024-12-13 14:09:31
0
12,124
Boky
79,278,528
386,861
Trying to plot a time series with ordinal data in Altair
<p>I'm slowly understanding a problem that I have with a time series plot involving data over three financial years.</p> <p>Here's some sample data.</p> <pre><code> Financial Year Month Category Value FY 0 2022-04-01 2023 Apr Total 53,616.40 2022-2023 1 2022-05-01 2023 May Total 56,652.97 ...
<python><altair>
2024-12-13 13:47:12
1
7,882
elksie5000
79,278,424
618,579
Python importing CSV, adding square brackets
<p>I have the following code:</p> <pre><code># Read serial numbers from CSV with open('serials.csv', mode='r') as infile: reader = csv.reader(infile) serials = [row for row in reader] # Query warranty date for each serial number and update CSV for row in serials: data = {&quot;sn&quot;: row} respo...
<python><python-requests>
2024-12-13 13:05:47
4
2,513
Nathan
79,278,373
1,635,450
Python reverse dictionary key value reference relationships
<p>If I have a following dictionary:</p> <pre><code>{&quot;1&quot;: {&quot;2&quot;, &quot;3&quot;}, &quot;2&quot;: {&quot;3&quot;, &quot;4&quot;}, &quot;3&quot;: {&quot;2&quot;, &quot;4&quot;}} </code></pre> <p>In this dictionary, the key references the values in the set.</p> <p>How do I construct a new dictionary whic...
<python><dictionary><python-3.12>
2024-12-13 12:46:38
2
4,280
khteh
79,278,351
6,089,311
How to forward / backward fill null fields in a struct column using Polars?
<p>This code not fill null values in column. I want to some fields to forward and backward fill nulls.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df1 = pl.LazyFrame({ &quot;dt&quot;: [ &quot;2024-08-30&quot;, &quot;2024-08-02&quot;, ...
<python><dataframe><python-polars>
2024-12-13 12:36:46
2
586
Jan
79,278,344
5,838,180
Draw a Venn-diagram in python with one large area encompassing all other
<p>I used so far succesffully this code:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib_venn import venn2 # Define the areas for the Venn diagram area1 = 13552 # Area of the left ellipse area2 = 7887 # Area of the right ellipse intersection = 7747 # Area of the intersection # Calculate the unique ...
<python><matplotlib><venn-diagram>
2024-12-13 12:33:57
2
2,072
NeStack
79,278,333
8,024,622
KivyMD delete line in file when button ist pressed
<p>I'm having a screen showing me items saved in a file. Every line should be shown on the screen. This works well.</p> <p>What I want to acchieve is, when the button to the right of an element (icon: 'delete') is pressed, the line in that file is removed and the screen is refreshed.</p> <p>I really do not know how to ...
<python><kivy><kivymd>
2024-12-13 12:29:25
1
624
jigga
79,278,129
11,626,097
boto3 redshift client .describe_statement provides no error message
<p>I've run an sql query through boto3 redshift client's <em>execute_statement</em> function, and subsequently checked the status of the query with <em>describe_statement</em>.</p> <pre><code>result = client_redshift.execute_statement(Database= 'my_database', SecretArn= secret_arn, ...
<python><amazon-web-services><aws-lambda><amazon-redshift><boto3>
2024-12-13 11:23:02
0
679
tonneofash
79,278,086
19,356,117
How to convert Polars dataframe to numpy array which has certain dims?
<p>I have a Polars DataFrame with 300 basins, each basin having 100,000 time records, and each time record consisting of 40 variables, totaling 30 million rows and 40 variables. How can I reconstruct it into a NumPy array with the shape (300, 100,000, 40) without disrupting the corresponding data indices?</p> <p>Exampl...
<python><python-3.x><numpy><python-polars>
2024-12-13 11:07:05
1
1,115
forestbat
79,277,864
6,151,828
Define different class method depending on whether an input parameter is present/absent
<p>I would like to be able to define a different class method, depending on whether one of the inputs is present or not. Something like:</p> <pre><code>class mcmc(object): def __init__(self, X, Y=None): if Y is None: def input_vector(self, beta): return beta.dot(X) else: ...
<python>
2024-12-13 09:52:35
2
803
Roger V.
79,277,600
1,406,168
FastAPI deployed to an azure web app - getting environments variables
<p>I have deployed a FastAPI application to an azure web app. I would like to access the environment variables from the web app in fast api. Is that possible and if yes or do you do that? Both from azure ofcource, but also how do you manage locally when developing. As we speak I am only using a basic hello world templa...
<python><azure><azure-web-app-service><fastapi><azure-webapps>
2024-12-13 08:18:38
1
5,363
Thomas Segato
79,277,584
13,392,257
How to clear task resources and zombie processes
<p>I am building celery + django + selenium application. I am running selenium-based browsers in separate processes with help celery. Versions:</p> <pre><code>celery==5.2.6 redis==3.4.1 selenium-wire==5.1.0 Django==4.0.4 djangorestframework==3.13.1 </code></pre> <p>I found out that after several hours application gener...
<python><selenium-webdriver><celery>
2024-12-13 08:10:28
2
1,708
mascai
79,277,572
15,460,398
How to download the TestData dataset of open3d python
<p>I have installed open3d in Raspberry Pi 4 using the <a href="https://www.open3d.org/docs/0.9.0/getting_started.html" rel="nofollow noreferrer">documentation</a>: Command: <code>pip3 install open3d</code></p> <p>I can successfully import open3d in a Python program. But if I run the program from the <a href="https://w...
<python><python-3.x><open3d>
2024-12-13 08:06:31
1
361
BeamString
79,277,541
13,128,766
The "BadStatusLine" error when connecting to mail server with exchangelib
<p>I'm trying to connect to my mailbox with exchangelib. Options are: protocol SMTP, port 465. Code:</p> <pre><code>credentials = Credentials(MAIL_ACCOUNT, PASS) config = ExConfiguration(server=MAIL_SERVER + &quot;:&quot; + MAIL_SERVER_PORT, credentials=credentials) account = Account(MAIL_ACCOUNT,config=config, credent...
<python><exchangelib>
2024-12-13 07:49:44
1
451
Vad1m
79,277,352
1,084,174
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn while fine tuning llama
<p>This <a href="https://stackoverflow.com/questions/76780201/runtimeerror-element-0-of-tensors-does-not-require-grad-and-does-not-have-a-gr">answer</a> did not solve my problem.</p> <p>I was trying to fine tune llama model locally using LoRA, peft. Here is my code:</p> <pre><code>import torch from datasets import load...
<python><machine-learning><llama><fine-tuning><peft>
2024-12-13 06:02:07
0
40,671
Sazzad Hissain Khan
79,277,053
1,043,677
Spline lineal continuation on borders
<p>I have code interpolating a spline from a CDF that seems valid between the range x=40 and x=110. Below 40, I want a flat line at 0, and after 110, a flat line at 1 towards infinite.</p> <p>I have come up with this code:</p> <pre><code>def _find_spline(x_orig: np.ndarray, cdf: np.ndarray) -&gt; BSpline: # Find t...
<python><scipy><interpolation><spline>
2024-12-13 01:53:26
1
1,718
lqbweb
79,276,868
3,635,544
Exception has occurred: DatatypeMismatch column "occurence_timestamp" is of type timestamp without time zone but expression is of type bigint
<p>Here are the core steps and logics of my script below:</p> <ol> <li>Create and instantiate a <code>PostgreSQLDB</code> class object that does database operation</li> <li>Use view <code>vw_valid_case_from_db1</code> to get a list of <code>case_id</code> which will be included</li> <li><code>df_db1_case_table</code> i...
<python><sql><python-3.x><pandas><postgresql>
2024-12-12 23:27:57
1
4,775
KubiK888
79,276,761
10,934,417
How to convert the column with lists into one hot encoded columns?
<p>Assume, there is one DataFrame such as following</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'id':range(1,4), 'items':[['A', 'B'], ['A', 'B', 'C'], ['A', 'C']]}) df id items 1 [A, B] 2 [A, B, C] 3 [A, C] </code></pre> <p>Is th...
<python><pandas><numpy>
2024-12-12 22:20:26
1
641
DaCard
79,276,690
417,678
Django + FactoryBoy -> Postgres not converting datetime to utc correctly
<p>Okay, this is a weird one. I've got a Django model that I'm writing to Postgres via FactoryBoy for testing.</p> <pre><code>contract = ContractFactory( effective_date=datetime.datetime(2023, 1, 1, tzinfo=pytz.timezone('US/Central')) ) </code></pre> <p>I'm in US/Central, and I expect the database to store ...
<python><django><postgresql><datetime><timezone>
2024-12-12 21:44:21
1
6,469
mj_
79,276,647
5,837,992
How do I pass a row to a function using df.apply in Pandas
<p>I have a fairly complicated function that I need to run on each row of my dataframe - lambda functions won't work here. I want to pass multiple columns from the dataframe to the function.</p> <p>In my initial test, I tried passing the row and naming a single column (note that I will need to use multiple columns for ...
<python><pandas><apply>
2024-12-12 21:24:45
0
1,980
Stumbling Through Data Science
79,276,553
620,679
Sparse matrix in pandas/scipy with row and column indices
<p>I have a dataframe in pandas that looks like this:</p> <pre><code>&gt;&gt;&gt; df[['BranchNumber', 'ModelArticleNumber', 'ActualSellingPrice']].info() &lt;class 'pandas.core.frame.DataFrame'&gt; Index: 447970 entries, 0 to 500734 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ...
<python><pandas><scipy><sparse-matrix>
2024-12-12 20:46:06
1
4,041
Scott Deerwester
79,276,537
1,815,486
Calling a wrapped static method using self instead of class name passes self as arg
<p>This question is related to <a href="https://stackoverflow.com/questions/65461959/calling-a-static-method-with-self-vs-class-name">Calling a static method with self vs. class name</a> but I'm trying to understand the behavior when you wrap a static method so I can fix my wrapper.</p> <p>For example:</p> <pre><code>i...
<python><python-decorators>
2024-12-12 20:39:31
1
2,165
aiguofer
79,276,505
657,003
Assignment to global variable attribute in for loop is not available outside the scope of the loop
<p>This is a simplified version of this SO question (<a href="https://stackoverflow.com/questions/79274789/an-assignment-to-a-networkx-graph-edge-attribute-in-a-for-loop-is-properly-refle">link</a>) with some program output.</p> <p>Using Python and networkX under macOS, I am not able to assign a value to an edge attrib...
<python><networkx>
2024-12-12 20:26:49
1
2,809
Perry Horwich
79,276,455
7,233,155
Why doesn't mypy follow config in GitHub Actions?
<p>If I run mypy locally it will only type check certain files because the <code>pyproject.toml</code> file has the following inclusion:</p> <pre class="lang-ini prettyprint-override"><code>[tool.mypy] files = [ &quot;python/project/file1.py&quot;, &quot;python/project/file2.py&quot; ] strict = true </code></pr...
<python><github-actions><mypy>
2024-12-12 20:08:38
0
4,801
Attack68
79,276,411
5,547,553
How to resize figure to fit window on event in matplotlib?
<p>I've already got help with this problem, but stuck again.<br> I'm trying to pre-generate and store matplotlib figures in python, and then display them on a keyboard event (left-right cursor keys).<br> It is working fine, but will not fit the figures (after the first one) to the window.<br> How can I do that?<br> If ...
<python><matplotlib>
2024-12-12 19:49:38
0
1,174
lmocsi
79,276,400
28,063,240
How to get the index of a text node in BeautifulSoup?
<p>How can I get the source index of a text node in an HTML string?</p> <p>Tags have <code>sourceline</code> and <code>sourcepos</code> which is useful for this, but <code>NavigableString</code> does not have any directly-helpful properties like that (as far as I can find)</p> <p>I've thought about using</p> <pre class...
<python><beautifulsoup><lxml>
2024-12-12 19:46:42
1
404
Nils
79,276,360
5,312,606
attrs and class variables
<p>I really like the way how one can define classes via the <code>attrs</code> library. In particular how the usual syntax of python class variables is hijacked to define instance variables. But is there a way to get class variables with <code>attrs</code>?</p> <p>If I have the following code</p> <pre class="lang-py pr...
<python><class-variables><python-attrs>
2024-12-12 19:30:43
1
1,897
mcocdawc
79,276,283
2,475,195
How to reshape image tensor in pytorch
<p>I am playing with the MNIST dataset, where each image is represented as a grayscale row of length 784, and I want to reformat it as 28x28:</p> <pre><code>DIM = int(len(features)**0.5) X_train_tensor = torch.tensor(X_train_aug[features].values).float() X_train_tensor = X_train_tensor.view(len(X_train_tensor), 1, DIM,...
<python><deep-learning><pytorch><neural-network><conv-neural-network>
2024-12-12 18:58:49
0
4,355
Baron Yugovich
79,276,230
3,125,823
Callable default on unique field will not generate unique values upon migrating
<p>Using Django/DRF to create a CRUD api</p> <p>I'm trying to use the RandomUUID to create a UUID from Postgres:</p> <pre><code>from django.db import models from django.contrib.postgres.functions import RandomUUID class Year(models.Model): year_id = models.UUIDField( primary_key=True, default=RandomUUID, e...
<python><django><postgresql><django-models>
2024-12-12 18:38:05
1
1,958
user3125823
79,276,175
11,609,834
Is there a way to require Pytest to reload imports in a test file?
<p>TL;DR: I would like Pytest to reload imports in certain files when it runs those tests. Some of the imports in my code base have side effects that I need to control at test time. The behavior would basically be like <code>importlib.reload</code> for any module in the test file. Is this possible?</p> <p>Longer explan...
<python><pytest>
2024-12-12 18:18:16
0
1,013
philosofool
79,276,109
412,137
Poetry install failing with SSLError: Max retries exceeded on GitHub HTTPSConnectionPool
<p>I am encountering an error when running the poetry install command in my Python project. The error message is as follows:</p> <pre><code>HTTPSConnectionPool(host='github.com', port=443): Max retries exceeded with url: ... (Caused by SSLError(FileNotFoundError(2, 'No such file or directory'))) </code></pre> <p>I have...
<python><git><ssl><dependency-management><python-poetry>
2024-12-12 17:53:47
2
2,767
Nadav
79,275,888
1,987,477
Three plots sharing x-axis on top of each other as in figure
<p>I'm struggling with <code>matplotlib</code>.</p> <p>I'd like to get a plot like <a href="https://imgur.com/a/FfLKQi3" rel="nofollow noreferrer">this one</a> but with the code below I can only get <a href="https://imgur.com/a/utdr9vs" rel="nofollow noreferrer">this plot</a>.</p> <pre><code>f, (ax1, ax2, ax3) = plt.su...
<python><matplotlib>
2024-12-12 16:35:07
0
1,325
user123892
79,275,886
2,537,394
Speed up numpy looking for best indices
<p>I have a numpy array that maps x-y-coordinates to the appropriate z-coordinates. For this I use a 2D array that represents x and y as its axes and contains the corresponding z values:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np x_size = 2000 y_size = 2500 z_size = 400 rng = np.random.defau...
<python><arrays><numpy><coordinates><coordinate-transformation>
2024-12-12 16:34:55
4
731
YPOC
79,275,864
2,626,865
Approaches and problems with massively concurrent processing using concurrent.futures and/or asyncio
<p>I want to run billions of IO-bound tasks across a pool of thousands of threads. These are my challenges:</p> <ul> <li>Reduce memory usage. The thread pool from <code>concurrent.futures</code> uses an unbound queue. Too many submissions and memory usage balloons but too few and not enough work is accomplished.</li> <...
<python><memory-management><concurrency><python-asyncio><concurrent.futures>
2024-12-12 16:30:08
0
2,131
user19087
79,275,860
3,486,684
Joining two dataframes that share "index columns" (id columns), but not data columns, so that the resulting dataframe has a full spine of ids?
<p>I find myself doing this:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl import sys red_data = pl.DataFrame( [ pl.Series(&quot;id&quot;, [0, 1, 2], dtype=pl.UInt8()), pl.Series(&quot;red_data&quot;, [1, 0, 1], dtype=pl.UInt8()), ] ) blue_data = pl.DataFrame( [ ...
<python><python-polars>
2024-12-12 16:28:34
1
4,654
bzm3r
79,275,745
3,765,883
Odd boolean expression
<p>I'm trying to debug (rewrite?) someone else's Python/cherrypy web app, and I ran across the following 'if' statement:</p> <pre><code>if not filename.endswith(&quot;.dat&quot;) and ( filename.endswith(&quot;.dat&quot;) or not filename.endswith(&quot;.cup&quot;) ): raise RuntimeError( &quot;Waypoint fi...
<python><boolean-expression>
2024-12-12 15:49:09
2
327
user3765883
79,275,700
19,356,117
Why there is 'Unpickling Error' when using polars to read data for pytorch?
<p>I have changed my data tool from xarray to polars in recent, and use <code>pl.DataFrame.to_torch()</code> to generate tensor for training my Pytorch model. Data source's format is parquet file.</p> <p>For avoiding fork child processes, I use <code>torch.multiprocessing.spawn</code> to start my training process, howe...
<python><python-3.x><pytorch><multiprocessing><python-polars>
2024-12-12 15:34:00
1
1,115
forestbat
79,275,645
13,440,165
Can I create a multidimensional array containing a unit matrix without nested loops?
<p>Suppose I have a Numpy array <code>n</code> indices, where the first <code>n-2</code> represents some counting indices and the last 2 indices represent a square <code>MxM</code> matrix. I want to initialize this structure so it will contain copies of the unit matrix.</p> <p>Example (here N=3, M=2):</p> <pre><code>A ...
<python><numpy><numpy-ndarray>
2024-12-12 15:18:02
3
883
Triceratops
79,275,524
695,134
Invalid escape sequences in Python 3.12 in a Docker image
<p>I have the following code:</p> <pre><code>x = re.match(&quot;^(\d+\.\d+\.\d+\.\d+)$&quot;, url) </code></pre> <p>It all works fine and runs under a Docker instance with python 3.11 installed.</p> <p>The image has been upgraded to version 3.12 (it's a public GitLab repo) and now whenever we put any escape code in a s...
<python><python-3.x>
2024-12-12 14:43:37
0
6,898
Neil Walker
79,275,501
4,701,426
Manipulation of a Pandas dataframe most time- and memory-efficiently
<p>Please imagine I have a dataframe like this:</p> <pre><code>df = pd.DataFrame(index=pd.Index(['1', '1', '2', '2'], name='from'), columns=['to'], data= ['2', '2', '4', '5']) </code></pre> <p>df:</p> <p><a href="https://i.sstatic.net/UDavHvKE.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UDavHvKE.png"...
<python><pandas><dataframe><numpy><vectorization>
2024-12-12 14:36:54
1
2,151
Saeed
79,275,434
4,537,160
VSCode background processes triggering SSO in Python code
<p>I have a Python repo that I'm working on in VSCode.</p> <p>The repo structure is like this:</p> <pre><code>main_repo -- utils ---- client ------ my_client.py </code></pre> <p>my_client.py contains this code:</p> <pre><code>class CustomClient(DataClient): def __init__(self, client_type=None, lazy_init=False): ...
<python><visual-studio-code>
2024-12-12 14:13:36
0
1,630
Carlo
79,274,939
3,497,293
retrieving pagerduty dedup key of an incident using API
<p>I have a python program that generates <a href="https://developer.pagerduty.com/api-reference/" rel="nofollow noreferrer">Pagerduty(PD)</a> alerts using <a href="https://pagerduty.github.io/pdpyras/user_guide.html" rel="nofollow noreferrer">pdpyras</a> libraries. I have a case where i need to resolve the PD alerts a...
<python><pagerduty>
2024-12-12 11:31:33
0
1,454
Krishnom
79,274,781
10,482,316
Movesense Sensor Not Sending Data via Python Script but Works with Mobile App
<p>I am working with a Movesense sensor and attempting to collect data using the Python script provided in the documentation. The path and commands I am using have been verified as correct according to the Movesense API documentation and cross-checked with other reference code. The Python client successfully connects t...
<python><movesense><python-bleak>
2024-12-12 10:43:45
1
746
Shreyas Ramachandran
79,274,751
7,672,005
How to properly handle multi-GPU execution failing on one GPU due to OOM
<p>I'm working with multiple GPUs handling large amaounts of data. I want to create an out-of-memory (OOM) catch system that skips the current batch on all GPUs if any are out of memory.</p> <p>However, for reasons I don't understand only the OOM GPU reaches the dist.all_reduce synchronisation point. The rest don't log...
<python><error-handling><pytorch><distributed-computing><multi-gpu>
2024-12-12 10:34:14
0
534
Zyzyx
79,274,733
8,650,926
IFDRational is not JSON serializable using Pillow
<p>I am using PIL in python to extract the metadata of an image.</p> <p>Here is my code:</p> <pre><code>import json from PIL import Image, TiffImagePlugin import PIL.ExifTags img = Image.open(&quot;/home/user/DSCN0010.jpg&quot;) dct = { PIL.ExifTags.TAGS[k]: float(v) if isinstance(v, TiffImagePlugin.IFDRation...
<python><json><python-imaging-library><metadata>
2024-12-12 10:29:06
1
808
Mike Delta
79,274,475
4,139,024
altair grouped bar chart with quantitive axis
<p>When using a quantitive x axis the xOffset does not seem to work in altair, i.e. the bars are stacked but I would like to have them next to each other. When encoding the x-axis as ordinal <code>x=alt.X(&quot;Genre:O&quot;)</code> it works, but the sorting is wrong. Any idea how to solve this?</p> <pre><code>import a...
<python><visualization><altair>
2024-12-12 09:20:58
1
3,338
timbmg
79,274,376
7,218,871
Slice a numpy 2d array using another 2d array
<p>I have a 2D array of (4,5) and another 2D array of (4,2) shape. The second array contains the start and end indices that I need to filter out from first array i.e., I want to slice the first array using second array.</p> <pre><code>np.random.seed(0) a = np.random.randint(0,999,(4,5)) a array([[684, 559, 629, 192, 8...
<python><numpy><numpy-ndarray>
2024-12-12 08:52:10
4
620
Abhishek Jain
79,274,365
4,393,852
Exception in the class destructor
<p>I'm gettin an <code>ImportError</code> exception when execute code:</p> <pre><code>from requests import Session class web_client(object): def __init__(self, adapter: type): self.adapter = adapter self.s = Session() self.s.verify = False self.adapter.auth(self) def __del__(s...
<python><python-3.x>
2024-12-12 08:48:01
1
741
shmnff
79,274,171
1,084,174
Getting error while fine tuning using peft
<p>I was trying to fine tune using peft. Following is my code:</p> <pre><code>from peft import LoraConfig, TaskType, get_peft_model from transformers import AutoModelForSeq2SeqLM from transformers import AutoTokenizer, DataCollatorWithPadding from transformers import TrainingArguments from transformers import Trainer f...
<python><machine-learning><gpu><fine-tuning><peft>
2024-12-12 07:31:09
0
40,671
Sazzad Hissain Khan
79,273,969
26,579,940
Get list of kwargs for parent class
<p>For some Python packages, it will fetch and display a list of kwargs for a class, even if it is an inherited class.</p> <p>The following is an example of code that inherits Django's model class. I named the arg of the class as **kwargs, but vscode takes the kwargs of the parent class and shows it.</p> <p>How do I us...
<python>
2024-12-12 05:52:15
0
404
white.seolpyo.com
79,273,831
11,464
How do I export a darts' TCNModel to ONNX?
<p>I have a TCNModel that is trained on a time series:</p> <pre><code>model_air = TCNModel( input_chunk_length=13, output_chunk_length=12, n_epochs=3, dropout=0.1, dilation_base=2, weight_norm=True, kernel_size=5, num_filters=3, random_state=0, ...
<python><onnx><darts-python>
2024-12-12 04:30:39
0
7,639
lmsasu
79,273,770
188,331
Run Flask app in a sub-directory with error log and WSGI Process Group
<p>I try to migrate a Flask app from an Ubuntu 22.04 server (originally it is configured as a Virtual Host) to RHEL 9.4 server (as a sub-directory script), both running Apache web server and having WSGI module installed. From this <a href="https://stackoverflow.com/questions/14181364/running-a-flask-website-in-a-subdir...
<python><apache><flask><mod-wsgi><rhel9>
2024-12-12 03:45:16
0
54,395
Raptor
79,273,711
1,540,785
MariaDB in Docker - MariaDB Connector/Python was build with MariaDB Connector/C version 3.3.3, but loaded Connector/C library has version 10.3.39
<p>I can't figure out the error in my Docker container.</p> <p>I am using python:3.9-buster</p> <p>i am downloading, I think, the correct Connector/C version for MariaDB</p> <pre><code>RUN wget https://dlm.mariadb.com/2678574/Connectors/c/connector-c-3.3.3/mariadb-connector-c-3.3.3-debian-bullseye-amd64.tar.gz \ -O...
<python><docker><mariadb>
2024-12-12 03:04:11
1
371
kanadianDri3
79,273,621
342,553
Why is python mock assert_any_call not matching
<p>Given the doc for assert_any_call</p> <p><a href="https://i.sstatic.net/29chfiM6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/29chfiM6.png" alt="enter image description here" /></a></p> <p>I have a log statement I want to assert against</p> <pre class="lang-py prettyprint-override"><code>... logger...
<python><mocking><python-mock>
2024-12-12 01:47:21
2
26,828
James Lin
79,273,568
7,399,336
Get image or video from tweet using tweet id or url (with a good rate limit)
<p>I would like to replicate the <a href="https://twittervideodownloader.com/" rel="nofollow noreferrer">https://twittervideodownloader.com/</a> using python, it get all the videos url</p> <p><a href="https://i.sstatic.net/eAH6zQPv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eAH6zQPv.png" alt="exampl...
<python><twitter><tweepy><twitter-oauth><twitter-api-v2>
2024-12-12 01:11:28
0
361
AndresSp
79,273,432
6,024,187
python multiprocessing gets slower with additional cpus
<p>I'm trying to parallelize code that should be embarrassingly parallel and it just seems to get slower the more processes I use. Here is a minimally (dys)functional example:</p> <pre><code>import os import time import random import multiprocessing from multiprocessing import Pool, Manager, Process import numpy as n...
<python><multiprocessing>
2024-12-11 23:17:56
2
897
Finncent Price
79,273,274
13,118,009
How to use ntile() windows function or similar on hundreds of columns in AWS Databricks
<p>I've a table with 20 million rows and 400+ columns. Aside from the first column, I need to change all other columns to evenly distributed deciles, independent of other columns. My data reside in AWS Databricks. I'm running the python notebook as job using a job cluster with the following configuration:</p> <pre><cod...
<python><pyspark><databricks>
2024-12-11 21:47:10
1
6,494
Isolated
79,273,032
1,739,725
Run Python coroutine functions concurrently, but start additional coroutines as soon as particular coroutines have completed
<p>I have four total coroutines (<code>async def</code> functions): A, B, C, and D. C can't be called until I know the result of A, and D can't be called until I know the result of A <em>and</em> B. See the attached diagram. I want to run these coroutines concurrently such that the total time spent until I get the resu...
<python><concurrency><python-asyncio>
2024-12-11 19:58:55
3
2,186
Pwnosaurus
79,272,853
11,357,695
Comparing empty dataframes
<p>I have a function, <code>extract_redundant_values</code>, to extract redundant rows from a pandas dataframe. I am testing it by running on <code>in_df</code> to generate <code>out_df</code>. I am then comparing this against my expected output <code>expected_out_df</code>. They seem to have the same index, columns...
<python><pandas><dataframe><unit-testing><testing>
2024-12-11 18:50:46
1
756
Tim Kirkwood
79,272,800
13,147,413
Rearrange and encode columns in pandas
<p>i have data structured like this (working with pandas):</p> <pre><code>ID|comp_1_name|comp_1_percentage|comp_2_name|comp_2_percentage| 1| name_1 | 13 | name_2 | 33 | 2| name_3 | 15 | name_1 | 46 | </code></pre> <p>There are six comp_name/comp_percenta...
<python><pandas>
2024-12-11 18:25:16
2
881
Alessandro Togni
79,272,692
1,303,562
Locust on_start() method not executing requests
<p>I am using <code>Locust</code> for performance testing, and I have a task that performs an <code>API</code> call in the <code>on_start</code> method. The <code>on_start</code> method prints the &quot;started&quot; message, but the request inside the try block does not execute. The same request works fine when execut...
<python><locust>
2024-12-11 17:42:41
0
721
Dana Yeger
79,272,691
13,163,640
Kafka consumer is missing messages during deployment
<p>My consumers are inherited from the BasicKafkaConsumerV2. During deployments when the pods are rotating I am missing few messages which is visible from the offsets printed after the manual commit(). Kafka is not supposed to miss messages if not committed. What could be the problem here.</p> <p>run command:</p> <pre>...
<python><django><apache-kafka><apache-zookeeper><kafka-python>
2024-12-11 17:42:21
2
567
Dev
79,272,593
9,002,634
How to use DO $$ block with psycopg3?
<h3>Context</h3> <p>I have a table that is using temporal versioning where the &quot;active&quot; row (for a retailer) is where expire_tstamp is null.</p> <h3>Problem</h3> <p>I want to execute once to do an &quot;upsert&quot;.</p> <ol> <li>If there are no existing active rows for a retailer, insert.</li> <li>If there a...
<python><sql><postgresql><psycopg3>
2024-12-11 17:07:00
1
318
Viet Than
79,272,506
785,736
how to calculate ratio in group by in pandas
<p>I have the following pandas dataframe<br/></p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>ts</th> <th>tenant</th> <th>result</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>t1</td> <td>pass</td> </tr> <tr> <td>1</td> <td>t1</td> <td>pass</td> </tr> <tr> <td>1</td> <td>t2</td> <td>pass</t...
<python><pandas><group-by>
2024-12-11 16:37:48
3
4,580
Mr T.
79,272,387
20,591,261
How to use join_where() in Polars for conditional joins with date ranges?
<p>I have two Polars DataFrames:</p> <ol> <li>One (df) records the dates when items were sold.</li> <li>Another (df2) contains additional details, including dates and values for items.</li> </ol> <p>I want to join these DataFrames where the <code>ID</code> matches, and the sale date in <code>df</code> falls within a 1-...
<python><dataframe><python-polars>
2024-12-11 16:03:49
0
1,195
Simon
79,272,352
4,418,481
Re-override plotly-resampler reset axis behavior
<p>I created a Dash app that displays a figure in it. I have used plotly-resampler since I had to deal with large datasets.</p> <p>At the documentation of plotly-resampler, they mentioned this:</p> <blockquote> <p>The plotly autoscale event (triggered by the autoscale button or a double-click within the graph), does no...
<python><plotly><plotly-resampler>
2024-12-11 15:49:09
0
1,859
Ben