question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
79,444,501
2025-2-17
https://stackoverflow.com/questions/79444501/fpdf-header-and-background
I need to create a pdf with header, footer and background color. Tge following code is generating all 3, but it seems the footer is getting behind the pdf rect from fpdf import FPDF class PDF(FPDF): def header(self): self.set_font(family='Helvetica', size=8) self.cell(0, 10, 'test_header', align='L') def footer(self): ...
It looks like the issue is that you're setting the background colour after you draw the page. The way you're doing it paints the background colour over everything, like what would happen if you painted a room without taking the posters off the wall. From a quick google search, FPDF doesn't have a method for modifying t...
3
2
79,443,999
2025-2-16
https://stackoverflow.com/questions/79443999/how-to-open-an-image-parse-input-from-user-and-close-the-image-afterwards-in-p
This answer did not work for me, nor for some Mac users, and I did not find a working solution among the following similar questions: How to open an image in Python and close afterwards? How to Close an Image? How can I close an image shown to the user with the Python Imaging Library? How do I close figure in matplotl...
The answer below opens an image from a file path in a separate Window, then asks the questions in the CLI. After the questions are answered by the user, the image is closed. Requirements pip install tensorflow pip install matplotlib Solution def make_receipt_label(img_filepath): """ Opens an image, asks the user quest...
2
1
79,435,884
2025-2-13
https://stackoverflow.com/questions/79435884/fastapi-middleware-for-postgres-multi-tenant-schema-switching-causes-race-condit
I'm building a multi-tenant FastAPI application that uses PostgreSQL schemas to separate tenant data. I have a middleware that extracts an X-Tenant-ID header, looks up the tenant's schema, and then switches the current schema for the database session accordingly. For a single request (via Postman) the middleware works ...
I also implemented a multi-tenant FastAPI application using PostgreSQL via schemas. In my case, I avoided using middleware because the database session (obtained from SessionLocal) and its state need to be isolated per request. When using middleware, the connection (and its state) from the connection pool may be reused...
1
1
79,438,335
2025-2-14
https://stackoverflow.com/questions/79438335/how-to-make-pydantics-non-strict-coercive-mode-apply-to-integer-literals
I'm validating inputs to a function using Pydantic's @validate_call as follows: from typing import Literal from pydantic import validate_call @validate_call def foo(a: Literal[0, 90, 180, 270]) -> None: print(a, type(a)) I want Pydantic to perform its default type coercion like it does with the int type: foo(90) # Wor...
You can combine the BeforeValidator and the Literal like this: from typing import Annotated, Literal from pydantic import validate_call, BeforeValidator, ValidationError # First try has the following validator: # BeforeValidator(int) @validate_call def foo(a: Annotated[Literal[0, 90, 180, 270], BeforeValidator(float)])...
2
2
79,440,649
2025-2-14
https://stackoverflow.com/questions/79440649/iconipy-and-pyinstaller-issue
I would like to ask you for help with creation of .exe file from python script where I use customtkinter, iconipy libraries. pyinstaller: https://pyinstaller.org/en/stable iconimy: https://iconipy.digidigital.de/iconipy.html After creation of .exe file I finished with this error: My python code: from PIL import Imag...
Soved by adding iconipy "assets" folder into "_internal" as whole folder inside pyinstaller .spec file + add "iconipy" as hiddenimports:
1
1
79,442,012
2025-2-15
https://stackoverflow.com/questions/79442012/how-to-scrape-website-which-has-hidden-data-inside-table
I am trying to Scrape Screener.in website to extract some information related to stocks. However while trying to extract Quarterly Results section there are some field which is hidden and when click on + button it show additional information related to parent header. I need to have this information I am using below pyt...
As already commented, the content is reloaded on demand, but it is precisely these requests that can be replicated in order to obtain the content as well. To do this, you have to iterate over the rows of the table and make the request if necessary. import requests import pandas as pd from bs4 import BeautifulSoup url =...
1
3
79,442,094
2025-2-15
https://stackoverflow.com/questions/79442094/does-python-reads-all-lines-of-a-file-when-numpy-genfromtxt-is-executed
I have really large ASCII file (63 million lines or more) that I would like to read using numpy.genfromtxt(). But, it is taking up so much memory. I want to know what python actually does when numpy.genfromtxt() is executed. Does it read all the lines at once? Look at the below code, for example. import numpy as np dat...
It reads all the lines. It has to. That data array has to hold all of the file's data, and NumPy can't build an array with all of the file's data without reading all of the file. That said, the implementation uses a lot more memory than the output needs. The implementation parses the requested columns of the file's dat...
1
1
79,440,163
2025-2-14
https://stackoverflow.com/questions/79440163/tqdm-multiprocessing-and-how-to-print-a-line-under-the-progress-bar
I am using multiprocessing and tqdm to show the progress of the workers. I want to add a line under the progress bar to show which tasks are currently being processed. Unfortunately, whatever I do seems to end up with this being printed on top of the progress bar making a mess. Here is a MWE that shows the problem: fro...
You can add a separate bar at the bottom that displays only tasks. def progress_updater(self, total_tasks, progress, active_tasks): """Update tqdm progress bar and active task list on separate lines""" sys.stdout.write("\n") # Move to the next line for active task display sys.stdout.flush() with ( tqdm.tqdm(total=total...
2
4
79,441,934
2025-2-15
https://stackoverflow.com/questions/79441934/python-venv-install-skips-component-file-pointer-png
This is a strange issue. I maintain the pi3d python module and it contains this file github.com/tipam/pi3d/blob/master/src/pi3d/util/icons/pointer.png When I clone the repo locally it has the .png file but when the package is installed using pip it seems to be missing. This didn't used to be a problem. Is it something ...
It's because it's not present in tool.setuptools.package-data in pyproject.toml file. [tool.setuptools.package-data] "*" = ["*.fs", "*.vs", "*.inc", "*.gif"] With the previous configuration, you add all this extensions in your package as you can see in the next screenshot (content of the package uploaded on pypi). So...
1
1
79,430,185
2025-2-11
https://stackoverflow.com/questions/79430185/generate-all-paths-that-consists-of-specified-number-of-visits-of-nodes-edges
In a graph/chain there are 3 different states: ST, GRC_i and GRC_j. The following edges between the states exists: EDGES = [ # source, target, name ('ST', 'GRC_i', 'TDL_i'), ('ST', 'GRC_j', 'TDL_j'), ('GRC_i', 'GRC_j', 'RVL_j'), ('GRC_j', 'GRC_i', 'RVL_i'), ('GRC_j', 'ST', 'SUL_i'), ('GRC_i', 'ST', 'SUL_j'), ] The va...
To make things more readable, I will use the following notations: S, I and J are the nodes XY is the number of traversals of edge X -> Y The unknowns of the problem are IS and JS. They must be non-negative. Case 1: final state is S During a path, every node is entered and exited the same number of times. For node I,...
5
1
79,440,210
2025-2-14
https://stackoverflow.com/questions/79440210/python-shutting-down-child-thread-when-parent-dies
I have a parent Python task that starts a child task to listen for a USB/BLE response. Problem is that if the parent task dies, the child listener task keeps running and the process has to be killed. Parent Process: self.listenerTask = threading.Thread(target=self.listener, name="Listener", args=[interface]) Listener...
you can mark your listener thread as a daemon so that if the main (parent) process exits, the listener will automatically be killed. For example: # In your parent process where you create the thread self.listenerTask = threading.Thread( target=self.listener, name="Listener", args=[interface], daemon=True # Ensure the t...
1
3
79,439,852
2025-2-14
https://stackoverflow.com/questions/79439852/what-is-this-missing-class
I am coding a small project that goes through every class and prints them in the fashion of the Exception hierarchy at the very bottom of https://docs.python.org/3/library/exceptions.html. I got it to a readable point(not finished), and saw something interesting. It was a class called MISSING. I looked it up, nothing. ...
Ok, first, actually retreive the class: In [1]: def search_for_missing(cls): ...: if isinstance(cls, type): ...: subclasses = type.__subclasses__(cls) ...: else: ...: subclasses = cls.__subclasses__() ...: for sub in subclasses: ...: if sub.__name__ == "MISSING": ...: return sub ...: subsub = search_for_missing(sub) .....
2
3
79,439,828
2025-2-14
https://stackoverflow.com/questions/79439828/code-work-in-vscode-but-get-error-in-leetcode
""" 14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". """ class Solution: def longestCommonPrefix(self,strs: list[str]) -> str: list_length = len(strs) shortest_length = len(strs[0]) for i in range(li...
if shortest_length <= length than your shortest_char variable will not be defined. It is bad practice to define variables like that.
1
4
79,439,896
2025-2-14
https://stackoverflow.com/questions/79439896/cant-find-correct-select-html-tag-value-and-trying-to-wait-for-a-select-opti
I have an issue where I use a url that ends such as T-shirts page I am trying to scrape the product links off the pages. I have been trying for some time now, nothing is working yet. This is my current attempt after some Googling and reading the Playwright docs: Website html: <select id="prodPerPageSelTop"> <option val...
Even if your focus is to get the information with playwright - Therefore, I would just like point out additionally that scraping the information can also be implemented quite simply using requests and the endpoint via which the information is loaded: import requests page_num = 1 data = [] while True: json_data = reques...
2
3
79,436,180
2025-2-13
https://stackoverflow.com/questions/79436180/how-can-i-get-the-date-from-weeknr-and-year-using-strptime
I'm trying to get the date of monday given some weeknr and year. But I feel like strptime is just returning the wrong date. This is what I try: from datetime import date, datetime today = date.today() today_year = today.isocalendar()[0] today_weeknr = today.isocalendar()[1] print(today) print(today_year, today_weeknr) ...
There was an answer here before, but it got removed. I don't know why. The issue is that I was taking the weeknr from the isocalendar and later was parsing the isocalendar week,year into a date with non isocalendar directives. "%Y-W%W-%w" takes: %Y Year with century as a decimal number. %W Week number of the year (Mon...
1
1
79,437,187
2025-2-13
https://stackoverflow.com/questions/79437187/backward-lookup-is-not-working-in-django-5-x
We are migrating our django app from django==3.2.25 to django==5.1.6. OneToOneField, ManyToManyField are giving errors on revers lookup. Create fresh setup. python -m venv app_corp_1.0.X ./app_corp_1.0.X/bin/pip install django mkdir djangotutorial ./app_corp_1.0.X/bin/django-admin startproject mysite djangotutorial ./a...
The app_label is probably the culprit: you registered the models with an app_label that is not in INSTALLED_APPS, and as a result these are not registered. If I change the app_label to one in INSTALLED_APPS, it works. But you don't need to mention app_label: if you leave it, it will automatically install it in the app ...
3
1
79,438,489
2025-2-14
https://stackoverflow.com/questions/79438489/what-is-the-correct-way-to-please-the-typechecker-for-a-bytes-str-str-f
I have the following code: def from_utf8(string: bytes | str) -> str: if isinstance(string, bytes): return string.decode("utf-8") else: return string # <- type warning on this line pylance gives me a type warning on the return string line: Type "bytearray | memoryview[_I@memoryview] | str" is not assignable to return ...
Before Python 3.12, bytes was specified to behave as an alias of builtins.bytes | builtins.bytearray | builtins.memoryview. From the Python 3.10 docs (emphasis mine): class typing.ByteString(Sequence[int]) A generic version of collections.abc.ByteString. This type represents the types bytes, bytearray, and memoryview ...
2
3
79,433,451
2025-2-12
https://stackoverflow.com/questions/79433451/change-text-direction-in-python-pptx
I'm using the python‑pptx library to generate PowerPoint presentations on a Linux environment (Python 3.10). I need to add text to the slides, but it must display from right to left (RTL). I have tried the following approaches: Setting RTL on font runs: I attempted to set the RTL property with: run.font.rtl = True How...
Microsoft Office provides bidirectional writing only when a language which needs this is listed under Office authoring languages and proofing. See Change the language Office uses in its menus and proofing tools. The property rtl for right-to-left writing is a paragraph-property, not a character-property. Not clear why ...
1
2
79,438,104
2025-2-14
https://stackoverflow.com/questions/79438104/nest-dictionaries-within-a-list-into-respective-dictionaries
I have two lists, animal_list and outer_list. animal_list contains dictionaries within the list. outer_list is just a simple list with exact same elements animal_list = [{'animal': 'dog', 'color': 'black'}, {'animal': 'cat', 'color': 'brown'}] outer_list = ['pet', 'pet'] How can I combine the two lists to make a neste...
You can use a list comprehension that outputs a new dict for each key-value pair: [{key: value} for key, value in zip(outer_list, animal_list)] Demo: https://ideone.com/IDUJL8 Also, if it is truly guaranteed that outer_list always contains the same value throughout, you can simply extract the first item as a fixed key...
2
4
79,437,667
2025-2-13
https://stackoverflow.com/questions/79437667/how-to-count-unique-state-combinations-per-id-in-a-polars-dataframe
I have a Polars DataFrame where each id can appear multiple times with different state values (either 1 or 2). I want to count how many unique ids have only state 1, only state 2, or both states 1 and 2. import polars as pl df = pl.DataFrame({ "id": [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 9, 9, 10, 10, 10, 11, 11...
You could group by the id and use .all() and .any() to check the states. (df.group_by("id") .agg( one = (pl.col.state == 1).all(), two = (pl.col.state == 2).all(), both = (pl.col.state == 1).any() & (pl.col.state == 2).any() # both = pl.lit(1).is_in("state") & pl.lit(2).is_in("state") ) # .select(pl.exclude("id").sum()...
2
3
79,436,912
2025-2-13
https://stackoverflow.com/questions/79436912/python-convert-mm-dd-yyyy-to-yyyymmdd-using-date-format
I have a csv file with a partial format of something like: field1,bmm/bdd/byyyy,emm/edd/eyyyy,field4.... I am successfully creating a json file like this: { "field1": [ { "begDate": byyyybmmbdd, "endDate": eyyyyemmedd, "score": field4, ..... The python script that I was using works fine but it gives me deprecation wa...
You can avoid the deprecation warning by not trying to replace the deprecated date_parser with a callable in date_format (which expects a string, not a function). Instead, load the dates as objects and then convert them with pd.to_datetime and dt.strftime to get the format you want. For example: import pandas as pd fro...
1
3
79,436,352
2025-2-13
https://stackoverflow.com/questions/79436352/how-to-insert-a-column-at-a-specific-index-with-values-for-some-rows-in-a-single
I want to insert a column at a specific index in a Pandas DataFrame, but only assign values to certain rows. Currently, I am doing it in two steps: df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50] }) df.insert(1, 'NewCol', None) df.loc[[1, 3], 'NewCol'] = ['X', 'Y'] Is there a more concise way to ach...
Provide a Series with the correct indices to insert: df.insert(1, 'NewCol', pd.Series(['X', 'Y'], index=[1, 3])) Output: A NewCol B 0 1 NaN 10 1 2 X 20 2 3 NaN 30 3 4 Y 40 4 5 NaN 50
1
2
79,435,770
2025-2-13
https://stackoverflow.com/questions/79435770/create-json-from-csv-and-add-some-header-lines-with-pandas
I found this post which initially seemed to be exactly what I was looking for but it didn't help me: Adding Header and Footer to JSON output from Python I have a csv file which I read in as Pandas dataframe: import os import csv import json import pandas as pd csvFilePath = "Mypath" track = pd.read_csv(csvFilePath, hea...
Create a dictionary, assign it as a new dictionary key and export with json.dump: import json headlines['track'] = df.to_dict(orient='records') with open(path_out + 'result.json', 'w') as f: json.dump(headlines, f) Or as a string: import json headlines['track'] = df.to_dict(orient='records') print(json.dumps(headlines...
1
2
79,435,315
2025-2-13
https://stackoverflow.com/questions/79435315/numpy-random-size-and-shape-confusion
I was looking through some codes and saw this line, numpy.random.normal(size=x.shape). Where, x = numpy.linspace(1, 2, 100). I don't understand what this does. I've only come across, np.random.normal(size=1) before. Can someone please explain the difference in both the cases and their use.
From numpy.random.normal size: int or tuple of ints, optional Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn. shape return a tupl...
1
2
79,434,541
2025-2-12
https://stackoverflow.com/questions/79434541/create-a-new-column-of-dictionaries-where-keys-are-in-another-column-of-lists-a
I'm trying to create the "Related Quantities" column of a dataframe given the existing "Item", "Quantity", and "Related Items" columns. Item Quantity Related Items Related Quantities 0 Flowers 1 ['Bushes'] {'Bushes': 2} 1 Bushes 2 ['Flowers'] {'Flowers': 1} 2 Cars 3 ['Trucks', 'Motorcycles'] {'Trucks': 4, '...
Using df.apply with a lookup dictionary. import pandas as pd data = {'Item': ['Flowers', 'Bushes', 'Cars', 'Trucks', 'Motorcycles'], 'Quantity': [1, 2, 3, 4, 5], 'Related Items': [['Bushes'], ['Flowers'], ['Trucks', 'Motorcycles'], ['Cars', 'Motorcycles'], ['Cars', 'Trucks']]} df = pd.DataFrame(data) # Creates a dictio...
2
1
79,433,458
2025-2-12
https://stackoverflow.com/questions/79433458/lightgbm-force-variables-to-be-in-splits
Im trying to find a way to train a lightgbm model forcing to have some features to be in the splits, i.e.: "to be in the feature importance", then the predictions are afected by these variables. Here is an example of a the modeling code with an usless variable as it is constant, but the idea is that there could be an i...
As of this writing, LightGBM does not have functionality like "force at least 1 split on a given feature, but let LightGBM choose the threshold". However, it is possible to force LightGBM to split on specific features with specific thresholds. Here's an example (I tested it with lightgbm 4.5.0): import json import ligh...
3
1
79,434,556
2025-2-12
https://stackoverflow.com/questions/79434556/best-place-to-initialize-a-variable-from-a-postgres-database-table-after-django
I have a django project where I have some database tables. One of the database tables is designed to store messages and their titles. This helps me to create/alter these messages from my django-admin. Now I want to initialize a variable (as a dictionary) from this table as follows : MY_MSGS = {record.name : {'title':re...
I think the main concern is that you should not run the query immediately, but after Django has initialized the models, etc. We can do that by postponing the load procedure, and do it when we really need a message, with: def get_message(name): cache = get_message.cache if cache is None: cache = get_message.cache = { re...
1
2
79,434,429
2025-2-12
https://stackoverflow.com/questions/79434429/explode-dataframe-and-add-new-columns-with-specific-values-based-on-a-condition
I have a dataframe with 6 columns: 'Name', 'A', 'B', 'C', 'Val', 'Category' It looks like this: Name A B C Val Category x 1.1 0 0.2 NA NA y 0 0.1 0 NA NA z 0.5 0.1 0.3 NA NA I want to expand the dataframe such that for each value that is not 0 in columns 'A', 'B', 'C' you get an extra row. The column 'Val' is assigned...
You could replace the 0s with NaNs, rename the columns to your categories, reshape to long with stack, and join back to the original to duplicate the rows: out = (df .drop(columns=['Val', 'Category']) .join(df[['A', 'B', 'C']] .set_axis(['first', 'second', 'third'], axis=1) .rename_axis(columns='Category') .replace(0, ...
1
1
79,432,856
2025-2-12
https://stackoverflow.com/questions/79432856/when-i-create-an-array-of-numpy-floats-i-get-an-array-of-python-floats
The code: import sys import numpy as np print(f"We are using Python {sys.version}", file=sys.stderr) print(f"We are using numpy version {np.__version__}", file=sys.stderr) # 2.2.1 def find_non_numpy_floats(x: any) -> bool: if not (isinstance(x, np.float64)): print(f"Found non-numpy.float64: {x} of type {type(x)}", file...
numpy.vectorize converts the array to an array of object dtype first: # Convert args to object arrays first inputs = [asanyarray(a, dtype=object) for a in args] I don't know why. I can think of a few plausible reasons, but nothing stands out as a clear motivator. In any case, converting to object dtype builds an arra...
1
4
79,431,483
2025-2-11
https://stackoverflow.com/questions/79431483/polars-selectors-for-columns-that-are-nested-types
Some Polars operations, such as .sort() fail when passed a column with a Nested Type. This (sensible) choice about sort means I cannot use my usual sorting pattern of df.sort(pl.all()). import polars as pl NESTED_TYPES = [ pl.List, pl.Array, pl.Object, pl.Struct ] pl.exclude(NESTED_TYPES) Result: *.exclude([Dtype(List...
It is not very well supported yet, see https://github.com/pola-rs/polars/issues/9971 As a workaround, you can specify "all types except non-nested types" using the code shown in that Issue, or just loop over all dtypes you care about and specify pl.List(dtype) for each of them, but there aren't any good ways to say "al...
3
2
79,433,014
2025-2-12
https://stackoverflow.com/questions/79433014/what-is-the-difference-between-configdict-and-dict
What is the difference between ConfigDict and dict? ConfigDict: TypeAlias = dict[str, Union[str, list[str]]] What are the advantages of using ConfigDict? https://github.com/pytest-dev/pytest/pull/13193/files#diff-f1d27932fbd9530086080aa8df367309881fe90f204cdd69102ba59758644761
ConfigDict in the PR you linked to is a type alias to a dict where the key is a string and the value is either a string or a list of strings. In runtime, there isn't any functional difference. It's mainly useful in development time to save having to type the long dict definition each time and to avoid mistakenly using ...
1
5
79,432,139
2025-2-12
https://stackoverflow.com/questions/79432139/target-sum-algorithm-using-numpy
I have a numpy array of floats and a target sum. I am trying to find all possible combinations of elements that would add up to the target sum. I am struggling to come up with anything computationally effective that wouldn't require days to run. Constraints: the same value might appear in the array multiple times. 0 <...
As there are no negative values in the array, there are two types of early stopping that you can introduce to the code. When the current sum is larger than the target sum, then you do not need to continue adding values. You can sort the array and try adding values in order from smallest to largest, if adding a value i...
2
4
79,429,046
2025-2-11
https://stackoverflow.com/questions/79429046/tricky-reverse-regex-python-3-11
Can any one please help me with the reverse part of the regex? I got it almost right but the reverse is tricky because if I have an input as: Input = dogs and cats or (white or black) or (cat and (red or blue)) Current Regex Output = dogs.{0,10}cats|(white|black)|(cat.{0,10}(red|blue)) "OK regex" Current Regex Reverse ...
This code can just change the pattern to ((blue|red).{0,10}cat)|(black|white)|cats.{0,10}dogs. import re pattern = r'dogs.{0,10}cats|(white|black)|(cat.{0,10}(red|blue))' reg = re.compile(r'\w+|(\.\{\d+,\d+\})|[\(\)\|]') symbols = { ')': '(', '(': ')' } results = [] match = reg.search(pattern) end = 0 while match: _m =...
1
2
79,430,935
2025-2-11
https://stackoverflow.com/questions/79430935/why-does-my-a-algorithm-expand-nodes-differently-when-using-heapq-vs-a-set-for
I'm implementing an A* search algorithm for a maze solver in Python. Initially, I maintained the open set as a plain set and selected the node with the lowest f-score using: current = min(open_set, key=lambda cell: f_score[cell]) This version of the algorithm tended to explore in a directed fashion toward the goal (al...
Your heapq-based implementation uses an ascending counter for tiebreaking. This means that when there's a tie, the entry added to the heap earliest wins. When there are a lot of equally-promising candidates, this tends to explore all of them "together". Your set-based implementation's tiebreaking strategy is kind of ju...
3
3
79,430,379
2025-2-11
https://stackoverflow.com/questions/79430379/how-can-i-get-uv-to-git-pull-dependencies-on-uv-sync
In uv, I want to add a Git repository as a dependency which is easy in itself, but if we commit in the Git repository of the dependency, I want uv sync to do a Git pull for this Git repository. Basically, do a Git pull on the dependency Git repository and then apply the changed code for the dependency to my current vir...
TLDR. You can use uv sync --upgrade Explanation. Per documentation of uv sync: Syncing ensures that all project dependencies are installed and up-to-date with the lockfile. The lockfile doesn't change when the remote repository is updated, but it can be upgraded using uv lock --upgrade or uv sync --upgrade allowin...
4
2
79,429,531
2025-2-11
https://stackoverflow.com/questions/79429531/select-the-first-and-last-row-per-group-in-polars-dataframe
I'm trying to use polars dataframe where I would like to select the first and last row per group. Here is a simple example selecting the first row per group: import polars as pl df = pl.DataFrame( { "a": [1, 2, 2, 3, 4, 5], "b": [0.5, 0.5, 4, 10, 14, 13], "c": [True, True, True, False, False, True], "d": ["Apple", "App...
As columns You could use agg, you will have to add a suffix (or prefix) to differentiate the columns names: result = (df.group_by('d', maintain_order=True) .agg(pl.all().first().name.suffix('_first'), pl.all().last().name.suffix('_last')) ) Output: ┌────────┬─────────┬─────────┬─────────┬────────┬────────┬────────┐ │ ...
5
3
79,428,677
2025-2-11
https://stackoverflow.com/questions/79428677/batch-make-smoothing-spline-in-scipy
In scipy, the function scipy.interpolate.make_interp_spline() can be batched since its x argument must be one-dimensional with shape (m,) and its y argument can have shape (m, ...). However, the function scipy.interpolate.make_smoothing_spline() only accepts a y argument of shape (m,). Is there a simple way to batch th...
The PR that added batch support to make_smoothing_spline happened to be merged a few hours before this post. https://github.com/scipy/scipy/pull/22484 The feature will be available in SciPy 1.16, or you can get it early in the next nightly wheels. https://anaconda.org/scientific-python-nightly-wheels/scipy See also the...
3
2
79,428,650
2025-2-11
https://stackoverflow.com/questions/79428650/map-causing-infinite-loop-in-python-3
I have the following code: def my_zip(*iterables): iterators = tuple(map(iter, iterables)) while True: yield tuple(map(next, iterators)) When my_zip is called, it just creates an infinite loop and never terminates. If I insert a print statement, it is revealed that my_zip is infinitely yielding empty tuples! My expect...
The two pieces of code you provided are not actually "equivalent", with the function using generator expressions notably having a catch-all exception handler around the generator expression producing items for tuple output. And if you actually make the two functions "equivalent" by removing the exception handler: def m...
5
4
79,448,057
2025-2-18
https://stackoverflow.com/questions/79448057/how-does-maybenone-also-known-as-the-any-trick-work-in-python-type-hints
In typestubs for the Python standard library I noticed a peculiar type called MaybeNone pop up, usually in the form of NormalType | MaybeNone. For example, in the sqlite3-Cursor class I find this: class Cursor: # May be None, but using `| MaybeNone` (`| Any`) instead to avoid slightly annoying false positives. @propert...
A nice summary can be found in this comment explaining the "Any Trick" of typeshed. We tend to use it whenever something can be None, but requiring users to check for None would be more painful than helpful. As background they talk about xml.etree.ElementTree.getroot which in some case returns None (Happens when the ...
5
5
79,451,761
2025-2-19
https://stackoverflow.com/questions/79451761/using-pytest-twisted-functions-with-pytest-asyncio-fixtures
I have code that uses Twisted so I've written a test function for it and decorated it with @pytest_twisted.ensureDeferred. The function awaits on some Deferreds. Then, I need to run some aiohttp website in it so I've written a fixture that uses the pytest_aiohttp.plugin.aiohttp_client fixture, decorated it with @pytest...
According to the discussion in https://github.com/pytest-dev/pytest-twisted/issues/188 it doesn't seem possible without changing at least one of the plugins. However, if you control the async fixtures you need to use, you can use pytest-twisted for everything, decorating the fixtures with @pytest_twisted.async_yield_fi...
4
1
79,455,504
2025-2-20
https://stackoverflow.com/questions/79455504/load-phi-3-model-extract-attention-layer-and-visualize-it
I would like to visualize the attention layer of a Phi-3-medium-4k-instruct (or mini) model downloaded from hugging-face. In particular, I am using the following model, tokenizer: import torch from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline import pdb tokenizer = AutoTokenizer.from_pretrained("mi...
here is what you need to know: RUNNING COLAB CODE - https://colab.research.google.com/drive/13gP71u_u_Ewx8u7aTwgzSlH0N_k9XBXx?usp=sharing you want see attention weights from your phi3 model. first thing: you must tell model to output attentions. usually you do outputs = model(input_ids, output_attentions=True) then ou...
3
2
79,461,837
2025-2-23
https://stackoverflow.com/questions/79461837/opencv-python-ffmpeg-tag-is-not-supported-with-codec-id-12-and-format-mp4-m
I would like to use OpenCV in Python to compile a video from a number of images. I get the error OpenCV: FFMPEG: tag is not supported with codec id 12 and format 'mp4 / MP4 I searched here for an answer how to fix it. I got an answer in this post, but it does not generate a video, the file is just 5.7kB, no matter wh...
File Path Handling: The files list is being created using os.walk and glob, but the os.path.join(path, file) in the loop is redundant because files already contains the full paths. Grayscale vs. Color: You're reading the images in grayscale (cv2.IMREAD_GRAYSCALE), but the VideoWriter expects color images (3 channels)...
2
-1
79,464,391
2025-2-24
https://stackoverflow.com/questions/79464391/django-celery-sqlite-database-locked-on-concurrent-access
I have a local Django 5.1/Celery 5.4 project that is using SQLite. I am the only user. Certain model saves trigger a Celery task that queries (SELECT) for the updated record (using the Django ORM), then runs an API call to update a remote record based on the local data, and then runs another UPDATE locally. The task wr...
The solution in this particular case was to shorten my transaction times, i.e. don't hold on to a transaction while making an external API call. This means I have to be more careful about not letting the views and tasks step on each others toes. I'm still flummoxed that so-called "production ready" settings don't allow...
1
1
79,464,425
2025-2-24
https://stackoverflow.com/questions/79464425/how-to-outer-join-merge-two-frames-with-polars-while-updating-left-with-right-va
So I got two csv which I load as polars frames: left: track_name,type,yield,group 8CEB45v1,corn,0.146957,A A188v2,corn,0.86308,A B73v6,corn,0.326076,A CI6621v1,sweetcorn,0.0357792,A CML103v1,sweetcorn,0.510464,A right: track_name,type,yield,group 8CEB45v1,corn,0.999,A B1234,pepper,1,B B1235,pepper,2,B my code so far:...
The thing you're doing wrong is including yield in matching_columns. You don't want to match by it, you want it as a value. One idea to reconcile that would be matching_columns = list(set(left.select(pl.col(pl.String)).columns) & set(right.select(pl.col(pl.String)).columns)) Alternatively, you could start with your wa...
3
1
79,461,375
2025-2-23
https://stackoverflow.com/questions/79461375/stitching-images-with-two-different-camera-positions
It may not be possible to do what I want, but I thought I would throw the question out there just in case. I am attempting to stitch the following two images together that are taken from two different camera position. They are taken at the exact same time, and as you can see, they have different perspectives. I recogn...
You have two different optical origins. You are not gonna get a panorama of the spherical or any other "pretty" kind. Those you could get with arbitrary views/perspectives, as long as the cameras have practically the same optical origin. Best you can hope for is to get a stitched view of any plane (e.g. the field), fro...
5
4
79,464,907
2025-2-24
https://stackoverflow.com/questions/79464907/memory-keeps-increasing-in-pytorch-training-loop-even-with-empty-cache
I have a pytorch training script, and I'm getting an out-of-memory error after a few epochs even tho I'm calling torch.cuda.empty_cache(). The GPU memory just keeps going up and I can't figure out why. Here's basically what I'm doing: import torch from torch.utils.data import Dataset, DataLoader import numpy as np clas...
Yeah, the issue is that you're moving tensors to CUDA inside __getitem__(), which isn't a good idea when using multiple workers in DataLoader. When num_workers > 0, PyTorch spawns separate processes for loading data, but CUDA operations should only happen in the main process. This can lead to memory not being freed pro...
2
1
79,463,058
2025-2-24
https://stackoverflow.com/questions/79463058/how-to-pass-multiple-inputs-to-a-python-script-in-macos-shortcuts
I’ve been using a Python script to perform multiple find/replace actions at once. It that has 3 inputs right inside the code, in a form like this: def main(): text_passage = """ (Here be huge blocks of text) “"" to_replace_input = “"" (Here be large strings to look for, each on a new line) “”” replacements_input = """ ...
I found How to pass variables into shell script : r/shortcuts and there is screenshot which suggests that you can put variables in script and it will copy/paste values automatically: Image from answer on Reddit (author: Infamous_Pea6200):
2
1
79,464,878
2025-2-24
https://stackoverflow.com/questions/79464878/accessing-sql-server-configuration-manager-with-python
I'm using Python with the 'wmi' and 'pyodbc' libraries in order to automate a server inventory of a list of VMs. Per VM, I'm trying to get a list of all MS SQL Server products, the SQL Server database instance name, number of databases, databases on that engine, engine version, etc. and will eventually put it on a exce...
If you're trying to retrieve a list of SQL Server services (as seen in SQL Server Configuration Manager) using Python, the best approach is to use WMI (Windows Management Instrumentation). The win32_Product class retrieves too many irrelevant results (e.g., drivers, language packs), so instead, you should use win32_ser...
3
1
79,464,957
2025-2-24
https://stackoverflow.com/questions/79464957/you-cannot-access-body-after-reading-from-requests-data-stream-while-reading-js
I am currently working on a project where users will be able to authenticate themselves thanks to a form that I protected with a CSRF token, but for now I only take care of the server side party, here is the code: @api_view(['POST']) @csrf_protect @permission_classes([AllowAny]) def login(request): if request.method !=...
Your issue is this line: data = json.loads(request.body) From the documentation: Accessing request.POST inside middleware before the view runs or in process_view() will prevent any view running after the middleware from being able to modify the upload handlers for the request, and should normally be avoided. The Csrf...
2
1
79,464,314
2025-2-24
https://stackoverflow.com/questions/79464314/pandas-astype-becomes-in-place-operation-for-data-loaded-from-pickle-files
Pandas astype() appears to unexpectedly switch to performing in-place operations after loading data from a pickle file. Concretly, for astype(str), the data type of the input dataframe values is modified. What is causing this behavior? Pandas version: 2.0.3 Minimal example: import pandas as pd import numpy as np # crea...
This is a bug that has been fixed in pandas 2.2.0: Bug in DataFrame.astype() when called with str on unpickled array - the array might change in-place (GH 54654) As noted by Itayazolay in the PR, regarding the pickle MRE used there: The problem is not exactly with pickle, it's just a quick way to reproduce the probl...
1
2
79,464,593
2025-2-24
https://stackoverflow.com/questions/79464593/python-requests-disable-zstd-encoding
My Synology DS418play recently updated to the latest version of DSM7 that is available. I noticed that a lot of the python scripts that I had have started returning weirdly encoded data. Here is an example of the code: requests.get("https://www.23andmedatasettlement.com/").content returns b'(\xb5/\xfd\x04X\x1c&\x00\x...
I was able to find a commit that basically says if zstandard module is installed, add zstd to the Accept-Encoding. Running pip uninstall zstandard fixed my issue.
2
2
79,464,463
2025-2-24
https://stackoverflow.com/questions/79464463/python-pandas-identify-pairs-in-a-dataframe-based-on-both-a-string-similarity
I hope I am explaining this correctly. I have a dataframe in which i need to identify pairs of rows based on the string value of two columns. Each row in the pair must have a different string value in another column. I then need to add a new value to a new column based on TRUE or FALSE condition of that third column AN...
Hoping this helps, using data similar to the examples you shared. data = { 'name': ['John', 'John', 'Jane', 'Jane', 'Doe', 'Doe'], 'city': ['LA', 'LA', 'SF', 'SF', 'SD', 'SD'], 'item': ['Peanut Butter', 'Jelly', 'Peanut Butter', 'Peanut Butter', 'Jelly', 'Jelly'] } df = pd.DataFrame(data) We can then create a dictiona...
2
1
79,464,298
2025-2-24
https://stackoverflow.com/questions/79464298/python-polars-get-column-type-using-an-expression
In Python-Polars, I am trying to get the shrinked data type of a column using an expression, to be able to run validations against it. For example, I would like to build an expression that allows me to do the following: df = pl.DataFrame({"list_column": [[1, 2], [3, 4], [5, 6]]}) shape: (3, 1) ┌─────────────┐ │ list_co...
No. In first place, the data type for the list_column in your example is pl.List(pl.Int64()), so it would not be equal to pl.List - polars has a strong distinction between different nested types, and shrink_dtype does not currently works for that case at all. Secondly, the data type is always the same for all rows with...
2
5
79,457,847
2025-2-21
https://stackoverflow.com/questions/79457847/understanding-an-instance-of-pythons-struct-unpack
I found sample code for interrogating NTP servers on https://www.mattcrampton.com/blog/query_an_ntp_server_from_python/. The code is brief and well-written, but I don't understand the use of struct.unpack. This is the core code: client = socket.socket(AF_INET,SOCK_DGRAM) client.sendto(msg.encode('utf-8'),address) msg,a...
Following the documentation of struct, you are unpacking the first twelve (12) big-endian (!) unsigned 4-byte integers (I) of the NTP header into a tuple, of which you then extract the value at index 10 ([10]), i.e. the penultimate integer value. Following the definition of the NTP header format, this value is the firs...
2
4
79,463,169
2025-2-24
https://stackoverflow.com/questions/79463169/create-nested-lists-based-on-split-of-characters
I have a list made by strings, correctly cleaned (split(',') can be safely used), and correctly sorted depending on numbers. As a small example: l = ['C1', 'C1,C2', 'C2,C3', 'C3,C4', 'C4', 'C5', 'C5,C6', 'C6,C7', 'C7,C8', 'C8', 'C10', 'C10,C11', 'C11,C12', 'C12,C13', 'C13'] What I'm trying to achieve is to create as m...
If the input list is guaranteed to start and end with a single string and if there will always be at least one adjacent pair of single strings then: lst = ['C1', 'C1,C2', 'C2,C3', 'C3,C4', 'C4', 'C5', 'C5,C6', 'C6,C7', 'C7,C8', 'C8', 'C10', 'C10,C11', 'C11,C12', 'C12,C13', 'C13'] result = [[]] for e in lst: result[-1]....
2
1
79,461,242
2025-2-23
https://stackoverflow.com/questions/79461242/how-to-convert-float-columns-without-decimal-to-int-in-polars
The following pandas code removes all the .0 decimal precision if I have a float column with 1.0, 2.0, 3.0 values: import pandas as pd df = pd.DataFrame({ "date": ["2025-01-01", "2025-01-02"], "a": [1.0, 2.0], "c": [1.0, 2.1], }) print(df) columns = df.columns.difference(["date"]) df[columns] = df[columns].map(lambda x...
Something like this does the trick. Note that it is not typically advised to have the schema depend on the data itself. We can, however, avoid any for-by-row iteration and used a vectorised UDF with map_batches def maybe_cast_int(s: pl.Series) -> pl.Series: """Cast the Series to an Int64 type if all values are whole nu...
1
3
79,461,665
2025-2-23
https://stackoverflow.com/questions/79461665/django-admin-not-displaying-creation-date-field-despite-being-in-list-display
I have a Django project where I'm working on an e-commerce application. I'm using SQLite as my database, and I'm trying to add a creation_date field to my VendorProduct model so that it records when a product was created. What I Did I added the creation_date field to my VendorProduct model like this: models.py (VendorP...
list_display field is for List view only. It's the admin page listing instances of VendorProduct in your case. On your screenshot you have Add view which shows only editable fields. Since your creation_date field has auto_now_add option, it makes it non-editable. If you want to manually provide creation_date, but still...
2
5
79,451,592
2025-2-19
https://stackoverflow.com/questions/79451592/airflow-dag-gets-stuck-when-filtering-a-polars-dataframe
I am dynamically generating Airflow DAGs based on data from a Polars DataFrame. The DAG definition includes filtering this DataFrame at DAG creation time and again inside a task when the DAG runs. However, when I run the dag and I attempt to filter the polars dataframe inside the dynamically generated DAG, the task get...
after even just importing polars in the main process, it doesn't work with how Airflow forks the child process. Even if you tell Polars to be single-threaded. What works in this case is to make the child task run in a separate process. Here's a code that worked for me: import sys import subprocess from airflow import D...
2
3
79,459,880
2025-2-22
https://stackoverflow.com/questions/79459880/how-can-i-iterate-over-all-columns-using-pl-all-in-polars
I've written a custom function in Polars to generate a horizontal forward/backward fill list of expressions. The function accepts an iterable of expressions (or column names) to determine the order of filling. I want to to use all columns via pl.all() as default. The problem is that pl.all() returns a single expression...
Check out cum_reduce, which does a cumulative horizontal reduction. This is pretty much what you are after and saves you having to do any Python looping. Unfortunately, it reduces from left to right only. I've made this feature request to ask for right to left reductions, which should fully enable your use-case. Here's...
4
3
79,459,799
2025-2-22
https://stackoverflow.com/questions/79459799/how-to-update-folium-map-without-re-rendering-entire-map
I have a Folium map placed in PySide6 QWebEngineView. Map coordinates are updated each second and the map is recentered to the new position. However, this is re-rendering entire map with each update and it causes "flashing", which is not user friendly. I need to make the map to reposition by smooth dragging/sliding, or...
I discovered you can run JavaScript code to update data in html without rendering it again. You have to get layer name self.folium_map.get_name() and create JavaScript code with function layer_name.setView(coords) and run it with self.page().runJavaScript(js_code) It needs also to assign new coords to self.folium_map.l...
2
1
79,460,272
2025-2-22
https://stackoverflow.com/questions/79460272/regex-b-devanagiri
I have a regex in Python which uses \b to split words. When I use it on Devanagiri text, I notice that not all characters in the Unicode block are defined as word characters. Certain punctuation marks appear to be defined as non-word characters. This is fundamentally wrong as words in this script can end with these cha...
The problem with the pattern is that \b detects U+093E (DEVANAGARI VOWEL SIGN AA) and 0940 (DEVANAGARI VOWEL SIGN II) as non-word characaters, so the boundaries in the word पानी occur after each consonant and before the dependent vowels. It is critical to understand when working with Python regular expressions, with te...
1
3
79,458,994
2025-2-22
https://stackoverflow.com/questions/79458994/how-to-count-basic-math-operations-performed-in-a-python-recursive-function
I need to write a python script that counts the number of times these operations: +, -, *, //, %, >, <, ==, <=, >= are performed in a piece of python code relative to the input of N. Python Code: def bar(k): score = 0 for i in range(2, k + 1): j = i - 1 while j > 0: if i % j == 0: score = score // 2 else: score = score...
First of all, as you want to count both % and == as operations, the first base case should be return 2 instead of return 1. Also the constant terms you add in the other return statements seem all wrong. For instance, the second return statement should count 6 instead of 4 as its constant term: there are n % 3, n == 0, ...
3
3
79,458,938
2025-2-22
https://stackoverflow.com/questions/79458938/why-does-an-integer-inside-a-generator-function-swallow-the-object-of-send
I am not trying to achieve anything -- apart from learning how generator functions and coroutines work on a brick level, which I am not really getting yet, despite lots of reading.... $cat test.py #No integer def eee(): num = yield print(f"First num: {num}") num = yield print(f"Second num: {num}") num = yield print(f"T...
d "swallows" the 1 you sent it because you added this line yield 100 to ddd, that wasn't in eee. That line receives the 1. The 2 goes to the next yield.
2
3
79,457,881
2025-2-21
https://stackoverflow.com/questions/79457881/create-column-from-other-columns-created-within-same-with-columns-context
Here, column "AB" is just being created and at the same time is being used as input to create column "ABC". This fails. df = df.with_columns( (pl.col("A")+pl.col("B")).alias("AB"), (pl.col("AB")+pl.col("C")).alias("ABC") ) The only way to achieve the desired result is a second call to with_columns. df1 = df.with_colum...
Underlying Problem In general, all expressions within a (with_columns, select, filter, group_by) context are evaluated in parallel. Especially, there are no columns previously created within the same context. Solution Still, you can avoid writing large expressions multiple times, by saving the expression to a variable....
2
2
79,457,848
2025-2-21
https://stackoverflow.com/questions/79457848/how-to-perform-row-aggregation-across-the-largest-x-columns-in-a-polars-data-fra
I have a data frame with 6 value columns and I want to sum the largest 3 of them. I also want to create an ID matrix to identify which columns were included in the sum. So the initial data frame may be something like this: df = pl.DataFrame({ 'id_col': [0,1,2,3,4], 'val1': [10,0,0,20,5], 'val2': [5,1,2,3,10], 'val3': [...
Here are the steps: unpivot the val columns for each id_col group, sum the largest 3 columns using pl.col("value").top_k(3).sum() get a list of the names of those columns using pl.col("variable").top_k_by("value", k=3) Construct the flag columns (row-wise check if each column is in list of the top 3) using [pl.lit(...
2
2
79,457,702
2025-2-21
https://stackoverflow.com/questions/79457702/django-formset-nested-structure-not-posting-correctly-for-dynamic-fields
I’m working on a Django nested formset where users can: Add multiple colors to a product. For each color, add multiple sizes dynamically using JavaScript. Each size should have its own size_name, stock, and price_increment field. Issue When submitting the form, Django is incorrectly grouping multiple size field valu...
You need to group the color_size_formsets per color_formset, so: @login_required def add_product(request): if request.method == 'POST': # ... else: product_form = ProductForm() color_formset = ProductColorFormSet(prefix='colors') for index, color_form in enumerate(color_formset.forms): color_form.size_formset = Product...
2
1
79,456,037
2025-2-20
https://stackoverflow.com/questions/79456037/in-a-matplotlib-plot-is-there-a-way-to-automatically-set-the-xlim-after-it-has-b
I am working on a GUI where a user can specify the both the min and max x limit. When the value is left blank I would like it to be automatically calculated. One limit can be set while the other is automatically calculated by setting it to None. But after setting one limit and then setting it to None does not automatic...
As noted in the comment, we can "reset" to automatic axis limits using ax.set_xlim(auto=True) again followed by ax.autoscale_view(). # Later user changes their mind and leaves the first limit blank ax.set_xlim(auto=True) ax.autoscale_view() ax.set_xlim(None, 4) print(ax.get_xlim()) # prints: (0.8, 4.0)
2
2
79,457,363
2025-2-21
https://stackoverflow.com/questions/79457363/python-matplotlib-tight-layout-spacing-for-subplots
I'm using matplotlib to plot my data in a 4x2 grid of subplots. The matplotlib.pyplot.tight_layout automatically fits the subplots, legend, and text labels into a figure that I can save as png. However, when the legend is extremely long, tight_layout seems to add extra horizontal space to some subplots. What is the mos...
If you use the newer Constrained Layout rather than tight_layout then you can easily add a figure legend at the top right. Changes are: Create the figure with constrained layout fig, ax = plt.subplots(nrows=4, ncols=2, figsize=(10, 7), layout='constrained') Get hold of the legend handles and labels from a single axes...
1
2
79,457,237
2025-2-21
https://stackoverflow.com/questions/79457237/fit-function-stops-after-epoch-1
I have implemented this function to fit the model def fit_model(model, X_train_sequence_tensor,Y_train_sequence_tensor, epochs, val_set, time_windows, scaler): X_column_list = [item for item in val_set.columns.to_list() if item not in ['date', 'user', 'rank','rank_group', 'counts', 'target']] X_val_set = val_set[X_colu...
If epochs is not explicitly passed, Python may use a default value, which could be None or another unintended value. Explicitly passing epochs=epochs ensures that the function uses the value intended by the caller. Here is updated code: def fit_model(model, X_train_sequence_tensor,Y_train_sequence_tensor, epochs, val_s...
1
1
79,456,138
2025-2-21
https://stackoverflow.com/questions/79456138/is-it-correct-to-modify-django-db-connections-databases-dynamically-to-multipl
This is my first time developing a multi-tenant SaaS application in Django. In this SaaS each company has its own PostgreSQL database, and these databases are created dynamically when a company registers. I cannot predefine all databases in settings.DATABASES, as companies can register at any time without requiring a s...
You can use django-tenants library. Its designed for this purpose. https://django-tenants.readthedocs.io/en/latest/
1
1
79,456,808
2025-2-21
https://stackoverflow.com/questions/79456808/data-apparently-plotted-wrong-way-on-matplotlib
I am plotting a graph with date on the x axis and data on the y axis. However the graph is completly wrong and I don't understand why... df['Date_TrailClean'] = pd.to_datetime(df['Date_TrailClean']) # x axis values x = df['Date_TrailClean'] # corresponding y axis values y = df['AdjTotItems'] fig, ax = plt.subplots() # ...
import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates df = pd.read_excel('sample_data.xlsx') df['Date_TrailClean'] = pd.to_datetime(df['Date_TrailClean']) # Sort x-axis df = df.sort_values('Date_TrailClean') x = df['Date_TrailClean'] y = df['AdjTotItems'] fig, ax = plt.subplots(figsize=(...
2
2
79,455,366
2025-2-20
https://stackoverflow.com/questions/79455366/allow-enum-names-as-valid-inputs-with-pydantics-validate-call
This question asks about using the name of an enum when serializing a model. I want something like that except with the @validate_call decorator. Take this function foo(): from enum import Enum from pydantic import validate_call class Direction(Enum): NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 @validate_call def foo(d: Dire...
I can think of 2 options. The simplest solution would be to make Enum more flexible. from enum import Enum from pydantic import validate_call def normalize_enum_name(name: str) -> str: """A user-defined normalization function for enum names.""" # The results are only used as dictionary keys, so you can do whatever you ...
2
1
79,456,337
2025-2-21
https://stackoverflow.com/questions/79456337/how-to-subtract-data-between-columns-that-have-same-subfix
I have a sample dataframe as below that has same subfix as 001, 002, 003. import pandas as pd import numpy as np branch_names = [f"Branch_{i}" for i in range(1, 11)] date_1 = '20241231' date_2 = '20250214' date_3 = '20250220' data = { 'Branch': branch_names, date_1 + '_001': np.random.randint(60, 90, 10), date_1 + '_00...
You would typically use a MultiIndex here, which makes operations much easier than relying on substrings: # set "Branch" as index, convert columns to MultiIndex df2 = df.set_index('Branch') df2.columns = df2.columns.str.split('_', expand=True).rename(['date', 'id']) # perform the operation and join out = df2.join(df2[d...
3
2
79,453,988
2025-2-20
https://stackoverflow.com/questions/79453988/applying-numpy-partition-to-a-multi-dimensional-array
I need to find the k smallest element within a np.array. In a simple case you would probably use np.partition. import numpy as np a = np.array([7, 4, 1, 0]) kth = 1 p = np.partition(a, kth) print(f"Partitioned array: {p}") print(f"kth's smallest element: {p[kth]}") Partitioned array: [0 1 4 7] kth's smallest element: 1...
I would do the following: For simplified indexing, flatten everything except the axis of interest (if I understand you correctly, this is always the last axis), which produces an N×n-shaped array with N rows resulting from flattening and n columns representing the values along the axis of interest. Sort the values alo...
1
2
79,454,786
2025-2-20
https://stackoverflow.com/questions/79454786/detect-highlighted-text-in-docx
I'm trying to detect text that has a coloured background in a MS Word docx, to separate it from the "normal" text. from docx import Document ... # Load the document doc = Document(docx_path) highlighted_text = [] normal_text = [] # Iterate through all paragraphs for para in doc.paragraphs: # Iterate through all runs in...
This script performs well for me: from docx import Document def extract_highlighted_text(docx_path): doc = Document(docx_path) highlighted_texts = [] for para in doc.paragraphs: for run in para.runs: if run.font.highlight_color is not None: highlighted_texts.append(run.text) return highlighted_texts docx_file = "text.d...
2
2
79,454,687
2025-2-20
https://stackoverflow.com/questions/79454687/how-to-program-angled-movement-for-a-sonic-game
I've been trying to get a Sonic The Hedgehog game working in Pygame and it works for the most part. Sonic can run fast, jump across platforms like a normal platformer, gets affected by gravity, collects rings, etc. (check attached video) https://imgur.com/a/q1YrAXO However, I cannot for the life of me get Sonic to run ...
You can use vector math so that the character follows the surface angle. Create a horizontal movement vector and then rotate it by the negative of the surface angle. That way when the character position is updated the movement should be aligned along the slope. e.g. if not self.grounded: # Apply gravity normally when i...
2
1
79,452,824
2025-2-19
https://stackoverflow.com/questions/79452824/python-polars-encoding-continous-variables-from-breakpoints-in-another-dataframe
The breakpoints data is the following: breakpoints = pl.DataFrame( { "features": ["feature_0", "feature_0", "feature_1"], "breakpoints": [0.1, 0.5, 1], "n_possible_bins": [3, 3, 2], } ) print(breakpoints) out: shape: (3, 3) ┌───────────┬─────────────┬─────────────────┐ │ features ┆ breakpoints ┆ n_possible_bins │ │ ---...
Given that breakpoints will most likely be a very small DataFrame, I think the simplest and most efficient solution is something like: import polars as pl breakpoints = pl.DataFrame( { "features": ["feature_0", "feature_0", "feature_1"], "breakpoints": [0.1, 0.5, 1], "n_possible_feature_brakes": [3, 3, 2], } ) df = pl....
4
2
79,453,722
2025-2-20
https://stackoverflow.com/questions/79453722/how-can-i-avoid-getting-the-wrong-answer-when-calculating-with-njit-in-python
In order to improve the speed of my code in Python I use a njit library from numba. For the number 94906267, which I use in my calculations, I get a wrong answer. At the same time, if I do not use njit, my code gives a correct answer. Here are two examples. from numba import njit @njit def main_with_njit(): a = 9490626...
First things first. This error is only possible by first converting the operands to 64-bit floating point number. The reason for this is that 64-bit floating point numbers do not have the precision to represent 9007199515875289, and the result is instead rounded to 9007199515875288. You have not done anything to sugges...
1
5
79,454,104
2025-2-20
https://stackoverflow.com/questions/79454104/using-match-statement-with-a-class-in-python-3
Can somebody explain why in the following code Two matches? >>> class One: ... pass ... >>> class Two: ... pass ... >>> a = One() >>> >>> match a.__class__: ... case Two: ... print("is two") ... is two >>>
It's important to remember that match-case is not designed to be used as switch-case. It's created for Structural Pattern Matching, and the syntax is suited for that purpose. Here you can check various possible patterns that may be given for case statements. One that matches what you used is Capture Pattern, which alwa...
3
4
79,453,531
2025-2-20
https://stackoverflow.com/questions/79453531/using-a-python-library-installed-in-virtual-environment-from-script-running-in-s
There is a python library that only wants to be installed in a virtual environment, but how to import the library into scripts running in my standalone application that does not run in a virtual environment? I'm writing a a Delphi/Lazarus application using the component Python4Delphi and Python4Lazarus to run python sc...
There are two ways you can try to fix this: In your Delphi/Lazarus application, you could configure Python4Delphi to use the Python interpreter from your virtual environment instead of the system Python. This way, it will automatically have access to all packages installed in that virtual environment. PythonEngine1.D...
1
2
79,448,827
2025-2-18
https://stackoverflow.com/questions/79448827/python-cv2-imshow-memory-leak-on-macos
I believe I am witnessing a memory leak in the following Python code that calls OpenCV functions. Can you reproduce this? Why does this happen? How can I work around it or fix it? My environment: macOS (10.12 and 10.13) Python 3.8.10 OpenCV 3.4.18 NumPy 1.24.4 I've now also tested it on another machine in Python 3.9....
Thanks to user Christoph Rackwitz, the cause of the problem was identified as cv2.destroyAllWindows(). It seems to be present only on Mac systems and a bug report was filed, but apparently, there aren't currently any plans on fixing it.
2
1
79,453,687
2025-2-20
https://stackoverflow.com/questions/79453687/pandas-merge-single-column-with-double-column-dataframe-without-commas-for-singl
I have 2 DataFrame with different columns and want to merge to csv without comma for the one having single column. How can we remove comma for the one having single column? import pandas as pd # 1st DataFrame with single column pd_title = pd.DataFrame(['Category: A', '']) # 2nd DataFrame with double columns data = [ ["...
There is no direct way to do this in pandas since you're using rows of data as header. You could however convert to CSV string and post-process it: import re with open('/content/test.csv', 'w') as f: f.write(re.sub(',*\n,+\n', '\n\n', result.to_csv(index=False, header=False))) A better option would be to first create ...
1
2
79,450,492
2025-2-19
https://stackoverflow.com/questions/79450492/how-does-the-epsilon-parameter-behave-in-scipy-interpolate-rbfinterpolator
I've been trying to port some code from using scipy.interpolate.Rbf to scipy.interpolate.RBFInterpolator. However I have the impression that the epsilon parameter has a different behavior in the latter -- in fact in my tests it seems like at least with the multiquadric kernel I can vary this parameter by multiple order...
However I have the impression that the epsilon parameter has a different behavior in the latter It is different. Specifically, Rbf's epsilon divides distance, and RBFInterpolator multiplies it. Here is a source explaining why RBFInterpolator changes this from Rbf: epsilon scales the RBF input as r*epsilon rather tha...
3
3
79,452,813
2025-2-19
https://stackoverflow.com/questions/79452813/python-polars-how-to-apply-function-across-multiple-cols
How to extend this df = df.select( pl.col("x1").map_batches(custom_function).alias("new_x1") ) to something like df = df.select( pl.col("x1","x2").map_batches(custom_function).alias("new_x1", "new_x2") ) Or the way to go is doing it one by one df = df.select( pl.col("x1").map_batches(custom_function).alias("new_x1") ...
The syntax df.select( pl.col("x1", "x2").some_method_chain() ) is equivalent to df.select( pl.col("x1").some_method_chain(), pl.col("x2").some_method_chain(), ) Especially, your example is almost correct, but fails on the last call to pl.Expr.alias in the method chain [...].alias("new_x1", "new_x2"). You basically tr...
2
2
79,452,715
2025-2-19
https://stackoverflow.com/questions/79452715/how-can-i-make-cuts-into-a-numerical-column-based-on-a-categorical-column
I have a very large dataset (about 10^7 rows and 1000 columns) and need to make cuts into one of the columns, for trining/validation separation, with the bins changing based on another column. I am pretty new to python and am using this function: SEGMENT is either A, B or C, and DATE is what I am cutting (yes, it is a ...
You could use a groupby.apply to handle all rows of a SEGMENT simultaneously: df['CLASS'] = (df.groupby('SEGMENT', group_keys=False)['DATE'] .apply(lambda x: pd.cut(x, bins=cuts[x.name]['cut'], labels=cuts[x.name]['class'], ordered=False)) ) Example output: SEGMENT DATE CLASS 0 A 20240102 training 1 A 20241215 out 2 ...
2
2
79,452,360
2025-2-19
https://stackoverflow.com/questions/79452360/pandas-list-dates-to-datetime
I am looking to convert a column with dates in a list [D, M, Y] to a datetime column. The below works but there must be a better way? new_df = pd.DataFrame({'date_parts': [[29, 'August', 2024], [28, 'August', 2024], [27, 'August', 2024]]}) display(new_df) ## Make new columns with dates new_df = pd.concat([new_df, new_d...
Just combine the parts into a single string, and pass to to_datetime: new_df['release_date'] = pd.to_datetime(new_df['date_parts'] .apply(lambda x: '-'.join(map(str, x))), format='%d-%B-%Y') Output: date_parts release_date 0 [29, August, 2024] 2024-08-29 1 [28, August, 2024] 2024-08-28 2 [27, August, 2024] 2024-08-27...
3
3
79,452,237
2025-2-19
https://stackoverflow.com/questions/79452237/how-does-pd-where-work-with-callables-as-parameters
The basics of using Pandas where with callables seems simple. np.random.seed(0) df = pd.DataFrame(np.random.randn(8, 4), columns=['A', 'B', 'C', 'D']) df["test"] = range(1,9) def MyBool(x): print(1) return ( x > 0 ) def MyFunc(x1): print(1) return x1['A'] df.where( cond = lambda x: MyBool(x), other = lambda x: MyFunc(x...
The logic is quite simple, for each False in the output of the cond callable, the matching value in the result of other will be used as replacement. If other is a scalar, this value is used. The matching value is identified by position if the callable returns an array, and by alignment for a DataFrame: df = pd.DataFram...
2
2
79,448,337
2025-2-18
https://stackoverflow.com/questions/79448337/using-re-sub-and-replace-with-overall-match
I was just writing a program where I wanted to insert a newline after a specific pattern. The idea was to match the pattern and replace with the overall match (i.e. capture group \0) and \n. s = "abc" insert_newline_pattern = re.compile(r"b") re.sub(insert_newline_pattern, r"\0\n", s) However the output is a\x00\nc, r...
You can use the form \g<0> in Python for the zeroeth group (or overall match from the pattern) which would be the same as $0 in PCRE (alternatively, in PCRE, you can use $& or \0 in replacement strings). s="abc" insert_newline_pattern=re.compile(r"b") re.sub(insert_newline_pattern,r"\g<0>\n",s) Result: 'ab\nc' This f...
5
8
79,447,890
2025-2-18
https://stackoverflow.com/questions/79447890/how-can-i-seperate-the-fringes-that-have-been-calculated-with-findpeaks
I would like to seperate the fringes (the red curved lines) that I have calculated with scipy findpeaks how can I achive it. I would like to seperate them and store in the text file. import numpy as np from scipy.signal import find_peaks import matplotlib.pyplot as plt X = np.load('X.npy') Y = np.load('Y.npy') P_new =...
I had reasonable success using HDBSCAN. I first ran find_peaks to find peaks along y (rather than along x) - these are the black lines. I then clipped the image to within the blue square, and clustered the points using HDBSCAN. The final clusterings are coloured. To plot a particular cluster, you could use: view_clust...
2
2
79,450,950
2025-2-19
https://stackoverflow.com/questions/79450950/pandas-indexing
Can someone explain what is meant by Both loc and iloc [in Pandas] are row-first, column-second. This is the opposite of what we do in native Python, which is column-first, row-second. Because I thought when accessing arrays or lists of lists, the first index always represents the row: matrix = [ [1,2,3], # row 1, in...
I would say that statement is incorrect or, at least, very misleading and likely to cause confusion. Both iloc and loc are row-first & column-second, but this is exactly the same as how indexing works in native Python and your example. First index refers to the row, and the second index refers to the column. Your examp...
1
2
79,450,810
2025-2-19
https://stackoverflow.com/questions/79450810/pandas-groupby-multiple-columns-aggregate-some-columns-add-a-count-column-of-e
The data I am working with: data (140631115432592), ndim: 2, size: 3947910, shape: (232230, 17) VIN (1-10) object County object City object State object Postal Code float64 Model Year int64 Make object Model object Electric Vehicle Type object Clean Alternative Fuel Vehicle (CAFV) Eligibility object Electric Range floa...
Your question would benefit from a minimal reproducible example. That said, the count doesn't really depend on a particular column, as long as you don't have missing values, thus pick any one that matches this criterion and add another aggregation (you can use one of the grouping columns or Model Year since you know it...
2
1
79,450,409
2025-2-19
https://stackoverflow.com/questions/79450409/how-to-parse-xls-data-including-merged-cells-using-python-pandas
How to parse xls data to this struct, both row and column have merged cells, simply use df.index.to_series().ffill() cannot handle. { "time": "time", "category": "A", "variety": "A1", "specification": "S1", "unit": "U1", "average": 1.25, "region": "RegionA", "market": "MarketA", "price": 1.1, }
I figured out this solution: def test_xls_parse(): file_path = 'test.xls' df = pd.read_excel(file_path, engine='xlrd') time_label = df.iloc[0, 0] categories = df.iloc[1, 2:] varieties = df.iloc[2, 2:] specifications = df.iloc[3, 2:] units = df.iloc[4, 2:] averages = df.iloc[5, 2:] regions = df.iloc[6:, 0].ffill() marke...
2
1
79,450,672
2025-2-19
https://stackoverflow.com/questions/79450672/python-pandas-multi-column-sorting-problem
I want to sort the first column according to the internal algorithm, and then sort the second column according to the custom sorting method The test data is as follows: A B Ankang Shaanxi Ankang Southeast Baoding Anguo Baoding Anguo Northeast Baoding Anguo Baoding Anguo Southeast Changsha Hunan Changsha Hunan Bright A...
The basic logic you can use for column 'B': Series.str.split + access str[-1] + Series.map df['B'].str.split().str[-1].map(sort_dicts) 0 1.0 1 0.0 2 1.0 3 NaN 4 0.0 5 3.0 6 4.0 7 3.0 8 4.0 9 2.0 10 NaN 11 4.0 12 2.0 Name: B, dtype: float64 Couple of ways to sort using this logic: Option 1 Chain calls to df.sort_valu...
3
1
79,449,532
2025-2-18
https://stackoverflow.com/questions/79449532/python-polars-creating-new-columns-based-on-the-key-value-pair-of-a-dict-match
Sorry if the title is confusing. I'm pretty familiar with Pandas and think I have a solid idea of how I would do this there. Pretty much just brute-force iteration and index-based assignment for the new columns. I recently learned about Polars, though, and want to try it for the parallelization/speed and to stay fresh ...
First of all, the large majority of Polars' DataFrame operations are not in place, so you must re-assign to the variable if updating in a loop. Next, for the "Food Provided" column, you should use Polars' list data type. This works natively with Polars' other operations and prevents substring-like issues (e.g., pineapp...
3
4
79,447,988
2025-2-18
https://stackoverflow.com/questions/79447988/0-dimensional-array-problems-with-numpy-vectorize
numpy.vectorize conveniently converts a scalar function to vectorized functions that can be applied directly to arrays. However, when inputting a single value into the vectorized function, the output is a 0-dimentional array instead of the corresponding value type, which can cause errors when using the result elsewhere...
Short answer: You can unwrap 0-d results into scalars while keeping n-d results (n>0) by indexing with an empty tuple (). Better yet, I would try to avoid using @np.vectorize altogether – in general, but in particular with your given example where vectorization is not necessary. Long answer: Following these answers t...
2
4
79,449,057
2025-2-18
https://stackoverflow.com/questions/79449057/confused-by-silent-truncation-in-polars-type-casting
I encountered some confusing behavior with polars type-casting (silently truncating floats to ints without raising an error, even when explicitly specifying strict=True), so I headed over to the documentation page on casting and now I'm even more confused. The text at the top of the page says: The function cast includ...
It is accepted in Python (and more generally) that casting a float to an int will truncate the float and not raise an exception. E.g. in Python: >>> int(5.8) 5 Similarly, in Polars, casting a float to an int can be converted from the source data type to the target data type. For anyone else looking, this answer provid...
2
4
79,448,603
2025-2-18
https://stackoverflow.com/questions/79448603/how-to-convert-a-pandas-dataframe-to-numeric-future-proof
Until now I used to convert all values in a pandas dataframe with combined numerical and string entries to numeric values if possible in one easy step, using .map and .to_numeric with "errors = 'ignore'". It worked perfectly, but after updating to the latest version of Pandas (2.2.3) I get a FutureWarning. import panda...
When you use errors='ignore', to_numeric returns the original Series. As mentioned in the documentation: errors {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’ If ‘raise’, then invalid parsing will raise an exception. If ‘coerce’, then invalid parsing will be set as NaN. If ‘ignore’, then invalid parsing will return t...
2
3
79,446,920
2025-2-18
https://stackoverflow.com/questions/79446920/why-gcd-is-needed-in-this-algorithm-finding-all-groups-of-three-points-are-colli
I was trying to solve this coding challenge: "Given an array of pairs, each pair (x, y), which are both integer, denotes coordinate of a point in Cartesian coordinate plane, find many groups of three points are collinear." It turns out this below is the correct algorithm: def gcd(x, y): if y == 0: return x else: return...
A clarification: Many thanks for fellow no comment's teaching, indeed the GCD in OP's posted solution is needed, and my original answer is wrong. Taking points = [(0, 0), (999999997, 999999998), (999999998, 999999999)] as an example, the difference between 999999997/999999998 and 999999998/999999999 appears only after ...
3
5
79,448,739
2025-2-18
https://stackoverflow.com/questions/79448739/flatten-a-multi-dimensional-list
Say we have a multi-dimensional list, but with random dimensions, like: [ [ [1, 2, [3, 4]], [[5, 6], 7] ], [8, 9, [10]] ] Is there any short way to flatten everything and just get the list [1, 2, ..., 10] ? I know there's solution for list of lists, such as loops or comprehension list, but here we assume that we don't...
A recursive function can make quick work of this: test = [ [ [1, 2, [3, 4]], [[5, 6], 7] ], [8, 9, [10]] ] def flatten(l): for item in l: if isinstance(item, list): for i in flatten(item): yield i else: yield item print(list(flatten(test))) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] This function iterates through each item in ...
1
4
79,447,920
2025-2-18
https://stackoverflow.com/questions/79447920/subtracting-1-from-a-numpy-array-gives-two-different-answers
Why are outputs in the two cases different. I am new to this library Case 1 import numpy as np np.random.seed(2) array = np.random.random((3,1)) print('Printing array : \n', array) print('printing array - 1 : \n',array-1) Output : Printing array : [[0.4359949 ] [0.02592623] [0.54966248]] printing array - 1 : [[-0.5640...
The reason why you got different arrays has been explained elaborately by @Jon Skeet. One workaround is to customize a function by packing the random seed together with the random number generator function, e.g., def runif(shape, seed = 2): np.random.seed(seed) return np.random.random(shape) for iter in range(2): prin...
1
0