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,975,594
2024-9-11
https://stackoverflow.com/questions/78975594/should-i-use-djangos-floatfield-or-decimalfield-for-audio-length
I use: duration = float(ffmpeg.probe(audio_path)["format"]["duration"]) I collect an audio/video's length and want to store it using my models. Should I use models.DecimalField() or models.FloatField()? I use it to calculate and store a credit/cost in my model using credit = models.DecimalField(max_digits=20, decimal_...
I think the most sensical way is to use a DurationField model field [Django-doc]. Django will look what database the backend uses, and try to work with the most sensical column type the database offers: class MyModel(models.Model): duration = models.DurationField() and work with: from datetime import timedelta MyModel....
2
0
78,988,010
2024-9-15
https://stackoverflow.com/questions/78988010/explode-multiple-columns-with-different-lengths
I have a dataframe like: data = { "a": [[1], [2], [3, 4], [5, 6, 7]], "b": [[], [8], [9, 10], [11, 12]], } df = pl.DataFrame(data) """ ┌───────────┬───────────┐ │ a ┆ b │ │ --- ┆ --- │ │ list[i64] ┆ list[i64] │ ╞═══════════╪═══════════╡ │ [1] ┆ [] │ │ [2] ┆ [8] │ │ [3, 4] ┆ [9, 10] │ │ [5, 6, 7] ┆ [11, 12] │ └─────────...
Here's one approach: min_length = pl.min_horizontal(pl.col('a', 'b').list.len()) out = (df.filter(min_length != 0) .with_columns( pl.col('a', 'b').list.head(min_length) ) .explode('a', 'b') ) Output: shape: (5, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 2 ┆ 8 │ │ 3 ┆ 9 │ │ 4 ┆ 10 │ │ 5 ┆ 11...
7
6
78,979,491
2024-9-12
https://stackoverflow.com/questions/78979491/how-can-i-avoid-using-pl-dataframe-iter-rows-and-instead-vectorize-this
I have two polars dataframes containing a unique ID and the name of a utility. I am trying to build a mapping of entries between these two dataframes. I am using polars_fuzzy_match to do a fuzzy string search against entries. My first dataframe (wg_df) is approximately a subset of the second (eia_df). In my code below ...
polars-fuzzy-match would need to add support for vectorization. (i.e. at the Rust level) The polars_ds plugin has vectorized functions backed by the impressive RapidFuzz library. import polars_ds as pds (eia_df .lazy() .join(wg_df.lazy(), how="cross") .with_columns( score = pds.str_fuzz(pl.col.utility_name, pl.col.util...
2
0
78,974,836
2024-9-11
https://stackoverflow.com/questions/78974836/fitting-multidimensional-data-with-python-symfit-odemodel
I am trying to fit the parameters of an ODE to data with two dimensions, which should generally be possible, according to the example Fitting multidimensional datasets. This is my failed attempt so far import symfit as sf import numpy as np # data x = np.arange(0,19) data = 10e-4 * np.array([8,10,12,11,10,15,25,37,46,4...
inp has to be defined as an expression and integrated into the expression d mp / dt. To do so, the data for inp has to be fit so as to reproduce data2. Since data2 looks like a square wave, a Fourier series is used to fit the data. The following is the code implementing these ideas: import symfit as sf import numpy as ...
2
1
78,985,516
2024-9-14
https://stackoverflow.com/questions/78985516/how-to-automatically-download-or-warn-about-a-non-pypi-dependency-of-a-python-pa
I have a Python package, which is distributed on PyPi. It depends on number of other packages available on PyPi and on Psi4, which is only distributed on Conda repositories (https://anaconda.org/psi4/psi4), not on PyPi. Now, my package is distributed as wheel package via hatchling, so my pyproject.toml looks similar to...
If you use a setup.py instead of pyproject.toml, you can add an installation check for psi4. pyproject.toml does not natively support conda packages. For setup.py, you can approach it like: import subprocess import sys try: import psi4 except ImportError: subprocess.check_call([sys.executable, "-m", "conda", "install",...
2
1
78,985,089
2024-9-14
https://stackoverflow.com/questions/78985089/modifying-multiple-dimensions-of-jax-array-simultaneously
When using the jax_array.at[idx] function, I wish to be able to set values at both a set of specified rows and columns within the jax_array to another jax_array containing values in the same shape. For example, given a 5x5 jax array, I might want to set the values, jax_array.at[[0,3],:][:,[1,2]] to some 2x2 array of va...
JAX follows the indexing semantics of NumPy, and NumPy's indexing semantics allow you to do this via broadcasted arrays of indices (this is discussed in Integer array indexing in the NumPy docs). So for example, you could do something like this: import jax.numpy as jnp x = jnp.zeros((4, 6), dtype=int) y = jnp.array([[1...
2
2
78,983,916
2024-9-13
https://stackoverflow.com/questions/78983916/implementing-discriminated-unions-in-pydantic-without-using-nested-models
I'm trying to implement discriminated unions in Pydantic to select the correct class based on user input using the discriminator parameter. While the documentation suggests creating a nested model class to handle this easily, I'd like to use this functionality without introducing an additional nested model and have a s...
You can use TypeAdapter instead of RootModel: from typing import Literal, Union, Annotated from pydantic import BaseModel, Field, TypeAdapter class Cat(BaseModel): pet_type: Literal["cat"] meows: int class Dog(BaseModel): pet_type: Literal["dog"] barks: float class Lizard(BaseModel): pet_type: Literal["reptile", "lizar...
2
3
78,983,868
2024-9-13
https://stackoverflow.com/questions/78983868/keep-only-rows-that-have-at-least-one-null
I am trying to do basically the opposite of drop_nulls(). I want to keep all rows that have at least one null. I want to do something like (but I don't want to list all other columns): for (name,) in ( df.filter( pl.col("a").is_null() | pl.col("b").is_null() | pl.col("c").is_null() ) .select("name") .unique() .rows() )...
It sounds like you are looking for pl.Expr.any_horizontal. The following will keep all rows containing at least one null value (in any of the columns). df.filter(pl.any_horizontal(pl.all().is_null()))
4
3
78,980,521
2024-9-13
https://stackoverflow.com/questions/78980521/mapping-over-arrays-of-functions-in-jax
What is the most performant, idiomatic way of mapping over arrays of functions in JAX? Context: This GitHub issue shows a way to apply vmap to several functions using lax.switch. The example is reproduced below: from jax import lax, vmap import jax.numpy as jnp def func1(x): return 2 * x def func2(x): return -2 * x def...
For the kind of operation you're doing, where the functions are applied over full axes of an array in a way that's known statically, you'll probably get the best performance via a simple Python loop: def map_functions(functions: list[Callable[[Array], Array], x: Array) -> Array: assert len(functions) == x.shape[0] retu...
2
1
78,982,423
2024-9-13
https://stackoverflow.com/questions/78982423/how-to-propagate-null-in-a-column-after-first-occurrence
I have 2 data sets: The first one describes what I expect: expected = { "name": ["start", "stop", "start", "stop", "start", "stop", "start", "stop"], "description": ["a", "b", "c", "d", "e", "f", "g", "h"], } and the second one describes what I observe: observed = { "name": ["start", "stop", "start", "stop", "stop", "...
The check whether any null value appeared in an increasing window can be done using a cumulative evaluation, such as pl.Expr.cum_sum. A when-then-otherwise construct can be used to propagate null values accordingly. In your example, this might look as follows. ( observed_df .join( expected_df, on=["index", "name"], how...
4
2
78,982,686
2024-9-13
https://stackoverflow.com/questions/78982686/filter-polars-dataframe-on-records-where-column-values-differ-catching-nulls
Have: import polars as pl df = pl.DataFrame({'col1': [1,2,3], 'col2': [1, None, None]}) in polars dataframes, those Nones become nulls: > df ┌──────┬──────┐ │ col1 ┆ col2 │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪══════╡ │ 1 ┆ 1 │ │ 2 ┆ null │ │ 3 ┆ null │ └──────┴──────┘ Want: some command that returns the last two rows...
It is mentioned somewhat at the end of the .filter() docs. There are "missing" functions: .eq_missing() .ne_missing() df.filter(pl.col.col1.ne_missing(pl.col.col2)) shape: (2, 2) ┌──────┬──────┐ │ col1 ┆ col2 │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪══════╡ │ 2 ┆ null │ │ 3 ┆ null │ └──────┴──────┘
2
3
78,981,683
2024-9-13
https://stackoverflow.com/questions/78981683/error-installing-trottersuzuki-package-in-venv-numpy-not-found-error-even-thoug
It says numpy not installed even though it is installed. I thought may be the venv is not accessible to pip (which it should be, because numpy is installed inside the venv) and I installed it system wide using sudo apt install python3-numpy as you can see in the very last of the following snippet. vanangamudi@kaithadi:...
trottersuzuki doesn't provide binary wheels, only sdist. When installing from a source distribution modern pip first build a wheel in a new isolated virtual environment. In this isolated venv there is no numpy. For pip to install numpy during build phase there must be a file pyproject.toml in the package that lists num...
2
1
78,981,438
2024-9-13
https://stackoverflow.com/questions/78981438/unittest-class-init-mock-exception-raised
#!/usr/bin/env python3 import unittest from unittest.mock import patch class User(object): def __init__(self): self.__name = None self.__authorised_users = ["me", "you"] local_input = input("please provide your windows 8 character lower case login: ") if local_input not in self.__authorised_users: raise ValueError("you...
You can patch User.__init__ with a wrapper that suppresses ValueError: def ignore(func, exception): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except exception: pass return wrapper class TestUser(unittest.TestCase): @patch('builtins.input', lambda *args:"y") @patch.object(User, '__init__', ignore(U...
2
2
78,979,081
2024-9-12
https://stackoverflow.com/questions/78979081/python-exception-stack-trace-not-full-when-function-is-wrapped
I have two files t.py: import functools import traceback def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: traceback.print_exception(e) return wrapped @wrapper def problematic_function(): raise ValueError("Something went wrong") and t2.py: ...
To print the full stack trace you can unpack traceback.walk_tb to obtain the last frame of the stack from the traceback, and pass it to traceback.print_stack as a starting frame to output the entire stack: def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except E...
2
1
78,980,426
2024-9-13
https://stackoverflow.com/questions/78980426/flag-the-max-value-in-each-column-of-a-dataframe-as-true-and-the-rest-as-false
I have a DataFrame that I am rounding. After the round, I subtract the original from the resultant. This gives me a data frame with a shape identical to the original, but which contains the amount of change the rounding operation caused. I need to transform this into a Boolean where there is a true flag for the max of ...
You can use idxmax to get the position of column with the max value, and use numpy broadcasting to match the position with the column. m = c.columns.to_numpy() == c.idxmax(axis=1).to_numpy()[:, None] new_df = pd.DataFrame(np.where(m, True, False), columns=c.columns) End result: 0 1 2 3 4 5 6 False False False True Fa...
2
1
78,978,186
2024-9-12
https://stackoverflow.com/questions/78978186/correct-way-to-find-dimension-after-broadcasting-in-numpy
Suppose I am given a few numpy arrays, say a, b and c, which are assumed to be broadcastable. Is there a standard or othwerwise an elegant way to find the array shape after broadcasting? Of course, something like (a+b+c).shape would work, but is very inefficient if I am only interested in the shape of the result.
You can use broadcast_shapes. Like this result_shape = np.broadcast_shapes(a.shape, b.shape, c.shape) Here is the documentation page: https://numpy.org/doc/stable/reference/generated/numpy.broadcast_shapes.html Good luck!
2
3
78,977,665
2024-9-12
https://stackoverflow.com/questions/78977665/django-autoreload-raises-typeerror-unhashable-type-types-simplenamespace
When I upgrade importlib_meta from version 8.4.0 to 8.5.0 (released just yesterday, Sep 11 2024), I get the following error when I start running the development server with python manage.py runserver: File "/app/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packa...
The problematic commit in importlib_meta puts a types.SimpleNamespace object in sys.modules["zipp.compat.overlay.zipfile"]: zipfile = types.SimpleNamespace(**vars(importlib.import_module('zipfile'))) ... sys.modules[__name__ + '.zipfile'] = zipfile # type: ignore[assignment] Here's the invocation error site in django:...
5
3
78,976,021
2024-9-12
https://stackoverflow.com/questions/78976021/azure-monitor-open-telemetry-python-package-raising-exception-when-python-app-de
I have a Python web application built with Plotly Dash and deployed on Azure App Service using Python 3.12. As Azure App Service has not yet enabled Python 3.12 version to have application insight enabled, I have utilized the package: azure-monitor-opentelemetry==1.6.2 within my application to log exceptions into my a...
Version 1.6.2 also upgrades azure-monitor-opentelemetry-exporter to "1.0.0b29" and it has the braking changes. Just downgrade to azure-monitor-opentelemetry-exporter = "1.0.0b28" and maybe to azure-monitor-opentelemetry = "1.6.1". It will solve the issue for now. In general, I think that config should be done differntl...
3
1
78,977,145
2024-9-12
https://stackoverflow.com/questions/78977145/derived-python-dataclass-cannot-override-default-value
In the following code snippet the dataclass Derived is derived from dataclass Base. The Derived dataclass is setting new default values for field1 and field2. from dataclasses import dataclass @dataclass class Base: field1: str field2: str = "default_base_string" @dataclass class Derived(Base): field1 = "default_string...
To set default values in Derived you need to add the type annotation @dataclass class Derived(Base): field1: str = "default_string1" field2: str = "default_string2" print(Derived()) # Derived(field1='default_string1', field2='default_string2')
2
2
78,975,956
2024-9-11
https://stackoverflow.com/questions/78975956/python-list-comprehension-two-loops-with-three-results
I can ask my question best by just giving an example. Let's say I want to use a list comprehension to generate a set of 3-element tuples from two loops, something like this: [ (y+z,y,z) for y in range(10) if y%2==0 for z in range(20) if z%3==0 ] This works, giving me [(0, 0, 0), (3, 0, 3), (6, 0, 6), (9, 0, 9), (12, 0...
You can do: out = [ (x, y, z) for y in range(10) if y % 2 == 0 for z in range(20) if z % 3 == 0 for x in [y + z] # <-- initialize `x` in list-comprehension ] This is optimized since Python 3.9: https://docs.python.org/3/whatsnew/3.9.html#optimizations
3
5
78,974,383
2024-9-11
https://stackoverflow.com/questions/78974383/how-can-i-build-distribute-install-python-packages-with-limited-access-to-pa
At my workplace pip is not able to access the outside world to download packages. I'm not sure what system exactly is preventing this, but ideally I shouldn't be installing any old packages from the internet anyway. The only way I can install packages from online is to download a source distribution or wheel from the P...
In my situation it seems that the most straightforward course of action is to ignore the fact that directly using setup.py is discouraged and do it anyway. With setup.py importing setup from setuptools I'm able to build a package that can be installed with pip by running python setup.py sdist Of the suggestions in the ...
2
0
78,975,219
2024-9-11
https://stackoverflow.com/questions/78975219/maintaining-order-in-polars-data-frame-after-partition-by
Does polars.DataFrame.partition_by preserves the order of rows within each group? I understand that group_by does, even when maintain_order=False. From documentation: Within each group, the order of rows is always preserved, regardless of this argument. But nothing is mentioned for the partition_by operation. I guess t...
partition_by is implemented by just doing a group_by and extracting the groups into separate DataFrames. I see no reason why we would change that, so I think it's safe to assume the order within each group is preserved, at least with the default arguments. I'll see if we can get the docs to match group_by's docs in tha...
2
2
78,975,044
2024-9-11
https://stackoverflow.com/questions/78975044/quickest-way-to-iterate-over-a-pandas-dataframe-and-perform-an-operation-on-a-co
I have a table that is laid out somewhat like this: t linenum many other columns 1234567 0 ... 1234568 0 ... 1234569 0 ... 1234570 1 ... 1234571 1 ... Except it is very, very large. As in, the raw .dat files can get up to 20 gb. I have them converted into .h5 files so they are slightly smaller, but st...
You can use a groupby on 'linenum' and then transform to populate each group df['timewithinline'] = df.groupby('linenum')['t'].transform(lambda x: x - min(x)) If the times are already sorted, you can use: df['timewithinline'] = df.groupby('linenum')['t'].transform(lambda x: x - x.iloc[0])
3
3
78,974,451
2024-9-11
https://stackoverflow.com/questions/78974451/how-to-map-scores-from-one-table-to-another-when-the-cell-contains-operators
I performed OLS regression on a dataset and I have the predicted Diagnostic_Score but the mapping table (norms) can have two operators - e.g. >= and <=. Is there a way to map the predicted score to the percentile? My first thought was to map the scores that I can match and the ones that do not match I know must to be a...
You can extract the prefix and perform a merge and a merge_asof: # add group/score norms[['group', 'Predicted Score']] = ( norms['Diagnostic_Score'] .astype(str) .str.extract(r'([<>]=|)(\d+)') .astype({1: 'int'}) ) # ensure scores are sorted (for the merge_asof) norms.sort_values(by='Predicted Score', inplace=True) # d...
2
2
78,973,393
2024-9-11
https://stackoverflow.com/questions/78973393/pandas-rename-function-not-working-within-jupyter-notebook
I have a pandas dataframe ('df3') which columns I would like to rename.It is a subset of another dataframe, and I'm working in a jupyter notebook. Getting all infos from the dataframe structure: df3.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 29 entries, 104 to 132 Data columns (total 15 columns): # Column...
If need rename by index of columns set values in list comprehension: df.columns = [col_names.get(i, i) for i in range(len(df.columns))] Or: df.columns = pd.Series(range(len(df.columns))).replace(col_names) If need set first N values by values of dictionary: df.columns = list(col_names.values())[:len(df.columns)] But...
2
2
78,972,997
2024-9-11
https://stackoverflow.com/questions/78972997/how-to-use-threading-in-python-in-an-unblocking-way
I have a complete "working" python code which is supposed to contain two threads which run simultaneously, which populate some lists in a dict, and when the user presses CRTL-C these two threads should be stopped and some output from both threads should be written to a file: import sys import time import threading impo...
Apart from various typos (forgotten import json and threads=[]) the main problem is in t = threading.Thread(target=handler.run()). The target parameter is expected to be a function object, not the result of the call of that function. Here this code immediately calls the never ending function to assign its never coming ...
2
2
78,972,018
2024-9-11
https://stackoverflow.com/questions/78972018/polars-replacing-values-of-other-groups-to-the-values-of-a-certain-group
I have the following Polars.DataFrame: df = pl.DataFrame( { "timestamp": [1, 2, 3, 1, 2, 3], "var1": [1, 2, 3, 3, 4, 5], "group": ["a", "a", "a", "b", "b", "b"], } ) print(df) out: shape: (6, 3) ┌───────────┬──────┬───────┐ │ timestamp ┆ var1 ┆ group │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str │ ╞═══════════╪══════╪═══════...
I think for generic solution your approach with join works fine, you could probably try something like this as well: filter() to filter var1 column to leave only values where group == a first() to get the value. over() to limit it to certain timestamp. coalesce() to fallback to actual value if value for group == a doe...
2
1
78,971,919
2024-9-11
https://stackoverflow.com/questions/78971919/error-when-executing-regular-expression-with-python
the file "catalogo_no_linebreak.txt" contains a list of products, grouped in one line, i'am using the regular expression (re.split()) to try Retrieve the record of each product and logo after saving to the "saida.txt" file. The txt_format() function is where I process and use the regular expression "result = re.split(r...
This code assumes that each product line starts with an ID of the same format. then separate the text using the ID and print the ID and Content without line breaks Solution import re content = """ 0453.000045-00453.213.00022733-0UMA ALIANÇA, DE: OURO, OURO BRANCO; CONSTAM: amolgada(s), PESOLOTE: 4,40G (QUATRO GRAMAS E ...
2
3
78,971,681
2024-9-11
https://stackoverflow.com/questions/78971681/how-can-i-import-polars-type-definitions-like-joinstrategy
JoinStrategy is an input to join: https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.join.html My static type checking tool seems to be able to get a hold of JoinStrategy, but I'm not sure how/from where. Usually, type stub packages are available on PyPI, but nothing obvious stands out in ...
Types can be provided by one of two things: a separate type package, and by the same package. In this case it's being provided by the same package. If you read the source code, you can find where the type comes from. Example: from polars._typing import JoinStrategy Note that _typing denotes that this is part of the Po...
4
4
78,957,805
2024-9-6
https://stackoverflow.com/questions/78957805/packing-python-wheel-with-pybind11-using-bazel
I am trying to generate a wheel file using bazel, for a target that has pybind dependencies. The package by itself works fine (though testing), but when I'm packing it, the .so file is missing from the site_packges folder. This is my build file: load("@pybind11_bazel//:build_defs.bzl", "pybind_extension") load("@python...
try deps = [":example.so"]
3
1
78,964,057
2024-9-9
https://stackoverflow.com/questions/78964057/can-i-perform-a-bit-wise-group-by-and-aggregation-with-polars-or
Let's say I have an auth field that use bit flags to indicate permissions (example bit-0 means add and bit-1 means delete). How do I bitwise-OR them together? import polars as pl df_in = pl.DataFrame( { "k": ["a", "a", "b", "b", "c"], "auth": [1, 3, 1, 0, 0], } ) The dataframe: df_in: shape: (5, 2) ┌─────┬──────┐ │ k ...
Update. Bitwise aggregation was implemented in version 1.9.0. So now you can use pl.Expr.bitwise_or(): ( df_in .group_by("k", maintain_order=True) .agg(pl.col.auth.bitwise_or()) ) shape: (3, 2) ┌─────┬──────┐ │ k ┆ auth │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═════╪══════╡ │ a ┆ 3 │ │ b ┆ 1 │ │ c ┆ 0 │ └─────┴──────┘ Previous...
3
2
78,960,111
2024-9-7
https://stackoverflow.com/questions/78960111/singular-matrix-during-b-spline-interpolation
According to the literature about B Splines, including Wolfram Mathworld, the condition for Cox de Boor's recursive function states that: In python, this would translate to: if (d_ == 0): if ( knots_[k_] <= t_ < knots_[k_+1]): return 1.0 return 0.0 where: d_: degree of the curve knots_: knot vector k_: index of the ...
The mathematical condition is the correct one, B-Spline basis functions are defined on a half-open interval. However, it presents a problem when the knot vector is clamped, as you show in your example. The problem is that in this case the mathematical function isn't defined at t=1, and the result in the code is that it...
2
2
78,970,312
2024-9-10
https://stackoverflow.com/questions/78970312/supabase-python-client-returns-an-empty-list-when-making-a-query
My configuration is very basic. A simple supabase database with one table. I use supabase-py to interact with it. The problem is that I always get an empty list : from supabase import create_client URL = "MY_URL_HERE" API_KEY = "MY_API_KEY_HERE" supabase = create_client(URL, API_KEY) response = supabase.table("prod_vxf...
Does it mean that anyone on the internet (even without knowing url + api key) can access (read and write) my database and its tables ? It's publicly as in the database role PUBLIC: The special “role” name PUBLIC can be used to grant a privilege to every role on the system. That is every role inside that db, not the...
3
2
78,964,911
2024-9-9
https://stackoverflow.com/questions/78964911/optapy-hard-constraint-is-not-respected-in-a-vrp
I am just starting using OptaPy, I tried to mimic the VRP quickstart and created the classes as such: # The place to start the journey and end it. @problem_fact class Depot: def __init__(self, name, location): self.name = name self.location = location def __str__(self): return f'Depot {self.name}' # The customers infor...
The problem was that the model cannot relax the problem, so instead of breaking it returned unreasonable results, When I gave it 1 vehicle and 50 orders and the vehicle capacity was 26, it assigned all the 50 orders on that vehicle. But when I increased vehicles to 2, it found a feasible solution and returned 26, 24 re...
2
0
78,966,048
2024-9-9
https://stackoverflow.com/questions/78966048/how-to-change-background-color-of-st-text-input-in-streamlit
I am trying to change the background color of st.text_input() box but unable to do so. I am not from web/app development background or with any html css skills so please excuse my naive or poor understanding in this field. So far I have tried: using this link test_color = st.write('test color') def text_input_color(url...
I wouldn't rely on classes like .st-bd, .st-bb, or .st-b7 they are dynamically generated by Streamlit and can change (versions or runs). I would rather use aria-label. import streamlit as st st.markdown(""" <style> .stTextInput input[aria-label="test color"] { background-color: #0066cc; color: #33ff33; } .stTextInput ...
2
1
78,955,489
2024-9-6
https://stackoverflow.com/questions/78955489/odoo-models-linking-issues-self-id-giving-unknown43
I'm working with Odoo 16 and have encountered a problem with linking two models and handling _unknown values. Specifically, I have two models: nkap_custom_paiement and account.payment.register. The former is a custom model inheriting from account.payment, and the latter is a TransientModel used for payment registration...
That's just a typo on your class nkap_custom_paiement. The comodel for the field related_payment_id is account.payment.register and not account.register.payment. If Odoo can't find the related model on e.g. a Many2one field in its model pool, it will fill it with model name _unknown (click) def setup_nonrelated(self, m...
2
0
78,960,340
2024-9-7
https://stackoverflow.com/questions/78960340/how-can-i-follow-an-http-redirect
I have 2 different views that seem to work on their own. But when I try to use them together with a http redirect then that fails. The context is pretty straightforward, I have a view that creates an object and another view that updates this object, both with the same form. The only thing that is a bit different is tha...
My bad. I use initial=initial_data in the POST part of the create view. Which makes no sense. When moving the initial=initial_data to the GET part then it works. The test_update_resource_from_non_origin_site_and_redirect test still fails though. I'm going to investigate since the feature works fine from within the web ...
3
0
78,971,305
2024-9-10
https://stackoverflow.com/questions/78971305/how-can-i-optimize-the-performance-of-this-numpy-function
Is there any way optimizing the performance speed of this function? def func(X): n, p = X.shape R = np.eye(p) delta = 0.0 for i in range(100): delta_old = delta Y = X @ R alpha = 1. / n Y2 = Y**2 Y3 = Y2 * Y W = np.sum(Y2, axis=0) transformed = X.T @ (Y3 - (alpha * Y * W)) U, svals, VT = np.linalg.svd(transformed, full...
I tried to rewrite some stuff to speed things up. The only things I changed (apart from some formatting maybe) were removing the computation of the unused delta, pulling the transposition of X out of the loop as well as factorizing out the multiplication with Y for the computation of transformed which results in one fe...
3
2
78,971,412
2024-9-10
https://stackoverflow.com/questions/78971412/how-to-measure-new-change-in-data
Suppose you have this dataframe d = {'date':['2019-08-25', '2019-09-01', '2019-09-08'], 'data':[31, 31, 31]} df_sample = pd.DataFrame(data=d) df_sample.head() and you want to measure how much new data comes in on average each week. For example, we had 31 new rows on 8/25 and then on 9/1 we got an additional 31 rows so...
If your data is cumulative, you need a cumsum before pct_change: df_sample['change'] = df_sample['data'].cumsum().pct_change().mul(100) Output: date data change 0 2019-08-25 31 NaN 1 2019-09-01 31 100.0 2 2019-09-08 31 50.0 Intermediate: date data cumsum change 0 2019-08-25 31 31 NaN 1 2019-09-01 31 62 100.0 2 2019...
2
2
78,966,115
2024-9-9
https://stackoverflow.com/questions/78966115/how-to-correctly-use-ctypes-get-errno
I'm trying to test some binary library with ctypes and some of my tests involve errno. I'm therefore trying to retrieve it to check the error cases handling but when trying to use ctypes.get_errno() I weirdly get 0 as errno ("Success") which isn't what I was expecting. Why does this occur? Is ctypes.get_errno() actuall...
Unlike your handwritten get_errno, ctypes get_errno does not access the os errno value, but a private copy that is filled after certain function calls. The docs state: [...] a ctypes mechanism that allows accessing the system errno error number in a safe way. ctypes maintains a thread-local copy of the systems errno v...
2
4
78,967,924
2024-9-10
https://stackoverflow.com/questions/78967924/polars-cumsum-alternatives
I have below pandas snippet which I want to convert to polars to try, Expected output for polars is same as pandas but failing as cumsum is missing, how to achieve similar output?: import pandas as pd import numpy as np data = { 'date': pd.date_range(start='2024-09-01', periods=12), 'reserved_before': [0, 1, 2, np.nan,...
Here's one approach: import polars as pl from datetime import date pl_df = pl.DataFrame({ 'date': pl.date_range(start=date(2024, 9, 1), end=date(2024, 9, 12), interval='1d', eager=True), 'reserved_before': [0, 1, 2, None, None, 1, 2, 3, None, 3, 4, 5] }) groups = pl.col('reserved_before').is_not_null().rle_id() pl_df =...
2
3
78,968,248
2024-9-10
https://stackoverflow.com/questions/78968248/counting-number-of-separate-events-in-dataframe
I am trying to count the number of separate events in a Dataframe (not number of occurences) Let's say i have this dataframe : df = pd.DataFrame([1, 2, 2, 2, 1, 1, 1, 1, 2, 1], columns=["events"]) And i want to count the number of separate events. If i use df.value_counts() It' going to give me the number of occurenc...
Craft a mask (with shift and ne) to remove the successive duplicates and value_counts: df.loc[df['events'].ne(df['events'].shift()), 'events'].value_counts() Output: events 1 3 2 2 Name: count, dtype: int64
2
2
78,966,219
2024-9-9
https://stackoverflow.com/questions/78966219/smoothing-out-the-sharp-corners-and-jumps-of-a-piecewise-regression-load-displac
I am having a stubborn problem with smoothing out some sharp corners that the simulation software does not really like. I have the following displacement/ load/ damage vs step/time: The source data can be found here. Here's the code for importing the data and plotting the above plot: df = pd.read_csv("ExampleforStack....
Simplest solution is apply a low pass filter to your sharp cornered function(s). Convolving it with a Gaussian with an appropriate width should give it all of the smoothness properties that you desire. The data are so finely spaced that you might even be able to get away with a simple boxcar average over 11-21 samples ...
1
2
78,963,645
2024-9-9
https://stackoverflow.com/questions/78963645/tkinter-progress-bar-works-on-linux-but-not-on-windows
I wrote the following basic code sample that creates a main window with a button. When the button is pressed a second window with a progress bar should appear and stay open until the progress is complete. This works fine on Linux but on Windows the second window appears blank with no progress bar. Given that this will ...
Thanks to @acw1668 who pointed out in the comments that .update_idletasks() may not handle pending creation of widgets. Adding pb.update() or also pb.wait_visibility(pw) before pb.pack() will ensure the creation and visibility of the progress window and bar. Documentation here
2
1
78,965,088
2024-9-9
https://stackoverflow.com/questions/78965088/using-gekko-to-optimize-two-matrix-vector-equations
I wanted to use Gekko to solve an optimization (production mix) problem, I have a few numpy arrays, which I want to use in some vectorized equation. They idea is, I have two simple matrix equations: Ax < b and Cx = y Where I will use previously prepared (const) numpy arrays for A,b,C. Also, Y is a variable (int). X is ...
Here is an example with sample values for A, b, and C. import numpy as np from gekko import GEKKO # Initialize model m = GEKKO(remote=False) # Given matrices and constants A = np.array([[1, 2], [3, 4]]) # Example matrix A b = np.array([55, 41]) # Example vector b C = np.array([2, 3]) # Example row vector C # Constraint...
2
0
78,964,171
2024-9-9
https://stackoverflow.com/questions/78964171/how-to-use-the-input-of-a-field-only-if-it-is-visible
How do I manage that an input field value is empty, if it is not shown. In the example the text caption field is empty and not shown. If I show it by ticking "Show text caption field" and enter any text, the text appears in the output field. If I then untick "Show text caption field" the output field should also be emp...
Here you can extend the render.text such that the displayed value of the ui.output_text_verbatim is input.caption() if input.show() else "": from shiny import App, Inputs, Outputs, Session, render, ui app_ui = ui.page_fluid( ui.input_checkbox("show", "Show text caption field", False), ui.panel_conditional( "input.show"...
2
0
78,966,184
2024-9-9
https://stackoverflow.com/questions/78966184/how-can-i-inverse-a-slice-of-an-array
I want to do something along the lines of... import numpy as np arr = np.linspace(0, 10, 100) s = slice(1, 10) print(arr[s]) print(arr[~s]) How could I apply the "not" operator to a slice, so that in this case arr[~s] would be the concatenation of arr[0] and arr[10:]?
np.delete will do what you want: np.delete(arr, s) For something more complex than a slice, you may want to store the index. To do that, you can invert a mask built from the slice: mask = np.ones(arr.shape, dtype=bool) mask[s] = False arr[mask] OR mask = np.zeros(arr.shape, dtype=bool) mask[s] = True arr[~mask] You ...
1
5
78,963,578
2024-9-9
https://stackoverflow.com/questions/78963578/dataclass-inheriting-using-kw-only-for-all-variables
I am practicing on using the super function and dataclass inheritance in general. I have enabled the kw_only attribute for cases when the parent class has default values. I completely understand that super doesn't need to be used in a dataclass if you're just passing variables and I can avoid using super here. My goal ...
You shouldn't define an __init__ method in a data class if you don't have any custom initialization logics. And if you do have custom initialization logics, you should define them in a __post_init__ method instead. Your code produces the error because the __init__ method of the subclass calls the __init__ method of the...
1
4
78,963,338
2024-9-8
https://stackoverflow.com/questions/78963338/polars-transform-string-containing-key-values
Trying to figure out how to transform a k-v string that is inside a column where the k-v string is separated by commas, and could contain different keys. The different keys would then be transformed into their own columns, where missing values would contain nulls. For example, pl.DataFrame({ "apple": [1, 2, 3], "data":...
You could attempt to reformat it as JSON objects. df.with_columns(pl.format('{"{}"}', pl.col("data").str.replace_many({"=": '":"', ", ": '","'}) )) shape: (3, 3) ┌───────┬──────────────┬───────────────────────┐ │ apple ┆ data ┆ literal │ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str │ ╞═══════╪══════════════╪═════════════════...
2
1
78,962,922
2024-9-8
https://stackoverflow.com/questions/78962922/add-transition-argument-after-must-be-a-mapping-not-str-transitions-py
I just try make simple graph with transitions library : from transitions.extensions.diagrams import HierarchicalGraphMachine from IPython.display import display, Markdown states = ['engoff' , 'poweron' , 'engon' , 'FCCActions' #'emgstatus' , "whevent" , 'new data receive' ,{'name' : 'cores', 'final': True, 'parallel' :...
This value: 'transitions': ['CalculateandLearning', 'newdata', 'done!'] should be wrapped in another list: 'transitions': [['CalculateandLearning', 'newdata', 'done!']] Full source code: from transitions.extensions.diagrams import HierarchicalGraphMachine from IPython.display import display, Markdown states = ['eng...
2
2
78,962,124
2024-9-8
https://stackoverflow.com/questions/78962124/daytime-and-nightime-occurrence-duration-of-an-event
I want to find the daytime and night-time occurrence duration of an event from its' start time to end time. The event duration is volatile and can take place for a long time. I can't figure out a formula. I am seeking to figure out the duration with a formula or VBA code or Python code. Link to the sample file with man...
If you find it hard to calculate NightTime, I suggest you calculate DayTime first, and use TotalHourse - DayTime for night time, then you wouldn't need to worry about "crossing midnight". So, for day time duration, here is the formula (in K10) =(INT(E10)-INT(D10))*(F10-G10)-MEDIAN(MOD(D10,1),G10,F10)+MEDIAN(MOD(E10,1),...
3
6
78,953,580
2024-9-5
https://stackoverflow.com/questions/78953580/run-anthropic-api-in-parallel
I successfully ran OpenAI GPT4o in parallel with multiprocessing: def llm_query(chunk): context, query = get_prompt_synonyms() input1, output1 = get_example() response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": context}, {"role": "user", "content": f'Input data is {input1...
I usually use ThreadPoolExecutor. Minimal example from anthropic import Anthropic from concurrent.futures import ThreadPoolExecutor TEMPERATURE = 0.5 CLAUDE_SYSTEM_MESSAGE = "You are a helpful AI assistant." anthropic_client = Anthropic(api_key=ANTHROPIC_API_KEY) def call_anthropic( prompt, model_id="claude-3-haiku-202...
2
0
78,958,965
2024-9-6
https://stackoverflow.com/questions/78958965/how-do-i-read-a-struct-contents-in-a-running-process
I compiled a C binary on a linux machine and executed it, in that binary I have a struct called Location defined as follows typedef struct { size_t x; size_t y; } Location; and here is my main function int main(void) { srand(0); Location loc; while (1) { loc.x = rand()%10; loc.y = rand()%10; sleep(2); } return 0; } H...
We know the location is located in the stack somewhere, open maps file calculated stack size, start and end address, then open memory file in bytes mode and read stack bytes, loop over the bytes until you find a bytes sequence that maps to a given struct. PS I have to add a third attribute to struct for sake of making ...
4
2
78,947,404
2024-9-4
https://stackoverflow.com/questions/78947404/can-the-superres-module-in-opencv-only-be-used-in-c
I have built OpenCV4 on Windows 11. When I attempt to use the superres module by Python, I encountered an error: module 'cv2' has no attribute 'superres' import cv2 model = cv2.superres.createSuperResolution_BTVL1() I had included the superres module when building OpenCV. Cmake info: Then I found using C++ is ok. So ...
The Python wrappers for OpenCV are generally automatically generated (there are some hand-written ones, but that's a tiny fraction). In order for this to happen, annotations in form of macros have to present in the header file(s) of the respective module. For free-standing functions and classes this is usually CV_EXPOR...
2
2
78,956,628
2024-9-6
https://stackoverflow.com/questions/78956628/static-type-checking-or-ide-intelligence-support-for-a-numpy-array-matrix-shape
Is it possible to have static type checking or IDE intelligence support for a numpy array/matrix shape? For example, if I imagine something like this: A_MxN: NDArray(3,2) = ... B_NxM: NDArray(2,3) = ... Even better would be: N = 3 M = 2 A_MxN: NDArray(M,N) = ... B_NxM: NDArray(N,M) = ... And if I assign A to B, I wou...
It's possible to type the shape of an array, like was mentioned before. But at the moment (numpy 2.1.1), the shape-type of the ndarray is lost in most of numpys own functions. But the shape-typing support is gradually improving, and I'm actually personally involved in this. But that doesn't mean that you can't use shap...
2
4
78,960,741
2024-9-7
https://stackoverflow.com/questions/78960741/offset-points-in-matplotlib-pyplot-annotate-gives-unexpected-results
I am using the following code to generate a plot with a sine curve marked with 24 'hours' over 360 degrees. Each 'hour' is annotated, however the arrow lengths decrease (shrivel?) with use and even their direction is incorrect. The X axis spans 360 degrees whereas the Y axis spans 70 degrees. The print statement verifi...
By default the text is aligned at its bottom left corner. You might want to change this to align at its centre. ax.annotate(str(i), xy=(hr_x[i], hr_y[i]), xytext=(arrow_x, arrow_y), xycoords='data', textcoords='offset points', arrowprops=arrow_style, verticalalignment='center', horizontalalignment='center')
2
5
78,957,889
2024-9-6
https://stackoverflow.com/questions/78957889/avoiding-double-for-loops-with-polars
I am trying to use Polars to determine revenue forecast for many products. I have these product names and prices and current revenues based on these prices. Some of these products' revenues are not direct multiplication of quantity and prices but involve a complicated function (distributor percentage etc and more) so I...
transpose() to convert pixies_df rows to columns. join() to link it to main_df. main_df.join( pixies_df .transpose( include_header=True, header_name="xxx", column_names = list(map(str, range(pixies_df.height))) ), on="xxx" ) ┌─────┬───────┬─────┬─────┬─────┐ │ xxx ┆ price ┆ 0 ┆ 1 ┆ 2 │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │...
2
1
78,958,661
2024-9-6
https://stackoverflow.com/questions/78958661/merge-two-dataframes-with-only-one-column
I would like to merge two dataframes which have only one column say df1 and df2 as below. Expected output dataframe as df3. import pandas as pd data1 = [ 'A', 'B', 'C'] df1 = pd.DataFrame(data1,columns=['name']) data2 = [ 'B', 'C', 'D'] df2 = pd.DataFrame(data2,columns=['name']) data3 = [ ['A',], ['B','B'], ['C','C'], ...
Quick hack, you could merge passing one of the keys as Series: df1.merge(df2, left_on='name', right_on=df2['name'], how='outer').drop(columns='name') Output: name_x name_y 0 A NaN 1 B B 2 C C 3 NaN D If you don't drop you'll also get a column with the merged values: df1.merge(df2, left_on='name', right_on=df2['name'...
2
2
78,955,298
2024-9-6
https://stackoverflow.com/questions/78955298/python-opencv-draws-polygons-outside-of-lines
[edited] It appears there is a new bug in opencv that introduces an issue causing fillPoly's boundaries to exceed polylines's. Here is humble code to draw a red filled polygon with a blue outline. import cv2 import numpy as np def draw_polygon(points, resolution=50): # create a blank black canvas img = np.zeros((resolu...
Where there's a will there's a way. fillPoly appears to be able to draw as a line when given only two vertices. And that line matches the edges of the previously drawn polygon. \o/ I modified my code to draw the edges as a single fillPoly call and it seems to work decently. I would still prefer if fillPoly and polyLine...
3
4
78,956,204
2024-9-6
https://stackoverflow.com/questions/78956204/selenium-failed-to-download-document
I am currently working on a web scraper and each time i am trying to click or try to get the href of a certain link button with it, it gives me absolutly nothing. However, I tried and I must point out that when I go to the website myself, the link which i need to click works and the data is accessible but when i'm am u...
You can get the pdf link from the static html, no need for selenium: import requests from bs4 import BeautifulSoup from urllib.parse import urljoin import os def extract_pdf_link(url): response = requests.get(url, headers=HEADERS) soup = BeautifulSoup(response.text, 'html.parser') pdf_url = urljoin(url, soup.select_one...
2
2
78,958,489
2024-9-6
https://stackoverflow.com/questions/78958489/sort-a-list-of-objects-based-on-the-index-of-the-objects-property-from-another
I have a tuple, RELAY_PINS that holds GPIO pin numbers in the order that the relays are installed. RELAY_PINS is immutable, and its ordering does not change, while the order that the devices are defined in changes frequently. The MRE: from random import shuffle, randint class Device: def __init__(self, pin_number): sel...
You can use sorted with a key function: from random import randint, shuffle class Device: def __init__(self, pin_number: int): self.pin_number = pin_number def __str__(self) -> str: return str(self.pin_number) def __repr__(self) -> str: return f'Device(pin_number={self.pin_number})' RELAY_PINS: tuple[int, ...] = (14, 1...
2
1
78,957,769
2024-9-6
https://stackoverflow.com/questions/78957769/pandas-2-0-3-problems-keeping-format-when-file-is-saved-in-json-or-csv-format
Here is some random code. # create df import pandas as pd df2 = pd.DataFrame({'var1':['1_0','1_0','1_0','1_0','1_0'], 'var2':['X','y','a','a','a']}) df2.to_json('df2.json') # import df df2 = pd.read_json('df2.json') df2 This is the expected output: var1 var2 0 1_0 X 1 1_0 y 2 1_0 a 3 1_0 a 4 1_0 a However it generat...
This is due to the fact that underscores are valid separators in python (often used as thousand separator: 1_000 is 1000). You could force the dtype upon import (or use dtype=False): df2 = pd.read_json('df2.json', dtype='str') If you want to keep dtype detection for the other columns: df2 = pd.read_json('df2.json', dt...
3
4
78,955,408
2024-9-6
https://stackoverflow.com/questions/78955408/specify-attributes-in-constructor-in-python
I'm confused about the differences of the following codes: class car: def __init__(self, weight): self.weight = weight class car: def __init__(self, weight): self.weight = 0 class car: def __init__(self, weight=0): self.weight = weight class car: def __init__(self, weight=0): self.weight = 0 class car: def __init__(sel...
You get confused by concepts of function arg, default value for the arg, and member variable, you are mixing them so badly. Function argument For def __init__(self,weight) you are expecting a variable passed in when calling the constructor, which is given the name "weight". It is a function argument. Default value f...
2
2
78,957,463
2024-9-6
https://stackoverflow.com/questions/78957463/convert-empty-lists-to-nulls
I have a polars DataFrame with two list columns. However one column contains empty lists and the other contains nulls. I would like consistency and convert empty lists to nulls. In [306]: df[["spcLink", "proprietors"]] Out[306]: shape: (254_654, 2) ┌───────────┬─────────────────────────────────┐ │ spcLink ┆ proprietor...
selectors.by_dtype to select all columns of type pl.List(pl.String). list.len() to determine if list is empty. df = pl.DataFrame({ "spcLink": [[],[]], "proprietors": [None,["xxx"]] }, schema={"spcLink": pl.List(pl.String), "proprietors": pl.List(pl.String)}) ┌───────────┬─────────────┐ │ spcLink ┆ proprietors │ │ ---...
3
2
78,953,307
2024-9-5
https://stackoverflow.com/questions/78953307/assertdataframeequal-doesnt-throw-error-with-none-dataframe-in-pyspark
When I try to assert a dataframe using the PySpark API, if a dataframe is none, I do not get the assertion error, but instead, the method returns false. Is it a bug, or should I handle my test verification differently? from pyspark.testing.utils import assertDataFrameEqual assertDataFrameEqual(spark.createDataFrame([("...
When running the code you run, I do get an error for your code: [INVALID_TYPE_DF_EQUALITY_ARG] Expected type Union[DataFrame, ps.DataFrame, List[Row]] for `expected` but got type None. I do not see why this could be different for you: all versions containing this function start with the same check for None values, as ...
2
2
78,957,022
2024-9-6
https://stackoverflow.com/questions/78957022/apply-multiple-window-sizes-to-rolling-aggregation-functions-in-polars-dataframe
In a number of aggregation function, such as rolling_mean, rolling_max, rolling_min, etc, the input argument window_size is supposed to be of type int I am wondering how to efficiently compute results when having a list of window_size. Consider the following dataframe: import polars as pl pl.Config(tbl_rows=-1) df = pl...
You can use comprehension to generate a DataFrame for each value in periods list and then concat() DataFrames into single long DataFrame: periods = [2, 3] pl.concat( df.with_columns( mean_period = pl.lit(p), rolling_mean = pl.col.price.rolling_mean(p).over("symbol") ) for p in periods ) ┌────────┬───────┬─────────────┬...
2
1
78,957,012
2024-9-6
https://stackoverflow.com/questions/78957012/itertools-product-in-dataframe
Inputs: arr1 = ["A","B"] arr2 = [[1,2],[3,4,5]] Expected output: short_list long_list 0 A 1 1 A 2 2 B 3 3 B 4 4 B 5 Current output: short_list long_list 0 A [1, 2] 1 A [3, 4, 5] 2 B [1, 2] 3 B [3, 4, 5] Current Code (using itertools): import pandas as pd from itertools import produc...
IIUC use DataFrame contructor with DataFrame.explode: arr1 = ["A","B"] arr2 = [[1,2],[3,4,5]] df = (pd.DataFrame({'short_list':arr1, 'long_list':arr2}) .explode('long_list') .reset_index(drop=True)) print (df) short_list long_list 0 A 1 1 A 2 2 B 3 3 B 4 4 B 5 Another idea is use flattening zipped arrays to list of tu...
2
2
78,956,588
2024-9-6
https://stackoverflow.com/questions/78956588/polars-selector-for-columns-of-dtype-pl-list
In the polars documentation regarding selectors, there are many examples for selecting columns based on their dtypes. I am missing pl.List How can I quickly select all columns of type pl.List within a pl.DataFrame?
At the moment it's not possible to select all lists with selectors, but if you have lists of specific type, you can do it: df.select(cs.by_dtype(pl.List(pl.Int64)))
5
3
78,955,998
2024-9-6
https://stackoverflow.com/questions/78955998/add-new-column-with-multiple-literal-values-to-polars-dataframe
Consider the following toy example: import polars as pl pl.Config(tbl_rows=-1) df = pl.DataFrame({"group": ["A", "A", "A", "B", "B"], "value": [1, 2, 3, 4, 5]}) print(df) shape: (5, 2) ┌───────┬───────┐ │ group ┆ value │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═══════╪═══════╡ │ A ┆ 1 │ │ A ┆ 2 │ │ A ┆ 3 │ │ B ┆ 4 │ │ B ┆ 5 │ └──...
You could assign it as a column and .explode() df.with_columns(indicator=vals).explode("indicator") shape: (15, 3) ┌───────┬───────┬───────────┐ │ group ┆ value ┆ indicator │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞═══════╪═══════╪═══════════╡ │ A ┆ 1 ┆ 10 │ │ A ┆ 1 ┆ 20 │ │ A ┆ 1 ┆ 30 │ │ A ┆ 2 ┆ 10 │ │ A ┆ 2 ┆ 20 │...
2
1
78,956,523
2024-9-6
https://stackoverflow.com/questions/78956523/valueerror-could-not-use-apoc-procedures-please-ensure-the-apoc-plugin-is-inst
I'm trying to use the Neo4jGraph class from the langchain_community.graphs module in my Python project to interact with a Neo4j database. My script here: from langchain.chains import GraphCypherQAChain from langchain_community.graphs import Neo4jGraph from langchain_openai import ChatOpenAI enhanced_graph = Neo4jGraph(...
This is a known error: copy this file 'apoc-5.14.0-core.jar' from /var/lib/neo4j/labs/ to /var/lib/neo4j/plugins update this file /var/lib/neo4j/conf/neo4j.conf dbms.security.procedures.unrestricted=apoc.* dbms.security.procedures.allowlist=apoc.* Git link with solutions : https://github.com/langchain-ai/langchain/...
2
3
78,948,684
2024-9-4
https://stackoverflow.com/questions/78948684/why-does-the-size-of-a-python-struct-depend-on-the-endianess
Why does the size of a struct change if endianness is specified, notably even when the endianness matches the native endianness of the platform? Example: >>> import struct >>> struct.calcsize("BI") 8 >>> struct.calcsize(">BI") 5 >>> struct.calcsize("<BI") 5 >>> Why is the extra padding added?
If byte ordering is not specified then it's implicitly "@" in which case both the size and alignment are native. See the "Format Strings" section of this document. You will note that "@" is the only format string prefix that forces alignment. The format character "I" denotes an unsigned integer which has a size of 32 b...
3
1
78,949,086
2024-9-4
https://stackoverflow.com/questions/78949086/install-a-pre-release-version-of-python-on-m1-mac-using-conda
I would like to install python 3.13.0rc1 with conda on an M1 Mac. However, conda create fails with error message "python 3.13.0rc1** is not installable because it requires _python_rc, which does not exist (perhaps a missing channel)": % conda search python ... python 3.12.4 h99e199e_1 pkgs/main python 3.12.5 h30c5eda_0...
python_rc is under the python_rc label, seehere, you can specify it directly in your command line like this: conda create --name py python=3.13.0rc1 conda-forge/label/python_rc::_python_rc --channel conda-forge --override-channels
2
3
78,955,088
2024-9-5
https://stackoverflow.com/questions/78955088/what-does-mean-to-numpy-apply-along-axis-and-how-does-it-differ-from-0
I was trying to get a good understanding of numpy apply along axis. Below is the code from the numpy documentation (https://numpy.org/doc/stable/reference/generated/numpy.apply_along_axis.html) import numpy as np def my_func(a): """Average first and last element of a 1-D array""" return (a[0] + a[-1]) * 0.5 b = np.arra...
In summary: Given the above context, what is the difference between () and 0? The first one represents a zero dimensional array with one element. The second one represents a one dimensional array with zero elements. A zero dimensional array always has a single element. Example: >>> array = np.array(42) >>> array arra...
3
4
78,954,564
2024-9-5
https://stackoverflow.com/questions/78954564/how-to-structure-python-package-to-allow-for-testing
I'm having trouble being able to get my code to be executable and testable. Here's my project's file structure: project/ ├── .pytest_cache/ │ ├── src/ │ ├── __init__.py | ├── .pytest_cache/ │ ├── module1.py │ └── module2.py │ ├── tests/ | ├── .pytest_cache/ | ├── __init__.py | └── test_module.py | ├── venv/ where both...
Before diving into testing, ensure your project is structured properly. Project Structure Your src/ directory should contain a subdirectory with the name of your module: super-cool-module/ ├── src/ │ └── super_cool_module/ │ ├── __init__.py │ ├── submodule1.py │ └── submodule2.py ├── tests/ │ ├── __init__.py │ ├── test...
2
2
78,953,917
2024-9-5
https://stackoverflow.com/questions/78953917/why-are-aes-256-cbc-results-in-php-and-python-different-when-using-the-same-keys
I'm trying to encrypt the same string in PHP and Python using AES-256-CBC with the same keys and IVs. However, the results of both languages ​​are different, even though I am using the same encryption method and the same data. In PHP, I am using openssl_encrypt, while in Python I am using pycryptodome with PKCS7 paddin...
The php hash function returns a hexadecimal representation of the bytes, so cutting 16 characters of that with substr leads to "20139ebeee312271" for your IV (similar result for key). These are not true bytes, they're characters in the range [0-9a-f]. This is not what you intend to do. The Python sha256 .digest() funct...
2
3
78,953,646
2024-9-5
https://stackoverflow.com/questions/78953646/creating-json-style-api-call-dict-from-pandas-df-data
Scenario: I have a dataframe which contains one row of data. Each column is an year and it has the relevant value. I am trying to use the data from this df to create a json style structure to pass to an API requests.post. Sample DF: +-------+-------+-------+-------+-------+-------+-------------+-------------+----------...
You could transpose, rename_axis, reset_index, convert to_dict as records: test_input.T.rename_axis('period').reset_index().to_dict('records') In your case: parameters['overrideData'] = (test_input.T.rename_axis('period') .reset_index().to_dict('records') ) Output: [{'period': '2020', 'Total': 23648.0}, {'period': '2...
3
2
78,953,239
2024-9-5
https://stackoverflow.com/questions/78953239/minimum-periods-in-rolling-mean
Say I have: data = { 'id': ['a', 'a', 'a', 'b', 'b', 'b', 'b'], 'd': [1,2,3,0,1,2,3], 'sales': [5,1,3,4,1,2,3], } I would like to add a column with a rolling mean with window size 2, with min_periods=2, over 'id' In Polars, I can do: import polars as pl df = pl.DataFrame(data) df.with_columns(sales_rolling = pl.col('s...
You can use case statement and count: duckdb.sql(""" from df select *, case when count(*) over rolling2 = 2 then mean(sales) over rolling2 end as sales_rolling window rolling2 as ( partition by id order by d rows between 1 preceding and current row ) """).sort('id', 'd') ┌─────────┬───────┬───────┬───────────────┐ │ id...
4
4
78,950,277
2024-9-4
https://stackoverflow.com/questions/78950277/how-to-insert-to-a-table-with-auto-increment
I'm trying to insert new users to a table in MySQL when they register. I am using a FlaskApp on PythonAnywhere. Here is my query: INSERT INTO user_profile (email, user_name, first_foo) VALUES (%s, %s, 0); This is run from my flask_app code: def connect_db(query, params): db_connection= MySQLdb.connect("<username>.mysq...
From the OP's comment this worked, after each transaction such as INSERT, UPDATE, DELETE queries, adding commit() was pivotal after execute(). cursor = db_connection.cursor() cursor.execute(query, params) db_connection.commit() # <- add this
3
1
78,951,465
2024-9-5
https://stackoverflow.com/questions/78951465/why-the-result-is-different-numpy-slicing-and-indexing
Basically I want to obtain a part of the variable "cubote". I tried two methods that should work in the same way, but it didn't. My code: import numpy as np # Create a 3x3x3 cube cubote = np.arange(27).reshape(3,3,3) # Compare the results result1 = cubote[0:2,0:2,0:2] result2 = cubote[0:2][0:2][0:2] print(result1) pri...
The difference in the results between result1 and result2 comes down to how indexing works in NumPy. Explanation of result1: result1 = cubote[0:2, 0:2, 0:2] In this case, you are applying slicing across all three dimensions at once. This means you are extracting a sub-cube with indices in the ranges [0:2] in all three...
2
5
78,950,848
2024-9-4
https://stackoverflow.com/questions/78950848/get-size-of-png-from-bytes
I am trying to extract the size of an PNG image from a datastream Consider the starting data of the stream 137 80 78 71 13 10 26 10 0 0 0 13 73 72 68 82 0 0 2 84 0 0 3 74 8 2 0 0 0 195 81 71 33 0 0 0 ... ^ ^ ^ ^ ^ ^ which contains the following information signature: 137 80 78 71 13 10 26 10 IHDR chunk of: length 0 ...
You can think of each byte as a base-256 digit of the respective dimension. So 0 * 256^3 + 0 * 256^2 + 2 * 256 + 84 = 596, and 0 * 256^3 + 0 * 256^2 + 3 * 256 + 74 = 842. The next two bytes are important as well, where 8 is the bit depth, and 2 is the color type. 8 means 8 bits per component, and 2 means three componen...
2
1
78,950,899
2024-9-4
https://stackoverflow.com/questions/78950899/getting-the-group-key-when-using-group-by-applylist
This is the first time I'm working with Pandas so I'm completely new to this. I was able to group an instance list per account. Now while iterating into that list I would need the account number (group key) to be able to do something with it. This is an example of the csv file: enter image description here #Using Panda...
You should use Series.items: for group, account in df_group.items(): print(f'{group=}') print(account) Or, maybe better, don't aggregate and loop over the GroupBy object: for group, account in df.groupby('account')['instance-id']: print(f'{group=}') print(list(account)) Output: group='111111111111111' ['i-124f1c3c401...
2
1
78,950,667
2024-9-4
https://stackoverflow.com/questions/78950667/group-elements-in-dataframe-and-show-them-in-chronological-order
Consider the following dataframe, where Date is in the format DD-MM-YYY: Date Time Table 01-10-2000 13:00:03 B 01-10-2000 13:00:04 A 01-10-2000 13:00:05 B 01-10-2000 13:00:06 A 01-10-2000 13:00:07 B 01-10-2000 13:00:08 A How can I 1) group the observations by Table, 2) sort the rows according to Date and Time within e...
Use groupby.transform and numpy.lexsort: date = pd.to_datetime(df['Date']+' '+df['Time']) out = df.iloc[np.lexsort([ date, df['Table'], date.groupby(df['Table']).transform('min') ])] Alternatively, using an intermediate column: date = pd.to_datetime(df['Date']+' '+df['Time']) out = (df.assign(date=date, min_date=date....
2
4
78,950,432
2024-9-4
https://stackoverflow.com/questions/78950432/is-there-a-scenario-where-foo-in-listbar-cannot-be-replaced-by-foo-in-bar
I'm digging into a codebase containing thousands of occurrences of foo in list(bar), e.g.: as a boolean expression: if foo in list(bar) or ...: ... in a for loop: for foo in list(bar): ... in a generator expression: ",".join(str(foo) for foo in list(bar)) Is there a scenario (like a given version of Python, a k...
I've sometimes done/seen that when bar got modified in the loop, e.g.: bar = {1, 2, 3} for foo in list(bar): bar.add(foo + 1) With your replacement, that raises RuntimeError: Set changed size during iteration. Attempt This Online! An example from Python's standard library for k in list(_config_vars): if k.startswith(...
8
11
78,950,520
2024-9-4
https://stackoverflow.com/questions/78950520/use-format-specifier-to-convert-float-int-column-in-polars-dataframe-to-string
I have this code: import polars as pl df = pl.DataFrame({'size': [34.2399, 1232.22, -479.1]}) df.with_columns(pl.format('{:,.2f}', pl.col('size'))) But is fails: ValueError - Traceback, line 3 2 df = pl.DataFrame({'size': [34.2399, 1232.22, -479.1]}) ----> 3 df.with_columns(pl.format('{:,.2f}', pl.col('size'))) File p...
As outlined by @mozway, general format strings are not yet supported as part of pl.format. The corresponding feature request already contains a nice polars implementation of (the most common) C-style sprint formatting. If efficiency is not too much of an issue (e.g. in exploratory data analysis), you can simply use pl....
3
3
78,950,364
2024-9-4
https://stackoverflow.com/questions/78950364/abstract-base-class-property-setter-absence-not-preventing-class-instantiation
I'm trying to get abstract properties to work, enforcing property getter & setter definitions in downstream classes. from abc import ABC, abstractmethod class BaseABC(ABC): @property @abstractmethod def x(self): pass @x.setter @abstractmethod def x(self, value): pass class MyClass(BaseABC): def __init__(self, value): s...
TL;DR property doesn't just override the getter; it overrides the setter with None as well. In MyClass, property creates a brand new property with the given getter and no setter; it doesn't simply override the getter of the inherited property. The definition of MyClass.x is equivalent to def x_getter(self): return sel...
2
1
78,948,241
2024-9-4
https://stackoverflow.com/questions/78948241/os-environ-and-os-getenv-interact-strangely-in-a-unittest
I have a python class class EnvironmentParser: def __init__(self): self.A = os.getenv('A', 'a') + ".json" self.B = os.getenv('B', 'b') + ".json" The purpose of this class is to have some default file identifiers (eg. a.json and b.json) but if the need arises, this should be changeable at runtime by running the python ...
What is going on here is that unit tests are run in lexicographic order. This means that even though test_example_with_custom_values() is defined after test_example_with_default_values(), it's run before it and the environment variables are set. One way to manage this would be to use the approaches suggested in the lin...
2
4
78,950,176
2024-9-4
https://stackoverflow.com/questions/78950176/failed-to-produce-a-json-response-containing-a-phone-number-based-on-a-license-n
I've created a script to fetch a phone number based on a license number from this webpage, using Python with the requests module. The script is supposed to produce a JSON response containing the phone number I'm interested in. When I manually input this license number 354206 in the search box and hit the search button,...
You can try: import json import requests url = "https://azroc.my.site.com/AZRoc/s/sfsites/aura?r=5&other.ARCP_ContractorSearch.getRecords=1" message = { "actions": [ { "id": "176;a", "descriptor": "apex://ARCP_ContractorSearch/ACTION$getRecords", "callingDescriptor": "markup://c:ARCP_ContractorSearch", "params": {"sear...
2
2
78,950,075
2024-9-4
https://stackoverflow.com/questions/78950075/pd-pivot-table-lambda-function-to-join-column-values-with-exceptions-not-working
I am currently working with a dataframe looking at Kentucky oil wells with pandas and want to create a pivot table using an API identifier. Since ther are various duplicates, I also wanted to join non unique values. Below is an example of the dataframe: import pandas as pd df = pd.DataFrame({'API': ['16101030580000', '...
You should filter the values within the join: list_none = ['none', 'nan', 'NAN', 'None', '0000/00/00', '000'] df1 = pd.pivot_table( df, index='API', aggfunc=lambda x: ','.join( i for i in x.unique().astype(str) if i not in list_none ), sort=False, ) Alternative using a custom function: def cust_join(x): x = x.dropna()...
2
1
78,949,093
2024-9-4
https://stackoverflow.com/questions/78949093/how-to-resolve-attributeerror-module-fiona-has-no-attribute-path
I have a piece of code that was working fine until last week, but now it's failing with the following error: AttributeError: module 'fiona' has no attribute 'path' I’ve ensured that all the necessary libraries are installed and imported. Does anyone have any ideas on what might be going wrong or how I can resolve this ...
TL;DR update to geopandas==0.14.4 OR pin fiona to version 1.9.6 -- It seems fiona recently upgraded to 1.10.0 (as of 2024-09-04 01:14 UTC) and that may have broken some older versions of geopandas, which only depend on fiona being higher than some version, not lower than. Upon closer look, geopandas up to version 0.14....
12
23
78,949,414
2024-9-4
https://stackoverflow.com/questions/78949414/consecutive-count-of-binary-column-by-group
I am attempting to create a 'counter' of consecutive binary values = 1, resetting when the binary value = 0, for each group. Example of data: data = {'city_id': [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6], 'week': [1, 2, 3, 4, 5, 6, 7, 1...
The issue with your approach is that you're repeatedly slicing. You should use the builtin groupby functions for efficiency. You can form a custom group with groupby.cumsum to reset the groups on 0s, then use this to compute the consecutive counts: df['consecutive'] = df.groupby( ['city_id', df['binary'].eq(0).groupby(...
2
4
78,947,332
2024-9-4
https://stackoverflow.com/questions/78947332/how-to-install-torch-without-nvidia
While trying to reduce the size of a Docker image, I noticed pip install torch adds a few GB. A big chunk of this comes from [...]/site-packages/nvidia. Since I'm not using a GPU, I'd like to not install the nvidia things. Here is a minimal example: FROM python:3.12.5 RUN pip install torch (Ignoring -slim base images,...
As (roundaboutly) documented on pytorch.org's getting started page, Torch on PyPI is Nvidia enabled; use the download.pytorch.org index for CPU-only wheels: RUN pip install torch --index-url https://download.pytorch.org/whl/cpu Also please remember to specify a somewhat locked version of Torch, e.g. RUN pip install to...
3
6
78,925,963
2024-8-29
https://stackoverflow.com/questions/78925963/unexpected-value-passed-to-langchain-tool-argument
I'm trying to create a simple example tool that creates new user accounts in a hypothetical application when instructed to do so via a user prompt. The llm being used is llama3.1:8b via Ollama. So far what I've written works, but it's very unreliable. The reason why it's unreliable is because when LangChain calls on my...
Prompt engineering (what you are attempting here), is far from an exact science. However, there are ways you can clarify the schema of the tool. One example (from their docs) is getting it to parse your docstrings: @tool(parse_docstring=True) def create_user(username: str): """Creates a user Args: username: username of...
4
2
78,923,480
2024-8-28
https://stackoverflow.com/questions/78923480/how-to-use-doc-in-blacksheep-api
Use blacksheep create with the following options to create an example API: ✨ Project name: soquestion 🚀 Project template: api 🤖 Use controllers? Yes 📜 Use OpenAPI Documentation? Yes 🔧 Library to read settings essentials-configuration 🔩 App settings format YAML This will generate a simple API based on BlackSheep, ...
Given how documentation handler is defined in BlackSheep example, you cannot easily use that particular instance. The reason being docs is local to configure_docs function, therefore it cannot be used outside of it. However, that documentation decorator is simply an instance of OpenAPIHandler class, so you can move its...
4
1
78,922,047
2024-8-28
https://stackoverflow.com/questions/78922047/non-equi-join-in-polars
If you come from the future, hopefully this PR has already been merged. If you don't come from the future, hopefully this answer solves your problem. I want to solve my problem only with polars (which I am no expert, but I can follow what is going on), before just copy-pasting the DuckDB integration suggested above and...
update join_where() was released in version 1.7.0: ( windows_df .join_where( events_df, pl.col.time >= pl.col.start_time, pl.col.time <= pl.col.stop_time, ) .sort("name", "start_time") .pivot(on="name", index=["start_time","stop_time"], aggregate_function="len", values="time") .fill_null(0) ) ┌────────────┬───────────┬...
5
2
78,925,696
2024-8-29
https://stackoverflow.com/questions/78925696/when-should-i-include-the-score-benefit-of-a-local-decision-when-using-minimax
In the Stone Game problem, Alice and Bob take turns picking a pile of stones from the start or the end. The goal is to maximize Alice's total def play(turn, left, right): if left > right: return 0 end = piles[right] + play(1 - turn, left, right - 1) start = piles[left] + play(1 - turn, left + 1, right) return max(start...
The function we're trying to maximize is f := amount of stones alice gets. That's why we only add stones for Alice; the function we're maximizing doesn't include the amount of stones Bob gets. So then why does the first algorithm work? Turns out it's not generally correct, and only works because this specific problem c...
3
0
78,927,692
2024-8-29
https://stackoverflow.com/questions/78927692/how-to-get-all-styling-parameter-configurable-by-ttk-style-configure-for-a
I have been searching the answer for this question from a long time but with no success had to ask it here. I am able to get the styling parameter for from the tcl documentation, but my question is how can I achieve the same result programmatically. For example in Tkinter, we can use widget.configure() with no paramete...
After reading the source code I think I got some ideas. The problem why you can't get the rowheight and indent options for your treeview is that these options are not attached to any elements at all. They are only stored in some special so-called option table (which I think is a "hashtable"). But in order to actually s...
4
2
78,945,268
2024-9-3
https://stackoverflow.com/questions/78945268/efficient-conversion-of-timezone-aware-timestamps-to-datetime64m-in-pandas
I have the following code that creates a DataFrame representing the data I have in my system: import pandas as pd data = { "date": [ "2021-03-12 19:50:00-05:00", "2021-03-12 19:51:00-05:00", "2021-03-12 19:52:00-05:00", "2021-03-12 19:53:00-05:00", "2021-03-12 19:54:00-05:00", "2021-03-12 19:55:00-05:00", "2021-03-12 1...
Unfortunately there is no "minute" unit for pandas datetimes. You can choose from "D,s,ms,us,n" for day, second, millisecond, microsecond, or nanosecond respectively. This listing can be found under the "unit" argument in the docs of pandas.to_datetime That said, you can still parse this data and convert it to a second...
2
3
78,923,112
2024-8-28
https://stackoverflow.com/questions/78923112/how-to-read-joystick-input-from-logitech-extreme-3d-pro-in-python
I'm working on a Python program to read inputs from a Logitech Extreme 3D Pro joystick. I am able to receive raw data from the joystick, but I'm struggling to correctly interpret the X and Y values from this data. Problem: I have raw data as shown in the attached image. From the array, each value represents a different...
I have found a package called Pygame which is used to easily read remote data. It automatically reads the HID descriptor to determine the number of buttons and analogue controls. Using the Pygame package is a good solution for this issue.
2
1
78,945,659
2024-9-3
https://stackoverflow.com/questions/78945659/check-if-series-has-values-in-range
I have a Pandas dataframe that has user information and also has a column for their permissions: UserName Permissions John Doe 02 John Doe 11 Example 09 Example 08 User3 11 I am trying to create a new column called User Class that is based on their Permissions (looking at all of the users permissions). If a user has a...
Another possible solution: df['User Class'] = ( df.groupby('UserName')['Permissions'] .transform(lambda x: 'Admin' if (x < 10).all() else 'User' if (x >= 10).all() else 'Admin/User')) Output: UserName Permissions User Class 0 John Doe 2 Admin/User 1 John Doe 11 Admin/User 2 Example 9 Admin 3 Example 8 Admin 4 User3 1...
7
6
78,944,602
2024-9-3
https://stackoverflow.com/questions/78944602/how-can-i-override-the-default-behavior-of-listmyenum
I have a custom enum, MyEnum, with some elements that have different names but the same value. from enum import Enum class MyEnum(Enum): A = 1 B = 2 C = 3 D = 1 # Same value as A Consequently, list(MyEnum) returns only the names of some of the members (the first name for each value): >>>list(MyEnum) [<MyEnum.A: 1>, <M...
A class method is not the same as an instance method on a metaclass, which is what __iter__ for Enum is. You need to define a new metaclass, which you can use to define a new subclass of Enum that does what you are looking for. A caveat: I make no claim that replacing the current behavior of EnumType.__iter__ with your...
3
3