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
78,944,702
2024-9-3
https://stackoverflow.com/questions/78944702/convert-logx-log2-to-log-2x-in-sympy
I received a sympy equation from a library. It makes extensive use of log2, but the output was converted to log(x)/log(2). This makes reading the results messy. I would like to have sympy simplify this equation again with a focus on using log2 directly where possible. How could this be done? Example: (log(A) / log(2)) ...
Basically, you can just reverse the process: replace log(w) with log(2) * log2(w) and let sympy cancel all the factors of log(2) / log(2). The only wrinkle is that you don't want to substitute when you find log(2) itself, but that's easy enough. You just use a wildcard, and check if the matched value is literally 2 bef...
3
2
78,944,749
2024-9-3
https://stackoverflow.com/questions/78944749/explode-polars-rows-on-multiple-columns-but-with-different-logic
I have this code, which splits a product column into a list, and then uses explode to expand it: import polars as pl import datetime as dt from dateutil.relativedelta import relativedelta def get_3_month_splits(product: str) -> list[str]: front, start_dt, total_m = product.rsplit('.', 2) start_dt = dt.datetime.strptime...
Concat the appropriate number of trailing 0s to price_paid before calling .explode() on both product and price_paid at once: print( df.with_columns( pl.col("product").map_elements(get_3_month_splits, return_dtype=pl.List(str)) ) .with_columns( pl.concat_list( pl.col("price_paid"), pl.lit(0).repeat_by(pl.col("product")....
2
1
78,942,459
2024-9-3
https://stackoverflow.com/questions/78942459/bar-chart-with-slanted-lines-instead-of-horizontal-lines
I wish to display a barchart over a time series canvas, where the bars have width that match the duration and where the edges connect the first value with the last value. In other words, how could I have slanted bars at the top to match the data? I know how to make barcharts using either the last value (example 1) or t...
You can use Matplotlibs Axes.fill_between to generate these types of charts. Importantly this will accurately represent the gap between your rows where they exist, whereas the approach with the bars will make that gap appear to be wider than they truly are unless you set the edgewidth of the bars to 0. Additionally, fo...
2
2
78,942,670
2024-9-3
https://stackoverflow.com/questions/78942670/how-to-detect-a-circle-with-uncertain-thickness-and-some-noise-in-an-binary-imag
The input image is here : the input image I try to use cv2.HoughCircles in opencv-python to find the expected circle, but the result is noise as in this picture : result in param2=0.2 the code is: import cv2 import numpy as np img = cv2.imread('image.png') # apply GaussianBlur kernel_size = (15, 15) sigma = 0 blurred_i...
This is sort of a static solution for now, but if you always have such nice contrast and you can accuretly get the coordinates, then fitting a circle with least square might not be such a bad idea: def fit_circle(x, y): A = np.c_[x, y, np.ones(len(x))] # design matrix A with columns for x, y, and a constant term f = x*...
3
6
78,942,406
2024-9-3
https://stackoverflow.com/questions/78942406/how-to-smooth-a-discrete-stepped-signal-in-a-vectorized-way-with-numpy-scipy
I have a signal like the orange one in the following plot that can only have integer values: As you can see, the orange signal in a bit noisy and "waffles" between levels sometimes when its about to change to a new steady state. I'd like to "smooth" this effect and achieve the blue signal. The blue signal is the orang...
There could be a lot of different strategies, based on DataFrame.rolling processing. In example: t = pd.Series([ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 1, 2, 2, 3, 1, 2, 2, 1, 1, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]) min_at_row = 3 t_smoothed = t.copy() t_smoothed[ t.rolling(min_at_row, min...
2
2
78,942,495
2024-9-3
https://stackoverflow.com/questions/78942495/why-does-my-code-fail-to-turn-to-the-second-page
1st i tried working in a program that generates random pokemon so we can create teams to play in showdown. It looked like this import tkinter as tk from tkinter import * import random import pypokedex root = tk.Tk() #main #1ra página inicio = Frame(root) inicio.grid(row=0, column=0) ttl = Label(inicio, text="¿Quienes j...
Note that cantidad_jugadores is zero because it is set by the line: cantidad_jugadores = len(jugadores) As jugadores is an empty list when the above line is executed. So the code block inside the while loop inside generar_pokimones() will not be executed because numero_pokimons (which is calculated from the value of c...
2
1
78,941,537
2024-9-2
https://stackoverflow.com/questions/78941537/opencv-not-able-to-detect-aruco-marker-within-image-created-with-opencv
I encountered an issue while trying out a simple example of creating and detecting aruco-images. In the following code-snippet, I generate aruco images, save them to a file and then load one of these files for detection: import cv2 aruco_dict= cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_ARUCO_ORIGINAL) params = cv...
These markers need a "quiet zone" around them so the edge of the marker is detectable. That quiet zone should be a white border. You may have heard of this in relation to QR codes. generateImageMarker() does not produce a quiet zone around the marker. This is as it should be. The image contains just the imagery that go...
2
2
78,940,370
2024-9-2
https://stackoverflow.com/questions/78940370/how-to-translate-pandas-dataframe-operations-to-polars-in-python
I am trying to convert some pandas DataFrame operations to Polars in Python, but I am running into difficulties, particularly with row-wise operations and element-wise comparisons. Here is the pandas code I am working with: df_a = pd.DataFrame({ "feature1": [1, 2, 3], "feature2": [7, 8, 9], }) df_b = pd.DataFrame({ "fe...
Polars has dedicated horizontal functions for "row-wise" operations. df_a.max_horizontal() shape: (3,) Series: 'max' [i64] [ 7 8 9 ] For DataFrames, Polars will "broadcast" the operation across all columns if the right-hand side is a Series. df_a == df_a.max_horizontal() # df_a.select(pl.all() == pl.Series([7, 8, 9])...
2
1
78,939,900
2024-9-2
https://stackoverflow.com/questions/78939900/exploding-multiple-column-list-in-pandas
I've already tried everything posted here but nothing is working, so please don't mark this as duplicate because I think the problem is different. I have a json like this: [{'Id': 1, 'Design': ["09", '10', '13' ], 'Research': ['Eng', 'Math'] }] Plus other non-list colums. This is repeated for 500 ids. I need to explod...
You can use json_normalize and a deduplication-explode (as presented here): tmp = pd.json_normalize(json) def explode_dedup(s): s = s.explode() return s.set_axis( pd.MultiIndex.from_arrays([s.index, s.groupby(level=0).cumcount()]) ) ids = ['Id'] cols = tmp.columns.difference(ids) out = (tmp[ids] .join(pd.concat({c: exp...
2
1
78,938,398
2024-9-1
https://stackoverflow.com/questions/78938398/find-a-fragment-in-the-whole-image
Globally, my task is to determine the similarity / dissimilarity of two .jpg files. Below I will describe the process in more detail. I have five (in reality there are more) template .jpg files. And I have a new .jpg file, which I must match with each template .jpg file to make a decision - is the new .jpg file similar...
I wrote up an example to guide you in the direction of classifying by relying on text instead of structural similarity between the documents. My folder is organized like this: I have two training images and three test images. The training images are in the template folder and the images I want to classify are in the t...
2
1
78,938,073
2024-9-1
https://stackoverflow.com/questions/78938073/why-doesnt-the-repeated-number-go-up-in-the-traceback-as-i-increase-the-recur
When I run a recursive function and it exceeds the recursion depth limit, the below error is displayed: Python 3.12.4+ (heads/3.12:99bc8589f0, Jul 27 2024, 11:20:07) [GCC 12.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> def f(): f() ... >>> f() Traceback (most recent call last...
I figured out that this relates to sys.tracebacklimit variable. It limits the traceback size. >>> def f(): f() ... >>> >>> import sys >>> sys.setrecursionlimit(2000) >>> >>> f() Traceback (most recent call last): File "<stdin>", line 1, in f File "<stdin>", line 1, in f File "<stdin>", line 1, in f [Previous line repea...
2
2
78,939,233
2024-9-2
https://stackoverflow.com/questions/78939233/match-columns-from-column-list-in-a-dataframe-and-rename-them-in-python
I have column list - col_list = ['Subsidiary','State of Jurisdiction of Incorporation','Jurisdiction ofIncorporationor Organization','Jurisdiction of Incorporation or Organization', 'Subsidiaries','State or Other Jurisdiction of Organization','Jurisdiction ofIncorporation orOrganization', 'Company Name', 'State of Inco...
If there are 2 lists for entity_name and entity_place create dictionary and pass to rename: L1 = ['Subsidiary','Subsidiaries','Company Name','Legal Name', 'Entity', 'Name of Company/Jurisdiction of Incorporation or Formation','Name of Company'] L2 = ['Jurisdiction', 'State of Jurisdiction','Place of Formation'] d = {**...
2
1
78,929,948
2024-8-29
https://stackoverflow.com/questions/78929948/load-a-saved-on-disk-duckdb-instance-into-a-new-in-memory-duckdb-instance
I'm working on a project where, in a first stage, I pull some raw data, do a bunch of processing of it in duckdb, and end up with a bunch of tables that are used by a bunch of downstream components that also operate in duckdb. I'd like to have the outputs from the first stage persist on disk, and not be modified by the...
I'd like to have the outputs from the first stage persist on disk This can be accomplished using a DuckDB EXPORT DATABASE statement. ... the downstream components need to at least be able to create views and temporary tables. Further, there's no reason to have the downstream components operate on-disk... the data is...
2
1
78,938,440
2024-9-1
https://stackoverflow.com/questions/78938440/using-regex-to-split-subsections-with-unique-titles
I'm struggling to find a way to split a corpus of legal documents I have, by section. I've been trying to do this with regex, and while I've come reasonably close, I'm looking to see if there's a way I can refine the output even more to consolidate the number of matches that result from the regex script. Each document ...
The pattern is just missing some instructions on where and what to split at the patterns you provided. I wrote this pattern that gives more instructions on where to split the string, and remove the roman numeral redundancy. string = """ legal doc """ pattern = r'(?=\b(?:[IVXL]+\.)|CONCLUSION)' answer = re.split(pattern...
3
3
78,938,211
2024-9-1
https://stackoverflow.com/questions/78938211/computing-cross-sectional-rankings-using-a-tidy-polars-dataframe
I need to compute cross-sectional rankings across a number of trading securities. Consider the following pl.DataFrame in long (tidy) format. It comprises three different symbols with respective prices, where each symbol also has a dedicated (i.e. local) trading calendar. df = pl.DataFrame( { "symbol": [*["symbol1"] * 6...
Well you can simplify the process without the need of explode and to avoid the need to pivot and unpivot: returns = df.drop_nulls().with_columns( pl.col("price").pct_change(n=2).over("symbol").alias("return") ) shape: (16, 4) ┌─────────┬────────────┬───────┬──────────┐ │ symbol ┆ date ┆ price ┆ return │ │ --- ┆ --- ┆ -...
3
2
78,924,799
2024-8-28
https://stackoverflow.com/questions/78924799/i-cant-get-selenium-chrome-to-work-in-docker-with-python
I have a classic "it works on my machine" problem, a web scraper I ran successfully on my laptop, but with a persistent error whenever I tried and run it in a container. My minimal reproducible dockerized example consists of the following files: requirements.txt: selenium==4.23.1 # 4.23.1 pandas==2.2.2 pandas-gbq==0.22...
You override the chrome_options variable just before sending it to webdriver.Chrome() so there are no options defined, --disable-dev-shm-usage (this option solves that issue) in particular. Just remove chrome_options = Options() just before the driver initialization. As a side note, consider using --headless=new instea...
2
1
78,933,402
2024-8-30
https://stackoverflow.com/questions/78933402/tkinter-with-images
With the following code, I can not display an image in a tkinter cell: from tkinter import * from tkinter import filedialog from PIL import Image, ImageTk root = Tk() root.geometry=("1000x1000") def orig(): orig_image = filedialog.askopenfilename(filetypes=[("Image file", "*.jpg"), ("All files", "*.")]) my_img = ImageT...
there are some issues of your code Unfortunately, the geometry method is being assigned incorrectly. It should be invoked instead of assigned. To the first code block, you made a definition of a function orig() but let it remain unevaluated. The PhotoImage object needs to be held on to as an attribute to prevent it ...
3
1
78,933,210
2024-8-30
https://stackoverflow.com/questions/78933210/is-string-slice-by-copy-a-cpython-implementation-detail-or-part-of-spec
Python does slice-by-copy on strings: Does Python do slice-by-reference on strings? Is this something that all implementations of Python need to respect, or is it just a detail of the CPython implementation?
Copying underlying memory on str slices is chosen because reference counting / garbage collection becomes complicated otherwise, and reference counting itself is an implementation detail of CPython. Therefore copying string slices is also an implementation detail. Copying could, in theory, be avoided in the implementat...
5
3
78,933,132
2024-8-30
https://stackoverflow.com/questions/78933132/type-hinting-a-generator-send-type-any-or-none
I have a generator that does not use send() values. Should I type its send_value as Any or None? import typing as t def pi_generator() -> t.Generator[int, ???, None]: pi = "3141592" for digit in pi: yield int(digit) pi_gen = pi_generator() next(pi_gen) # 3 pi_gen.send('foo') # 1 pi_gen.send(pi_gen) # 4 Reasons I see f...
Quoting the docs for typing.Generator: If your generator will only yield values, set the SendType and ReturnType to None: def infinite_stream(start: int) -> Generator[int, None, None]: while True: yield start start += 1 Setting SendType to None is the recommended way to communicate that the generator does not expect...
4
6
78,934,877
2024-8-31
https://stackoverflow.com/questions/78934877/how-do-i-formalize-a-repeated-relationship-among-disjoint-groups-of-classes-in-p
I have Python code that has the following shape to it: from dataclasses import dataclass @dataclass class Foo_Data: foo: int class Foo_Processor: def process(self, data: Foo_Data): ... class Foo_Loader: def load(self, file_path: str) -> Foo_Data: ... #---------------------------------------------------------------- @da...
You can use abstract base classes (ABCs) with Generics. This way you can define a common interface while ensuring type safety: from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Generic, TypeVar # generic type variable for Data T = TypeVar('T', bound='BaseData') @dataclass class Ba...
2
3
78,932,535
2024-8-30
https://stackoverflow.com/questions/78932535/python-async-thread-safe-semaphore
I'm looking for a thread-safe implementation of a Semaphore I can use in Python. The standard libraries asyncio.Semaphore isn't thread-safe. The standard libraries threading.Semaphore doesn't have awaitable interface. I am using sanic which has multiple threads (workers) but also an asynchronous loop on each thread. I ...
If you are saying that you need a single semaphore instance to be used across all the threads, then create a threading.Semaphore instance and am async function acquire_semaphore such as the following: import asyncio import threading from concurrent.futures import ThreadPoolExecutor executor = ThreadPoolExecutor() semap...
2
3
78,933,467
2024-8-30
https://stackoverflow.com/questions/78933467/how-can-access-the-pointer-values-passed-to-and-returned-by-c-functions-from-pyt
Can my python code have access to the actual pointer values received and returned by C functions called through ctypes? If yes, how could I achieve that ? I'd like to test the pointer values passed to and returned from a shared library function to test an assignment with pytest (here, to test that strdup didn't return...
A return type of ctypes.c_char_p is "helpful" and converts the return value to a Python string, losing the actual C pointer. Use ctypes.POINTER(ctypes.c_char) to keep the pointer. A return type of ctypes.c_void_p is also "helpful" and converts the returned C address to a Python integer, but can be cast a more specific ...
3
4
78,933,109
2024-8-30
https://stackoverflow.com/questions/78933109/multiply-an-input-by-5-raised-to-the-number-of-digits-of-each-numbers-but-my-co
I'm trying to multiply an input * 5 raised to the power of the input. I tried this: def multiply(n): return 5 ** len(str(n)) * n I tried (n = -2), but instead of giving me -10, which is the correct answer, it gave me -50 Why doesn't this output the correct numbers when n is negative?
you are directly checking the length of your input by casting it to string: >>> n = -2 >>> str(n) '-2' # String with length of two -> '-' and '2' (string 2) >>> len(str(n)) 2 Maybe you can try this (not sure if it's good or bad, but will work as you expected): # The dirty way.. def multiply(num: int): # Initialize a v...
2
1
78,932,957
2024-8-30
https://stackoverflow.com/questions/78932957/accessing-pokeapi-taking-a-long-time
I want to get a list of names of pokemon from the first 150 that have a hp less than a particular value. Here's what I've got so far: def get_pokemon_with_similar_hp(max_hp): pokemon_names = [] poke_data = [] for i in range(1, 151): api_url = f"https://pokeapi.co/api/v2/pokemon/{i}" pokemon_response = requests.get(api_...
According to the API documentation you can use GraphQL query, so you can do this in one request. E.g.: import requests graphql_url = "https://beta.pokeapi.co/graphql/v1beta" # https://beta.pokeapi.co/graphql/console/ payload = { "operationName": "samplePokeAPIquery", "query": r"query samplePokeAPIquery($maxhp: Int) {po...
3
3
78,932,341
2024-8-30
https://stackoverflow.com/questions/78932341/why-does-2x-x-x-in-ieee-floating-point-precision
I would expect this to only hold when the last bit of the mantissa is 0. Otherwise, in order to subtract them (since their exponents differ by 1), x would lose a bit of precision first and the result would either end up being rounded up or down. But a quick experiment shows that it seems to always hold (assuming x and ...
If we had to do arithmetic only in the floating-point format, even for internal values during the arithmetic, then, yes, 2*x - x would not always yield x. For example, with four-bit significands, we could have: Expression Value/Calculation x 1.001•20 (9) 2*x 1.001•21 (18) 2*x - x 1.001•21 − 1.001•20 = 1.001...
5
5
78,932,725
2024-8-30
https://stackoverflow.com/questions/78932725/pandas-sort-one-column-by-custom-order-and-the-other-naturally
Consider the following code: import pandas import numpy strs = ['custom','sort']*5 df = pandas.DataFrame( { 'string': strs, 'number': numpy.random.randn(len(strs)), } ) sort_string_like_this = {'sort': 0, 'custom': 1} print(df.sort_values(['string','number'], key=lambda x: x.map(sort_string_like_this))) which prints ...
You can use a condition in the sort key function: df.sort_values( ["string", "number"], key=lambda x: x.map(sort_string_like_this) if x.name == "string" else x, ) string number 7 sort -1.673626 3 sort -0.212634 5 sort -0.071417 9 sort 0.413497 1 sort 0.489508 8 custom -1.787110 0 custom 0.230875 4 custom 0.535791 2 c...
3
4
78,932,231
2024-8-30
https://stackoverflow.com/questions/78932231/rotating-a-curve-using-python
I have written following code to rotate a curve by specified angle and return new equation. I know when we want to rotate the axes by an angle A then new coords become X=xcosA-ysinA and Y=xsinA+ycosA. when i test my fxn on the hyperbola x^2+y^2=1 . Expected equations is 2xy-1=0 but my fxn gives -2xy-1=0 Where I am doin...
You swapped the sign on the sin terms of the transformation matrix. Here is how it should look like for a positive rotation: def rotate_1(f, theta): x, y, a, b = sp.symbols('x y a b') rotation_matrix = sp.Matrix([[sp.cos(theta),sp.sin(theta)],[-sp.sin(theta), sp.cos(theta)]]) transformed_coords = rotation_matrix * sp.M...
2
2
78,932,164
2024-8-30
https://stackoverflow.com/questions/78932164/python-average-values-in-2d-array
I want to generate a twodimensional array in Python and I would like to iterate through each element and take an average. An element i should be averaged using the 8 surrounding array elements (including element i). I generated the twodimensional array with a frame of zeros using Forming a frame of zeros around a matri...
What you want is a 2D convolution, use scipy.signal.convolve2d with numpy.ones to get the sum: from scipy.signal import convolve2d out = convolve2d(B, np.ones((3, 3), dtype='int'), mode='same') Output: array([[ 1, 3, 6, 5, 3], [ 5, 12, 21, 16, 9], [12, 27, 45, 33, 18], [11, 24, 39, 28, 15], [ 7, 15, 24, 17, 9]]) If y...
2
2
78,931,947
2024-8-30
https://stackoverflow.com/questions/78931947/finding-the-maximum-product-of-an-array-element-and-a-distance
An array of integers is given. It is necessary to find the maximum product of the distance between a pair of elements and the minimum element of this pair. For example, [2, 5, 2, 2, 1, 5, 2] -> 20, 5 and 5 (5 * (5-1)); [1, 2] -> 1 In the first example, the maximum product is obtained if we take 5 and 5(a[1] and a[5]). ...
O(n log n): from itertools import accumulate from bisect import bisect_left a = [2,5,2,2,1,5,2] print(max( x * (j - bisect_left(m, x)) for a in [a, a[::-1]] for m in [list(accumulate(a, max))] for j, x in enumerate(a) )) Attempt This Online! Assume the best pair has the smaller-or-equal value as the right value. For e...
2
1
78,932,035
2024-8-30
https://stackoverflow.com/questions/78932035/filter-or-join-a-polars-dataframe-by-columns-from-another-dataframe
I have two pl.DataFrames: from datetime import date import polars as pl df1 = pl.DataFrame( { "symbol": [ "sec1", "sec1", "sec1", "sec1", "sec1", "sec1", "sec2", "sec2", "sec2", "sec2", "sec2", ], "date": [ date(2021, 9, 14), date(2021, 9, 15), date(2021, 9, 16), date(2021, 9, 17), date(2021, 8, 31), date(2020, 12, 31)...
You can unpivot, then join: df1.join( df2.unpivot(index='symbol', value_name='date').drop('variable'), on=['symbol', 'date'], how='inner', ) Output: ┌────────┬────────────┬───────┐ │ symbol ┆ date ┆ price │ │ --- ┆ --- ┆ --- │ │ str ┆ date ┆ i64 │ ╞════════╪════════════╪═══════╡ │ sec1 ┆ 2021-09-17 ┆ 3 │ │ sec1 ┆ 2021...
3
4
78,931,529
2024-8-30
https://stackoverflow.com/questions/78931529/conditional-deduplication-in-polars
I have a dataset i'm trying to remove duplicate entries from. The lazyframe i'm working with is structured like this: df = pl.from_repr(""" ┌──────┬────────────┬──────────────────┬───────┐ │ id ┆ title ┆ type ┆ type2 │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str ┆ i64 │ ╞══════╪════════════╪══════════════════╪═══════╡ ...
Create a preference table indicating how much you want each combination: preference = pl.DataFrame({ "type": ["journal article", "book chapter", "book chapter"], "iris_type": [35, 41, 42], "preference": [0, 1, 2] }) Join the preference table with your data table: joined = df.lazy().join(preference.lazy(), on=["typ...
4
3
78,931,082
2024-8-30
https://stackoverflow.com/questions/78931082/abstract-base-class-function-pointer-python
I'd like to make an abstraction of one of my api classes to resolve the following problem. Let's say I have a base class like: class AbstractAPI(ABC): @abstractmethod def create(self): pass @abstractmethod def delete(self): pass And a concrete class: class API(AbstractAPI): def create(self): print("create") def delete...
Rather than directly referencing the abstract class method function_pointer=AbstractAPI.create, you can write a function that calls the named create() method on a given object. function_pointer = lambda api : api.create() or def function_pointer(api): return api.create()
2
2
78,931,016
2024-8-30
https://stackoverflow.com/questions/78931016/numpy-built-in-function-to-find-largest-vector-in-an-matrix
I have a 2D numpy matrix: arr = np.array([(1, 2), (6, 0), (3, 3), (5, 4)]) I am trying to get the output: [5, 4] I have tried to do the following: max_arr = np.max(arr, axis=0) But this finds the largest value in each column of the matrix, regardless of the vectors from which those values come from. Maybe there is so...
Compute the sum per row, then get the position of the maximum with argmax and use this for indexing: out = arr[arr.sum(axis=1).argmax()] Output: array([5, 4]) Intermediates: arr.sum(axis=1) # array([3, 6, 6, 9]) arr.sum(axis=1).argmax() # 3 variant: all maxes If you can have multiple maxima, you can use instead: out ...
2
3
78,930,856
2024-8-30
https://stackoverflow.com/questions/78930856/what-is-an-equivalent-of-in-operator-for-2d-numpy-array
Using Python lists: a = [[0, 1], [3, 4]] b = [0, 2] print(b in a) I'm getting False as an output, but with Numpy arrays: a = np.array([[0, 1], [3, 4]]) b = np.array([0, 2]) print(b in a) I'm getting True as an output. What is an equivalent of in operator above for 2D Numpy arrays?
In the NumPy array case, b in a is interpreted as checking if any element of b is in a, rather than checking for the presence of b as a whole array. You can use the numpy.all function along with numpy.any to compare rows: a = np.array([[0, 1], [3, 4]]) b = np.array([0, 2]) is_row_present = np.any(np.all(a == b, axis=1)...
2
3
78,929,964
2024-8-29
https://stackoverflow.com/questions/78929964/utf-16-as-sequence-of-code-units-in-python
I have the string 'abç' which in UTF-8 is b'ab\xc3\xa7'. I want it in UTF-16, but not this way: b'ab\xc3\xa7'.decode('utf-8').encode('utf-16-be') which gives me: b'\x00a\x00b\x00\xe7' The answer I want is the UTF-16 code units, that is, a list of int: [32, 33, 327] Is there any straightforward way to do that? And of...
The simple solution that may work in many cases would be something like: def sort_of_get_utf16_code_units(s): return list(map(ord, s)) print(sort_of_get_utf16_code_units('abç') Output: [97, 98, 231] However, that doesn't work for characters outside the Basic Multilingual Plane (BMP): print(sort_of_get_utf16_code_unit...
2
6
78,926,011
2024-8-29
https://stackoverflow.com/questions/78926011/gekko-deep-learning-does-not-find-solution
I want to create a regression ANN model with Gekko. I made this model using tf_Keras, and it works very well. Unfortunately, it is not possible to convert the Keras model to a Gekko amp model. Therefore, I need to make it using the Gekko Brain class. However, it fails to find a solution. Here is my dataset: ss10_1k_con...
There is a way to import models from TensorFlow directly into Gekko. Here is an example from the Gekko documentation: from gekko import GEKKO x = m.Var(.0,lb = 0,ub=1) y = Gekko_NN_TF(model,mma,m,n_output = 1).predict([x]) m.Obj(y) m.solve(disp=False) print('solution:',y.value[0]) print('x:',x.value[0]) print('Gekko So...
2
1
78,929,543
2024-8-29
https://stackoverflow.com/questions/78929543/iterating-over-each-dataframe-in-a-list-of-dataframes-and-changing-name-of-first
I'm trying to iterate through a list of datraframes and do two things, replace blanks with "_" (which I've done) and add a suffix to the first column of each dataframe. I know I can access the first column of the each dataframe via the print row within the loop below, but I'm having trouble adding the suffix to the fir...
After replacing blanks with underscore, you can add suffix to the first columns of each dataframe in the following way: first_column = dfs[i].columns[0] # get first column dfs[i].rename(columns={first_column: first_column + '_suffix'}, inplace=True) # Add a suffix to the first column
2
1
78,927,980
2024-8-29
https://stackoverflow.com/questions/78927980/hiding-facet-row-axis-in-altair-chart
I'm using a faceted chart in Altair in order to split a lengthy timeline into multiple rows. My initial dataset is a pandas dataframe with "Start" and "End" timestamp columns and a "Product" string column. I bin the dataset into roughly equal rows by evenly dividing the time range: timestamp_normalized = (data.Start - ...
To remove both the header title and labels you can use alt.Row('Row').header(None). You could also control them individually via alt.Row('Row').header(title=None, labels=False) For versions of Altair prior to 5: alt.Row('Row', header=alt.Header(title=None, labels=False))
2
2
78,929,128
2024-8-29
https://stackoverflow.com/questions/78929128/how-to-get-unique-value-count-in-a-polars-series-excluding-null-values
I am working with a Polars Series in Python and I need to obtain the number of unique values in the series. However, I want to exclude any null values from the result. For example, given the following Series: series = pl.Series([1, 2, None, 4, 2, 4, None]) The result should be 3 unique values (1, 2, and 4). What is th...
Drop the nulls using .drop_nulls() and count the unique values using .n_unique(). Also, the correct way to represent null values in a call to pl.Series is using Python's None. pl.Null might have worked earlier but it doesn't in the latest polars. import polars as pl series = pl.Series([1, 2, None, 4, 2, 4, None]) print...
2
3
78,927,891
2024-8-29
https://stackoverflow.com/questions/78927891/what-is-password-based-authentication-in-the-usercreationform-in-django
I creat a signup form in django using django forms and when i run my code there is field i didnt expect Password-based authentication i did not use it and i have no idea what it is so anyone can tell me what it is and how i can remove it from user signup form? form.py from django import forms from django.contrib.auth ...
That field comes from BaseUserCreationForm, the superclass of UserCreationForm. This is actually a regression in Django 5.1, and will be fixed when https://github.com/django/django/pull/18484 is released in Django 5.1.1. As a workaround, you should be able to delete the field from your subclass with class RegisterForm(...
2
3
78,923,273
2024-8-28
https://stackoverflow.com/questions/78923273/compare-two-boolean-arrays-considering-a-tolerance
I have two boolean arrays, first and second that should be mostly equal (up to a tolerance). I would like to compare them in a way that is forgiving if a few elements are different. Something like np.array_equal(first, second, equal_nan=True) is too strict because all values must be the same and np.allclose(first, seco...
Simon's answer was pretty close to what I needed. However, I preferred using a volume overlapping metric (eg dice and IoU) instead of normalizing by the size of the voxel. Dice and IoU range [0, 1], which is pretty convenient in this case, with 0 meaning no overlap and 1 meaning perfect overlap. Dice implementation: to...
3
1
78,926,086
2024-8-29
https://stackoverflow.com/questions/78926086/parsing-numeric-data-with-thousands-seperator-in-polars
I have a tsv file that contains integers with thousand separators. I'm trying to read it using polars==1.6.0, the encoding is utf-16 from io import BytesIO import polars as pl data = BytesIO( """ Id\tA\tB 1\t537\t2,288 2\t325\t1,047 3\t98\t194 """.encode("utf-16") ) df = pl.read_csv(data, encoding="utf-16", separator="...
To allow for possible multiple , separators use .str.replace_all: df = df.with_columns(pl.col('B').str.replace_all(",", "").cast(pl.Int64)) which gives for the sample data: shape: (3, 3) ┌─────┬─────┬──────┐ │ Id ┆ A ┆ B │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪══════╡ │ 1 ┆ 537 ┆ 2288 │ │ 2 ┆ 325 ┆ 104...
5
3
78,925,412
2024-8-28
https://stackoverflow.com/questions/78925412/finding-the-k-th-largest-element-using-heap
I am trying to solve the leetcode problem: kth-largest-element-in-an-array I know a way to solve this is by using a heap. However, I wanted to implement my own heapify method for practice, and here is my code: def findKthLargest(self, nums: List[int], k: int) -> int: def heapify(nums: List[int], i: int): print(nums, i)...
There are a few problems with your (partial) heap-sort algorithm: The loop should start from the last non-leaf node (a node with at least one child) and move to the root. In your code, the loop starts from the last element. Starting from the last element won't help in building the heap correctly because leaf nodes (w...
2
1
78,924,751
2024-8-28
https://stackoverflow.com/questions/78924751/how-can-i-consolidate-all-rows-with-the-same-id-in-polars
I have a Polars dataframe with a lot of duplicate data I would like to consolidate. Input: shape: (3, 2) ┌─────┬──────┐ │ id ┆ data │ │ --- ┆ --- │ │ i64 ┆ str │ ╞═════╪══════╡ │ 1 ┆ a │ │ 1 ┆ b │ │ 1 ┆ c │ └─────┴──────┘ My current (non-working) solution: df = pl.DataFrame({'id': [1, 1, 1], 'data': ['a', 'b', 'c']}) ...
The following gives you a df in the format you want: import polars as pl df = ( pl.DataFrame({"id": [1, 1, 1], "data": ["a", "b", "c"]}) .group_by("id") .agg(pl.col("data")) .with_columns(structure=pl.col("data").list.to_struct()) .unnest("structure") .drop("data") ) print(df) """ ┌─────┬─────────┬─────────┬─────────┐ ...
5
5
78,925,371
2024-8-28
https://stackoverflow.com/questions/78925371/creating-a-column-by-if-else-statements
I have a data frame with 4 columns. The columns are: Home_team, Away_team, Home_team_goal, Away_team_goal I want to create a winner column by using goals. I wrote the code below, but when I run it, I get only home teams in the winner column. A = ['A', '1', 'D', '2'] B = ['B', '2', 'E', '2'] C = ['C', '3', 'F', '2'] df ...
Here another approach: def Winner(x): if x > 0: return 1 elif x < 0: return 2 else: return 0 df['Winner'] = df['Average'].apply(Winner)
2
0
78,925,432
2024-8-28
https://stackoverflow.com/questions/78925432/pandas-unpack-list-of-dicts-to-columns
I have a dataframe that has a field called fields which is a list of dicts (all rows have the same format). Here is how the dataframe is structured: formId fields 123 [{'number': 1, 'label': 'Last Name', 'value': 'Doe'}, {'number': 2, 'label': 'First Name', 'value': 'John'}] I am trying to unpack the fields column so ...
Personally, I'd construct new dataframe: df = pd.DataFrame( [ {"formId": form_id, **{f["label"]: f["value"] for f in fields}} for form_id, fields in zip(df["formId"], df["fields"]) ] ) print(df) Prints: formId Last Name First Name 0 123 Doe John
5
2
78,925,465
2024-8-28
https://stackoverflow.com/questions/78925465/find-rows-where-pandas-dataframe-column-which-is-a-paragraph-or-list-contains
I have a Pandas DataFrame which contains information about various jobs. I am working on filtering based on values in some lists. I have no problem with single value conditional filtering. However, I am having difficulties doing conditional filtering on the Job Description field, which is essentially a paragraph and mu...
IIUC, you can use pd.Series.apply() + any(): out = dftest[dftest["Job Skills"].apply(lambda x: any(s in skills for s in x))] print(out) Prints: Job Posting Time Type Job Location Job Description Job Skills 0 Data Scientist Full Time Colorado asdfas fasdfsad sadfsdaf sdfsdaf [Algorithms, Data Analysis, Data Mining, Da...
3
1
78,925,467
2024-8-28
https://stackoverflow.com/questions/78925467/how-to-have-decorated-function-in-a-python-doctest
How can I include a decorated function inside a Python doctest? def decorator(func): def wrapper() -> None: func() return wrapper def foo() -> None: """ Stub. Examples: >>> @decorator >>> def stub(): ... """ if __name__ == "__main__": import doctest doctest.testmod() Running the above with Python 3.12 throws a SyntaxE...
Multi-line commands should use ... for continuation lines. So the proper way is to use ... instead of >>> on the second line: def foo() -> None: """ Stub. Examples: >>> @decorator ... def stub(): ... """
4
4
78,925,207
2024-8-28
https://stackoverflow.com/questions/78925207/real-and-imaginary-part-of-a-complex-number-in-polar-form
I am a bit confused about the proper way to deal with complex numbers in polar form and the way to separate its real and imaginary part. Notice that I am expecting as real part the radius, as imaginary part the angle. The inbuilt re and im functions get always the real and imaginary part of the Cartesian representation...
Maybe you are looking for Abs and arg functions? z = -4 + I*4 print(Abs(z), arg(z)) # 4*sqrt(2) 3*pi/4 z = 4* sqrt(2) * exp(I * pi * 3/4) print(Abs(z), arg(z)) # 4*sqrt(2) 3*pi/4
3
3
78,925,095
2024-8-28
https://stackoverflow.com/questions/78925095/how-to-swap-values-between-two-columns-based-on-conditions-in-python
I am trying to switch values between the Range and Unit columns in the dataframe below based on the condition that if Unit contains -, then replace Unit with Range and Range with Unit. To do that, I am creating a unit_backup column so that I don't lose the original Unit value. 1. dataframe sample_df = pd.DataFrame({'Ra...
When you access df['unit_backup'], you get a scalar string value, not a pandas Series, so calling .str on it raises an error. To fix it you can check the condition directly on the string value in a row-wise approach: def range_unit_correction_fn(df): # creating backup of Unit column df['unit_backup'] = df['Unit'] # con...
3
0
78,924,586
2024-8-28
https://stackoverflow.com/questions/78924586/how-to-correctly-render-a-3d-surface-date-axis
I'm having some problems rendering axis date correctly in Shiny for Python with plotly surface plots. In particular, axis of type date are render as floats. Find here an example in shiny playground. Note that same exact code works if I render the figure with fig.show() outside of Shiny for Python (i.e. the x axis rende...
Replace the @render_widget with express.render.ui and replace the return fig with return ui.HTML(fig.to_html()) (see express.ui.HTML and plotly.io.to_html). Link to playground import plotly.graph_objects as go import pandas as pd import numpy as np from shiny.express import render, ui def plotSurface(plot_dfs: list, n...
2
1
78,924,591
2024-8-28
https://stackoverflow.com/questions/78924591/how-to-use-numpy-financials-irr-when-theres-a-withdrawal-of-value-in-the-middl
I am trying to calculate the IRR for a month using numpy_financial, but I am not succeeding. At which position in the array am I making a mistake? For example: initial_balance = 579676.18 final_balance = 2921989.17 From what I understand from the documentation, the final balance should be treated as a withdrawal (posi...
According to the document: Thus, for example, at least the first element of values, which represents the initial investment, will typically be negative. Your initial_balance should be negative, rest everything is correct in your example. from numpy_financial import irr final_array = [-initial_balance, 0, 22700.00, 0,...
2
1
78,924,081
2024-8-28
https://stackoverflow.com/questions/78924081/syntax-error-near-token-on-bash-script-initialising-conda
I've been asked to add some BASH script to a server .bashrc file so I can then initialise conda. When I log into the server, I get the following message: Last login: Wed Aug 28 16:57:04 2024 from {IP ADDRESS} -bash: /home/{username}/.bashrc: line 129: syntax error near unexpected token `then' -bash: /home/{username}/.b...
Your file is filled with non-ASCII characters. For example, here's a hexdump of line 7: $ sed -n 7p foo.sh | xxd 00000000: e280 afe2 80af e280 af20 6966 205b 202d ......... if [ - 00000010: 6620 222f 6f70 742f 616e 6163 6f6e 6461 f "/opt/anaconda 00000020: 332f 6574 632f 7072 6f66 696c 652e 642f 3/etc/profile.d/ 000000...
2
6
78,923,520
2024-8-28
https://stackoverflow.com/questions/78923520/filter-a-pandas-row-if-it-is-significantly-larger-than-neighbours-given-that-it
I have a dataframe like this Name Year Value 0 Mexico 1961 14357 1 Mexico 1961 15161 2 Mexico 1961 514658 3 Mexico 1962 15559 4 United States of America 1977 2191197 5 United States of America 1978 2470734 6 United States of America 1978 52470734 7 United States of America 1979 2737377 8 United States of America 1979 ...
You probably want to compare the previous or the next value, as if you only compare to the next one you will not be able to fix any errors that happen to be the last entry for that country. So create a lag and lead column grouped by country using pandas.DataFrame.shift() and then create a Boolean mask of values to repl...
3
2
78,921,222
2024-8-28
https://stackoverflow.com/questions/78921222/polars-unexpected-behaviour-when-using-drop-nans-on-all-columns
I have a simple Polars dataframe with some nulls and some NaNs and I want to drop only the latter. I'm trying to use drop_nans() by applying it to all columns and for whatever reason it replaces NaNs with a literal 1.0. I am confusion. Maybe I'm using the method wrong, but the docs don't have much info and definitely d...
What happens in your example is that drop_nans works on a per-column basis. It will first convert the series [float('nan'), 1, float('nan')] to [1], and then broadcast that value to the entire column when combined with ["a", "b"]. It does this because Polars doesn't have a concept of a scalar value yet, and it will tre...
4
5
78,922,012
2024-8-28
https://stackoverflow.com/questions/78922012/django-how-to-create-foreignkey-field-when-annotate
I wanted to create a ForeignKey field in Django using .annotate, but I couldn't find any option for it, maybe it doesn't exist. I just want to LEFT JOIN a specific model with a specific condition. But now I have to do it like this: queyrset = Invoice.objects.annotate(provided_amount=Subquery(InvoicePayment.objects.filt...
Please don't use related_name='+': it means querying in reverse is now a lot harder. We can name the relation payments instead: class InvoicePayment(models.Model): invoice = models.ForeignKey( Invoice, on_delete=models.CASCADE, related_name='payments' ) date = models.DateField() provided_amount = models.DecimalField( m...
2
2
78,921,783
2024-8-28
https://stackoverflow.com/questions/78921783/regex-how-to-match-a-line-between-two-optional-characters-that-are-not-include
The regex should match /exampleline - match exampleline exampleline - match exampleline exampleline/ - match exampleline /exampleline/ - match exampleline I tried ?\/(.+)\/? but it didn't work /exampleline/ and exampleline/ matched exampleline/, instead of exampleline
You can use negative lookarounds to assert that a match does not start with and does not end with a /: (?!/).+(?<!/) Demo: https://regex101.com/r/EKOvzG/2
4
1
78,902,565
2024-8-22
https://stackoverflow.com/questions/78902565/how-do-i-install-python-dev-dependencies-using-uv
I'm trying out uv to manage my Python project's dependencies and virtualenv but I can't see how to install all my dependencies for local development, including the dev dependencies. In my pyproject.toml I have this kind of thing: [project] name = "my-project" dependencies = [ "django", ] [tool.uv] dev-dependencies = [ ...
To expand on the other good answers by Phil Dependency Groups With uv >= 0.4.27 we can use the new Python packaging feature dependency groups to make pyproject uv-agnostic: [project] name = "my-project" dynamic = ["version"] requires-python = ">=3.10" dependencies = ["django"] [dependency-groups] dev = ["factory-boy"] ...
13
8
78,901,681
2024-8-22
https://stackoverflow.com/questions/78901681/exporting-only-dev-dependencies
Is there a command for uv that exports/extracts just the dependencies declared as dev dependencies from the pyproject.toml file, for example to pass test dependencies to tox? uv add Django uv add pytest --dev Results in this pyproject.toml: [project] dependencies = [ "django>=4.2.15", ] [tool.uv] dev-dependencies = [ ...
Update uv to the version 0.4.11 or greater (uv self update), and use the following command: uv export --only-dev --no-hashes | awk '{print $1}' FS=' ;' > requirements-dev.txt
2
1
78,907,444
2024-8-23
https://stackoverflow.com/questions/78907444/is-it-possible-use-vs-code-to-pass-multiple-command-line-arguments-to-python-scr
According to the official documentation "Python debugging in VS Code", launch.json can be configured to run with specific command line arguments, or you can use ${command:pickArgs} to input arguments at run time. Examples of putting arguments in launch.json: Specifying arguments in launch.json for Python Visual Studio...
Answering my own question after further testing. I will leave it unaccepted for a while to see if other answers come in. TL;DR This is possible as long as there are no spaces in the path to the Python interpreter. The fact that it breaks if there are spaces in the path is a currently open bug. The question arises becau...
8
7
78,900,274
2024-8-22
https://stackoverflow.com/questions/78900274/scipy-1-14-1-breaks-statsmodels-0-14-2
After installation of scipy 1.14.1 a previously viable Python program now fails. The original program is more complex so here's a MRE: import pandas as pd import plotly.express as px if __name__ == "__main__": data = { "Date": [0, 7, 14, 21, 28], "Value": [100, 110, 120, 115, 122] } df = pd.DataFrame(data) px.scatter(d...
Update: This issue has now been fixed in statsmodels 0.14.3. The rest of this answer is of historical interest only. This looks like a bug to me, so I filed issues against SciPy, statsmodels, and the statsmodels maintainer filed an issue against NumPy. Here's a summary of what I've learned from those issues. Cause of ...
2
3
78,912,175
2024-8-25
https://stackoverflow.com/questions/78912175/combine-cross-between-2-dataframe-efficiently
I am working with 2 datasets. One describes some time windows by their start and stop times. The second one contains a big list of events with their corresponding timestamps. I want to combine this into a single dataframe that contains the start and stop time of each window, together with how many events happened durin...
The mentioned non-equi joins PR has been merged as part of Polars 1.7.0 It is called .join_where() and is just an inner join for now. (actions_df .join_where(events_df, pl.col.start <= pl.col.time, pl.col.stop >= pl.col.time ) .pivot( on = "name", values = "time", aggregate_function = pl.len() ) ) shape: (3, 7) ┌─────...
3
1
78,911,891
2024-8-25
https://stackoverflow.com/questions/78911891/could-not-parse-modelproto-from-meta-llama-3-1-8b-instruct-tokenizer-model
I tried to use Llama 3.1 without relying on external programs, but I was not successful. I downloaded the Meta-Llama-3.1-8B-Instruct model, which includes only the files consolidated.00.pth, params.json, and tokenizer.model. The params.json file contains the following configuration: { "dim": 4096, "n_layers": 32, "n_he...
The way you should think about using llm model is that you have to pass it information systematically. Since you are using a publicly available model they come with things like weights, cfg etc... so you don't need to declare yours. All you need do is to start by declaring the file-paths of your model(i.e where you dow...
6
1
78,912,212
2024-8-25
https://stackoverflow.com/questions/78912212/how-to-make-cpython-report-vectorcall-as-available-only-when-it-will-actually-he
The Vectorcall protocol is a new calling convention for Python's C API defined in PEP 590. The idea is to speed up calls in Python by avoiding the need to build intermediate tuples and dicts, and instead pass all arguments in a C array. Python supports checking if a callable supports vectorcall by checking if the resul...
If it looks like PyObject_Call is faster for you, that's probably some sort of inefficiency on the Rust side of things, and you should look into optimizing that. Trying to bypass vectorcall doesn't actually provide the Python-side speedup you're thinking of. Particularly, the tuple you're creating is overhead, not an o...
8
1
78,904,911
2024-8-23
https://stackoverflow.com/questions/78904911/pydantic-is-not-compatible-with-langchain-documents
I am using LangChain 0.2.34 together with Python 3.12.5 to build a RAG architecture and Pydantic 2.8.2 for validation. It appears that some LangChain classes are not compatible with Pydantic although I explicitly allow arbitrary types. Or am I missing something? Here is a code sample and the respective error. from typi...
Langchain is using the functionality in pydantic v1. Define your model with v1 syntax: from pydantic.v1 import BaseModel, ConfigDict ... You can read about their migration plan + pydantic compatibility here: How to use LangChain with different Pydantic versions
2
3
78,918,133
2024-8-27
https://stackoverflow.com/questions/78918133/django-viewflow-passing-field-values-via-urls-upon-process-start
Is it possible **, to pass a value to a process via the startup url/path. I have a process model with a note field. I want to start a new process flow and pass the note to the url e.g. http://server.com/my_process/start/?note=mynote
Since Viewflow is a thin workflow layer built on top of Django, URL parameter processing works just like in Django. Parameters are available in the request.GET object, and you can use them in a custom view according to your needs. For example, to pre-initialize a user form with a value from the URL, you can create a cu...
2
1
78,906,787
2024-8-23
https://stackoverflow.com/questions/78906787/how-to-update-the-content-of-a-div-with-a-button-using-fasthtml
Using FastHTML, I would like to create a navigation bar that updates a div's content based on the item clicked. I wrote the following piece of code, but nothing happens when I click the buttons: the #page-content div doesn't update, and I don't see the logs of the GET methods being triggered. from fasthtml.common impor...
The issue came from the fact that I was wrapping my Body component into an Html component manually. Removing the Html component, FastHTML takes care of the wrapping automatically and also includes the required scripts. Here is my updated piece of code: from fasthtml.common import * app = FastHTML() @app.route("/", meth...
2
1
78,920,796
2024-8-27
https://stackoverflow.com/questions/78920796/cannot-reproduce-working-crc-16-ccitt-kermit-with-c
I found an example of working CRC-16/CCITT KERMIT python code shown below: def make_crc_table(): poly = 0x8408 table = [] for byte in range(256): crc = 0 for bit in range(8): if (byte ^ crc) & 1: crc = (crc >> 1) ^ poly else: crc >>= 1 byte >>= 1 table.append(crc) return table table = make_crc_table() def crc_16_fast(m...
We can try rewriting Python code, if it's the one we must follow (so not to try getting ready solution and see if it is doing the same, instead we are writing C# code accordingly to Python code). Here's C# snippet with some comments that point out, which Python code is related in particular code block: var poly = 0x840...
3
1
78,907,902
2024-8-24
https://stackoverflow.com/questions/78907902/how-do-i-do-calculations-with-a-sliding-window-while-being-memory-efficient
I am working with very large (several GB) 2-dimensional square NumPy arrays. Given an input array a, for each element, I would like to find the direction of its largest adjacent neighbor. I am using the provided sliding window view to try to avoid creating unnecessary copies: # a is an L x L array of type np.float32 sw...
Since using sliding_window_view is not efficient for your use case, I will provide an alternative using Numba. First, to simplify the implementation, define the following argmax alternative. from numba import njit @njit def argmax(*values): """argmax alternative that can take an arbitrary number of arguments. Usage: ar...
8
6
78,920,271
2024-8-27
https://stackoverflow.com/questions/78920271/is-there-a-best-practice-for-defining-optional-fields-in-pydantic-models
I'm working with Pydantic for data validation in a Python project and I'm encountering an issue with specifying optional fields in my BaseModel. from pydantic import BaseModel class MyModel(BaseModel): author_id: int | None # Case 1: throws error author_id: Optional[int] # Case 2: throws error author_id: int = None # C...
The reason you encounter an error is that there is no default value. The annotations don't actually do anything by themselves. All of the options bellow work, and they are pretty much equivalent under the hood. The third option is now recommended for projects only using Python 3.10+ from pydantic import BaseModel class...
2
3
78,919,290
2024-8-27
https://stackoverflow.com/questions/78919290/how-to-set-value-for-serializers-field-in-drf
I have a web page in which I show some reports of trades between sellers and customers. So for this purpose, I need to create an API to get all of the trades from database, extract necessary data and serialize them to be useful in web page. So I do not think of creating any model and just return the data in JSON format...
You should use SerializerMethodField and also stick to Django ORM to fetch data instead of iterating over it: views.py class IndicatorView(APIView): def get(self, request): serializer = IndicatorSerializer(Trade.objects.all()) return Response(serializer.data) serializers.py class IndicatorSerializer(serializers.Serial...
3
1
78,918,585
2024-8-27
https://stackoverflow.com/questions/78918585/count-same-consecutive-numbers-in-list-column-in-polars-dataframe
I have a pl.DataFrame with a column comprising lists with integers. I need to assert that each consecutive integer is showing up two times in a row at a maximum. For instance, a list containing [1,1,0,-1,1] would be OK, as the number 1 is showing up max two times in a row (the first two elements, followed by a zero). T...
The following could be used. Perform run-length encoding of the list using pl.Expr.rle. This produces a list of structs. Each struct contains a (unique) list value and the corresponding run length. Check whether the maximum run length in the list is at most 2. Ensure the result is of type bool by selecting the first...
3
5
78,917,816
2024-8-27
https://stackoverflow.com/questions/78917816/filter-rows-inside-window-function-in-python-polars
I need to compute the Herfindahl–Hirschman index ("HHI", the sum of squared market shares) but leaving out the firm represented in the row. Here's an example: df = (pl.DataFrame({ 'year':(2023, 2023, 2023, 2024, 2024, 2024), 'firm':('A', 'B', 'C', 'A', 'B', 'C'), 'volume':(20, 50, 3, 25, 13, 5) }) .with_columns( sum = ...
You can take out the denominator from the sum of squares: .with_columns( leaveout_sum = (pl.col.volume.sum().over('year')) - pl.col.volume, leaveout_sum_of_sq = (pl.col.volume**2).sum().over('year') - pl.col.volume**2 ) .with_columns( leaveout_hhi = pl.col.leaveout_sum_of_sq / pl.col.leaveout_sum**2 )) I left out the ...
3
2
78,917,261
2024-8-27
https://stackoverflow.com/questions/78917261/longest-complete-subsequence-of-ordered-vowels
Given a string made up of "a", "e", "i", "o", or "u", find the longest subsequence of vowels in order. For example, is the string is "aeiaeiou", then the answer is 6, making the subsequence "aaeiou". Another example is: "aeiaaioooaauuaeiou" where the answer is 10. A complete subsequence means that you need to have all...
O(n) by keeping track of the max length for each last-of-the-subsequence vowel (e.g., maxlen[3] tells the max length of an ordered subsequence ending with 'o'): def find_longest_dp2(vowels): maxlen = [0] * 5 for v in vowels: i = 'aeiou'.find(v) maxlen[i] = max(maxlen[:i+1]) + 1 return max(maxlen) Or if all five vowels...
5
3
78,914,940
2024-8-26
https://stackoverflow.com/questions/78914940/is-it-possible-to-adjust-qlineedit-icon-spacing
I'm planning to use a QLineEdit with three actions added via addAction(). Easy enough and it looks like this: (squares as icons for the example) But a minor annoyance is that I find the spacing between the icons a bit too large. Is it possible to adjust this spacing? QLineEdit doesn't seem to have an accessible layout...
Actions shown in QLineEdit (including that used for the "clear button") are implemented privately. The addAction(<action|icon>, position) is an overload of QWidget::addAction() that, after calling the base implementation, also creates an instance of a private QToolButton subclass (QLineEditIconButton). The reasoning be...
2
1
78,915,972
2024-8-26
https://stackoverflow.com/questions/78915972/drop-row-with-3-columns-value-equal
I would like to drop the row with all three columns have equal value. e.g. import pandas as pd data = [ ['A',2,2,2], ['B',2,2,3], ['C',3,3,3], ['D',4,2,2], ['E',5,5,2] ] df = pd.DataFrame(data,columns=['name','val1','val2','val3']) print(df) In above example, row 0 and row 2 will be dropped since the value is equal.
You can easily drop rows where specified columns have equal values using the following steps: Step 1: Use df[['val1', 'val2', 'val3']].nunique(axis=1) to calculate the number of unique values in each row across these columns. Step2 : where the number of unique values >= then filter the rows Here is code snippet to guid...
2
2
78,915,951
2024-8-26
https://stackoverflow.com/questions/78915951/find-the-index-of-the-first-non-null-value-in-a-column-in-a-polars-dataframe
I need to find the first non-null value in a column over a grouped pl.DataFrame. import polars as pl df = pl.DataFrame( { "symbol": ["s1", "s1", "s2", "s2"], "trade": [None, 1, -1, None], } ) shape: (4, 2) ┌────────┬───────┐ │ symbol ┆ trade │ │ --- ┆ --- │ │ str ┆ i64 │ ╞════════╪═══════╡ │ s1 ┆ null │ │ s1 ┆ 1 │ │ s2...
Here's one way using .arg_true().first(): print( df.group_by("symbol").agg( pl.col("trade").is_not_null().arg_true().first().alias("first-non-null") ) ) Output: ┌────────┬────────────────┐ │ symbol ┆ first-non-null │ │ --- ┆ --- │ │ str ┆ u32 │ ╞════════╪════════════════╡ │ s1 ┆ 1 │ │ s2 ┆ 0 │ └────────┴──────────────...
2
3
78,914,882
2024-8-26
https://stackoverflow.com/questions/78914882/replace-a-cell-in-a-column-based-on-a-cell-in-another-column-in-a-polars-datafra
Consider the following pl.DataFrame: import polars as pl df = pl.DataFrame( { "symbol": ["s1", "s1", "s2", "s2"], "signal": [0, 1, 2, 0], "trade": [None, 1, None, -1], } ) shape: (4, 3) ┌────────┬────────┬───────┐ │ symbol ┆ signal ┆ trade │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞════════╪════════╪═══════╡ │ s1 ┆ 0 ┆...
For this, a when-then-otherwise construct may be used. We create a condition that evaluates to True exactly for the first rows (create index on the fly using pl.int_range) in each group with signal not equal to 0. Based on that condition, we either select the value in the signal or trade column. df.with_columns( trad...
3
4
78,914,836
2024-8-26
https://stackoverflow.com/questions/78914836/is-there-a-way-to-include-column-index-name-with-pandas-dataframe-to-csv
Is there a way to include the column (not rows!) index name in the output when calling Pandas' dataframe.to_csv() method? For example: import pandas as pd iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv') pivot_iris = iris.pivot_table(index='species', columns='sepal_length', v...
You can't really include the index names in a CSV. What you could do is to create a MultiIndex: pivot_iris = (pd.concat({'sepal_length': iris.pivot_table(index='species', columns='sepal_length', values='sepal_width')}, axis=1) .rename_axis(columns=(None, 'species')).reset_index() ) pivot_iris.to_csv('pivot_iris.csv', i...
3
2
78,914,504
2024-8-26
https://stackoverflow.com/questions/78914504/pandas-dataframe-with-mixed-periods-1m-6m-and-12m-to-dataframe-with-one-per
I have a dataframe with income for a certain period of time. The period is given by a start date and an end date (For example 2023-04-01 and 2023-06-30). The period can vary between 3, 6 and 12 months. My goal is to bring everything to the same period, but I did not find an easy way to do it. This is how I am doing it ...
You can create new rows with Index.repeat, add months by counter by GroupBy.cumcount and create datetimes by Series.dt.to_timestamp: df = pd.DataFrame({'date':['2023-04-01', '2023-01-01'], 'date_to':['2023-06-30', '2023-06-30'], }).apply(pd.to_datetime).assign(net_revenues=[100,20]) print (df) date date_to net_revenues...
2
2
78,913,782
2024-8-26
https://stackoverflow.com/questions/78913782/how-can-i-run-python-package-using-google-collab
I want to run the DAN repo. I am using Google Cloud Collab. I cloned the project on my Google Drive in the following directory /content/drive/MyDrive/DAN/DAN Trying to run An example script file is available at OCR/document_OCR/dan/predict_examples to recognize images directly from paths using trained weights. using co...
!python3 spawns a new interpreter which doesn't know about sys.path.append(...) above it, it only affects the current interpreter. instead either use runpy.run_path to execute a file within the current interpreter, or modify os.environ["PYTHONPATH"] by appending :/your_path to it before calling !python3 so it will carr...
2
2
78,913,464
2024-8-26
https://stackoverflow.com/questions/78913464/how-to-filter-on-uniqueness-by-condition
Imagine I have a dataset like: data = { "a": [1, 4, 2, 4, 7, 4], "b": [4, 2, 3, 3, 0, 2], "c": ["a", "b", "c", "d", "e", "f"], } and I want to keep only the rows for which a + b is uniquely described by a single combination of a and b. I managed to hack this: df = ( pl.DataFrame(data) .with_columns(sum_ab=pl.col("a") ...
.struct() to combine a and b into one column so we can check uniqueness. n_unique() to check uniqueness. over() to limit the calculation to be within a + b. df.filter( pl.struct("a","b").n_unique().over(pl.col.a + pl.col.b) == 1 ) ┌─────┬─────┬─────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str │ ╞═════╪═════╪...
4
4
78,910,189
2024-8-24
https://stackoverflow.com/questions/78910189/using-einsum-for-transpose-times-matrix-times-transpose-xaxt
So I have m number of different vectors (say x), each one is (1,n), stacked horizontally, totally in a (m,n) matrix we call it B, and a matrix (A) with dimension (n,n). I want to compute xAx^T for all vectors x, output should be (m,1) How can I write an einsum query for this given B and A? Here is a sample without eins...
Using einsum and tensordot : import torch import numpy as np A = torch.tensor([[1.0, 0.0, 0.0, 0.0], [0.0, 2.0, 0.0, 0.0], [0.0, 0.0, 3.0, 0.0], [0.0, 0.0, 0.0, 4.0]]) B = torch.tensor([[1.0, 4.0, 7.0, 10.0], [2.0, 5.0, 8.0, 11.0], [3.0, 6.0, 9.0, 12.0]]) # Using einsum res_using_einsum = torch.einsum('bi,ij,bj -> b',B...
3
1
78,896,435
2024-8-21
https://stackoverflow.com/questions/78896435/function-takes-foo-subclass-and-wraps-it-in-bar-else-returns-type-unaltered
I have the following code: from typing import TypeVar, Any, Generic class Foo: ... class Bar(Generic[FooT]): def __init__(self, foo: FooT): self._foo = foo FooT = TypeVar('FooT', bound=Foo) T = TypeVar('T') def func(a: FooT | T) -> Bar[FooT] | T: if isinstance(a, Foo): return Bar(a) return a def my_other_func(a: Foo) -...
Use typing.overload: from typing import TypeVar, Generic class Foo: ... FooT = TypeVar('FooT', bound=Foo) class Bar(Generic[FooT]): def __init__(self, foo: FooT): self._foo = foo T = TypeVar('T') @overload def func(a: FooT) -> Bar[FooT]: ... @overload def func(a: T) -> T: ... def func(a): if isinstance(a, Foo): return ...
2
1
78,910,274
2024-8-25
https://stackoverflow.com/questions/78910274/how-to-maintain-original-order-of-attributes-when-using-ruamel-yaml-dump
I am using a pydantic model to store some data. The model itself is not relevant, the relevant part is that the pydantic model.dump_to_json() gives me a string like this: str_val = '{"aspect":{"name":"tuskhelm_of_joritz_the_mighty"},"affix":[{"name":"maximum_life"},{"name":"intelligence"}]}' Note that "aspect" is list...
The safe loader doesn't preserve the order of the keys of a mapping, neither in pure mode or when using the C extension. It essentially follows the YAML specification, which says keys are unordered, and the behaviour of PyYAML from which it was forked, so the dumper activily sorts the output keys. If you leave out the ...
3
2
78,909,971
2024-8-24
https://stackoverflow.com/questions/78909971/exponential-plot-in-python-is-a-curve-with-multiple-inflection-points-instead-of
I am trying to draw a simple exponential in python. When using the code below, everything works fine and the exponential is shown import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np def graph(func, x_range): x = np.arange(*x_range) y = func(x) plt.plot(x, y) graph(lambda x: pow(3,...
I can't make time to nail this now, but the graph looks a whole lot like what I'd expect if integer arithmetic is overflowing. numpy's ints are fixed-width, unlike Python's ints (which are unbounded). In particular, >>> 3**20 3486784401 >>> _.bit_length() 32 so at the point things start to go crazy the result is overf...
2
5
78,909,690
2024-8-24
https://stackoverflow.com/questions/78909690/functools-partial-with-bound-first-argument-and-args-and-kwargs-interprets-ca
Using python 3.10: I have a function with a first argument and then *args and **kwargs. I want to bind the first argument and leave the *args and **kwargs free. If I do this and the bound function gets called using a list of arguments, python interprets it as multiple values for the bound argument. An example: from fun...
a is the first parameter to function foo1. If you want a partial, do not use keyword: pfoo1 = partial(foo1, 10)
3
3
78,908,830
2024-8-24
https://stackoverflow.com/questions/78908830/how-can-i-adjust-the-white-empty-space-around-a-matplotlib-table-to-match-the-ta
There's extra white, empty space around my Matplotlib table, causing my table to get squished as if the figsize wasn't big enough. If I increase the figsize, the table displays normally, but then the white, empty space gets even bigger. Additionally, the title gets misplaced over the table when the number of rows passe...
I think you need to try suptitle for title and play with bbox parameter of table. import matplotlib.pyplot as plt import pandas as pd import numpy as np def create_pivot_table( title: str, pivot_table: pd.core.frame.DataFrame, ): """ Creates a Matplotlib table from a Pandas pivot table. Returns fig and ax. """ fig_widt...
3
2
78,900,439
2024-8-22
https://stackoverflow.com/questions/78900439/how-to-show-two-outputs-of-the-same-function-without-running-it-twice
I have this function that iterates over my data and generates two outputs (in the example, the function check(). Now I want to show both outputs on different cards. AFAIK the card ID has to be the same as the function that generates the output. In my example, the function check() is run twice, which is very inefficient...
Rewrite your check() function such that it modifies a reactive.value() which contains the odd and the even numbers from the input. check() is decorated by reactive.effect() and reactive.event(), where the event is input.check_numbers. Then check() only gets executed once when the user clicks the button. And then, insid...
2
1
78,908,245
2024-8-24
https://stackoverflow.com/questions/78908245/python-pandas-dataframe-row-name-change
How can I replace the first index 0 with "Color" and 1 with "Size"? import pandas as pd clothes = {"shirt": ["red", "M"], "sweater": ["yellow", "L"], "jacket": ["black", "L"]} # pd.DataFrame.from_dict(clothes) df = pd.DataFrame.from_dict(clothes) df I tried like this but nothing changes. The output shows index name as...
don't use from_dict, but the DataFrame constructor directly: df = pd.DataFrame(clothes, index=['color', 'size']) If the DataFrame is already existing, set_axis: df = pd.DataFrame(clothes) df = df.set_axis(['color', 'size']) output: shirt sweater jacket color red yellow black size M L L
2
1
78,907,326
2024-8-23
https://stackoverflow.com/questions/78907326/cant-update-data-in-data-base-via-patch-method-in-django
I have a model of items, and I need to write CRUD operations with data. Post and get works, but patch - no, and I can`t understand why serializers.py class CreateItemSerializer(serializers.ModelSerializer): photo = serializers.ImageField(max_length=None, allow_empty_file=True, allow_null=True) class Meta: model = Creat...
The logic of the save method differ depending on the parameter you delivered when the DRF Serializer object was created. In the case of the patch method, it is the process of modifying an existing instance. That's why when you create a Serializer in the patch method, you need to forward not only the data sent by the cl...
2
1
78,907,265
2024-8-23
https://stackoverflow.com/questions/78907265/polars-keep-the-biggest-value-using-2-categories
I have a polars dataframe that contain some ID, actions, and values : Example Dataframe: data = { "ID" : [1, 1, 2,2,3,3], "Action" : ["A", "A", "B", "B", "A", "A"], "Where" : ["Office", "Home", "Home", "Office", "Home", "Home"], "Value" : [1, 2, 3, 4, 5, 6] } df = pl.DataFrame(data) I want to select for each ID and ac...
The over and unique could be combined into a group_by .arg_max() can give you the index of the max .get() will extract the corresponding values at that index (df.group_by("ID", "Action") .agg( pl.all().get(pl.col("Value").arg_max()) ) ) shape: (3, 4) ┌─────┬────────┬────────┬───────┐ │ ID ┆ Action ┆ Where ┆ Value │ ...
4
3
78,903,312
2024-8-22
https://stackoverflow.com/questions/78903312/why-is-my-locally-installed-python-package-not-found-when-installed-as-an-editab
I am using Python 3.10.7 64-bit in VSCode. I have a Python package "pxml" built using setuptools. It is in a folder with an empty __init.py__ and a pyproject.toml containing: [build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [project] name = "pxml" version = "0.0.1" dependencies = [] Whe...
For the package structure shown in your question, this is import statement is incorrect: import pxml pxml is not a top-level import, it is a submodule of a package named XML. If python -c "import pxml" works that is only by accident and you happen to have pxml visible on sys.path for some reason - perhaps the subdirec...
2
1
78,904,654
2024-8-23
https://stackoverflow.com/questions/78904654/how-to-make-a-selection-in-the-colorbar-of-an-altair-plot
Recently, I started using Altair and liked it a lot. However, I stumbled across something I could not figure out using the docs: I have a scatter plot that encodes some continuous data as color. Is there a way of selecting a range of these values via the colorbar? Similar to how it is possible to select discrete featur...
As @joelostblom mentioned in his comment you can use a second plot to generate a color scale with a selection interval. I have implemented this using a mark_tick with good results. Most of the options for the scale chart's y encoding are only for aesthetics and can be removed / tweaked as desired. cars = data.cars() co...
3
1
78,904,263
2024-8-23
https://stackoverflow.com/questions/78904263/better-way-to-get-list-of-keys-which-has-the-same-value-from-a-output-dict
I'm trying to get all keys from a python dict which has the same value. as part of this, I have made the below attempt and it works. but checking if there is a neater way to do this. I have gone through the thread Finding all the keys with the same value in a Python dictionary b = {'a1': ['b1', 'b2', 'b3'], 'a2': ['b1'...
Why not go for defaultdict it is proven to be quite efficient and faster and you dont have to worry about getting errors such as the famous KeyError.. Ref: Stackoverflow_old_question I am not sure but python lawyers might have me for this and also tuple my guess is that your b1, b2, b3 needs to be immutable, I would go...
2
1
78,904,936
2024-8-23
https://stackoverflow.com/questions/78904936/is-there-a-better-way-to-replace-all-non-ascii-characters-from-specific-columns
There are some sentences and words in Chinese and Japanese that I just want to drop. Or if there is a better solution than just dropping them, I would like to explore them as well. import pandas as pd import re # Define the function to check for English text def is_english(text): # Regex pattern for English letters, nu...
If you just want to keep ASCII characters, be explicit, select those and drop the rest with str.replace: df = pd.DataFrame({'col': ['Aaäá😀αあ今']}) df['ascii'] = df['col'].str.replace(r'[^\x00-\x7F]', '', regex=True) You can also remove specific character ranges: # removing CJK, CJK symbols, hiragana, katakana # you ca...
2
2
78,904,801
2024-8-23
https://stackoverflow.com/questions/78904801/polars-dataframe-decimal-precision-doubles-on-mul-with-integer
I have a Polars (v1.5.0) dataframe with 4 columns as shown in example below. When I multiply decimal columns with an integer column, the scale of the resultant decimal column doubles. from decimal import Decimal import polars as pl df = pl.DataFrame({ "a": [1, 2], "b": [Decimal('3.45'), Decimal('4.73')], "c": [Decimal(...
The scale indeed seems to double. You could cast back to the original dtype: cols = ['c', 'd', 'e'] df.with_columns(pl.col(c).mul(pl.col('a')).cast(df[c].dtype) for c in cols) Note that there currently doesn't seem to be a way to access the dtype in an Expr, but this is a discussed feature. Example: ┌─────┬─────┬─────...
4
3
78,901,146
2024-8-22
https://stackoverflow.com/questions/78901146/why-does-recurse-true-cause-dill-not-to-respect-globals-in-functions
If I pickle a function with dill that contains a global, somehow that global state isn't respected when the function is loaded again. I don't understand enough about dill to be anymore specific, but take this working code for example: import multiprocessing import dill def initializer(): global foo foo = 1 def worker(a...
With the recurse=True option, dill.dump builds a new globals dict for the function being serialized with objects that the function refers to also recursively serialized. The side effect is that when deserialized with dill.load, these objects are reconstructed as new objects, including the globals dict for the function....
4
1
78,902,034
2024-8-22
https://stackoverflow.com/questions/78902034/use-one-regex-to-extract-information-from-two-patterns
I would like to simplify below regex logic with one regex statement. Then it's easier to understand the logic. import re content = """ [ 1.765989] initcall init_module.cfi_jt+0x0/0x8 [altmode_glink] returned 0 after 379 usecs [ 0.001873] initcall selinux_init+0x0/0x1f8 returned 0 after 85 usecs """ for line in content....
The tricky part is apparently how you identify a function name, which can be be matched by non-left-bracket characters followed by either a right bracket or a plus sign followed by non-spaces: for ts, func, ret, val in re.findall( r'\[\s*([\d.]+)] initcall .*?([^[]+)(?:]|\+\S+) ' r'returned (\d+) after (\d+) usecs', co...
3
1
78,903,730
2024-8-22
https://stackoverflow.com/questions/78903730/pandas-list-all-unique-values-based-on-groupby
I have a dataframe that has worksite info. District# Site# Address 1 1 123 Bayview Ln 1 2 456 Example St 2 36 789 Hello Dr 2 44 789 Hello Dr I am trying to transform this dataframe to add a column with the highest Site# as well as the distinct addresses when I group by District#. Here is an example of what I want the ...
You can use groupby and agg to get the Max Site Number and List all the addresses Then merge back to the original dataframe: grouped_df = df.groupby('District#').agg(Max_Site_Num=('Site#', 'max'), All_District_Addresses=('Address', lambda x: list(set(x))).reset_index() df = df.merge(grouped_df,on='District#') Output: ...
4
5