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
βŒ€
78,151,710
4,732,111
How to initialise a polars dataframe with column names from database cursor description?
<p>I'm connecting to Postgres Database using psycopg2 connector and using cursor property, i'm fetching the records along with their column names. Here is the code snippet of the same:</p> <pre><code>rds_conn = psycopg2.connect( host=config.RDS_HOST_NAME, database=config.RDS_DB_NAME, user=config...
<python><pandas><dataframe><python-polars><rust-polars>
2024-03-13 06:47:32
1
363
Balaji Venkatachalam
78,151,027
15,412,256
Polars Customized Function Returns Multiple Columns
<p><code>_func</code> is designed to return two columns:</p> <pre class="lang-py prettyprint-override"><code>from polars.type_aliases import IntoExpr, IntoExprColumn import polars as pl def _func(x: IntoExpr): x1 = x+1 x2 = x+2 return pl.struct([x1, x2]) df = pl.DataFrame({&quot;test&quot;: np.arange(...
<python><dataframe><python-polars>
2024-03-13 03:01:28
3
649
Kevin Li
78,151,000
1,592,380
Adding shapely polygon to geopandas
<p><a href="https://i.sstatic.net/joIfj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/joIfj.png" alt="enter image description here" /></a></p> <p>I'm working with jupyterlab . I'm trying to save the points of a Ipyleaflet polygon to geopandas (like in <a href="https://gregfeliu.medium.com/turning-coord...
<python><pandas><jupyter><gis><geopandas>
2024-03-13 02:49:47
1
36,885
user1592380
78,150,997
2,307,441
pd.wide_to_long in python is slow
<p>I have a dataframe with 55049 rows and 667 columns in it.</p> <blockquote> <p>Sample dataframe structure as follows:</p> </blockquote> <pre><code> data = { 'g1': [1], 'g2': [2], 'g3': [3], 'st1_1': [1], 'st1_2': [1], 'st1_3': [1], 'st1_4': [1], 'st1_5': [5], 'st1_6': [5], ...
<python><pandas><dataframe><transform>
2024-03-13 02:48:58
0
1,075
Roshan
78,150,864
9,357,484
Export displacy graphics as an image file shows an empty file
<p>I want to export displacy graphics as an image file. I run the following code block in Jupyter Notebook and generate an svg file name sample.svg.</p> <p>The code block is</p> <p>import spacy</p> <pre><code>from spacy import displacy from pathlib import Path nlp = spacy.load('en_core_web_lg') sentence_nlp = nlp(&qu...
<python><jupyter-notebook><nlp><spacy><displacy>
2024-03-13 01:51:25
1
3,446
Encipher
78,150,678
637,517
Shell one liner custom curl command with if else handling
<p>I'm trying to read a url using <strong>curl</strong> command, and expecting command to exit with return code 0 or 1 based on response of curl after parsing the response json.</p> <p>I tried to parse a json response, but notable to make it working in if else condition.</p> <p><em>URL - localhost:8080/health</em></p> ...
<python><linux><shell><curl><command>
2024-03-13 00:29:52
8
6,158
subodh
78,150,613
13,945,013
Setting up a Python project for packaging and distribution via Homebrew
<p>I'm trying to create a Homebrew formula for a Python project.</p> <p>Here's the Homebrew formula:</p> <pre class="lang-rb prettyprint-override"><code>class Scanman &lt; Formula include Language::Python::Virtualenv desc &quot;Using LLMs to interact with man pages&quot; url &quot;https://github.com/nikhilkmr300...
<python><homebrew><python-packaging>
2024-03-13 00:07:39
1
1,262
Nikhil Kumar
78,150,478
7,571,086
Installing PyTorch with Python version 3.11 in a Docker container
<p>I see on the official PyTorch page that PyTorch supports Python versions 3.8 to 3.11.</p> <p>When I actually try to install PyTorch + CUDA in a Python 3.11 Docker image, it seems unable to find CUDA drivers, e.g.</p> <pre><code>FROM python:3.11.4 RUN --mount=type=cache,id=pip-build,target=/root/.cache/pip \ pip ...
<python><docker><pytorch><python-3.11>
2024-03-12 23:14:46
1
380
Sishaar Rao
78,150,431
10,305,444
Getting `ValueError: as_list() is not defined on an unknown TensorShape.` when trying to tokenize as part of the model
<p>I am trying to do tokenization as part of my model, as it will reduce my CPU usage, and RAM, on the other hand, it will utilize my GPU more. But I am facing an issue saying <code>ValueError: as_list() is not defined on an unknown TensorShape.</code></p> <p>I have created a <code>Layer</code> called <code>Tokenizatio...
<python><numpy><tensorflow><keras><tokenize>
2024-03-12 22:55:21
0
4,689
Maifee Ul Asad
78,150,355
3,121,548
`from typing` vs. `from collections.abc` for standard primitive type annotation?
<p>I'm looking at the <a href="https://github.com/python/cpython/blob/3.12/Lib/typing.py" rel="noreferrer">standard library documentation</a>, and I see that <code>from typing import Sequence</code> is just calling <code>collections.abc</code> under the hood.</p> <p>Now originally, there was a deprecation warning/error...
<python><python-typing><standard-library>
2024-03-12 22:32:32
1
1,164
Dave Liu
78,150,317
9,783,587
Jupyter on VScode doesn't work with pyenv+poetry
<p>I'm trying to create a new Jupyter notebook in VScode. This is what I did so far:</p> <p>Step 1: installed VScode Jupyter extension.<br /> Step 2: created a virtual environment using pyenv.<br /> Step 3: installed jupyter using poetry.</p> <p>Maybe not relevant, but I also selected the virtual environment's interpre...
<python><visual-studio-code><jupyter-notebook>
2024-03-12 22:21:39
0
361
MaterialZ
78,150,295
10,083,382
Find a combination of column values exists in Lookup table
<p>Suppose that I have 2 dataframes <code>d1</code> and <code>d2</code> which can be generated using code below.</p> <pre><code>d1 = pd.DataFrame({'c1':['A', 'B', 'C', 'D', 'E', 'F'], 'c2': ['G', 'H', 'I', 'J', 'K', 'L'], 'val':[10, 20, 30, 40, 50, 60]}) d2 = pd....
<python><python-3.x><pandas><join><lookup-tables>
2024-03-12 22:15:08
1
394
Lopez
78,150,282
7,896,849
Choices from enum in pydantic
<p>I have a pydantic (v2.6.1) class with an attribute and I want to limit the possible choices user can make. I can use an enum for that. But the catch is, I have multiple classes which need to enforce different choices. See the example below,</p> <pre><code>from enum import Enum from pydantic import BaseModel, Validat...
<python><pydantic>
2024-03-12 22:08:07
1
11,971
Sreeram TP
78,150,149
110,129
Monkeypatch 'print' to 'yield' for streaming output
<p>I am using a long running function from a library that's primarily called from a CLI, and the status is shown by print statements. Something like this:</p> <pre class="lang-py prettyprint-override"><code>def long_running_function(): ... LOGGER.info(&quot;first thing done&quot;) ... LOGGER.info(&quot;...
<python><fastapi><server-sent-events><starlette>
2024-03-12 21:32:14
1
1,750
Jono
78,149,987
12,708,740
Append lists of elements as rows in df based on groupby
<p>I have two pandas dataframed called <code>df</code> and <code>legend</code>:</p> <pre><code>df = pd.DataFrame({'object': ['dog', 'dog', 'cat', 'mouse'], 'personID': [1, 1, 2, 3], 'word': ['paw', 'head', 'whisker', 'tail'], 'included': [1, 1, 1, 1]}) legend =...
<python><pandas><dataframe>
2024-03-12 20:53:32
1
675
psychcoder
78,149,967
3,826,115
Use xr.apply_unfunc on a function that can only take scalars, with an input of multi-dimensional DataArrays
<p>Lets say I have some function <code>f</code> that can only take in scalar values:</p> <pre><code>def f(a, b): # Ensure inputs are scalars assert(np.isscalar(a) and np.isscalar(b)) result1 = a + b result2 = a * b return result1, result2 </code></pre> <p>I also have two 2D xarray DataArrays:</...
<python><python-xarray>
2024-03-12 20:48:48
1
1,533
hm8
78,149,918
6,238,676
Split record into two records with a calculation based on condition
<p>As title says, Let's say I have following dataframe</p> <pre><code>import pandas as pd df = pd.DataFrame({'UID':['A','B','C','D'],'FlagVal':[0,100,50,90],'TrueVal':[1000,1000,1000,1000]}) ndf = df.loc[~df['FlagVal'].between(0,100,inclusive='neither')] mdf = df.loc[df['FlagVal'].between(0,100,inclusive='neither')] ...
<python><pandas>
2024-03-12 20:38:16
2
627
Prish
78,149,798
1,278,288
pytest, xdist, and sharing generated file dependencies
<p>I have multiple tests that need require an expensive-to-generate file. I'd like the file to be re-generated on every test run, but no more than once. To complicate the matter, both these tests as well as the file depend on an input parameter.</p> <pre><code>def expensive(param) -&gt; Path: # Generate file and re...
<python><pytest><pytest-xdist>
2024-03-12 20:09:10
1
1,830
nishantjr
78,149,683
48,956
How to save what jupyter's display() shows?
<p>Jupyter's display function is great for displaying a variety of objects (e.g. a dataframe). It seems that for many (most?) cases internally a bitmap, SVG, or HTML asset is created? Is there a way to generically save to file what <code>display()</code> shows?</p> <p>I only see examples to do <em>similar</em> via 3rd...
<python><jupyter-notebook><jupyter>
2024-03-12 19:42:36
1
15,918
user48956
78,149,673
15,412,256
Polars Customized Expression Constructor Function
<p>I want to change the first <code>n</code> rows with certain values in Polars. The normal use case is solved in the <a href="https://stackoverflow.com/questions/78143771/polars-replacing-the-first-n-rows-with-certain-values">previous post</a>.</p> <p>However, I want to achieve this by constructing a customized functi...
<python><dataframe><numpy><python-polars>
2024-03-12 19:40:21
1
649
Kevin Li
78,149,633
3,599,856
Create a Sparkline Bar Chart Within a Pandas Dataframe Column
<p>I am looking to replicate the image below in a pandas dataframe within a Jupyter notebook. The title of orders in 2020 is not needed. I discovered this page <a href="https://github.com/crdietrich/sparklines/blob/master/Pandas%20Sparklines%20Demo.ipynb" rel="nofollow noreferrer">https://github.com/crdietrich/sparklin...
<python><pandas><matplotlib><plotly><sparklines>
2024-03-12 19:30:40
1
373
Joe Rivera
78,149,556
3,079,439
Unknown Document Type Error while using LLamaIndex with Azure OpenAI
<p>I'm trying to reproduce the code from documentation: <a href="https://docs.llamaindex.ai/en/stable/examples/customization/llms/AzureOpenAI.html" rel="nofollow noreferrer">https://docs.llamaindex.ai/en/stable/examples/customization/llms/AzureOpenAI.html</a> and receive the following error after <code>index = VectorSt...
<python><azure><azure-openai><llama><llama-index>
2024-03-12 19:15:49
1
3,158
Keithx
78,149,546
6,145,729
MultiIndex DataFrame to a Standard index DF
<p>How do I convert a MultiIndex DataFrame to a Standard index DF?</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'old_code': ['00000001', '00000002', '00000003', '00000004'], 'Desc': ['99999991', '99999992 or 99999922', 'Use 99999993 or 99999933', '99999994']}, ) df1.set_index('old_code', inplace=True) df2=df1...
<python><python-3.x><pandas>
2024-03-12 19:13:20
1
575
Lee Murray
78,149,496
1,744,491
Deploy AWS stack using pulumi error: no stack named 'dev' found
<p>I'm trying to deploy a stack using pulumi in my AWS account. My deploy.yml looks like this:</p> <pre><code>name: Pushes Glue Scripts to S3 # Controls when the workflow will run on: # Triggers the workflow on push or pull request events but only for the &quot;main&quot; branch push: branches: [ &quot;main&qu...
<python><amazon-web-services><github-actions><pulumi>
2024-03-12 19:03:55
1
670
Guilherme Noronha
78,149,480
4,994,787
Why does Lark split names into separate characters?
<p>I'm trying to parse a simple text like this:</p> <pre><code>test abc </code></pre> <p>Lark grammar is here:</p> <pre><code>start: test test: &quot;test&quot; _WSI name _NL name: (LETTER | DIGIT | &quot;_&quot;)+ %import common.WS_INLINE -&gt; _WSI %import common.NEWLINE -&gt; _NL %import common.LETTER %import comm...
<python><lark>
2024-03-12 19:00:05
1
418
Grrruk
78,149,421
1,317,018
Unfolding tensor containing image into patches
<p>I have a batch of size <code>4</code> of size <code>h x w = 180 x 320</code> single channel images. I want to unfold them series of <code>p</code> smaller patches of shape <code>h_p x w_p</code> yielding tensor of shape <code>4 x p x h_p x w_p</code>. If <code>h</code> is not divisible for <code>h_p</code>, or <code...
<python><python-3.x><pytorch>
2024-03-12 18:49:39
1
25,281
Mahesha999
78,149,331
381,179
Pylance (VSCode) not displaying docstrings from my Rust (PyO3, Maturin) extension
<p>In Rust</p> <pre class="lang-rust prettyprint-override"><code>use pyo3::prelude::*; #[pyfunction] /// Returns the answer to life, the universe, and all the rest pub fn get_answer() -&gt; usize { 42 } #[pymodule] fn answers(_py: Python, m: &amp;PyModule) -&gt; PyResult&lt;()&gt; { m.add_function(wrap_pyfuncti...
<python><visual-studio-code><rust><pylance><pyo3>
2024-03-12 18:31:56
1
9,723
cadolphs
78,149,197
1,350,796
Visual editor for PIL?
<p>Is there a way to visually edit images and generate Pillow code that will correspond to those edits, ala recording a macro? I'm interested in creating Pillow code that will do different image transformation and compositions but it is a pain to develop everything purely in code - the feedback loop of running the scri...
<python><image><animation><image-processing><python-imaging-library>
2024-03-12 18:04:18
0
7,040
Andrew
78,149,126
14,121,088
Wrong dates when loading from s3 to Redshift
<p>I have an automatic process that is loading data from a s3 bucket in parquet format to a table in Redshift. And it was working fine</p> <p>But now, since 2024, the dates loaded in my redshift table look something like this: '2377-03-22 02:49:51:703' and before, when it was working fine it looked for example like thi...
<python><sql><amazon-web-services><amazon-s3><amazon-redshift>
2024-03-12 17:51:41
0
355
tonga
78,149,104
4,933,822
scipy butterworth filter has no delay? What's the trick?
<p><strong>On the following graph:</strong></p> <ul> <li><strong>Orange</strong>: original signal</li> <li><strong>Blue</strong> : butterworth filter from scipy applied.</li> <li><strong>Grey</strong> : a custom implementation of butterworth filter applied.</li> </ul> <p><a href="https://i.sstatic.net/63dXX.png" rel="n...
<python><scipy><butterworth>
2024-03-12 17:46:10
1
890
Julien
78,149,019
4,902,934
How to parse an unpickleable object from startup event to a function used in multiprocessing pool?
<p>Here are my code:</p> <pre><code>from multiprocessing import Pool from functools import partial from fastapi import FastAPI clientObject = package.client() # object not pickle able app = FastAPI() def wrapper(func, retries, data_point): # wrapper function to add a retry mechanism retry = 0 while retry...
<python><multiprocessing><fastapi><starlette>
2024-03-12 17:30:12
1
1,030
HienPham
78,148,971
4,133,524
Cannot import "deprecated" class from warnings module
<p>I am using code similar to</p> <pre><code>from warnings import deprecated @deprecated def test(): print(&quot;test&quot;) test() </code></pre> <p>I am getting an error (python 3.11) with &quot;cannot load deprecated from warnings&quot; and I was wondering if anybody knows why that is.</p> <p>I noticed that <a ...
<python>
2024-03-12 17:21:37
1
426
Barry
78,148,951
12,162,229
Coloring rows of dataframe in excel using xlsxwriter
<p>Here is my code, my problem seems to be writing the dataframe to excel creates formatting that I cannot overwrite:</p> <pre><code>import polars as pl import xlsxwriter as writer df = pl.DataFrame({ &quot;A&quot;: [1, 2, 3, 2, 5], &quot;B&quot;: [&quot;x&quot;, &quot;y&quot;, &quot;x&quot;, &quot;z&quot;, &q...
<python><xlsxwriter><python-polars>
2024-03-12 17:17:24
1
317
AColoredReptile
78,148,746
4,933,822
scipy butterworth filter to arm cmsis
<p>Witn scipy, I did some experiments with a butterworth filter like this:</p> <pre><code>sos = butter(order, normal_cutoff, btype='low', analog=False, output=&quot;sos&quot;) </code></pre> <p>I expect sos to be the coefficient of the filter.</p> <p>I need to port this filter to an arm platform. There are several filte...
<python><scipy><arm><cmsis>
2024-03-12 16:39:11
1
890
Julien
78,148,739
12,399,409
Expand unique values of a column into multiple columns, for X columns in a DataFrame
<p>I need to convert a DataFrame in the following shape:</p> <pre><code>import pandas as pd import numpy as np # input DataFrame df = pd.DataFrame({ 'foo': ['one', 'one', 'one', 'two', 'two', 'two', 'three', 'three', 'three'], 'tak': ['dgad', 'dgad', 'dgad', 'ogfagas', 'ogfagas', 'ogfagas', 'adgadg', 'adgadg', '...
<python><pandas><dataframe><pivot><data-cleaning>
2024-03-12 16:37:52
3
803
semblable
78,148,722
2,452,562
Problems with transitive imports in Python3
<p>I'm having a problem with some (likely badly-written) Python2 code, which I'm trying to convert to Python3. I'm sure this has been answered somewhere else before, but my Google-fu is not up to this task. I'm developing this on Ubuntu 18. (I know, Python2 and Ubuntu 18 are way way EOL, but my company is very slow ...
<python><python-module>
2024-03-12 16:33:59
0
580
Ken P
78,148,567
6,233,888
Avoid delayed patching
<p>I'm working on a Python project where I use <code>diskcache.Cache.memoize</code> for caching. I want to write unit tests for my code, and I'm having trouble figuring out how to properly mock <code>diskcache.Cache.memoize</code> using pytest without being delayed in my mocks.</p> <p>Here's a simplified version of my ...
<python><unit-testing><caching><mocking><monkeypatching>
2024-03-12 16:10:18
0
410
Daniel BΓΆckenhoff
78,148,519
1,714,692
Type hinting a dictionary with a given set of keys and values
<p>Suppose I have an Enum class in Python:</p> <pre><code>class MyEnum(Enum): A = &quot;a&quot; B = &quot;b&quot; </code></pre> <p>I have a function that is returning for each of the possible (two in this case) enum values a given type: suppose for both of them it is returning a DataFrame. I want to type hint, ...
<python><python-typing><python-3.8><typeddict>
2024-03-12 16:01:48
1
9,606
roschach
78,147,928
10,053,485
Pycharm: Decorated function with default parameter alerted as unfilled
<p><strong>Pycharm Version: 2023.1.5</strong> (up to date at time of writing)</p> <p>I'm building a decorator for an async function, which should retry to execute the decorated function when an error is detected.</p> <p>The code itself appears to work fine, but Pycharm still suggests the parameter with a default value ...
<python><pycharm><default-arguments>
2024-03-12 14:29:18
0
408
Floriancitt
78,147,903
5,547,553
How to create a conditional incremented column in polars?
<br> I'd like to create a conditional incremented column in polars.<br> It should start from 1 and increment only if a certain condition (pl.col('code') == 'L') is met.<br> <pre><code>import polars as pl df = pl.DataFrame({'file': ['a.txt','a.txt','a.txt','a.txt','b.txt','b.txt','c.txt','c.txt','c.txt','c.txt','c.txt']...
<python><python-polars>
2024-03-12 14:25:31
3
1,174
lmocsi
78,147,867
462,169
How can I distribute a Python application into an empty environment?
<p>I have a python3 app that I have written I need to install on a production, linux, server. For various reasons, this linux installation is very barebones. It will not have any version of python. It will not have Docker or anything similar. I don't know why that is the case, but those are my requirements. How ca...
<python><pyinstaller><python-venv><python-packaging>
2024-03-12 14:19:55
2
1,647
Wanderer
78,147,737
4,096,572
python-xarray: How to create a Dataset and assign results of an iteration to the Dataset?
<p>I have a for loop which is running some analysis on some data and returning some values. For boring reasons, this loop cannot easily be vectorised. I want to create a Dataset and then assign the result of the for loop to the Dataset as I iterate through.</p> <h1><code>Dataset.update</code></h1> <p>If I write some co...
<python><numpy><python-xarray>
2024-03-12 13:57:18
1
605
John Coxon
78,147,654
525,865
How to iterate a list from a to z - to scrape data and transform it into dataframe?
<p>Currently working on a scraper that collects the data of german insurances - here we have a comprehensive list of data insurances-companies from <strong>a to z</strong></p> <p>our <strong>menbers:</strong></p> <p><a href="https://www.gdv.de/gdv/der-gdv/unsere-mitglieder" rel="nofollow noreferrer">https://www.gdv.de/...
<python><pandas><web-scraping><beautifulsoup><python-requests>
2024-03-12 13:47:42
1
1,223
zero
78,147,561
11,462,274
How working correctly with Beautifulsoup to not generate Type Checking alerts in VSCode
<p>Page Source example:</p> <pre class="lang-python prettyprint-override"><code>from bs4 import BeautifulSoup, Tag, ResultSet from re import compile page_source = &quot;&quot;&quot; &lt;html&gt; &lt;body&gt; &lt;div class=&quot;block_general_statistics&quot;&gt; &lt;table&gt; &lt;tbody&gt; &lt;...
<python><visual-studio-code><beautifulsoup><python-typing>
2024-03-12 13:34:31
1
2,222
Digital Farmer
78,147,513
9,097,114
Compare and find nearest matching string by iterating rows from same column
<p>I am new to Python and trying to get output iterating over rows from same column</p> <pre><code># Import pandas library import pandas as pd # initialize list of lists data = [[1, 'AA,AC,BC,DE'], [2, 'AA,AD,BC,D'], [3, 'A,C,BC,E'],[4, 'AA,AC,BC,DEEE'],[5, 'KK']] # Create the pandas DataFrame df = pd.DataFrame(dat...
<python><pandas>
2024-03-12 13:26:29
1
523
san1
78,147,487
5,669,713
Assign output of expanded pandas str.extract to new columns of same dataframe when rows are filtered with .loc
<p>I have a dataframe with some registration types and some alphanumeric registration numbers for certain types. If a row has a certain type, I need to perform a regex operation on the relevant number, potentially splitting it into two, and return two columns based on that operation to the original dataframe. I am rece...
<python><pandas><regex><dataframe>
2024-03-12 13:22:50
0
355
Alex Howard
78,147,374
2,473,382
Python typing with explicit hint not used
<p>Why in the following code, <code>a</code> is not seen as being of type <code>LineString</code>? Pyright does not see any issue there with using a as an <code>int</code>.</p> <pre class="lang-py prettyprint-override"><code>from typing import cast import shapely from shapely.geometry.linestring import LineString def...
<python><python-typing>
2024-03-12 13:04:26
0
3,081
Guillaume
78,147,330
12,297,666
How create a list with only the months that have complete days in Python
<p>Consider the following DateTimeIndex:</p> <pre><code>from calendar import monthrange import pandas as pd index_h = pd.date_range(start='2022-01-04 00:00:00', end='2023-01-10 23:00:00', freq='H') </code></pre> <p>We can see that both January/2022 and January/2023 are incomplete.</p> <p>How can I create a list that c...
<python><pandas>
2024-03-12 12:59:07
0
679
Murilo
78,147,108
666,066
Pyinstaller generating difference executable sizes on two difference laptops
<p>I have a Python project that is converted to an executable using pyinstaller.</p> <p>The same executable is generated on another laptop and the size of the executable is not the same.</p> <p>The version of python on both Windows laptops is same. The list of python plugins is the same on both Windows laptops.</p> <p>...
<python><pyinstaller>
2024-03-12 12:26:17
1
774
KeithSmith
78,147,082
3,697,202
How can I type the return type of a subclass in Python?
<p>I use the service object pattern in my codebase. I have a base class for service objects:</p> <pre class="lang-py prettyprint-override"><code>from abc import ABC, abstractmethod from typing import Generic, TypeVar T = TypeVar(&quot;T&quot;, contravariant=True) # input type R = TypeVar(&quot;R&quot;, covariant=True...
<python><mypy><python-typing><pyright>
2024-03-12 12:21:55
0
1,057
tao_oat
78,146,998
1,079,320
I want to replace the url_for() call entirely
<p>I've had tremendous success using the following tutorial to stream a sequence of JPEG images from OpenCV using Flask: <a href="https://www.aranacorp.com/en/stream-video-from-a-raspberry-pi-to-a-web-browser/" rel="nofollow noreferrer">https://www.aranacorp.com/en/stream-video-from-a-raspberry-pi-to-a-web-browser/</a>...
<python><flask>
2024-03-12 12:09:52
1
670
lincolnberryiii
78,146,960
7,896,849
Exclude fields from a pydantic class
<p>I have a class like this,</p> <pre><code>from pydantic import BaseModel, Field class MyClass(BaseModel): field_1: str = Field(description='Field 1') field_2: dict = Field(description='Field 2') field_3: list = Field(description='Field 3') </code></pre> <p>I want to create child class inherting...
<python><pydantic>
2024-03-12 12:04:27
2
11,971
Sreeram TP
78,146,867
5,547,553
Element of list of tuples is truncated in python 3.9
<br> I'm trying to populate a list with tuples of key and regex expressions. Looking at the populated list looks good, but when I want to print it or write to file, then it gets truncated: <pre><code># coding: utf-8 import re regs = [] regs.append(('szerzodes_felmondas', re.compile(r'\b(szerzΓΆdΓ©sΓ©rΕ‘l|szerzΓΆdΓ‘st|szer...
<python>
2024-03-12 11:49:51
1
1,174
lmocsi
78,146,684
2,706,344
Unstack only the last three columns
<p>We start with this data:</p> <pre><code>import numpy as np import pandas as pd data=pd.DataFrame(data=np.random.rand(10,5),columns=['headA','headB','tailA','tailB','tailC']) </code></pre> <p><a href="https://i.sstatic.net/Bw7Nx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Bw7Nx.png" alt="enter imag...
<python><pandas><multi-index>
2024-03-12 11:23:02
1
4,346
principal-ideal-domain
78,146,641
1,377,912
Python ThreadPoolExecutor(max_workers=MAX_PARALLEL_REQUESTS) asyncio analog
<p>When I use ThreadPoolExecutor, I can send a requests batch with limitation of parallel requests like this:</p> <pre class="lang-py prettyprint-override"><code>with ThreadPoolExecutor(max_workers=MAX_PARALLEL_REQUESTS) as pool: results = list(pool.map(request_func, requests_input_data)) </code></pre> <p>How can I...
<python><python-asyncio><ipython-parallel>
2024-03-12 11:16:12
1
1,409
andre487
78,146,532
16,765,847
Display image using shiny in python
<p>I want to display an image using Shiny in Python, but I cannot find an error in the code. The file is not uploaded once I open the app and input the image.</p> <p>Here is the code:</p> <pre><code>from pathlib import Path from shiny import render from shiny.express import input, ui from shiny import App, Inputs, Outp...
<python><py-shiny>
2024-03-12 10:58:32
1
1,006
Isaac
78,146,531
15,519,366
Twitter API media upload fails with FileNotFoundError
<h1>What I want to do</h1> <p>I'm currently coding a Twitter bot which just creates a tweet with a couple of media with the Python wrapper &quot;Twikit&quot;. This is the Python code &quot;betsuaka_test.py&quot; I wrote is below:</p> <pre><code>from twikit import Client client = Client('ja') client.login( aut...
<python><twitter><twitterapi-python>
2024-03-12 10:58:19
1
827
ten
78,146,106
6,915,206
Django data getting saved in wrong model Why its saving the Model B,C data in model A
<p>I have 3 django models <code>CustomerDetail</code> <code>CarrierForm</code> <code>InfluencerModel</code> When i am trying to save data in <code>CarrierForm</code> or <code>InfluencerModel</code> through different different page's forms its getting saved in model <code>CustomerDetail</code> Why its happening tell me ...
<python><html><django><django-models><django-forms>
2024-03-12 09:52:40
1
563
Rahul Verma
78,145,973
4,095,235
Bug in large sparse CSR binary matrices multiplication result
<p>This boggles my mind, is this a known bug or am I missing something? If a bug is there a way to circumvent it?</p> <hr /> <p>Suppose I have a relatively small binary (0/1) n x q <code>scipy.sparse.csr_matrix</code>, as in:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from scipy import spars...
<python><scipy><sparse-matrix>
2024-03-12 09:31:41
1
3,709
Giora Simchoni
78,145,819
9,785,875
What's the best practice of configuring logging in Python?
<p>It seems that <code>logging</code> is not that easy to use in Python. For example, I need to use <code>logging</code> for logs, and I also need to import other stuff from some other packages.</p> <p>If I write my code like below:</p> <pre><code>import logging import foo from bar import baz logging.basicConfig(...) ...
<python><logging><pep8>
2024-03-12 09:07:18
0
644
Hank Chow
78,145,755
5,767,535
Unexplained behaviour from vectorized partial function using `numpy` and `functools`
<p>I am trying to vectorize a partial function which takes two arguments, both of them lists, then does something to the pairwise elements from the lists (using <code>zip</code>). However, I am finding some unexpected behaviour.</p> <p>Consider the following code:</p> <pre class="lang-py prettyprint-override"><code>imp...
<python><numpy><vectorization><functools>
2024-03-12 08:56:14
2
2,343
Daneel Olivaw
78,145,667
2,508,672
Python comparing data in Pandas format mismatch
<p>I have the input below with data (test.csv)</p> <pre><code>date,time 26-02-2024,8:01 26-02-2024,8:01 26-02-2024,7:59 26-02-2024,7:59 26-02-2024,7:56 26-02-2024,7:55 26-02-2024,7:55 26-02-2024,7:53 26-02-2024,7:52 26-02-2024,7:52 </code></pre> <p>Now I have the code below</p> <pre><code>df = pd.read_csv('test.csv') d...
<python><pandas>
2024-03-12 08:39:30
1
4,608
Md. Parvez Alam
78,145,559
19,565,276
How to combine members of flags when values are tuples
<p>I have an enum Flag defined like this:</p> <pre><code>@unique @verify(CONTINUOUS) class DaysEnum(IntFlag): ONE = (1, &quot;One Day&quot;) TWO = (2, &quot;Two Days&quot;) THREE = (3, &quot;Three Days&quot;) FOUR = (4, &quot;Four Days&quot;) FIVE = (5, &quot;Five Days&quot;) SIX = (6, &quot;Six...
<python><enums>
2024-03-12 08:18:59
1
311
Lucien Chardon
78,145,511
15,915,172
How to retrain the existing vertex AI model using more data? Is there any process with python?
<p>I am learning Google's vertex AI, AutoML with Python. I have created the single label dataset, pipelines, endpoint and deployed the model using google's UI.</p> <p>Now I have more data then how to append that into existing dataset? or retrain the existing model?</p>
<python><google-cloud-vertex-ai><automl><google-prediction>
2024-03-12 08:12:16
1
784
Rakesh Saini
78,145,418
13,734,451
Looping through list of lists then create a dataframe
<p>I have a list containing sublists. I want to loop through all the sublist and extract the data, save them in individual lists then create a dataframe. When I try doing so the values get mixed up....</p> <pre><code> fulllist = [ [ {'Variable': 'First_Name', 'Answer': 'Anne'}, {'Variable': 'Middle_Name', 'Answer': '...
<python><pandas><dataframe>
2024-03-12 07:56:28
3
1,516
Moses
78,145,023
9,394,465
file with quotes in any of the fields to be retained as is in pandas
<p>I have been trying so many options but not able to retain the quotes present in the input file onto my output file.</p> <p>Reproducible code:</p> <pre><code># Input file csv_data = '''A,B,C,D,E 234,mno,C22,U, 567,pqr,&quot;C3&quot;&quot;&quot;,U,5555 999,abc,&quot;C99&quot;,D,9999 ''' # Load CSV data into dataframe...
<python><pandas>
2024-03-12 06:27:37
1
513
SpaceyBot
78,144,868
13,801,302
How to add langchain docs to LCEL chain?
<p>I want to create a chain in langchain. And get the following error in short</p> <pre><code>TypeError: Expected a Runnable, callable or dict.Instead got an unsupported type: &lt;class 'str'&gt; </code></pre> <p>You find the complete error message at the end.</p> <p><strong>What I want to do?</strong></p> <p>First I p...
<python><langchain><information-retrieval><data-retrieval>
2024-03-12 05:45:27
1
621
Christian01
78,144,776
10,483,893
python: With GIL, is it still possible to have deadlocks with threading? (Not multi-processing)
<p>python: With GIL, is it still possible to have deadlocks with threading? (Not multi-processing)</p> <p>Below code will produce deadlock situation (Updated per Amadan, added sleep):</p> <pre><code>import threading import time # Two resources resource1 = threading.Lock() resource2 = threading.Lock() def function1():...
<python><multithreading><gil>
2024-03-12 05:13:40
1
1,404
user3761555
78,144,558
6,803,114
Open folder button in streamlit
<p>I have built a streamlit application which reads a file and processes it and stores it in a file folder which is already defined.</p> <p>Now I want to create a button in streamlit where after file is processed it should display a button, which on click opens the respective folder. Screenshot for reference: <a href="...
<python><python-3.x><streamlit>
2024-03-12 03:47:58
0
7,676
Shubham R
78,144,557
303,863
Efficient modular arithmetic in Z3
<p>I want to work with integer modulo 3 under addition in BitVec, so basically (a+b)%3. Note BitVec is much faster than integer so I want to make sure all operations are inside BitVec.</p> <p>I would need to create bit vectors of size 3. This is because compute a+b would need 3 bits, although taking the modulus, the re...
<python><z3><z3py>
2024-03-12 03:47:22
1
2,206
Chao Xu
78,144,401
2,694,184
How could I handle superclass and subclass cases
<p><strong>Problem statement:</strong></p> <p>I have 100s of py files which defines pydantic schema. Suddenly I need to treat empty string as None. I am expecting minimal changes across all the files.</p> <p><strong>Approach I implemented:</strong></p> <p>I created an inherited class such as</p> <pre><code>class Constr...
<python>
2024-03-12 02:42:47
1
23,098
Gibbs
78,144,376
11,188,140
Applying a specified rule to build an array
<p>Consider array <code>a</code> whose columns hold random values taken from 1, 2, 3:</p> <pre><code>a = np.array([[2, 3, 1, 3], [3, 2, 1, 3], [1, 1, 1, 2], [1, 3, 2, 3], [3, 3, 1, 3], [2, 1, 3, 2]]) </code></pre> <p>Now, consider array <code>b</code...
<python><arrays><numpy>
2024-03-12 02:34:12
1
746
user109387
78,144,199
6,654,904
Error BadGzipFile when read gz file via python gzip
<p>The source file is json and we zipped it to gz format. The file is good. I am able to open the file with notepad++</p> <pre><code>import gzip # Open the GZIP file in text mode ('rt') with gzip.open('example.gz', 'rt') as f: file_content = f.read() print(file_content) </code></pre> <p>The error I get is</p> ...
<python><json><gzip>
2024-03-12 01:16:45
1
353
Anson
78,144,080
4,555,858
Update parent class variable from child class in Python
<p>The code below has two classes, and I am trying to update the parent class variable from the <code>Child1</code> class.</p> <pre><code>class Parent: def __init__(self): self.shared_variable = &quot;I am a shared variable&quot; class Child1(Parent): def __init__(self): super().__init__() ...
<python><inheritance>
2024-03-12 00:36:05
1
483
Prateek Daniels
78,144,060
1,159,783
Type-checking dynamic attribute creation using Mypy plugins
<p>I have a codebase that uses a deeply weird pattern for defining command-line options. It looks like this:</p> <pre class="lang-py prettyprint-override"><code># opts.py def group(): o = OptionsGroup() return o, o.define options = _SomeOptionsSingletonClass() def define(name: str, type_: Type, default: bool...
<python><mypy><python-typing>
2024-03-12 00:27:00
1
2,769
David Reed
78,143,969
6,597,296
Is it possible to output emojis in a CMD.EXE window with Python?
<p>If I open a Command window tab in the Windows Terminal, either of the following methods would work correctly:</p> <pre class="lang-py prettyprint-override"><code>print(&quot;\U0001F600&quot;) </code></pre> <pre class="lang-py prettyprint-override"><code>print(&quot;\N{grinning face}&quot;) </code></pre> <pre class="...
<python><console><emoji>
2024-03-11 23:53:52
1
578
bontchev
78,143,771
15,412,256
Polars replacing the first n rows with certain values
<p>In Pandas we can replace the first <code>n</code> rows with certain values:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({&quot;test&quot;: range(10)}) df_pd = df.to_pandas() df_pd.iloc[0:5] = float(&quot;nan&quot;) df_pd </code></pre> <pre><code> test 0 NaN 1 Na...
<python><dataframe><python-polars>
2024-03-11 22:46:40
3
649
Kevin Li
78,143,604
1,422,096
How does this embedded Python packaging find its lib files?
<p>Blender(*) for Windows is shipped with an embedded Python, like this:</p> <pre><code>blender-2.79b-windows64\ 2.79\ python\ bin\ python.exe python35.dll # only these 2 files lib\ asyncio\ collections\ ...
<python><blender><python-embedding>
2024-03-11 21:57:28
1
47,388
Basj
78,143,576
1,018,826
Python and PCRE regex that are the same give different outputs for the same input
<p>I am trying to implement the <code>minbpe</code> library in <a href="https://github.com/GoWind/tokenizig/blob/main/src/main.zig#L33" rel="nofollow noreferrer">zig</a>, using a wrapper over <a href="https://github.com/liyu1981/jstring.zig" rel="nofollow noreferrer">PCRE library</a>.</p> <p>The pattern in Python is <c...
<python><regex><pcre><pcre2>
2024-03-11 21:48:55
2
483
draklor40
78,143,403
1,035,279
How can I eliminate the segfaults that occur in working code only when debugging with ipdb?
<p>I am using:</p> <ul> <li>Python: 3.11.0</li> <li>Django: 4.2.8</li> <li>djangorestframework 3.14.0</li> <li>sqlite: 3.38.5</li> </ul> <p>When I'm debugging and I use 'n' to go over a method, I sometimes get a segfault where there is no problem running the code normally. I can move my 'ipdb.set_trace()' to immediatel...
<python><django><django-rest-framework><ipdb>
2024-03-11 21:03:21
1
16,671
Paul Whipp
78,143,337
2,248,721
Generate smoother colormap for contour plot
<p>My data set contains approximately thousands of values in four columns <em>X, Y, Z, error of Z</em> -</p> <pre><code>1.2351e+00 -6.3115e-02 0.0000e+00 0.0000e+00 1.2417e+00 -6.3115e-02 0.0000e+00 0.0000e+00 1.2483e+00 -6.3115e-02 0.0000e+00 0.0000e+00 1.2549e+00 -6.3115e-02 0.0000e+00 0.0000e+00 1.2615e+00 ...
<python><matplotlib><contour><colormap><contourf>
2024-03-11 20:46:39
1
433
aries0152
78,143,281
12,820,205
App to store and view multiple instances of itself
<p>My Toga-based app has the user enter information in a series of boxes. In the end, the information is used to start a number of processes governed by a scheduler. Once the processes are started, progress should be displayed to the user through continuous updates of a status box.</p> <p>The user is to run several ins...
<python><beeware>
2024-03-11 20:31:51
1
1,994
rjen
78,143,259
8,740,854
How to create the @iterator_cache decorator?
<p><strong>Question:</strong> How to create the <code>iterator_cache</code> decorator ?</p> <pre class="lang-py prettyprint-override"><code>@iterator_cache def cheap_eval(numbers: Tuple[int]) -&gt; Tuple[int]: print(&quot;cheap eval of {numbers}&quot;) return expensive_eval(numbers) def expensive_eval(numbers:...
<python><caching>
2024-03-11 20:29:25
2
472
Carlos Adir
78,143,186
13,181,599
How to run juggernaut model in local
<p>I want to run fine-tuned stable diffusion models in my local pc using python. For example juggernaut: <a href="https://huggingface.co/RunDiffusion/Juggernaut-XL-v9" rel="nofollow noreferrer">https://huggingface.co/RunDiffusion/Juggernaut-XL-v9</a></p> <p>This is my code (it works with stable-diffusion-xl-base-1.0):<...
<python><machine-learning><pytorch><stable-diffusion><fine-tuning>
2024-03-11 20:12:01
2
301
Mahammad Yusifov
78,143,178
3,288,004
How to check multiple items for nullity in an AND fashion in Python
<p>I was wondering if there's a Pythonic/hacky way to check for all (or none) items and dependencies in a set to be null.</p> <p>Suppose I have a variable <code>foo</code> that is a dict, but can be nullable:</p> <pre class="lang-py prettyprint-override"><code>foo: Optional[dict] = None </code></pre> <p>And I want to c...
<python><python-3.x><conditional-statements>
2024-03-11 20:10:17
3
2,069
Tiago Duque
78,143,080
6,273,533
FileNotFoundError: [WinError 2] The system cannot find the file specified: find extensions in os.listdir
<p>Trying to delete all but one file in a given directory. Looked at other related posts but my question seems specific to getting names from os.listdir and needing full path with extensions to use os.remove:</p> <pre><code># delete files from the save path but preserve the zip file if os.path.isfile(zip_path): fo...
<python><listdir>
2024-03-11 19:47:00
1
709
geoJshaun
78,143,064
159,072
How can I compute this?
<p>Suppose I have the following numpy array:</p> <pre><code>import numpy as np my_data = np.array( [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5]]) # obtain the length n = len(my_data) # 5 </code></pre> <p>I want to do this computation for t=0, 1, 2, 3, 4.</p> <ol> <li>take the t-th row</li> <li>compute d...
<python><numpy>
2024-03-11 19:42:56
1
17,446
user366312
78,142,890
17,800,932
Passing additional arguments for Python's `websockets` `serve` function
<p>I am prototyping a WebSocket server using Python's <a href="https://websockets.readthedocs.io/en/stable/index.html" rel="nofollow noreferrer"><code>websockets</code> library</a>.</p> <pre class="lang-py prettyprint-override"><code>async def receive_websocket_message(websocket, send_queue: asyncio.Queue, receive_queu...
<python><websocket><python-asyncio>
2024-03-11 19:02:24
1
908
bmitc
78,142,676
7,179,546
How can I process a request to AzureChatOpenAI that is too big?
<p>I'm trying to perform a question to AzureChatOpenAI that is very big. Therefore I'm getting the following error:</p> <pre><code>openai.BadRequestError: Error code: 400 - {'error': {'message': &quot;This model's maximum context length is 8192 tokens. However, your messages resulted in 37571 tokens (37332 in the messa...
<python><azure-openai>
2024-03-11 18:14:06
1
737
Carabes
78,142,403
13,578,682
Why are these two datetimes not equal?
<pre><code>from datetime import datetime, timedelta from zoneinfo import ZoneInfo chi = ZoneInfo(&quot;America/Chicago&quot;) nyc = ZoneInfo(&quot;America/New_York&quot;) dt1 = datetime(2024, 3, 10, 3, 30, tzinfo=chi) dt2 = datetime(2024, 3, 10, 2, 30, tzinfo=chi) print(dt1 == dt1.astimezone(nyc)) print(dt2 == dt2.ast...
<python><datetime><timezone><dst>
2024-03-11 17:20:05
1
665
no step on snek
78,142,241
14,244,437
Annotations returning pure PK value instead of Django HashID
<p>In my application the user can assume one of 3 different roles.</p> <p>These users can be assigned to programs, and they can be assigned to 3 different fields, each of those exclusevely to a role.</p> <p>In my API I'm trying to query all my users and annotate the programs they are in:</p> <pre><code>def get_queryset...
<python><django><postgresql><django-orm><hashids>
2024-03-11 16:45:11
0
481
andrepz
78,142,224
4,168,794
Finetuing BERT with masking and having multiple correct labels
<p>I aim to fine-tune a BERT model for a specific task involving simple arithmetic operations like &quot;5 + 3 = 8&quot; or &quot;7 plus 2 equals 9&quot;. My dataset comprises thousands of examples where one operand, operator, or result is masked. For instance:</p> <ul> <li>Masked: &quot;1 added to [MASK] equals 7&quot...
<python><nlp><huggingface-transformers><bert-language-model>
2024-03-11 16:43:12
1
655
abbassix
78,142,209
18,494,333
Read from audio output in PyAudio through loopbacks [Python record system output]
<p>I'm writing a program that records from my speaker output using <code>pyaudio</code>. I am on a Raspberry Pi. I built the program while using the audio jack to play audio through some speakers, but recently have switched to using the speakers in my monitor, through HDMI. Suddenly, the program records silence.</p> <p...
<python><pyaudio><loopback><portaudio><pulseaudio>
2024-03-11 16:40:00
1
387
MillerTime
78,142,190
6,145,729
Python 3 Data Frame string manipulation to extract numbers between 8 to 12 characters
<p>I'm not sure where to start with this one.</p> <p>I have a list of obsolete items with a new item_code listed somewhere in the description column. Item codes are always between 8 &amp; 12 characters so all other numbers in the description should be ignored.</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'Ite...
<python><python-3.x><pandas>
2024-03-11 16:36:36
1
575
Lee Murray
78,142,171
4,547,189
Pandas select rows with values are present for all elements in array
<p>Firstly the title of the post may not do justice to the question, so my humble apologies for this.</p> <p>Here is the question:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>Date</th> <th>Type</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>2024-03-11</td> <td>3</td> <td>3</td> </tr...
<python><pandas>
2024-03-11 16:31:07
1
648
tkansara
78,142,075
14,775,478
What is a vectorized way to detect feature drift in pandas columns?
<p>I'm working on very large pandas dataframes that hold time series with significant feature drift. The drift is often sudden (e.g., the features would be 1.5-2.0x times larger than a few periods earlier).</p> <p>I found several solutions to detect 'concept drift'. One convenient option is <a href="https://riverml.xyz...
<python><pandas><filtering><feature-engineering><drift>
2024-03-11 16:14:42
1
1,690
KingOtto
78,142,072
2,611,009
square root function on Python using Spyder
<p>I'm just starting out using both Python under Spyder. I was about to do a simple square root calculation. I see that in Python, you need to do an &quot;import math&quot;. I did that in Spyder and got an error: 'math' imported but unused. I tried using sqrt() but that threw an error. There's something fundamenta...
<python><spyder>
2024-03-11 16:14:13
3
413
Clem
78,141,853
1,422,096
Folder structure inside Python "embedded" packaging
<p>I distribute a ready-to-run software for Windows written in Python by:</p> <ul> <li>shipping the content of an embedded version of Python, say <code>python-3.8.10-embed-amd64.zip</code></li> <li>adding a <code>myprogram\</code> package folder (= the program itself)</li> <li>simply run <code>pythonw.exe -m myprogram...
<python><windows><python-packaging><python-embedding><pth>
2024-03-11 15:38:55
1
47,388
Basj
78,141,847
2,812,625
Pandas remove strings after character occurance
<p>I am trying to remove the last occurrence of the string where there is a hyphen(-) leaving all the other strings alone that do not mean that criteria:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th style="text-align: center;">Name1</th> <th style="text-align: right;">ID</th> <th style="t...
<python><pandas>
2024-03-11 15:38:21
1
446
Tinkinc
78,141,829
163,536
How do I avoid circular imports when using sqlalchemy relationship() with type annotations?
<p>I'm declaring my models like so:</p> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations class Parent(Base): ... children: Mapped[list[Child]] = relationship(&quot;Child&quot;, back_populates=&quot;parent&quot;) class Child(Base): ... parent_id: Mapped[Optional[str]] ...
<python><sqlalchemy><python-typing>
2024-03-11 15:35:58
2
1,180
lorg