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
βŒ€
77,971,552
14,488,413
How to write a python function that splits and selects first element in each pandas column
<p>I have a dataframe <code>df</code> with double entries separated by a <code>,</code> in some columns. I want to write a function to extract only the entry before the <code>,</code> for columns with double entries.</p> <p>Example: <code>20.15,20.15</code> split to <code>20.15</code></p> <p>See the dataframe</p> <pre...
<python><pandas><user-defined-functions>
2024-02-10 00:55:27
2
322
nasa313
77,971,363
5,091,507
Python nested directories import error "ImportError: attempted relative import with no known parent package"
<p>I have a project where the files and directories are structured as below:</p> <pre><code>Project/ β”œβ”€ __init__.py β”œβ”€ main.py β”œβ”€ Utils/ └─ general_utils.py └─ __init__.py └─ Baselines/ └─ __init__.py └─ random/ └─ __init__.py └─ random.p...
<python><python-3.x><import><nested>
2024-02-09 23:32:43
1
1,047
A.A.
77,971,348
395,857
How can one add a label to a Markdown box in Gradio?
<p>I tried:</p> <pre><code>import gradio as gr with gr.Blocks(css=&quot;footer{display:none !important}&quot;) as demo: answer = gr.Markdown(value='[StackOverflow](https://stackoverflow.com/)', label=&quot;Answer&quot;) demo.launch(share=True) </code></pre> <p>but to my surprise, the label &quot;Answer&quot; doesn'...
<python><gradio>
2024-02-09 23:28:17
1
84,585
Franck Dernoncourt
77,971,075
169,947
Python: load resources without using __init__.py files
<p>I have a directory of JSON Schema files that's distributed with a python package. Some code in the package uses the schema files to validate data.</p> <p>The way I'm currently loading the schema files is like so:</p> <pre><code>from importlib import resources from myapp.schema import v1 as schema_v1 ... def _sche...
<python><resources><jsonschema><init>
2024-02-09 22:02:02
0
24,277
Ken Williams
77,971,020
6,361,813
MultiIndex Dataframe: Sort values for each group
<p>Assume I have a <code>pandas</code> MultiIndex Dataframe similar to the one below. How do I sort the values for each group by preserving the assignment and order of the indexes? The code below works for the sorting, but I fail to resave the sorted values and <code>inplace</code> does not seem to work.</p> <pre><code...
<python><pandas><group-by>
2024-02-09 21:45:08
3
407
Pontis
77,971,003
8,713,442
How to create list column with alias in polars dataframe
<p>I have table which has some columns in it . I need to run some rules to match data with incoming data and provide score .</p> <p>I am trying to create list of score and find best out of it but below mentioned piece is not running . it is giving error</p> <pre><code>import polars as pl import jaro def test_polars...
<python><python-polars>
2024-02-09 21:39:52
1
464
pbh
77,970,924
893,254
Using a functor as a stateful callback function in Python
<p>If I have a function which takes a callback function as an argument, how can I create a functor object which can be used in place of a callback function, if that callback function takes some set of arguments?</p> <h1>Context:</h1> <p>Kafka producers take a callback function.</p> <pre><code>producer.produce( topic=...
<python>
2024-02-09 21:19:59
1
18,579
user2138149
77,970,839
6,461,882
Vectorized way to copy elements from pandas Series to python built-in array
<p>Is there a vectorized way to copy elements from a pandas Series to a python built-in array? For example:</p> <pre class="lang-py prettyprint-override"><code>from array import array import pandas as pd s = pd.Series(range(0, 10, 2)); s += 0.1 a = array('d', [0.0]*10) # I am looking for a vectorized equivalent of the...
<python><arrays><pandas><vectorization><series>
2024-02-09 20:57:43
1
2,855
S.V
77,970,659
6,458,245
Huggingface pipeline error: IndexError: too many indices for tensor of dimension 2
<p>Anyone know why I get that error when I run the pipeline?</p> <pre><code>from transformers import AutoModelForSequenceClassification from transformers import AutoTokenizer from transformers import pipeline modeltemp = AutoModelForSequenceClassification.from_pretrained(&quot;bert-base-cased&quot;, num_labels=5) toke...
<python><pytorch><huggingface-transformers><huggingface>
2024-02-09 20:20:41
1
2,356
JobHunter69
77,970,391
9,698,518
Benchmarking with Pytest Parallelized Cython Code results in Fatal Python Error
<p>I have the following test:</p> <pre class="lang-py prettyprint-override"><code>import array def test_parallel_cython_clip(benchmark: Any) -&gt; None: benchmark.pedantic( math_cython.parallel_cython_clip_vector, args=(array.array(&quot;f&quot;, [0.0]),-1.0,1.0,array.array(&quot;f&quot;, [0.0])), ...
<python><parallel-processing><pytest><cython><benchmarking>
2024-02-09 19:24:17
1
672
mgross
77,970,307
1,786,165
Parsing single line and multi line comments with Arpeggio
<p>I'm trying to use Arpeggio to parse file containing single line and multi line comments.</p> <p>Arpeggio's documentation suggests to have a look at their &quot;simple&quot; example to see how to deal with them (see <a href="https://textx.github.io/Arpeggio/2.0/configuration/#comment-handling" rel="nofollow noreferre...
<python><python-3.x><peg><arpeggio>
2024-02-09 19:02:23
1
644
Stefano Bragaglia
77,970,235
21,107,707
Detect arrow key being pressed while an `input()` is running in Python
<p>I am creating a REPL for a programming language, and I want to allow arrow keys to cycle through past inputs, much like the official Python REPL does. In order to take user input, I'm doing something like this:</p> <pre class="lang-py prettyprint-override"><code>code = input(&quot; &gt; &quot;) # stuff here to proce...
<python>
2024-02-09 18:46:17
3
801
vs07
77,970,172
5,594,008
Fakeredis, mocking django cache function in DRF tests
<p>I'm using fakeredis to mock my Django tests</p> <p>settings.py</p> <pre><code>CACHES = { &quot;default&quot;: { &quot;BACKEND&quot;: &quot;django_redis.cache.RedisCache&quot;, &quot;LOCATION&quot;: &quot;redis://127.0.0.1:6382&quot;, &quot;TIMEOUT&quot;: env.int(&quot;CACHE_TIMEOUT&quot;,...
<python><django><fakeredis>
2024-02-09 18:33:52
1
2,352
Headmaster
77,970,082
17,274,113
importing geopandas throws error `module 'os' has no attribute 'add_dll_directory'`
<p><code>enter code here</code>when importing geopandas: <code>import geopandas as gpd</code> error <code>module 'os' has no attribute 'add_dll_directory'</code> is thrown.</p> <p>geopandas version: 0.9.0</p> <p>python version: 3.7</p> <p>operating system: Windows 10</p> <p><strong>Constraint:</strong></p> <p>I am work...
<python><dll><environment><arcgis><geopandas>
2024-02-09 18:13:00
0
429
Max Duso
77,970,057
12,846,524
Customtkinter thread causing strange freezing issue after self.destroy() is called under certain conditions
<h2>Outline of task</h2> <p>I have a GUI created using CustomTKinter that acquires data when a 'start' button is clicked, and a 'stop' button that stops the data acquisition. These are controlled by an instance of threading.Thread in another class that uses a state variable (ThreadState) and a boolean (get_data) to con...
<python><multithreading><user-interface><customtkinter>
2024-02-09 18:09:23
1
374
AlexP
77,970,004
18,476,381
Pytest Unit Testing API's best practice and dependencies
<p>I'm using pytest to test various API's I have created and was curious on some best practices as my tests are getting more complicated in a sense that some api's depend on the creation of others. Example below.</p> <p>Lets say I have a service that creates purchase-orders, each purchase-order can have multiple line-i...
<python><unit-testing><pytest>
2024-02-09 17:57:40
0
609
Masterstack8080
77,969,965
13,088,678
concat a value and Null columns
<p>I have a dataframe having 3 columns.</p> <ul> <li>column1 - int</li> <li>column2 - array of struct</li> <li>column3 - array of struct</li> </ul> <p>Im trying to concatenate column2 and column3. However when any one of the column contains null/none, then whole concatenated column becomes null/none, even when one of ...
<python><apache-spark><pyspark>
2024-02-09 17:51:08
1
407
Matthew
77,969,964
23,260,297
Deprecation Warning with groupby.apply
<p>I have a python script that reads in data from a csv file</p> <p>The code runs fine, but everytime it runs I get this Deprecation message:</p> <pre><code>DeprecationWarning: DataFrameGroupBy.apply operated on the grouping columns. This behavior is deprecated, and in a future version of pandas the grouping columns wi...
<python><pandas><dataframe>
2024-02-09 17:50:46
7
2,185
iBeMeltin
77,969,927
731,351
polars: select values from group_by list with a value from another column
<p>Starting with df:</p> <pre><code>df = pl.DataFrame( { &quot;seq&quot;: &quot;foo bar bar duk duk baz baz baz zed&quot;.split(), &quot;seq_grp&quot;: &quot;aa bb bb dd dd cc cc cc zz&quot;.split(), &quot;match&quot;: &quot;aa cc bb dd dd ff cc cc yy&quot;.split(), &quot;score&quot;: ...
<python><python-polars>
2024-02-09 17:40:12
2
529
darked89
77,969,902
824,167
How to override task decorator in Airflow for testing?
<p>I am using a <code>@task.external_python</code> decorator that points to a custom <code>venv</code> with some additional dependencies.</p> <p>I want to be able to write an integration tests where I mock certain API's <code>requests-mock</code> and have entire DAG run end to end. That means that my pytest and dag sho...
<python><airflow>
2024-02-09 17:34:52
1
2,300
Vlad Miller
77,969,878
11,330,134
Insert outer dict value to inner dict list
<p>I have a nested <code>dict</code> of lists and dicts I want to ultimately iterate through and output to a dataframe.</p> <p>This sample dictionary has five items so I'm expecting a dataframe of five rows; however, it is doubling up and producing ten rows.</p> <p>There are nested lists and dicts. I want to keep the o...
<python><pandas><dictionary>
2024-02-09 17:30:28
1
489
md2614
77,969,833
17,556,733
How do I create an aws rds aurora database with some tables with python aws cdk?
<p>I want to create an AWS stack with the python aws-cdk library.</p> <p>The requirements are as such: There must exist an aurora3 mysql database and it needs to have 2 tables (as a reduced example, lets say <code>table1</code> needs to have 2 fields: <code>id</code> of integer type and <code>name</code> of string type...
<python><amazon-web-services><aws-cdk><amazon-aurora>
2024-02-09 17:20:50
1
495
TheMemeMachine
77,969,738
2,812,625
Vertica_python and Sqlalchemy Insert
<p>I am using sqlalchemy and vertica_python to pull down tables into python and would like to writ tables to my own schema there after but am getting an error on the df.to_sql() I can read tables with the connection string.</p> <pre><code>engine = sqlalchemy.create_engine('vertica+vertica_python://username:password@loc...
<python><pandas><sqlalchemy><vertica-python>
2024-02-09 17:03:37
0
446
Tinkinc
77,969,707
616,460
Resolve relative or absolute path relative to another path
<p>Given a path that may be absolute or relative, I'd like to resolve its absolute path relative to another given path (if it's relative), without changing the current directory.</p> <p>For example, assuming the current working directory is <code>/cwd</code>:</p> <pre><code>def resolve_path (relative_to, path_to_resolv...
<python><python-3.x><path>
2024-02-09 16:58:00
1
40,602
Jason C
77,969,675
12,684,429
How to identify anomalous data automatically
<p>I'm looking to remove anomalous data from a dataset in python and as per comments below, I believe the best way to do this is to have a rolling average - and then remove data if it falls 2-3 std outside of that rolling average.</p> <p>So far I have the below but it doesn't seem to be doing what I want it to as the e...
<python><data-cleaning>
2024-02-09 16:51:41
0
443
spcol
77,969,660
2,443,551
Django messages with javascript fetch() API and redirect
<p>I am doing a request with the <code>fetch()</code> API to a django view, which will set a message with the <code>messages</code> app and redirect the request. I can capture the redirect with <code>response.redirected</code> and the <code>messages</code>-cookie is set, but when i do the redirect with <code>location.r...
<javascript><python><django>
2024-02-09 16:49:33
1
451
dequid
77,969,654
8,713,442
Error while finding similarity between polars dataframe column and string variable
<p>I need to find a similarity between the column in the polar data frame and the input value.I am using jaro_winkler_metric . I am getting errors while doing it. We don't want to use UDF functions as it slows the process.</p> <pre><code>import polars as pl import jaro def test_polars(): name='savah' data = {...
<python><python-polars>
2024-02-09 16:48:57
1
464
pbh
77,969,516
10,533,225
TypeError: object Response can't be used in 'await' expression
<p>I am trying to execute this unit test. I would like to asynchronously await the GET as it takes a while to retrieve data. However, I am getting: <code>TypeError: object Response can't be used in 'await' expression</code>.</p> <pre><code>@pytest.mark.asyncio async def test_get_report(report_service, client, headers):...
<python><pytest><python-asyncio>
2024-02-09 16:24:46
1
583
Tenserflu
77,969,478
4,933,902
How to convert XGBClassifier with dart booster to ONNX?
<p>I need to convert a XGBClassifier with booster='dart' into an onnx model. But the converting failed with an error on last line:</p> <pre><code>.venv\Lib\site-packages\onnxmltools\convert\xgboost\common.py&quot;, line 40, in get_xgb_params gbp = config[&quot;learner&quot;][&quot;gradient_booster&quot;][&quot;gbtree_m...
<python><scikit-learn><xgboost><onnx><xgbclassifier>
2024-02-09 16:18:13
1
910
JoGe
77,969,278
1,555,306
Pandas - Getting weird indexing and shape when reading multiple CSVs
<p>I am trying to read and merge some CSVs but I am getting an index added, which is messing up the final CSV. I have tried <code>index_col=None</code>, <code>index_col=False</code> and <code>index_col=0</code> (since my first column is epoch time) but nothing seems to be helping.</p> <p>CSV1:</p> <pre><code>1704067200...
<python><pandas><dataframe>
2024-02-09 15:44:29
1
773
masterpiece
77,969,174
20,122,390
How to use lru_cache in a Python coroutine?
<p>I need to implement lru_cache from Python's functools library in a coroutine, so I have this:</p> <pre><code>async def send_logs_simulation(self, simulation_id: int, logs: str): company_id = await self.get_company_id(simulation_id=simulation_id) data_room = { &quot;id&quot;: simulation_id...
<python><functools>
2024-02-09 15:26:15
0
988
Diego L
77,969,124
2,813,152
soup find link with specific `th` element appearing in DOM before
<p>I try to find specific links in my HTML. I have this code</p> <pre><code>website_link = infobox.find('a', class_='external', href=True) </code></pre> <p>This finds multiple links. But I only want links that are in a <code>td</code> element, that has a <code>th</code> Element before, with the content <code>Website</c...
<python><beautifulsoup>
2024-02-09 15:18:16
1
4,932
progNewbie
77,969,045
3,034,610
On-the-fly downsampling with prometheus
<p>Every second we want to collect a range of metrics from a bunch of servers and store them in prometheus. We'll keep these high resolution metrics for say, 24 hours before discarding. We're looking for a way to downsample the metrics to 5 second and 1 minute averages so we can store these for much longer. We're wonde...
<python><prometheus>
2024-02-09 15:04:49
1
351
Andrew Holway
77,968,928
7,620,499
Gantt charts in plotly
<p>Hi I have created a Gantt chart with simple code that I find online:</p> <pre><code># gantt is just my pandas dataframe import plotly.figure_factory as ff fig = ff.create_gantt(gantt, colors = ['rgb(170, 14, 200)', width = 742, height = 580) fig.show() </code></pre> <p>For some reason when I run this the output see...
<python><python-3.x><plotly><gantt-chart><highcharts-gantt>
2024-02-09 14:45:07
0
1,029
bernando_vialli
77,968,655
5,070,569
How to use Lagrange interpolation polynomial for functions of multiple variables?
<p>In the case of interpolating a function of a single variable, things are relatively simple:</p> <pre class="lang-py prettyprint-override"><code>def create_basic_polynomial(x_values, i): def basic_polynomial(x): divider = 1 result = 1 for j in range(len(x_values)): if j != i: ...
<python><machine-learning><math><interpolation>
2024-02-09 13:59:16
0
468
Artyom Ionash
77,968,612
6,212,718
Polars: smart way to avoid "window expression not allowed in aggregation"
<p>I have the following code which works.</p> <pre><code>import numpy as np import polars as pl data = { &quot;date&quot;: [&quot;2021-01-01&quot;, &quot;2021-01-02&quot;, &quot;2021-01-03&quot;, &quot;2021-01-04&quot;, &quot;2021-01-05&quot;, &quot;2021-01-06&quot;, &quot;2021-01-07&quot;, &quot;2021-01-08&quot...
<python><python-polars>
2024-02-09 13:53:12
1
1,489
FredMaster
77,968,463
4,431,798
Synchronous OCR with Azure Cognitive Services without Additional API Calls
<p>I'm currently using Azure Cognitive Services for optical character recognition (OCR) on images. I've implemented the OCR functionality using both synchronous and asynchronous methods provided by the Azure Python SDK. However, I'm concerned about the cost and the need for periodic API calls when using the asynchronou...
<python><azure><asynchronous><ocr><azure-cognitive-services>
2024-02-09 13:27:45
0
441
SoajanII
77,968,445
10,353,865
pandas crosstab: include all levels
<p>From the pandas docs of <code>pd.crosstab</code>:</p> <p>&quot;Any input passed containing Categorical data will have <strong>all</strong> of its categories included in the cross-tabulation, even if the actual data does not contain any instances of a particular category.&quot;</p> <p>So what am I actually doing wron...
<python><pandas><pivot-table>
2024-02-09 13:24:13
1
702
P.Jo
77,968,430
453,851
Caching files from hive layout S3 in Polars
<p>Does polars offer way to cache files it downloads from a hive layout S3 bucket?</p> <p>The use case is that we have a datalake containing several TB of data. For certain tasks we may need to pull a sizable chunk of that data, but there is some overlap between S3 objects used in several tasks. It wouldn't be practic...
<python><amazon-s3><hive><parquet><python-polars>
2024-02-09 13:21:00
0
15,219
Philip Couling
77,968,372
3,566,606
Mypy Plugin for Replacing Custom TypeAlias with NotRequired
<p>I want to write a mypy plugin in order to introduce a type alias for <code>NotRequired[Optional[T]]</code>. (As I found out in <a href="https://stackoverflow.com/questions/77954574/generic-type-alias-for-notrequired-and-optional">this question</a>, it is not possible to write this type alias in plain python, because...
<python><python-typing><mypy>
2024-02-09 13:12:52
1
6,374
Jonathan Herrera
77,968,229
6,930,340
Mocking joblib cache using pytest
<p>I want to test a function that uses <code>joblib</code>'s caching functionality.</p> <p>I am wondering how to skip the cache and call the actual function when performing a unit test using pytest? Is it suitable to mock something like <code>joblib.Memory</code>?</p> <p>Let's say I have the following function:</p> <pr...
<python><mocking><pytest><joblib>
2024-02-09 12:46:45
1
5,167
Andi
77,968,049
1,610,765
select.select() isn't accepting my socket and returns empty lists
<p>I wished to write a script for something that would act as both a server and a client. For the server part I decided I should create an SSL socket <code>accept()</code> loop that would listen to new connections forever, and to make it non-blocking so that the client part can work I decided to use <code>select</code>...
<python><sockets><ssl><select>
2024-02-09 12:11:02
1
1,506
Chiffa
77,968,009
4,996,681
How to add spine arrows AND offset the spine
<p>I can do either one of these separately, but not together. I think the question comes down to: after offsetting spines in a Matplotlib figure, how does one find the spine bounds in a coordinate system that can be used to plot arrowheads on the ends of the spines?</p> <p><a href="https://i.sstatic.net/YPBNq.png" rel=...
<python><matplotlib>
2024-02-09 12:04:49
2
323
Luce
77,967,806
1,555,306
Pandas to_csv for multiple rows/timestamps of the same symbol
<p>I am fetching a constant stream of data into a dataframe, which I now need to save into multiple CSVs.</p> <p>For example, I am fetching OHLCV data from Binance and I get this dataframe:</p> <pre><code> sym o h l \ 2024-02-09 11:15:59.594 ETHUSDT ...
<python><pandas>
2024-02-09 11:31:10
1
773
masterpiece
77,967,795
5,838,180
In plotly how to define colour and marker when adding a 3D trace?
<p>I am running successfully the following plotly code to create a 3D plot:</p> <pre><code>import plotly.express as px import plotly.graph_objs as go fig = px.scatter_3d(df, x='x', y='y', z='z') </code></pre> <p>What I want to do next is to add more data points to the 3D plot AND define the marker shape (e.g. as squar...
<python><plotly><plotly-express>
2024-02-09 11:28:47
1
2,072
NeStack
77,967,592
8,040,369
Transform a df into a specific object structure
<p>I have a df which I am getting from a table</p> <pre><code>ID CAT SUB_CAT KEY VALUE ============================================= 1 AA AA_1 X 10 2 AA AA_1 Y 20 3 AA AA_1 Z 15 </code></pre> <p>Previously I was using the <strong>df.to_d...
<python><pandas><dataframe>
2024-02-09 10:54:45
1
787
SM079
77,967,563
2,971,574
Pyspark: Drop arrays of structs if condition is met
<p>I've got the following pyspark dataframe: <a href="https://i.sstatic.net/AfahM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AfahM.png" alt="enter image description here" /></a></p> <p>I'd like to remove all arrays from the column 'price_history' in which at least one of the following conditions is ...
<python><pyspark><databricks>
2024-02-09 10:49:24
1
555
the_economist
77,967,474
13,806,869
Pandas to_sql - NotImplementedError?
<p>I have a Pandas dataframe with the following columns in it:</p> <pre><code>account_number int64 prediction int64 probability_of_prediction float64 probability_of_redemption float64 </code></pre> <p>The dataframe is dtype: object.</p> <p>I want to upload its data into a table...
<python><pandas>
2024-02-09 10:30:49
0
521
SRJCoding
77,967,334
849,076
Getting min/max column name in Polars
<p>In polars I can get the horizontal max (maximum value of a set of columns for reach row) like this:</p> <pre><code>df = pl.DataFrame( { &quot;a&quot;: [1, 8, 3], &quot;b&quot;: [4, 5, None], } ) df.with_columns(max = pl.max_horizontal(&quot;a&quot;, &quot;b&quot;)) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ a ...
<python><dataframe><max><python-polars>
2024-02-09 10:09:12
4
8,641
leo
77,967,245
2,163,392
How to do fine tune and transfer learn CNNs in a new dataset using imagenet std and mean at data augmentation phase?
<p>I did some fine-tuning training using CNNs for diverse applications. Honestly, I never really needed to perform Imagenet normalization in new datasets as the results were already quite good without that procedure.</p> <p>Now I have for the first time a new dataset on which the results are really bad without the Imag...
<python><tensorflow><deep-learning><conv-neural-network><data-augmentation>
2024-02-09 09:54:06
0
2,799
mad
77,967,137
6,151,828
Pre-processing data within a Julia structure
<p>I would like to have a Julia structure with data and parameters contained with it, to be used with various functions. E.g., I start with data frame of numbers, but many functions use it as a matrix and also need to know its dimensions. In python I would use something like:</p> <pre><code>class my_class(object): ...
<python><class><data-structures><struct><julia>
2024-02-09 09:35:31
2
803
Roger V.
77,967,053
313,648
Cannot get Playwright to work in 2 separate scripts concurrently
<p>I am using the Playwright synchronous API in completely separate scripts and they all work fine when I run them at different times, but if I try to run the scripts at the same time, the script that started first seems to take ownership of the browser and the second (and subsequent) script fails with a message about ...
<python><playwright><playwright-python>
2024-02-09 09:20:00
1
532
Adrian
77,966,911
393,010
How to avoid almost duplicated uninformative type hints when function arguments should default to empty list/None
<p>Empty lists as default arguments is a gotcha in python, and adding type hints to the usual pattern of <code>=None</code> as default value make them quite messy.</p> <p>Is there any way to avoid giving the type hint twice (or even once?) in this example code:</p> <pre class="lang-py prettyprint-override"><code>class ...
<python><mypy><python-typing>
2024-02-09 08:48:53
1
5,626
Moberg
77,966,551
11,861,874
Excel Pivot Export from Pandas Dataframe
<p>I have multiple functions that generate multiple data frames of different lengths, I am aiming to consolidate all of them in one place and later pivot it out and export to Excel, here is an example of three different output data frames from three functions.</p> <pre><code>import pandas as pd data1 = {'Header':['L1'...
<python><pandas><dataframe>
2024-02-09 07:19:17
2
645
Add
77,966,503
11,861,874
Summing up Pandas dataframe in a loop
<p>I am trying to sum up multiple data frames in a loop so that I'll have one data frame that will show the total of all data frames.</p> <p>Please see here the example of what I am trying to achieve.</p> <pre><code>import pandas as pd data1 = {'Header':['L1','L2','L3'], 'Val1':[float(100),float(200),float(300)], ...
<python><pandas><dataframe>
2024-02-09 07:08:39
1
645
Add
77,966,463
1,616,785
sqlalchemy session.execute with positional arguments error
<p>I am trying to use positional arguments to be used in a lengthy insert query. But it doesnt seem to allow using positional arguments. I am using mysql. Below is the error</p> <pre><code>sqlalchemy.exc.ArgumentError: List argument must consist only of tuples or dictionaries </code></pre> <p>sample query with placehol...
<python><sqlalchemy>
2024-02-09 06:57:20
1
1,401
sjd
77,966,444
14,775,478
How to use Python pattern matching to match class types?
<p>How can we use Python's structural pattern matching (introduced in 3.10) to match the type of a variable without invoking the constructor / in a case where a new instantiation of the class is not easily possible?</p> <p>The following code fails:</p> <pre><code>from pydantic import BaseModel # instantiation requires...
<python><structural-pattern-matching>
2024-02-09 06:54:50
1
1,690
KingOtto
77,966,378
7,614,968
Why is there attribute error on the class?
<p>I am trying to understand that there is a class names test_class that inherits from BaseModel. I am defining a class attribute TEST_VALUE but there is attribute error.</p> <pre><code>from pydantic import BaseModel class test_class(BaseModel): &quot;&quot;&quot;load from env&quot;&quot;&quot; TEST_VALUE: str...
<python><python-3.x><class><oop><pydantic>
2024-02-09 06:39:07
1
635
palash
77,966,259
572,616
How to build a python wheel with a specific set of dependencies?
<p>I am building a python wheel and encounter a problem by specifying the dependencies. The <code>install_requires</code> parameter of the <code>setup</code> method receives:</p> <ul> <li><code>vtk_osmesa</code> and</li> <li><code>pyvista</code>.</li> </ul> <p>The problem above is, that <code>pyvista</code> has <code>v...
<python><pip><vtk><python-wheel><pyvista>
2024-02-09 06:03:20
0
14,083
Woltan
77,966,124
3,678,257
How to log traceback information using structlog
<p>I'm trying to set up an ELK based observability system in our project.</p> <p>So I started with revising a logging system in our Django based project. I have decided to start with <a href="https://www.structlog.org/en/stable/" rel="nofollow noreferrer">structlog</a> in order to obtain structured log files that are s...
<python><logging><python-logging><error-logging>
2024-02-09 05:18:18
1
664
ruslaniv
77,966,031
8,584,998
Check If Computer On Network Is Asleep Without Waking It Up (Python)
<p>I want a quick way to check if a computer on the LAN is awake or not given its IP address (on Windows) without waking it up. I wrote the following, which works:</p> <pre><code>def is_awake(ipOrName, timeout=0.05): try: tt = round(timeout*1000) cmdargs = [&quot;ping&quot;, &quot;-n&quot;, &quot;1&quot;, &qu...
<python><windows><ip-address><sleep-mode><wakeup>
2024-02-09 04:39:51
1
1,310
EllipticalInitial
77,966,005
10,461,632
Convert a dataframe to a nested dictionary with multiple levels
<p>Is there a cleaner way to convert my dataframe to a nested dictionary with more than one level? If possible, I want to avoid the double <code>for</code> loop that I needed to achieve the result.</p> <pre><code>from pprint import pprint a = pd.DataFrame([ {'col1': 'A', 'col2': 'Person 1', 'height': 1, 'weight': ...
<python><pandas>
2024-02-09 04:32:04
2
788
Simon1
77,965,998
8,645,552
Data("Subchunk2ID") chunk order in WAV files?
<p>I have a question about the data chunk of WAV files. We know that the chunk order in the WAV files is not fixed(i.e. data chunk is not necessarily the last chunk) and we can only assume that &quot;fmt&quot; chunk must appear before the &quot;data&quot; chunk. And WAV file header can be 44 bytes or 46 bytes or even b...
<python><c><audio><wav><audio-streaming>
2024-02-09 04:26:17
0
370
demid
77,965,769
8,616,751
Remove top and right spine in GeoAxesSubplot
<p>I'm trying to remove the top and right spine of a plot, and initially tried</p> <pre><code># Create a figure and axis with PlateCarree projection fig, ax = plt.subplots(figsize=(11, 6), subplot_kw={'projection': ccrs.PlateCarree()}) ax.coastlines() # Reintroduce spines ax.spines['top'].set_...
<python><matplotlib><cartopy><map-projections>
2024-02-09 02:48:52
1
303
scriptgirl_3000
77,965,711
16,113,865
How can I detect whether a widget in PyQt5, is a fixed size or not?
<p>I'm working with PyQt5, and I'm looking for a straightforward way to check whether a widget (e.g., QLabel or QPushButton) has a fixed size or not. The direct method isFixedSize() is not universally available.</p> <p>Could you please share any insights or methods that can efficiently determine if a PyQt5 widget has a...
<python><pyqt><pyqt5>
2024-02-09 02:17:53
0
492
tckraomuqnt
77,965,636
1,275,942
PyCharm "Interpreter Paths" -- What are they and where are they stored?
<p>I have a PyCharm project, named <code>pycharm_projects</code>. In it, I create a virtualenv Python interpreter, <code>example_virtualenv</code>. Then I click Interpreters -&gt; Show all -&gt; example_virtualenv -&gt; Show interpreter paths -&gt; Add path. I add <code>S:\example_python_folder</code>, making the list ...
<python><pycharm><jetbrains-ide><pythonpath>
2024-02-09 01:38:55
0
899
Kaia
77,965,595
8,996,209
How to translate a batch of txt files using gpt-4?
<p>I'm working on a Python script to translate plain text files located on a folder from English to Spanish. However, I'm facing an issue where the script doesn't work with SDK version 1.0.0 or newer. I've tried but get errors like:</p> <pre><code>You tried to access openai.ChatCompletion, but this is no longer support...
<python><openai-api>
2024-02-09 01:21:16
1
335
eera5607
77,965,579
8,997,728
Method that generate events in Json not running (Python)
<p>Hi there I have this python script below from a programming course to generate Json files (dictionaries) from events (concerts, shows, theatres) and can simulate a ticketing website with some additional info to keep track on the number of views, likes and clicks for each as customers interface with it over time. As ...
<python><sql><events>
2024-02-09 01:13:39
0
309
Estrobelai
77,965,487
6,162,679
Error when using "LID_USAGE" from the "swmm_api" package in Python?
<p>I am trying to extract individual LID settings for each subcatchment in SWMM using <code>LID_USAGE</code> from the <code>swmm_api</code> package. I have followed the example at <a href="https://markuspichler.gitlab.io/swmm_api/examples/how_to_add_LIDs.html" rel="nofollow noreferrer">https://markuspichler.gitlab.io/s...
<python>
2024-02-09 00:36:51
1
922
Yang Yang
77,965,294
2,097,240
Python wait for click
<p>I'm making a script in Python (without an interface) that requires the user to click certain places on the screen so I can retrieve the mouse position.</p> <p>With <code>pyautogui</code> it's pretty easy to get the <code>position</code> of the mouse. Yet, there seems to be no click event, wait click or anything like...
<python><onclick><pyautogui>
2024-02-08 23:23:09
0
86,748
Daniel MΓΆller
77,965,288
7,742,512
Trying to train a tensorflow model, but get: ImportError: cannot import name 'tensor' from 'tensorflow.python.framework'
<p>I have been trying train a pre trained model for a few days now, I am using:</p> <p>ssd_mobilenet_v2_fpnlite_640x640_coco17_tpu-8</p> <p>I have downloaded the models complied and the protos etc... I can get the object detection run in my own script on my webcam.</p> <p>But I can't get it to train.</p> <p>I'm using a...
<python><python-3.x><tensorflow>
2024-02-08 23:20:37
0
473
James Morrish
77,964,948
4,707,978
Airflow use case
<p>I have a question about for what to use airflow for with our current system.</p> <p>I have an api which, by using GCP Cloud Tasks, trigger some tasks like sending a welcome email after 2 days and sending useful notifications. This is all in our main api repo.</p> <p>Now I want for example add 1) a profile image face...
<python><airflow>
2024-02-08 21:49:58
1
3,431
Dirk
77,964,944
1,183,804
Olive to convert Whisper Model to Onnx
<p>I am trying to convert OpenAi Whisper model to Onnx with Olive, to merge the Model Files into one file, using:</p> <pre><code>python prepare_whisper_configs.py --model_name openai/whisper-tiny.en python -m olive.workflows.run --config whisper_cpu_fp32.json --setup python -m olive.workflows.run --config whisper_cpu_f...
<python><c#><onnx><olive>
2024-02-08 21:49:08
1
2,710
Rusty Nail
77,964,915
7,347,925
How to use axline with log scale axis?
<p>I'm trying to plot a linear line through zero:</p> <pre><code>fig, ax = plt.subplots() l2 = ax.axline(xy1=(0, 0), slope=0.3) ax.set_xlim(0.1, 10) ax.set_ylim(0.1, 10) </code></pre> <p>It works well:</p> <p><a href="https://i.sstatic.net/iT3qd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iT3qd.png...
<python><matplotlib><line-plot>
2024-02-08 21:42:51
1
1,039
zxdawn
77,964,875
23,260,297
Future Warning with groupby in pandas
<p>I have a python script that reads in data from a csv file</p> <p>The code runs fine, but everytime it runs I get this warning message:Β </p> <pre><code> FutureWarning: A grouping was used that is not in the columns of the DataFrame and so was excluded from the result. This grouping will be included in a future versio...
<python><pandas><dataframe>
2024-02-08 21:32:40
1
2,185
iBeMeltin
77,964,858
10,589,070
DuckDb Hash a Record
<p>I have a use case where I want to check for conflicts for slowly changing dimensions. In theory, I should be able to do this by hashing a record of the original table and compare it to a hash of the new record coming in if the ID's match.</p> <p>In SQL I can do this with a binary checksum and just provide a list of...
<python><duckdb>
2024-02-08 21:28:40
2
446
krewsayder
77,964,700
45,139
Tkinter not working on Debian 12 Bookworm, Python 3.11.5
<p>As the title states, I can't get tkinter code running. I get the error:</p> <blockquote> <p>No module named '_tkinter'</p> </blockquote> <blockquote> <p>import _tkinter # If this fails your Python may not be configured for Tk</p> </blockquote> <p>I'm running Debian 12 Bookwork, and Python 3.11.5, and after trying th...
<python><linux><tkinter><debian><python-3.11>
2024-02-08 20:48:01
0
3,947
LoveMeSomeCode
77,964,626
9,806,500
shinylive pyodide cannot install shiny package for a quarto dashboard
<p>I am attempting to embed a shinylive app in a quarto dashboard. App will let the user selectize filter a categorical variable in a seaborn barplot.</p> <p>However, I receive the following error in the panel where the app <em>should</em> appear:</p> <pre><code>Error starting app! Traceback (most recent call last): ...
<python><quarto><py-shiny><py-shinylive>
2024-02-08 20:32:35
0
635
M. Wood
77,964,507
16,179,502
Google drive python SDK throwing SSL errors
<p>I have the following method being used in my Flask app to create folders in my Google drive if they do not exist. If they do exist then their folder_id is returned.</p> <pre><code>def find_or_create_folder_in_google_drive(name, parent_id=None): query = f&quot;name='{name}'&quot; if parent_id: query ...
<python><flask><google-drive-api>
2024-02-08 20:10:51
0
349
Malice
77,964,493
940,158
Emulating an empty queryset with an abstract model
<p>I have a use case in which I have a ListAPIView that connects to a 3rd party (Stripe) API, fetches data (invoices) and returns that data to the user. I have a serializer, but I don't have a model.</p> <p>The entire code looks something like this:</p> <pre class="lang-py prettyprint-override"><code>class InvoicesList...
<python><django><drf-spectacular>
2024-02-08 20:07:18
0
15,217
alexandernst
77,964,446
11,277,108
Designing a model that can cope with dynamic field names that follow a set pattern
<p>I'd like to create a Pydantic model for the following example dictionary:</p> <pre><code>{&quot;response_code_count/R1&quot;: 23, &quot;response_code_count/PX1&quot;: 58, &quot;some_other_field&quot;: &quot;some_other_value&quot;} </code></pre> <p>The challenge is that whilst the <code>response_code_count</code> key...
<python><pydantic>
2024-02-08 19:57:19
1
1,121
Jossy
77,964,234
3,107,858
Meaning of VideoCapture prop definitions not in the opencv documentation
<p>Is there any to tell what the meaning of video capture properties that aren't defined in the official documentation? For example,</p> <pre><code>import cv2 cap = cv2.VideoCapture(filename) </code></pre> <p>Video properties can be polled with either: <code>cap.get(cv2.CAP_PROP_FPS)</code> or <code>cap.get(5)</code><...
<python><opencv><video-capture>
2024-02-08 19:13:00
1
3,230
DanGoodrick
77,964,071
10,969,942
Seeking Cython Optimization for Conditional Branching: Is There an Equivalent to switch?
<p>I am currently working on a Python project that I need to rewrite in Cython to enhance performance. In this Python code, there is a segment that uses a series of <code>if/elif</code> statements to determine the execution path for a task, <strong>which involves hundreds of branches. Additionally, this segment of code...
<python><c><switch-statement><cython><compiler-optimization>
2024-02-08 18:42:18
1
1,795
maplemaple
77,964,048
1,412,564
Django - how do I filter or exclude by two identical fields?
<p>We are using Django for our website. I have a query for model <code>User</code> and I want to exclude users which have two identical fields - in this case <code>id</code> and <code>username</code>. So if the <code>id</code>==<code>username</code>, I want to exclude them. How do I do it?</p> <p>The query looks like:<...
<python><django><django-queryset>
2024-02-08 18:37:19
1
3,361
Uri
77,963,963
1,559,401
PyAssimp error for any loaded file - Scene has not attribute meshes, materials or textures
<p>I am trying to get any sample (including the ones found in the Assimp repo) to work. Using <code>pyassimp 5.2.5</code> with Python 3.11.6. Below there is an example for a very basic call. I am loading an OBJ of a cube, which one can even write manually. :D</p> <pre><code>import pyassimp import pyassimp.postprocess ...
<python><assimp>
2024-02-08 18:19:30
1
9,862
rbaleksandar
77,963,500
4,575,197
TypeError: unhashable type: 'set' while renameing the DF in pandas version 2.1.4
<p>i have a huge dataframe now i want to rename one based on the values inside of the other one, if the columns match</p> <pre><code>for index,col in enumerate(news1.columns): for index_dic,col_dic in enumerate(dic.columns): if col==col_dic: print(col,dic.iloc[1, index_dic]) print(ty...
<python><pandas><dataframe><typeerror>
2024-02-08 16:59:16
1
10,490
Mostafa Bouzari
77,963,471
5,213,015
Django - Autocomplete Search Throws Error For Logged Out Users?
<p>I’m making some updates to the autocomplete portion of the search functionality in my application and for some reason i’m getting an error for logged out users that says <code>TypeError: Field 'id' expected a number but got &lt;SimpleLazyObject: &lt;django.contrib.auth.models.AnonymousUser object at 0x1088a5e20&gt;&...
<python><django><django-models><django-views><django-templates>
2024-02-08 16:54:45
2
419
spidey677
77,963,460
8,280,171
String Interpolation Convert to a Type
<p>I'm creating an s3 bucket using AWS CDK and i'm trying to usse string interpolation for the removal policy.</p> <pre><code>object_storage_bucket = s3.Bucket( self, &quot;object-storage-bucket&quot;, removal_policy=f&quot;RemovalPolicy.{props.s3_removal_policy}&quot;, a...
<python><aws-cdk>
2024-02-08 16:53:24
1
705
Jack Rogers
77,963,452
1,194,883
Running python code in a shell with VS code
<p>Using shift-enter, I can run a single line of code from some script in VS Code (using the standard Microsoft Python extension). If not already open, it pops open an ipython shell, and runs the line of code in that shell. The same works if I have consecutive non-indented lines of code β€” I just highlight all of them...
<python><visual-studio-code>
2024-02-08 16:52:14
0
20,375
Mike
77,963,331
305,563
Recursive IndentedBlock with optional contents
<p>IndentedBlock from pyparsing not dedenting</p> <p>I am trying to write a parser in pyparsing that has a container that has optional contents, and I'm not getting the results I'm expecting.</p> <p>Here's the simplest version that demonstrates my problem I could come up with:</p> <pre><code>from pyparsing import * ide...
<python><indentation><pyparsing>
2024-02-08 16:34:28
0
690
amertune
77,963,128
1,350,082
Mixed Integer Optimisation Using cvxpy
<p>I'm trying to solve an optimisation problem in python using CVXPY. Specifically, I am trying to optimise two available resources based on some data.</p> <p>Below is a toy example of the problem I am having. I have some data <strong>y</strong> which can be thought of as a vector of daily unit demand and I have two re...
<python><optimization><cvxpy>
2024-02-08 16:07:27
0
317
speeder1987
77,963,057
2,299,245
Making a empty/template raster using rioxarray / rasterio in Python
<p>I am currently trying to convert R code into Python. I am trying to make a 'template' raster file which I will then &quot;reproject_match&quot; many other rasters to in my workflow so that they all align.</p> <p>I can do it in R using the terra package, but am unsure how to do so in python using the rioxarray packag...
<python><r><python-xarray><terra><rasterio>
2024-02-08 15:58:18
1
949
TheRealJimShady
77,963,015
11,911,577
How to do 2 types of asynchronous tasks in parallel without disruption?
<p>The program I am writing needs to perform 2 types of tasks.</p> <ol> <li>Connect to list of clients.</li> <li>Do a series of tasks through connected clients.</li> </ol> <p>Assuming that the program is doing things like this:</p> <pre><code>import asyncio async def task(worker_id): print(f'worker {worker_id} sta...
<python><asynchronous><parallel-processing><task>
2024-02-08 15:50:48
0
766
Hamidreza
77,962,787
353,337
Measure pytest setup times
<p>With <code>--durations=10</code>, <a href="https://docs.pytest.org/" rel="nofollow noreferrer">pytest</a> shows the 10 slowest tests. I have many tests all of them run pretty fast, but test <em>creation</em> takes long here and there, especially in constructs like</p> <pre class="lang-py prettyprint-override"><code>...
<python><pytest>
2024-02-08 15:17:42
0
59,565
Nico SchlΓΆmer
77,962,719
4,527,660
Why is my python code in cloud function not executing slack bot slash command
<p>I am stuck with a basic python script. where I am integrating it with a slack <code>bot</code> and using <code>slash command</code> my slash command is <code>/delete-session</code> when this command is triggered in slack I would expect cloud function in GCP to return a message.How ever I tried to post message in th...
<python><flask><pip><slack>
2024-02-08 15:07:57
1
303
Waseem Mir
77,962,412
13,137,625
Correct way to load massive sql table into pyspark
<p>I have a table with 1 billion plus rows, that I am looking to basically pull into a dataframe and do a join with another table of lesser size. I have found that this works for a table with a limit under 1 million fairly fast, but over that and there is issues.</p> <p>Query</p> <pre><code>query = SELECT COL1, COL2 FR...
<python><mysql><dataframe><apache-spark><pyspark>
2024-02-08 14:21:06
0
305
andruidthedude
77,962,342
893,254
How to drop a subset of MultiIndex "columns" from a Pandas series or dataframe?
<p>Iterating over a pandas <code>DataFrame</code> using <code>iterrows()</code> produces a series of index <code>Series</code> pairs (tuples).</p> <pre><code>for timestamp, row in df.iterrows(): </code></pre> <p>I am aware that <code>iterrows()</code> is slow. Ignoring that issue for now -</p> <p>Some of the returned r...
<python><pandas><dataframe><series>
2024-02-08 14:09:58
2
18,579
user2138149
77,962,303
3,453,901
In Python the Apache Arrow ADBC driver causing silent program exit on connection attempt to PostgreSQL database
<p>My config:</p> <ul> <li>Windows</li> <li><code>python=3.11.7</code></li> <li><code>pandas=2.2.0</code></li> <li><code>adbc-driver-manager=0.9.0</code></li> <li><code>adbc-driver-postgresql=0.9.0</code></li> <li><code>pyarrow=15.0.0</code></li> </ul> <hr /> <p>Trying to implement the newish <code>ADBC Driver</code> f...
<python><pandas><postgresql><pyarrow>
2024-02-08 14:04:14
0
2,274
Alex F
77,962,211
8,771,082
How to subset multiple dataframes
<p>I have split data and metadata into separate dataframes for convenience. I would like to subset both at the same time, so I don't have to repeat myself. My example attempt below is a mess of if statements. This because .loc[], .iloc[], and whether to leave all columns in a certain dimension (:) are &quot;&quot;part ...
<python><pandas>
2024-02-08 13:49:38
1
449
Anton
77,962,153
19,318,120
Firestore paginate document fields
<p>This is my first time using Firestore. The project is written in Python. I've a collection let's say posts and then a document for each user that contains an array of his posts. Is there a way to paginate that array?</p> <p>to get a document</p> <pre><code>docoument = collection.document( str(document_id) ).get(...
<python><firebase><google-cloud-platform><google-cloud-firestore>
2024-02-08 13:41:52
1
484
mohamed naser