QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
βŒ€
79,145,554
3,846,286
Space complexity of grouping anagrams with hashmap
<p>I'm solving a leetcode question.</p> <blockquote> <p>Q: Given an array of strings <code>strs</code>, group all anagrams together into sublists. You may return the output in any order.</p> <p>Note: <code>strs[i]</code> is made up of lowercase English letters</p> </blockquote> <pre><code>class Solution: def groupA...
<python><space-complexity>
2024-10-31 16:28:34
1
651
chilliefiber
79,145,368
7,914,054
Unable to change the download button sidebar based on the tab chosen using Shiny Python
<p>I would like to change the download buttons that appear based on the tab that is chosen. For example, if the tab is Main Visualization, I would like the following buttons to appear: download_heatmap and download_distribution. I would like download_piechart and download_barchart to only appear if &quot;Additional Vis...
<python><button><download><reactive><py-shiny>
2024-10-31 15:41:22
0
789
QMan5
79,145,336
4,049,396
Stripna: Pandas dropna but behaves like strip
<p>It is a pretty common occurrence to have leading and trailing <code>NaN</code> values in a table or DataFrame. This is particularly true after joins and in timeseries data.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df1 = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6, 7],...
<python><pandas><dataframe><nan>
2024-10-31 15:32:52
4
4,814
Little Bobby Tables
79,145,328
3,042,850
Sudoku block checker in python
<p>This kind of question has been asked before but I came up with a solution I do not see very often. Now this works on my local host but when I input it into the University program it returns that I've failed the funcitonality check but I pass it on my local host. I need to check a 3 by 3 block with a row and column e...
<python><sudoku>
2024-10-31 15:29:48
1
309
user3042850
79,145,287
5,002,668
Sorting array along two dimensions
<p>Suppose you have data in form of a numpy array of shape <code>(100,3)</code>. The number 100 represents a number of sensors, for each sensor you have:</p> <ul> <li>x-coordinate (<code>data[:, 0]</code>)</li> <li>y-coordinate (<code>data[:, 1]</code>)</li> <li>reading, e.g. temperature (<code>data[:, 2]</code>)</li> ...
<python><arrays><sorting>
2024-10-31 15:17:31
0
1,845
a.smiet
79,145,275
843,458
python filename fails due to escape character
<p>I would like to read a filename. The string should be converted to a valid filename. However the input to the conversion fails.</p> <pre><code>xlsfile = base64.urlsafe_b64encode('C:\Users\matth\OneDrive\Dokumente\20241023-1904097928-umsatz.xlsx') df = pd.read_excel(xlsfile) </code></pre> <p>The problem is the sequen...
<python><string><unicode>
2024-10-31 15:13:54
0
3,516
Matthias Pospiech
79,145,258
6,930,340
Polars pl.when().then().otherwise() in conjunction with first row of group_by object
<p>I have a <code>pl.DataFrame</code> with some columns: <code>level_0</code>, <code>symbol</code>, <code>signal</code>, and a <code>trade</code>. The <code>trade</code> column simply indicates whether to buy or sell the respective <code>symbol</code> (&quot;A&quot; and &quot;B&quot;). It's computed <code>over(&quot;le...
<python><dataframe><python-polars>
2024-10-31 15:09:47
1
5,167
Andi
79,145,092
4,706,711
How I can match each returned embedding with the text I gave to him so I can save them into a db?
<p>I made this script that reads the text frpom pdf and for each paragraph calculates the mebddings using cohere embeddings api:</p> <pre><code> import os import cohere import time from pypdf import PdfReader from dotenv import load_dotenv from qdrant_client import QdrantClient from qdrant_client.models import Distanc...
<python>
2024-10-31 14:16:19
1
10,444
Dimitrios Desyllas
79,144,977
18,618,577
Compare dataframe with list
<p>I've a script that try to reach some router on the field (from a list in csv), then write a result csv file. My script have an early condition that check if there is an existing &quot;result.csv&quot; file, and look into it which router is &quot;offline&quot;, then make a list from it.</p> <p>Now I'm trying to compa...
<python><pandas><list>
2024-10-31 13:44:34
0
305
BenjiBoy
79,144,768
11,155,419
How to decode a protobuf Firestore event payload
<p>I have a Cloud Run Function, that gets triggered on <code>google.cloud.firestore.document.v1.written</code> Firestore event, as outlined below:</p> <pre class="lang-py prettyprint-override"><code>from cloudevents.http import CloudEvent import functions_framework from google.events.cloud import firestore from google....
<python><google-cloud-firestore><google-cloud-functions><protocol-buffers>
2024-10-31 12:35:27
0
843
Tokyo
79,144,738
7,975,962
Polars arithmetic operation using a boolean mask and different sized array
<p>I tried so hard with ChatGPT but couldn't make this work and it couldn't solve it either. How am I supposed to assign or increment set of values using a boolean mask? This is what I was doing with pandas.</p> <pre class="lang-py prettyprint-override"><code>validation_predictions = model.predict(validation_dataset) d...
<python><python-polars>
2024-10-31 12:26:22
3
974
gunesevitan
79,144,702
7,257,731
Plotly Choropleth - How to add outline to shape from geojson
<p>I want to draw an outline highlighting a shape in a Choropleth map drawn from a GeoJSON using Plotly (in my case over Dash).</p> <p>I have a dataframe &quot;df&quot; like this one:</p> <pre><code>state (string) value (float) STATE_1 50.0 STATE_2 30.5 STATE_3 66.2 </code></pre> <p>I have also a ...
<python><plotly><plotly-dash><choropleth>
2024-10-31 12:18:13
1
392
Samuel O.D.
79,144,692
11,633,074
remove bash colors when logging to file in flask
<p>I'm trying to modify the flask request formater so I get some logs on the console but I want the logs in my file to be colorless since those basically add ANSI characters that make the log reading harder.</p> <p>Here is what I have done until now, I made a class to setup my logs:</p> <pre class="lang-py prettyprint-...
<python><flask><logging><werkzeug>
2024-10-31 12:15:23
1
436
lolozen
79,144,498
18,554,284
Get Icon for any File/Exe on Windows using Python
<p>I tried to find a few answers but only found this exact question on <em>Stack Overflow</em> without any proper answer. I am trying to build an Alternate Shell to replace the Default Desktop but it wouldn't look good without Icons, so I tried several approaches such as locating the target files of the Shortcuts on De...
<python><windows><icons>
2024-10-31 11:18:14
1
789
KillerRebooted
79,144,456
14,743,705
Is there a more elegant way to change the structure of my dictionary data?
<p>I made this function because I needed to get data in a different order. It works, but I'm wondering if there is a better way.</p> <pre><code>def transform_data(self, data): &quot;&quot;&quot; before: data[subject][period][zodiak] = content after : data[zodiak][period][subject] = content &quot;&quot;&...
<python><dictionary><transformation>
2024-10-31 11:02:58
0
305
Harm
79,144,304
13,147,413
How to interpret "unresolved exception with suggestion" in Pyspark
<p>Cannot understand this <code>unresolved exception</code> error</p> <pre><code>AnalysisException: [UNRESOLVED_COLUMN.WITH_SUGGESTION] A column or function parameter with name `1_1473_C17_18979` cannot be resolved. </code></pre> <p>thrown by Pyspark when i apply this thresholding mechanism:</p> <pre><code>threshold = ...
<python><pyspark>
2024-10-31 10:14:13
0
881
Alessandro Togni
79,144,282
201,657
When using pytest-bdd how do I define a dataset should be operated on by a scenario?
<p>I am familiar with behave in which I can define data for a step like so:</p> <hr /> <pre class="lang-none prettyprint-override"><code>Feature: My feature Scenario: My scenario Given some data | order_nr | customer_name | delivery_date | | 1 | John Doe | 2023-10-01 | | 2 ...
<python><pytest-bdd>
2024-10-31 10:08:29
1
12,662
jamiet
79,144,183
489,010
Is there a way to capture name of group for a `group_by` in polars?
<p>Is there a way to get the name of a current group for any given iteration of a <code>group_by</code> instance without having to rely to the <code>GroupBy.__iter__()</code>?</p> <pre class="lang-py prettyprint-override"><code>pl.Config().set_fmt_str_lengths(100) df = pl.DataFrame({ 'fruit':['apple', 'pear', 'peac...
<python><python-polars><polars-plugins>
2024-10-31 09:40:29
1
5,026
pedrosaurio
79,143,954
3,649,629
Test suite to cover repository where all tests are run at once on python
<p>My tests are run correctly when I run them one by one, but failed interfering each other if I run them in test suite.</p> <pre><code>/postgresql/asyncpg.py&quot;, line 789, in _handle_exception raise translated_error from error sqlalchemy.exc.InterfaceError: (sqlalchemy.dialects.postgresql.asyncpg.InterfaceError...
<python><database><testing><pytest>
2024-10-31 08:28:05
1
7,089
Gleichmut
79,143,949
972,706
pycharm vs command line pytest
<p>When running my pytest testsuite from PyCharm, I have a successful result for all my tests. When running command line, I get module import errors.</p> <p><a href="https://i.sstatic.net/wjTSJCUY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wjTSJCUY.png" alt="folder structure" /></a></p> <p>pytest.in...
<python><pycharm><pytest>
2024-10-31 08:25:58
2
3,294
ShadowFlame
79,143,788
1,672,565
Parse Rust into AST with / for use in Python
<p>Usually it's the other way round, parsing Python with Rust, see <a href="https://github.com/RustPython/RustPython" rel="nofollow noreferrer">here</a> or <a href="https://github.com/astral-sh/ruff" rel="nofollow noreferrer">here</a> - in my case though I am looking for a way to <strong>parse Rust code with Python</st...
<python><rust><abstract-syntax-tree>
2024-10-31 07:28:32
1
3,789
s-m-e
79,143,531
956,424
Latency to be addressed in django for M2M relationship in ModelAdmin dropdown
<p>I have a group of mailboxes which needs to be populated based on customer login and the domains he owns. Customer:User is 1:1 relationship.</p> <p>Tried:</p> <p>views.py:</p> <pre><code>class MailboxAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authen...
<python><django>
2024-10-31 04:43:44
1
1,619
user956424
79,143,398
802,494
Why won't the Python debugger invoked as a module automaticaly enter into post-mortem debugging?
<p>Accordig to Python's official documentation at <a href="https://docs.python.org/3.12/library/pdb.html" rel="nofollow noreferrer">pdb</a>:</p> <p><em>You can also invoke pdb from the command line to debug other scripts. For example:</em></p> <p><code>python -m pdb myscript.py</code></p> <p><em>When invoked as a modul...
<python><debugging><redhat><pdb>
2024-10-31 03:22:32
0
978
Spartan
79,143,171
14,954,932
Reading an xlsx Excel file into a pandas dataframe with openpyxl generates value error
<p>I have written a code using selenium to download an xlsx excel file from a website, rename it and then open it with openpyxl. however, trying to read the file into a pandas dataframe with openpyxl leads to an error.</p> <p>The error is the following:</p> <pre><code>ValueError: Unable to read workbook: could not read...
<python><excel><pandas><dataframe><openpyxl>
2024-10-31 00:24:07
0
376
Economist Learning Python
79,142,749
3,250,928
Is it safe to use dataclasses with hidden/non-field inherited properties?
<p>I have a <code>dataclass</code> use strategy that is quite flexible, but I am unsure if it is relying on features that aren't part of the type contract. I am often telling people to not rely on the insertion order being the iterable order of a <code>dict</code> in python because only the <code>OrderedDict</code> has...
<python><inheritance><python-dataclasses>
2024-10-30 20:47:47
1
307
probinso
79,142,432
984,114
Apache Beam: Number of components does not match number of coders when using Timers
<p>My question is very similar to this <a href="https://stackoverflow.com/questions/77022836/apache-beam-wait-n-seconds-after-window-closes-to-execute-dofn">one</a></p> <p>I'm trying to add some timers to process some data later but i'm getting the following error</p> <pre><code>Error message from worker: generic::unkn...
<python><google-cloud-dataflow><apache-beam>
2024-10-30 18:42:30
1
1,286
Alex Fragotsis
79,142,341
967,621
Unindent and convert multiline string to single line
<p>I have several multiline strings with indentation in my code, such as this (simplified example):</p> <pre><code>def foo(): cmd = '''ls /usr/bin /usr/sbin /usr/local/bin''' print(f'{cmd=}') foo() </code></pre> <p>I want to <strong>remove indentation and unwr...
<python><string><indentation><multiline><heredoc>
2024-10-30 18:15:40
1
12,712
Timur Shtatland
79,142,186
3,486,684
How do I flatten the elements of a column of type list of lists so that it is a column with elements of type list?
<p>Consider the following example:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl pl.DataFrame(pl.Series(&quot;x&quot;, [&quot;1, 0&quot;, &quot;2,3&quot;, &quot;5 4&quot;])).with_columns( pl.col(&quot;x&quot;).str.split(&quot;,&quot;).list.eval(pl.element().str.split(&quot; &quot;)) ) </c...
<python><dataframe><python-polars>
2024-10-30 17:25:59
1
4,654
bzm3r
79,142,169
5,790,653
How to check the occurrences of a dictionary key in another list and create new output
<p>I have a <code>list</code> and a <code>dictionary</code> like this:</p> <pre class="lang-py prettyprint-override"><code>mydict = { 'some-id-string1': {'name': 'Saeed1', 'phone': '+989307333730', 'id': 'abc'}, 'some-id-string2': {'name': 'Saeed2', 'phone': '+989307333731', 'id': 'def'}, 'some-id-string3':...
<python><list-comprehension>
2024-10-30 17:20:01
1
4,175
Saeed
79,141,950
1,802,225
ValueError: Incompatible indexer with Series in pandas DataFrame
<ul> <li>python: 3.11</li> <li>pandas: 2.2.2</li> </ul> <p>I need to assign a dict value to 4-th row in df:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'agg': [None] * 5}) df['agg'] = df['agg'].astype(object) df.loc[3, 'agg'] = {'mm': 4} </code></pre> <p>It gives an error:</p> <pre><code>Trac...
<python><python-3.x><pandas><dataframe>
2024-10-30 16:20:41
1
1,770
sirjay
79,141,905
10,615,030
How to extract data from a map based on pattern
<p>I have a map like this (jpg image):</p> <p><a href="https://i.sstatic.net/M6BAGGcp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/M6BAGGcp.png" alt="input image map" /></a></p> <p>and the corresponding patterns:</p> <p><a href="https://i.sstatic.net/v8qwNgwo.png" rel="nofollow noreferrer"><img src="h...
<python><machine-learning><computer-vision><gis><qgis>
2024-10-30 15:58:26
0
587
BananaMaster
79,141,783
1,843,329
How do you pass options to doctest when running 'make doctest' from Sphinx?
<p>We use <code>make html</code> to build HTML docs from <code>.rst</code> docs and our Python code using Sphinx. We have also enabled the <a href="https://www.sphinx-doc.org/en/master/usage/extensions/doctest.html" rel="nofollow noreferrer">sphinx.ext.doctest</a> extension in Sphinx so that we can test any code sample...
<python><python-sphinx><doctest>
2024-10-30 15:28:31
0
2,937
snark
79,141,781
4,182,596
Get maximum previous nonmissing value within group in pandas dataframe
<p>I have a pandas dataframe with a group structure where the value of interest, <code>val</code>, is guaranteed to be sorted within the group. However, there are missing values in <code>val</code> which I need to bound. The data I have looks like this:</p> <pre><code>group_id id_within_group val 1 1 ...
<python><pandas>
2024-10-30 15:27:15
1
521
matnor
79,141,695
1,725,836
pylint scanning is different between Windows and Linux
<p>I have a Python project that I want to scan with Pylint. Once I run <code>pylint **/*.py</code> I get different results between Windows and Linux machines, under the same Python and Pylint versions, same working directory, and same <code>.pylintrc</code> config.</p> <pre><code>pylint 3.2.7 astroid 3.2.4 Python 3.12....
<python><pylint>
2024-10-30 15:04:33
1
9,887
nrofis
79,141,639
10,595,871
Concatenate multiple API calls
<p>In my code, I have a list of CU (IDs) that I use in a URL for an API call:</p> <pre><code>for chunk in cu_chunks: cu_string = ','.join(chunk) url = f'{base_url}?CU={cu_string}' response = requests.get(url) print(f'Status code for request with {len(chunk)} CUs: {response.status_code}') </code></pre> <...
<python><flask>
2024-10-30 14:52:32
0
691
Federicofkt
79,141,599
54,873
WIth pandas, how do I use np.where with nullable datetime colums?
<p><code>np.where</code> is great for pandas since it's a vectorized way to change the column based on a condition.</p> <p>But while it seems to work great with <code>np</code> native types, it doesn't play nice with dates.</p> <p>This works great:</p> <pre><code>&gt;&gt;&gt; df1 = pd.DataFrame([[&quot;a&quot;, 1], [&q...
<python><pandas>
2024-10-30 14:42:16
1
10,076
YGA
79,141,547
7,123,797
If a class doesn't overload the == operator, then what is the value of an object of that class?
<p>From the Python reference:</p> <blockquote> <p>Every object has an identity, a type and a value.</p> </blockquote> <blockquote> <p>Comparison operators implement a particular notion of what the value of an object is. One can think of them as defining the value of an object indirectly, by means of their comparison im...
<python><function>
2024-10-30 14:31:10
2
355
Rodvi
79,141,487
1,308,967
Interpolate heart beats from ECG based on r-peak timestamps
<p>I am trying to interpolate heart beats from an occasionally noisy ECG signal.</p> <p><a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC6679245/" rel="nofollow noreferrer">This paper</a> finds that it is more accurate to interpolate heart beats from a noisy ECG signal by interpolating on beat timestamp, rather than b...
<python><numpy><scipy><interpolation>
2024-10-30 14:19:33
0
6,522
Chris
79,141,476
1,171,746
How to properly close pywebview window from a button?
<p>How to properly close pywebview window from a button?</p> <p>I put together this <a href="https://github.com/Amourspirit/webview-py-editor/tree/main" rel="nofollow noreferrer">demo</a> of a Python Code Editor using <a href="https://pywebview.flowrl.com/" rel="nofollow noreferrer">pywebview</a> and <a href="https:/...
<python><codemirror><pywebview>
2024-10-30 14:17:23
0
327
Amour Spirit
79,141,394
2,886,575
numpy tuple-style argsort ordered pairs of ordered pairs?
<p>I have an array of ordered pairs of ordered pairs:</p> <pre><code>foo = np.array([ [[1, 3], [2, 4]], [[4, 1], [2, 3]], [[3, 2], [3, 1]], [[2, 4], [3, 1]], [[1, 2], [3, 4]]]) </code></pre> <p>I would like to <code>argsort</code> each pair of pairs, in the usual python tuple sort...
<python><numpy>
2024-10-30 13:52:24
1
5,605
Him
79,140,720
1,479,670
How to get bash-like editing and history with stdin.read() or input()?
<p>I have a command line tool which repeatedly gets input from the keyboard using <code>stdin.readline()</code>.</p> <p>When i type some text at the prompt i only have limited possibilities for editing, such as moving the cursor (left and right) and deleting a character.</p> <p>But, for example, if i move the cursor to...
<python><command-line-interface><stdin>
2024-10-30 10:42:59
2
1,355
user1479670
79,140,682
20,920,790
Why function on_failure_callback for Airflow dag not running on task fail?
<p>I got Airflow dag with on_failure_callback function. But on_failure_callback function not running on failure and I don't see logs.</p> <p>There code of my dag.</p> <p>All @tasks in this code works, there's no need to show special failing function. I work with task instance by adding **kwargs to functions (another op...
<python><airflow>
2024-10-30 10:32:04
1
402
John Doe
79,140,661
7,973,301
How to sum values based on a second index array in a vectorized manner
<p>Let' say I have a <em>value array</em></p> <pre class="lang-py prettyprint-override"><code>values = np.array([0.0, 1.0, 2.0, 3.0, 4.0]) </code></pre> <p>and an <em>index array</em></p> <pre class="lang-py prettyprint-override"><code>indices = np.array([0,1,0,2,2]) </code></pre> <p>Is there a vectorized way to sum th...
<python><numpy>
2024-10-30 10:25:13
3
970
Padix Key
79,140,294
9,516,820
Pytesseract TesseractError: Unable to Load Language Files
<p>I am trying to use pytesseract in my system. But I am getting the following error message</p> <pre><code>pytesseract.pytesseract.TesseractError: (1, 'Error opening data file /opt/homebrew/share/eng.traineddata Please make sure the TESSDATA_PREFIX environment variable is set to your &quot;tessdata&quot; directory. Fa...
<python><tesseract><python-tesseract>
2024-10-30 08:47:30
1
972
Sashaank
79,139,716
2,552,290
Is constructing a list from a list guaranteed to make a copy?
<p>I have some python code that takes an iterable (list or tuple or generator expression or any other iterable), and needs to copy it into a new list.</p> <p>The following works:</p> <pre><code>newlist = [x for x in olditerable] </code></pre> <p>But I'm wondering whether I can just do this instead:</p> <pre><code>newli...
<python>
2024-10-30 05:10:16
1
5,611
Don Hatch
79,139,651
6,197,439
Getting the size of an item (QStyledItemDelegate?) in a QTableView in PyQt5?
<p>In the example below (at end of the post), what I want to do, is to</p> <ul> <li>have an image applied to a QTableView item (cell) if it has empty contents (as a DecorationRole, since I might have other logic which might use BackgroundRole) <ul> <li>this image should scale/resize according to the cell size</li> </ul...
<python><pyqt5><qt5>
2024-10-30 04:22:44
1
5,938
sdbbs
79,139,406
4,701,426
Executing an scheduled task if the script is run too late and after the scheduled time, using the `schedule` library
<p>Imagine I want to run this function:</p> <pre><code>def main(): pass </code></pre> <p>at these scheduled times (not every random 3 hours):</p> <pre><code>import schedule schedule.every().day.at(&quot;00:00&quot;).do(main) schedule.every().day.at(&quot;03:00&quot;).do(main) schedule.every().day.at(&quot;06:00&quo...
<python><scheduled-tasks>
2024-10-30 01:22:57
1
2,151
Saeed
79,139,391
6,401,858
Zip 2 lists with an offset, but keep left and right leftover
<p>I have two lists that I would like to zip with an offset similar to here: <a href="https://stackoverflow.com/questions/45185354/join-two-offset-lists-offset-zip">Join two offset lists (&quot;offset zip&quot;?)</a></p> <p>However I would like to keep the left and right leftover too, so the final result = left + zippe...
<python><list>
2024-10-30 01:10:38
2
382
fariadantes
79,139,355
2,690,221
Why does hex give a different output than indexing into bytes in python?
<p>I'm trying to confirm this struct is being formatted correctly for network byte order, but printing out the bytes and printing out the hex of the bytes give me different output, with the hex being the expected output. But I don't know why they are different.</p> <pre><code>import ctypes class test_struct(ctypes.Big...
<python><hex><byte>
2024-10-30 00:41:00
1
421
Thundercleez
79,139,320
48,956
All of the async workers quit. When doesn't asyncio.run return?
<p>Anyone know why this asyncio.run fails to exit in this program when the child process quits? I run the program below, and then <code>pkill ssh</code> to kill the ssh process.</p> <p>AFAICT all of the async workers:</p> <ul> <li><code>runcommand</code></li> <li><code>read_from_process</code></li> <li><code>write_to_p...
<python><python-asyncio>
2024-10-30 00:14:39
0
15,918
user48956
79,139,271
4,549,682
How to install LightGBM on Ubuntu 20.04 with CUDA support
<p>I followed the instructions in the <a href="https://lightgbm.readthedocs.io/en/latest/Installation-Guide.html#build-cuda-version" rel="nofollow noreferrer">docs</a>, but also tried many other variations. All ended up in the same place, with this:</p> <pre><code>LightGBM] [Fatal] Check failed: (split_indices_block_si...
<python><cuda><lightgbm>
2024-10-29 23:27:30
1
16,136
wordsforthewise
79,139,264
15,412,256
Polars Time Series Path Dependent Event Outcome calculation
<p>In the demo DataFrame I have three events:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame( { &quot;timestamp&quot;: [1, 2, 3, 4, 5, 6, 7, 8], &quot;threshold&quot;: [8, None, None, None, 5, None, None, 8], &quot;value&quot;: [2, 3, 4, 5, 6, 7, 8...
<python><dataframe><time-series><python-polars>
2024-10-29 23:23:47
1
649
Kevin Li
79,139,225
82,474
Why does python successfully open a file when the filename is incorrect?
<p>I accidentally asked a python program to open a file with the wrong name -- with an extra <code>.</code> on the end, and it worked.</p> <p>So I started experimenting:</p> <pre><code>&gt;&gt;&gt; open('myfile.txt') &lt;_io.TextIOWrapper name='fruit.iml' mode='r' encoding='cp1252'&gt; &gt;&gt;&gt; open('myfile.txt.') ...
<python><windows><file>
2024-10-29 23:01:24
0
59,725
Eric Wilson
79,138,994
3,404,377
How can I check if the current environment satisfies a `requirements.txt`?
<p>I have a <code>requirements.txt</code> file. From a shell script, is there any way to determine if the current environment (whatever it might be) satisfies the <code>requirements.txt</code>?</p> <p>In particular, I don't want to install anything, reach out to the network, or check if updates are available. I'm also ...
<python><pip><requirements.txt>
2024-10-29 21:03:07
0
1,131
ddulaney
79,138,978
4,701,426
merging lists with identical elements but in different order in pandas series into one unique lists
<p>Consider this simple dataframe:</p> <pre><code>df = pd.DataFrame({'category' :[['Restaurants', 'Pizza'], ['Pizza', 'Restaurants'], ['Restaurants', 'Mexican']]}) </code></pre> <p>df:</p> <p><a href="https://i.sstatic.net/1Q0TRW3L.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/1Q0TRW3L.png" alt="ente...
<python><pandas><dataframe>
2024-10-29 20:57:16
1
2,151
Saeed
79,138,858
16,611,809
How can I highlight or select all Pandas code in Visual Studio Code
<p>I want to transition from Pandas to Polars in a big Python project. Is there a way to highlight or find all Pandas commands I've written in Visual Studio Code (or another IDE if necessary) so I would see what I'd need to edit?</p>
<python><pandas><visual-studio-code><refactoring>
2024-10-29 20:12:45
1
627
gernophil
79,138,666
6,811,048
Convert pandas merge code to pyspark join
<p>I have small problem with pyspark. I try to rewrite code from pandas where I have:</p> <pre><code>df.merge(df2, how=&quot;outer&quot;, left_on=[&quot;b&quot;], right_on=[&quot;b&quot;]) </code></pre> <p>And I have got columns <code>b</code>, <code>a_x</code> and <code>a_y</code>. But when I do it in pyspark like:</p...
<python><pandas><pyspark>
2024-10-29 19:22:09
3
649
Nju
79,138,641
4,392,566
Plottable Customize Bars
<p>Given this dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Grade':[2,3,4,5], 'start':[0,0,20,10], 'end':[100,90,80,100]}) Grade start end 0 2 0 100 1 3 0 90 2 4 20 80 3 5 10 100 </code></pre> <p>I would like to generate a...
<python><matplotlib><plottable>
2024-10-29 19:12:39
1
3,733
Dance Party
79,138,587
11,197,957
Hitting a stubborn ClientAuthenticationError while attempting to use the ContainerClient class
<p>I'm trying to run some integration tests in <strong>Azure</strong> via a pipeline designed by a previous team, and I'm not having much luck. Specifically, the pipeline keeps hitting a <code>ClientAuthenticationError</code>.</p> <p>This is a <strong>minimal working example</strong> of the <strong>Python</strong> code...
<python><azure><azure-blob-storage>
2024-10-29 18:58:11
1
734
Tom Hosker
79,138,547
9,848,275
ipfsapi issue with pyinstaller
<p>I'm running a simple script that downloads and uploads files from an IPFS node using ipfsapi. Everything works fine.</p> <p>But when running with Pyinstaller ( I use the <code>--onefile</code> option, but the same thing happens with default settings), I get the following error:</p> <pre><code>Traceback (most recent ...
<python><pyinstaller><ipfs-http-client>
2024-10-29 18:39:53
2
615
Matias Salimbene
79,138,384
16,611,809
Use np.where to create a list with same number of elements, but different content
<p>I have a pandas dataframe where a value sometimes gets NA. I want to fill this column with a list of strings with the same length as another column:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({&quot;a&quot;: [&quot;one&quot;, &quot;two&quot;], &quot;b&quot;: [&quot;th...
<python><pandas><numpy>
2024-10-29 17:45:42
2
627
gernophil
79,138,375
8,423,881
Python typing: accept kwargs only with some class' methods
<p>Is it possible to somehow extract some class' methods type and use them in <code>kwargs</code>?</p> <p>Example of what I want:</p> <pre class="lang-py prettyprint-override"><code>class A: prop: int = 10 def foo(self): pass def bar(self): pass def fun[T](**kwargs: Idk[T]): pass fun...
<python><python-typing>
2024-10-29 17:40:18
1
311
Malyutin Egor
79,138,298
17,702,266
Issue with Mentions and Hashtags via LinkedIn API
<p>We’re investigating a problem with the LinkedIn API where mentions and hashtags are not recognized when posting via the API. We’ve thoroughly reviewed the LinkedIn documentation and even attempted a hardcoded test using LinkedIn's example organization.</p> <p>Here are the details:</p> <p>According to the LinkedIn do...
<python><linkedin-api>
2024-10-29 17:16:24
0
642
DominicSeel
79,137,995
7,648
Seaborn legend not matching with plot lines
<p>I have the following code:</p> <pre><code>import pandas as pd import seaborn as sns import matplotlib.pyplot as plt v_exponents = range(2, 9) vs = [2 ** exponent - 1 for exponent in v_exponents] df = pd.read_csv('data/out/erdos_renyi_graph/path_lengths_dfs/stats.csv') for v in vs: df_filtered = df[df['V'] == v]...
<python><seaborn><legend>
2024-10-29 15:53:21
1
7,944
Paul Reiners
79,137,986
1,714,490
QtVirtualKeyboard/PyQt6 - how to programmatically select OSK language?
<p>I have several questions concerning <code>QtVirtualKeyboard</code> usage under PyQt6 so, since StackOverflow policy is &quot;just one question&quot; I will post several questions.</p> <p>First part will be the same because they all pertain to same setup.</p> <h2>Common Setup</h2> <p>I installed <code>QtVirtualKeyboa...
<python><pyqt6><qtvirtualkeyboard>
2024-10-29 15:49:47
0
3,106
ZioByte
79,137,955
1,714,490
QtVirtualKeyboard/PyQt6 - how to link OSK to specific input widget?
<p>I have several questions concerning <code>QtVirtualKeyboard</code> usage under PyQt6 so, since StackOverflow policy is &quot;just one question&quot; I will post several questions.</p> <p>First part will be the same because they all pertain to same setup.</p> <h2>Common Setup</h2> <p>I installed <code>QtVirtualKeyboa...
<python><pyqt6><qtvirtualkeyboard>
2024-10-29 15:41:48
0
3,106
ZioByte
79,137,935
8,533,290
Numpy: large number modulo numpy array
<p>I have a large number (&gt;64 Bit) and an array of small numbers.</p> <pre><code>import numpy as np n = 375562681772559479679199924760395898982847025172274709141095261928746039609 primes = np.array([2,3,5,7,11]) </code></pre> <p>In an earlier numpy version I could write <code>n % primes</code>, which was significant...
<python><numpy>
2024-10-29 15:38:22
0
720
Hennich
79,137,924
1,714,490
QtVirtualKeyboard/PyQt6 - how to install and deploy?
<p>I have several questions concerning <code>QtVirtualKeyboard</code> usage under PyQt6 so, since StackOverflow policy is &quot;just one question&quot; I will post several questions.</p> <p>First part will be the same because they all pertain to same setup.</p> <h2>Common Setup</h2> <p>I installed <code>QtVirtualKeyboa...
<python><pyqt6><qtvirtualkeyboard>
2024-10-29 15:36:10
0
3,106
ZioByte
79,137,908
11,261,546
Error when runing mlflow with sklearn model
<p>I'm training a <code>RandomForestRegressor</code> and keeping track of it using <code>mlflow</code></p> <p>Using the following code works perfectly <strong>only when</strong> <code>n_estimators</code> is lower than <code>90</code></p> <p>The code:</p> <pre><code>import mlflow import mlflow.sklearn from mlflow.models...
<python><scikit-learn><mlflow>
2024-10-29 15:30:45
0
1,551
Ivan
79,137,843
4,701,426
filtering a pandas dataframe string column using the `str.contains` method
<p>I have dataframe looking like this, where <code>long_category</code> reflects the category of businesses in the rows:</p> <pre><code>df = pd.DataFrame({ 'long_category': {0: 'Doctors, Traditional Chinese Medicine, Naturopathic/Holistic, Acupuncture, Health &amp; Medical, Nutritionists', 1: 'Shipping Centers, Loca...
<python><pandas><dataframe>
2024-10-29 15:13:06
2
2,151
Saeed
79,137,715
7,346,706
Flyer color in seaborn boxplot with palette
<p>I have a seaborn boxplot with a categorical variable to use for hue and a dictionary with a color for each category given as the palette argument. MWE:</p> <pre><code>import seaborn as sns from matplotlib import pyplot as plt cdict = {&quot;First&quot; : &quot;gold&quot;, &quot;Second&quot;: &quot;blue&quo...
<python><matplotlib><colors><seaborn>
2024-10-29 14:43:02
1
1,415
NicoH
79,137,578
695,134
VSCode fails with venv but works from terminal window manually
<p>I'm using Python 3.12.3, latest vscode and from a (Windows) terminal I can set up and run venv fine. If I am in vscode, go to th the terminal window and run all my commands (x\Scripts\activate.bat) it switches fine and uses the virtual environment.</p> <p>However, it is failing within vscode in both ways I know how:...
<python><visual-studio-code><virtualenv>
2024-10-29 14:09:52
1
6,898
Neil Walker
79,137,342
3,728,901
Kaggle: How to export old environment with existing download files?
<p>I do with old notebook</p> <pre><code>!pip freeze &gt; kaggle_environment.txt </code></pre> <p>resutl <a href="https://gist.githubusercontent.com/donhuvy/eecbaed4da2c04f42ae6960eff897e38/raw/a920cdf67f8c3e139e226ee4cdc7f1c498734a2e/kaggle_environment.txt" rel="nofollow noreferrer">https://gist.githubusercontent.com/...
<python><kaggle>
2024-10-29 13:03:24
1
53,313
Vy Do
79,137,181
7,709,727
How to get server's IP and port from Flask Python code
<p>I have a very simple Flask app (from <a href="https://flask.palletsprojects.com/en/stable/quickstart/" rel="nofollow noreferrer">https://flask.palletsprojects.com/en/stable/quickstart/</a>)</p> <pre class="lang-py prettyprint-override"><code># File name: app.py from flask import Flask app = Flask(__name__) @app.r...
<python><flask><werkzeug>
2024-10-29 12:20:23
1
1,570
Eric Stdlib
79,137,121
1,035,897
What API should I use to manage Alerts and Alert Rules in Azure?
<p>Looking in Azure portal I see this:</p> <p><a href="https://i.sstatic.net/pBPwUpWf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pBPwUpWf.png" alt="Alerts and Alert Rules in Azure Portal" /></a></p> <p>Further I have run with great success the following cli commands:</p> <pre><code>az monitor metric...
<python><azure><azure-python-sdk><alert-rules>
2024-10-29 12:01:53
1
9,788
Mr. Developerdude
79,137,093
25,606,333
Can dependency injection be used with django?
<p>I am very popular with using the technique of dependency injection to decouple my code. This would typically involve providing an object with functionality, into the constructor of it's dependent.</p> <p>For the first time, I am using django to make a web api (with a database of objects attached). I intended to inje...
<python><django><dependency-injection>
2024-10-29 11:53:17
2
1,064
Neil Butcher
79,136,816
16,891,669
Pyspark force schema while reading parquet
<p>I have a parquet source with the 'Year' column as long and I have specified it as int in my table. While reading parquet I specify the schema of the table to force it but it gives an error instead.</p> <pre class="lang-py prettyprint-override"><code>df = ( spark .read .schema(spark.table(f'{CATALOG_NAME}...
<python><apache-spark><pyspark><databricks>
2024-10-29 10:38:45
1
597
Dhruv
79,136,697
6,734,243
How to make a class extention detected by Intellisense?
<h2>Context</h2> <p>I'm building an extention package on top of a Google API called Google Earth Engine: <a href="https://geetools.readthedocs.io/en/latest/" rel="nofollow noreferrer"><code>geetools</code></a>. In short I want to add to an existing package object extra functions that are repetitive or complicated for n...
<python><visual-studio-code>
2024-10-29 10:06:15
0
2,670
Pierrick Rambaud
79,136,480
3,104,974
Explode / unpivot DataFrame containing count data to one row per item
<p>Context: Data transformation for a logistic regression problem. I have the following data structure:</p> <pre><code>df = pd.DataFrame({&quot;group&quot;: [&quot;A&quot;, &quot;B&quot;], &quot;total&quot;: [3, 5], &quot;occurrence&quot;: [2, 1]}) </code></pre> <p>I want to do sth. like <a href="https://pandas.pydata....
<python><pandas><dataframe><logistic-regression>
2024-10-29 09:09:41
4
6,315
ascripter
79,136,433
1,782,553
Add external dependency to my project with UV
<p>I would like to add an external project (cloning a public github repository) as a dependency to my python project managed by UV with minimum changes (especially to the external repo).</p> <p>The external project doesn't follow any python project standard, is not ment to be installed, and just has a <code>requirement...
<python><pyproject.toml><uv>
2024-10-29 08:58:42
0
1,647
Jav
79,136,379
12,545,137
Cannot modify Pandas dataframe read from Excel file
<p>I have a function to apply to a DataFrame as follows:</p> <pre><code>import pandas as pd from math import comb from itertools import combinations def find_match_total(row, total_col, sum_cols): size = len(row) data = row.loc[row.index.isin(sum_cols)].to_dict() total= row[total_col] keys = data.keys(...
<python><pandas><dataframe>
2024-10-29 08:37:00
0
584
Dinh Quang Tuan
79,136,314
10,132,474
how to let pip install show progress
<p>In the past, I install my personal package with <code>setup.py</code>:</p> <pre><code>python setup.py install </code></pre> <p>Now this method is deprecated, and I can only use <code>pip</code>:</p> <pre><code>python -m pip install . </code></pre> <p>However, the method with <code>setup.py</code> can show install m...
<python><pip><setup.py>
2024-10-29 08:13:45
1
1,147
coin cheung
79,136,294
3,100,115
How to run tests using each package pyproject.toml configuration instead of the top level pyproject.toml?
<p>I'm using <a href="https://docs.astral.sh/uv/concepts/workspaces/" rel="nofollow noreferrer"><code>uv</code></a> workspace with a structure that looks like the following example from the doc.</p> <pre><code>albatross β”œβ”€β”€ packages β”‚ β”œβ”€β”€ bird-feeder β”‚ β”‚ β”œβ”€β”€ pyproject.toml β”‚ β”‚ └── src β”‚ β”‚ └── bird_fee...
<python><pytest><uv>
2024-10-29 08:08:16
1
61,461
Sede
79,136,280
8,589,908
find_peaks - trimming both peak array and prominences
<p>I have two arrays of data from a scipy <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html" rel="nofollow noreferrer">signal.find_peaks</a> function.</p> <pre><code> p, prom_data = signal.find_peaks(spec, prominence=0.000010) prom = prom_data['prominences'] </code></pre>...
<python><arrays><scipy>
2024-10-29 08:04:48
1
499
Radika Moonesinghe
79,136,087
1,285,061
Django - get local listening IP address
<p>In Django, how can I get Django's local IP <code>192.168.1.200</code> that it is presently listening on?</p> <p>I need to use the IP in Django logging format.</p> <p>settings.py</p> <pre><code>ALLOWED_HOSTS = ['192.168.1.200', '127.0.0.1'] </code></pre> <p>Run server</p> <pre><code>python manage.py runserver 192.168...
<python><python-3.x><django>
2024-10-29 06:49:57
2
3,201
Majoris
79,136,054
1,300,818
Getting different SHA-224 values in Python and Kotlin Android
<p>Need to validate the Hash value for a Json response received from the backend. The hash value is properly calculated in Python and matched with backend server hash value which is correct. where as I am getting a different hash value always in the Kotlin Android. sharing the code snippets below.</p> <p>Python:</p> <p...
<python><android><kotlin><hash><sha>
2024-10-29 06:32:07
1
662
Ganesh
79,136,032
5,790,653
How to sort a dictionary by using len() function
<p>This is a dictionary I have:</p> <pre class="lang-py prettyprint-override"><code>mydict = { 4: {'K', 'H'}, 2: {'Y', 'X', 'Q', 'U'}, 8: {'A', 'T', 'S'}, } </code></pre> <p>It seems there are some ways to sort a dictionary that I tried but didn't work:</p> <pre class="lang-py prettyprint-override"><code>so...
<python>
2024-10-29 06:25:26
1
4,175
Saeed
79,135,844
3,464,927
pip3 upgrading Python dependencies - SSL error (unsafe legacy renegotiation failed)
<p>I'm trying to update some Python dependencies (mainly the remotior-sensus) using OSGeo4W, installed with QGIS 3.34.9. This is using Python 3.12.4.</p> <p>I'm following instructions on this site: <a href="https://semiautomaticclassificationmanual.readthedocs.io/en/latest/installation_win64.html#qgis-download-and-inst...
<python><pip>
2024-10-29 04:36:01
2
769
user25730
79,135,473
894,067
Why is VSCode not recognizing imports that aren't top level imports?
<p>I have the following code in a Python file in VSCode:</p> <pre class="lang-py prettyprint-override"><code># These work just fine import tensorflow as tf import numpy as np from collections import Counter # These have an error from tensorflow.keras.models import Sequential from sklearn.utils import resample </code><...
<python><visual-studio-code><pyright>
2024-10-29 00:28:50
0
20,944
Charlie Fish
79,135,371
11,865,845
Find the highest triplet
<p>I'm trying to create a function that receives a input list and return the sum of the highest triplet. My code is meant to take the highest 3 unique values (NO duplicates) and add them together and return the highest possible sum of the values. Not sure why but the following function doesn't work when I run the tests...
<python>
2024-10-28 23:14:59
4
564
Peter
79,135,297
2,192,824
Type hint with string constant
<p>I sometimes see people using string constant for type hint, like below:</p> <pre><code>def my_function(arg1: &quot;some_string&quot;, arg2: int) -&gt; None: pass </code></pre> <p>What does <code>arg1: &quot;some_string&quot;</code> mean? Under what condition should we use it like that?</p>
<python><python-typing>
2024-10-28 22:36:11
1
417
Ames ISU
79,135,214
272,023
How to cross-compile Rust-based Python wheel
<p>I want to create a Python wheel that will run on both Windows and Linux (x86_64 and possibly ARM). I want to write the data processing code in Rust and have Python call the Rust code, so I am going to need to have different wheels for each target.</p> <p>I can use <a href="https://github.com/PyO3/maturin" rel="nofol...
<python><rust><python-wheel>
2024-10-28 22:00:21
0
12,131
John
79,134,991
14,179,793
How to keep Python pexpect shell open
<p>I am trying to use pexpect to have a main processing loop that sends input to a number of other processes in order.</p> <p><strong>Code</strong><br /> pexpect_test.py</p> <pre><code>if __name__ == '__main__': count = 3 processes = [] for x in range(count): processes.append(pexpect.spawn('/bin/bas...
<python><pexpect>
2024-10-28 20:18:08
2
898
Cogito Ergo Sum
79,134,979
1,880,463
Relocated Subpackages in PySNMP
<p>I inherited some code that used PySNMP version 4.4.12, and while not very familiar with SNMP, it is my job to get some scripts working with the latest version of PySNMP. One issue I have is there was a function or class named MibVariable in pysnmp.entity.rfc3413.oneliner.cmdgen and it has been either relocated or de...
<python><pysnmp>
2024-10-28 20:13:14
0
327
stesteve
79,134,933
54,873
What is the new best way to mass-set values of an existing dataframe in pandas?
<p>Imagine I have a dataframe where I wish to change the existing values based on their location in the frame (e.g. <code>iloc</code>):</p> <pre><code>(Pdb) df = pd.DataFrame([[&quot;a&quot;, 1], [&quot;b&quot;, 2], [&quot;c&quot;, 3]], columns=[&quot;let&quot;, &quot;num&quot;]) (Pdb) df let num 0 a 1 1 b ...
<python><pandas>
2024-10-28 19:54:47
1
10,076
YGA
79,134,554
4,200,859
Working directory weirdness, no module named 'tools'?
<p>I'm really unclear about Python, imports, and working directory.</p> <p>I'm running python from my root directory, which contains a folder <code>tools</code> and within that, two python files: <code>tool.py</code> and <code>env.py</code>.</p> <p>My python run command is: <code>python tools/tool.py</code>, and within...
<python>
2024-10-28 17:49:48
0
639
Max
79,133,856
4,343,563
How to order dataframe based on substrings in column?
<p>I have a dataframe with string rows. I want to sort the entire dataframe based on the strings in this column. However, there are some rows that contains a substring that is the text in another row so it is messing up the order. My dataframe looks like:</p> <pre><code> col1 col2 col3 col4 Anim...
<python><pandas><dataframe><sorting>
2024-10-28 14:35:02
2
700
mjoy
79,133,681
10,818,184
why Python built-in str join() method is not faster than simple +=?
<pre><code>binary_str= np.random.randint(2,size=1000000,dtype='int') </code></pre> <p>method 1:</p> <pre><code>binary_str=''.join(binary_str.astype(str)) </code></pre> <p>method 2:</p> <pre><code>s='' for c in binary_str: s+=str(c) </code></pre> <p>I read many articles saying that method 1 is supposed to be much fa...
<python><performance>
2024-10-28 13:48:59
1
488
li_jessen
79,133,572
3,332,023
Change matplotlib yaxis offset from 1e-5 to caps 1E-5
<p>I have a plot in matplotlib and I can't get it to change from <code>1e-5</code> to <code>1E-5</code>. I've tried a lot, this seems to be the closest: <code>ax.yaxis.get_offset_text().set_text(ax.yaxis.get_offset_text().get_text().replace('e', 'E'))</code> if I run <code>print(ax.yaxis.get_offset_text().get_text().)<...
<python><matplotlib><plot>
2024-10-28 13:15:59
2
467
axel_ande
79,133,564
16,525,263
How to copy files and folders in HDFS using Pyspark
<p>I have folder structure like this on HDFS</p> <p><code>/user/test/data/data_backlog</code></p> <p>Inside <code>data_backlog</code>, I have date folders like below</p> <pre><code> dt=2023.01.01 part1.avro part2.avro dt=2023.01.02 part1.avro part2.avro </code></pre> <p>I need to co...
<python><pyspark>
2024-10-28 13:14:50
1
434
user175025