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,267,511 | 2024-4-3 | https://stackoverflow.com/questions/78267511/how-to-use-curve-fit-of-scipy-with-constrain-where-the-fitted-curve-is-always-un | I'm trying to fit a signal with an exponential decay curve. I would like to constrain the fitted curve to be always under the signal. How can I add such a constraint? I tried something with a residual function with a penalization but the fit is not good Here a minimal example import matplotlib.pyplot as plt import nump... | This is an exponential function, so use the logarithmic scale for both least-squared error and plotting. Use a lower-envelope constraint; works fine - import matplotlib.pyplot as plt import numpy as np from scipy.optimize import minimize, Bounds, NonlinearConstraint y_exper = np.array([0.13598974610162404,0.14204518683... | 3 | 3 |
78,268,766 | 2024-4-3 | https://stackoverflow.com/questions/78268766/fastest-way-to-extract-relevant-rows-pandas | I've got a very large pandas df that has the fields group, id_a, id_b and score, ordered by score so the highest is at the top. There is a row for every possible combination of id_a and id_b. I want to extract rows so that there is only one row per id_a and id_b, which reflects the highest score possible without repeat... | This looks to me line a linear_sum_assignment problem (i.e. maximizing the sum of score for unique pairs of id_a/id_b), you could use a pivot per group to do this: from scipy.optimize import linear_sum_assignment out = {} for group, g in (df.pivot(index=['group', 'id_a'], columns='id_b', values='score') .groupby(level=... | 4 | 2 |
78,268,740 | 2024-4-3 | https://stackoverflow.com/questions/78268740/import-from-confusion | I read the Python3 references for the Import statement here, in which it said: The from form uses a slightly more complex process: find the module specified in the from clause, loading and initializing it if necessary; for each of the identifiers specified in the import clauses: check if the imported module has an att... | It's checking the first module again, not the submodule. So for example, from foo import bar will find the foo module and check it for a bar attribute. If there's no such attribute there, it will attempt to import a foo.bar submodule. If this new import succeeds, it should ordinarily result in the submodule getting set... | 2 | 5 |
78,237,117 | 2024-3-28 | https://stackoverflow.com/questions/78237117/jupyter-doesnt-let-me-type-the-left-square-bracket | Recently I have installed Jupyter Notebook on my Mac for didactical use and I've noticed a problem: doing list = Jupyter doesn't let me type the left square bracket, and if I type that in a new line it allows me to type, for example: [] I've just tried to reinstall completely Jupyter from the prompt using Homebrew an... | This is a known issue: https://github.com/jupyterlab/jupyterlab/issues/15744 You can do: Settings → Settings Editor → JSON Settings Editor → Keyboard Shortcuts → User → paste → save paste: { "shortcuts": [ { "args": {}, "command": "inline-completer:next", "keys": [ "Alt ]" ], "selector": ".jp-mod-completer-enabled", "... | 4 | 8 |
78,251,318 | 2024-3-31 | https://stackoverflow.com/questions/78251318/optuna-hyperband-algorithm-not-following-expected-model-training-scheme | I have observed an issue while using the Hyperband algorithm in Optuna. According to the Hyperband algorithm, when min_resources = 5, max_resources = 20, and reduction_factor = 2, the search should start with an initial space of 4 models for bracket 1, with each model receiving 5 epochs in the first round. Subsequently... | You are using the default value of the parameter n_trials in the study.optimize function, which is None. According to the documentation, that means that it will stop evaluating configurations when it "times out". Optuna's Hyperband implementation is not identical to what was described in the original article. It has so... | 2 | 1 |
78,250,734 | 2024-3-31 | https://stackoverflow.com/questions/78250734/operator-class-gin-trgm-ops-does-not-exist-for-access-method-gin | psycopg2.errors.UndefinedObject: operator class "gin_trgm_ops" does not exist for access method "gin" Hello everybody, this is the whole message when I try to run pytest on my project which is written in Python/Django + db is postgresql and all sitting inside docker. I build a project on docker with django-cookiecutter... | Try adding to your migration: from django.contrib.postgres.operations import TrigramExtension operations = [ TrigramExtension(), ... ] | 2 | 3 |
78,238,232 | 2024-3-28 | https://stackoverflow.com/questions/78238232/python-3-7-4-and-3-10-6-asyncio-creating-multiple-tasks-in-vs-code-debug-call-st | When using asyncio and aiohttp, faced this issue and was wondering if it was an occurance limited to VSC only? This one keeps leaving residues from the previous loops. while True: loop.run_until_complete(get_data()) This runs without any residual tasks. while True: asyncio.run(get_data()) session = aiohttp.ClientSe... | This worked. Still not sure as to the different results between VSC and VSCodium with the initial code but nonetheless, for anyone else who stumbles through. async def fetch(url, params=None): if not self.session: self.session = aiohttp.ClientSession() async with semaphore: async with session.get(url, params=params) as... | 2 | 0 |
78,263,269 | 2024-4-2 | https://stackoverflow.com/questions/78263269/scrapy-and-great-expectations-great-expectations-not-working-together | I am trying to use the packages scrapy and great_expectations within the same virtual environment. There seems to be an issue with the compatibility between the two packages, depending on the order in which I import them in. Example: I created a virtual environment and pip installed the latest version of each package.... | This has been fixed as of 0.18.13 https://github.com/great-expectations/great_expectations/releases/tag/0.18.13 | 4 | 2 |
78,253,818 | 2024-4-1 | https://stackoverflow.com/questions/78253818/how-to-specify-column-data-type | I have the following code: import polars as pl from typing import NamedTuple class Event(NamedTuple): name: str description: str def event_table(num) -> list[Event]: events = [] for i in range(num): events.append(Event("name", "description")) return events data = {"events": [1, 2]} df = pl.DataFrame(data).select(events... | Quick fix right now Here's a map_batches implementation that should be at least marginally faster. def event_table(col: pl.Series) -> pl.Series: return pl.Series( [ [ Event("name", "description")._asdict() #note ._asdict() for _ in range(num) ] for num in col ] ) It uses nested list comprehensions which ought to be a ... | 5 | 3 |
78,239,484 | 2024-3-28 | https://stackoverflow.com/questions/78239484/why-does-dataframe-to-sql-slow-down-after-certain-amount-of-rows | I have a very large Pandas Dataframe ~9 million records, 56 columns, which I'm trying to load into a MSSQL table, using Dataframe.to_sql(). Importing the whole Dataframe in one statement often leads to errors, relating to memory. To cope with this, I'm looping through the Dataframe in batches of 100K rows, and importin... | I've found a solution, which might be useful for someone else looking to speed up a slow(ing) Dataframe.to_sql() operation, and has already tried things like the chunksizes and setting up the SQLALchemy connection with fast_executemany=True. Not sure what mechanism causes this change in performance, but it's worked for... | 2 | 1 |
78,264,205 | 2024-4-2 | https://stackoverflow.com/questions/78264205/not-allowed-to-access-non-ipm-folder | I've been using exchangelib library in python for a long time now to access emails in an email account. It's been working amazing. Out of the blue today, I get an error saying, KeyError: 'folders' During handling of the above exception, another exception occured: exchangelib.errors.ErrorAccessDenied: Not allowed to acc... | This is caused by a recent change in O365. We may be able to find a fix for it in exchangelib. Until then, a workaround is to navigate to folders using double slashes: msg_folder = my_account.root // 'Top of Information Store' // 'my_subfolder' This works by not collecting the full folder hierarchy first and navigatin... | 3 | 5 |
78,232,655 | 2024-3-27 | https://stackoverflow.com/questions/78232655/how-to-configure-ray-to-use-standard-python-logger-for-multiprocessing | I am trying to use Ray to improve the speed of a process and I want the log messages to be passed to the standard Python logger. This way, the application can handle formatting, filtering, and saving the log messages. However, when I use Ray, the log messages are not formatted according to my logger configuration and a... | As per the Ray documentation, every worker sets up its own logging, and so if you want to change the logging, you need to initialize it for every worker. The simplest way to do so is also given in the Ray documentation: # driver.py def logging_setup_func(): logger = logging.getLogger("ray") logger.setLevel(logging.DEBU... | 3 | 2 |
78,264,508 | 2024-4-2 | https://stackoverflow.com/questions/78264508/fastest-way-to-extract-moving-dynamic-crop-from-video-using-ffmpeg | I'm working on an AI project that involves object detection and action recognition on roughly 30 minute videos. My pipeline is the following: determine crops using object detection model extract crops using Python and write them to disk as individual images for each frame. use action recognition model by inputting a s... | Don't store the pictures. Store just the sequence of bounding boxes. Then, for whatever you wanted to do with that mountain of individual images, instead decode the video and read the sequence of boxes, and take your crops out of it like that, on the fly. I'd recommend using PyAV for video reading. It gives you the pre... | 2 | 2 |
78,264,069 | 2024-4-2 | https://stackoverflow.com/questions/78264069/mypy-cannot-infer-type-argument-difference-between-list-and-iterable | T = TypeVar("T", bound=Union[str, int]) def connect_lists(list_1: list[T], list_2: list[T]) -> list[T]: out: list[T] = [] out.extend(list_1) out.extend(list_2) return out connect_lists([1, 2], ["a", "b"]) mypy: error: Cannot infer type argument 1 of "connect_lists" [misc] T = TypeVar("T", bound=Union[str, int]) def ... | Iterable is covariant - an Iterable[int] is also an Iterable[int|str]. list is not covariant - a list[int] is not a list[int|str], because you can add strings to a list[int|str], which you can't do with a list[int]. mypy infers the types of [1, 2] and ["a", "b"] as list[int] and list[str] respectively. With the first d... | 8 | 4 |
78,263,331 | 2024-4-2 | https://stackoverflow.com/questions/78263331/python-module-with-name-main-py-doesnt-run-while-imported | Somebody asked me a question and I honestly didn't try it before, So it was interesting to know what exactly happens when we name a module __main__.py. So I named a module __main__.py, imported it in another file with name test.py. Surprisingly when I tried to run test.py it prints nothing and none of the functions of ... | When you run python test.py, the test.py module itself is already present in sys.modules with the key "__main__" (see top-level code environment in the docs). The import __main__ will just return this existing cache hit, so the presence of a __main__.py file on sys.path is irrelevant. These modifications to test.py wil... | 2 | 3 |
78,262,945 | 2024-4-2 | https://stackoverflow.com/questions/78262945/how-to-merge-two-lists-and-get-names-of-lists-with-the-highest-value-for-each-in | I am trying to compare two lists of odds from two bookmakers. They look like this: List1 = ['2.66', '3.79', '1.88', '1.61', '2.51', '1.29', '2.29', '2.56', '3.16', '2.05', '2.95', '2.64', '2.26', '3.17', '2.64', '2.25'] List2 = ['2.70', '4.40', '1.87', '1.56', '2.50', '1.26', '2.33', '2.60', '3.20', '2.04', '3.00', '2.... | You can combine argmax and take_along_axis: import numpy List1 = ['2.66', '3.79', '1.88', '1.61', '2.51', '1.29', '2.29', '2.56', '3.16', '2.05', '2.95', '2.64', '2.26', '3.17', '2.64', '2.25'] List2 = ['2.70', '4.40', '1.87', '1.56', '2.50', '1.26', '2.33', '2.60', '3.20', '2.04', '3.00', '2.65', '2.25', '3.20', '2.65... | 2 | 4 |
78,262,629 | 2024-4-2 | https://stackoverflow.com/questions/78262629/why-is-libopenblas-from-numpy-so-big | We are deploying an open source application based on numpy that includes libopenblas.{cryptic string}.gfortran-win32.dll. It is part of the Python numpy package. This dll is over 27MB in size. I'm curious why it is so big and where I can find the source for it to see for myself. Ultimately I'd like to see if it can be ... | OpenBLAS includes many optimized kernels for different CPU architectures and instruction sets. This is why the DLL is too large. Alternatives like BLIS and Intel's Math Kernel Library (MKL) exist. You can give a try to them if you consider. You can also build the library from the beginning and strip off the unnecessary... | 2 | 2 |
78,262,552 | 2024-4-2 | https://stackoverflow.com/questions/78262552/how-to-get-genericalias-super-types-in-python | Say I have a class defined as follows: class MyList(list[int]): ... I'm looking for a method that will return list[int] when I give it MyList, e.g.: >>> inspect.getsupers(MyList) [list[int]] The trouble is that no such method exists, as far as I can find. There is inspect.getmro(...), but this only returns list, not ... | Aha! This information is stored in .__orig_bases__. So: >>> MyList.__orig_bases__ (list[int],) And on 3.12+, the canonical way would be to use: >>> import types >>> types.get_original_bases(MyList) (list[int],) | 2 | 4 |
78,262,291 | 2024-4-2 | https://stackoverflow.com/questions/78262291/importerror-cannot-import-name-float-from-numpy-a-problem-with-abydos | I am using a library that requires abydos/distance/_aline.py to be imported. But as can be seen from the source code, it uses the old np_float: 25 from numpy import float as np_float which throws an error ImportError: cannot import name 'float' from 'numpy' (/usr/local/lib/python3.10/dist-packages/numpy/__init__.py) ... | Found a github issue from abydos right after posting this. Installing v0.6.0b from source solves the issue: !pip install git+https://github.com/chrislit/abydos.git Hope this helps anyone trying to use the library. The 0.5.0 version requirement seems to be everywhere. | 2 | 2 |
78,236,708 | 2024-3-28 | https://stackoverflow.com/questions/78236708/custom-json-encoder-not-being-called | I tried to apply martineau solution in this post to a slightly different case, but it seems that for some obscure (at least to me) reason, the custom encoder isn't called from the json.dump() method. from collections.abc import MutableMapping import json import numpy as np class JSONSerializer(json.JSONEncoder): def en... | This should probably be considered an implementation detail of the json package, and also it might be a Python version thing. In any case, it becomes crucial with your implementation: The dump() function internally calls the iterencode() method on your encoder (see lines 169 and 176 in the actual source code. Yet, the... | 2 | 2 |
78,260,128 | 2024-4-2 | https://stackoverflow.com/questions/78260128/django-cte-gives-queryset-object-has-no-attribute-with-cte | I have records in below format: | id | name | created | ----------------------------------------------- |1 | A |2024-04-10T02:49:47.327583-07:00| |2 | A |2024-04-01T02:49:47.327583-07:00| |3 | A |2024-03-01T02:49:47.327583-07:00| |4 | A |2024-02-01T02:49:47.327583-07:00| |5 | B |2024-02-01T02:49:47.327583-07:00| Model... | You need to mix in the CTEManager, otherwise you get a "vanilla" QuerySet: from django_cte import CTEManager class Model1(model.Models): name = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) objects = CTEManager() | 3 | 3 |
78,258,488 | 2024-4-2 | https://stackoverflow.com/questions/78258488/cant-use-gekko-equation | i want to define an equation in gekko, but than comes the error: Traceback (most recent call last): File "/Users/stefantomaschko/Desktop/Bundeswettbewerb Informatik/2.Runde/Päckchen/paeckchen_gurobi.py", line 131, in <module> m.solve() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-package... | Gekko optimization models can be defined by function calls but then the model is compiled into byte-code. The function fitness() is called only twice with the definition of the objective function and the equation: m.Minimize(fitness(var)) m.Equation(fitness(var) <= unmoeglich) You can inspect the model in the folder t... | 2 | 0 |
78,257,779 | 2024-4-1 | https://stackoverflow.com/questions/78257779/can-pandas-groupby-split-into-just-2-bins | Imagine I have this table: Col-1 | Col-2 A | 2 A | 3 B | 1 B | 4 C | 7 Groupby on Col-1 with a sum aggregation on Col-2 will sum A to 5, B to 5, and C to 7. What I want to know is if there is a baked in feature that allows aggregation on a target value in a column and then groups all other entries into another bin. Fo... | One solution is to make pd.Categorical from the Column 1 -> with two categories A for string A and Other for other strings. Then group by this categorical: tmp = pd.Categorical(df["Col1"], categories=["A", "Other"]).fillna("Other") out = df.groupby(tmp, observed=False)["Col2"].sum() print(out) Prints: A 5 Other 12 Nam... | 2 | 5 |
78,253,701 | 2024-4-1 | https://stackoverflow.com/questions/78253701/python-illegal-instruction-core-dumped-when-importing-certain-libraries-bea | I am using Python3.10 on Ubuntu 22.04.4, and I am trying to run code that I originally wrote on a Windows 11 machine. Whenever I run this script--main.py--it always stops at the import stages, and fails to import beautifulsoup4 and yfinance in particular: print("Starting imports.") import pandas print("Imported pandas.... | I have solved it! After further inspection of /var/log/syslog--the Ubuntu error/warning logfile--I found that there was a problem with some etree thing: kernel: [ 3887.864653] traps: python3[5907] trap invalid opcode ip:74ab4c0807c0 sp:7fffee156560 error:0 in etree.cpython-310-x86_64-linux-gnu.so[74ab4c04e000+329000] ... | 2 | 5 |
78,256,965 | 2024-4-1 | https://stackoverflow.com/questions/78256965/how-to-change-columns-valueslist-using-another-data-frame-in-python | I have two data frame, I need to change column values of first data frame that are in list, using second data frame. df1 = pd.DataFrame({'title':['The Godfather','Fight Club','The Empire'], 'genre_ids':[[18, 80],[18],[12, 28, 878]]}) title genre_ids 0 The Godfather [18, 80] 1 Fight Club [18] 2 The Empire [12, 28, 878] ... | You can also first map the genre IDs in df1 to their corresponding names using df2, and then replacing the genre IDs with the mapped names, like the following: import pandas as pd df1 = pd.DataFrame({'title':['The Godfather','Fight Club','The Empire'], 'genre_ids':[[18, 80],[18],[12, 28, 878]]}) df2 = pd.DataFrame({'id... | 3 | 0 |
78,257,104 | 2024-4-1 | https://stackoverflow.com/questions/78257104/isinstance-fails-on-an-object-contained-in-a-list-after-using-dill-dump-and-d | Is this expected behaviour (and if so, can someone explain why)? This only happens when using dill, not pickle. from pathlib import Path import dill class MyClass: def __init__(self) -> None: pass path = Path('test/test.pkl') # create parent directory if it does not exist path.parent.mkdir(exist_ok=True) x = [ MyClass(... | The reason or this is that dill is pickling and re-creating the MyClass class object when deserializing your object. Hence MyClass (also x[0].__class__) is a different object compared to the deserialized y[0].__class__ object, which causes the isinstance check to fail against MyClass. print(id(MyClass)) # 1404309697732... | 3 | 3 |
78,256,559 | 2024-4-1 | https://stackoverflow.com/questions/78256559/attributeerror-module-flax-traverse-util-has-no-attribute-unfreeze | I'm trying to run a model written in jax, https://github.com/lindermanlab/S5. However, I ran into some error that says Traceback (most recent call last): File "/Path/run_train.py", line 101, in <module> train(parser.parse_args()) File "/Path/train.py", line 144, in train state = create_train_state(model_cls, File "/Pa... | unfreeze is a method of Flax's FrozenDict class: (See FrozenDict.unfreeze). It appears that you have passed a Python dict where a FrozenDict is expected. To fix this, you should ensure that variables['params'] is a FrozenDict, not a dict. Regarding the error in your attempted replication: flax.traverse_util does not de... | 2 | 1 |
78,254,889 | 2024-4-1 | https://stackoverflow.com/questions/78254889/how-to-use-asyncio-serve-forever-without-freezing-gui | I am trying to create GUI with pyqt5 for tcp communication. I have 2 different .py file one for GUI and one for TCP. tcp.py contains tcpClients and tcpServer classes which has a function called tcp_server_connect (can be found below) to create connection between client and server. GUI has a button called connect and i ... | The issue is that Qt runs on the main thread, and trying to run an asyncio event loop on the same thread won't work. Both Qt and the event loop want to and need to control the entire thread. As a note, Qt did recently announce an asyncio module for Python, but that is still in technical preview. The below example, whic... | 2 | 1 |
78,251,324 | 2024-3-31 | https://stackoverflow.com/questions/78251324/odoo-16-make-fields-readonly-using-xpath | i am currently using odoo 16, where i have created a custom field and trying to make that field readonly. The readonly field should appear only if a non-administrator user is logged in This is my initial code:- <odoo> <data> <record id="product_template_only_form_view" model="ir.ui.view"> <field name="name">product.tem... | Try this: for base.group_user, the field will become read-only, and for base.group_system, it will become editable. <record id="product_template_only_form_view" model="ir.ui.view"> <field name="name">product.template.product.form</field> <field name="model">product.template</field> <field name="inherit_id" ref="product... | 2 | 1 |
78,253,534 | 2024-4-1 | https://stackoverflow.com/questions/78253534/why-does-np-exp1000-give-an-overflow-warning-but-np-exp-100000-not-give-an-u | On running: >>> import numpy as np >>> np.exp(1000) <stdin>:1: RuntimeWarning: overflow encountered in exp Shows an overflow warning. But then why does the following not give an underflow warning? >>> np.exp(-100000) 0.0 | By default, underflow errors are ignored. The current settings can be checked as follows: print(np.geterr()) {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'} To issue a warning for underflows just like overflows, you can use np.seterr like this: np.seterr(under="warn") np.exp(-100000) # Runtim... | 4 | 3 |
78,246,770 | 2024-3-30 | https://stackoverflow.com/questions/78246770/how-to-automating-code-formatting-in-vscode-for-jupyter-notebooks-with-black-for | I've been enjoying the convenience of the Black Formatter extension in Visual Studio Code, especially its "Format on Save" feature for Python files. Being able to automatically format my code upon saving with Ctrl+S has significantly streamlined my workflow. However, I've encountered a limitation when working with Jupy... | After setting up Black formatter, you could search for Notebook: formatOnSave and Notebook: formatOnCellExecution in settings(Ctrl+,). Check these options, You can make formatter work when you save the file in jupyter notebook. | 4 | 5 |
78,248,902 | 2024-3-30 | https://stackoverflow.com/questions/78248902/typing-a-function-decorator-with-conditional-output-type-in-python | I have a set of functions which all accept a value named parameter, plus arbitrary other named parameters. I have a decorator: lazy. Normally the decorated functions return as normal, but return a partial function if value is None. How do I type-hint the decorator, whose output depends on the value input? from functool... | I see two possible options here. First is "more formally correct", but way too permissive, approach relying on partial hint: from __future__ import annotations from functools import partial from typing import Callable, TypeVar, ParamSpec, Any, Optional, Protocol, overload, Concatenate R = TypeVar("R") P = ParamSpec("P"... | 2 | 1 |
78,249,645 | 2024-3-30 | https://stackoverflow.com/questions/78249645/polars-asof-join-on-next-available-date | I have a frame (events) which I want to join into another frame (fr), joining on Date and Symbol. There aren't necessarily any date overlaps. The date in events would match with the first occurrence only on the same or later date in fr, so if the event date is 2010-12-01, it would join on the same date or if not presen... | It sounds like you are on the right track using pl.DataFrame.join_asof. To group by the symbol the by parameter can be used. ( fr .join_asof( events, left_on="Date", right_on="Earnings_Date", by="Symbol", ) ) shape: (5, 5) ┌───────┬────────┬────────────┬───────────────┬───────┐ │ index ┆ Symbol ┆ Date ┆ Earnings_Date ... | 3 | 2 |
78,252,692 | 2024-3-31 | https://stackoverflow.com/questions/78252692/why-numpy-vectorize-calls-vectorized-function-more-times-than-elements-in-the-ve | When we call vectorized function for some vector, for some reason it is called twice for the first vector element. What is the reason, and can we get rid of this strange effect (e.g. when this function needs to have some side effect, e.g. counts some sum etc) Example: import numpy @numpy.vectorize def test(x): print(x)... | This is well defined in the vectorize documentation: If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs. If you don't want this, you can define otypes: import numpy def test(x): print(x) test = numpy.vectorize(test, otypes=[float]) test([1,2... | 2 | 5 |
78,252,285 | 2024-3-31 | https://stackoverflow.com/questions/78252285/attributeerror-module-numba-has-no-attribute-generated-jit | I am trying to run from ydata_profiling import ProfileReport profile = ProfileReport(merged_data) profile.to_notebook_iframe() in jupyter notebook. But I am getting an error: AttributeError: module 'numba' has no attribute 'generated_jit' I am running jupyter notebook in Docker container with requirements listed below... | The top API level function numba.decorated_jit is deprecated and removed from numba version>=0.59.0. I suggest to install last version where numba.decorated_jit is and that is numba==0.58.1 | 4 | 7 |
78,251,979 | 2024-3-31 | https://stackoverflow.com/questions/78251979/what-is-the-algorithm-behind-math-gcd-and-why-it-is-faster-euclidean-algorithm | Tests shows that Python's math.gcd is one order faster than naive Euclidean algorithm implementation: import math from timeit import default_timer as timer def gcd(a,b): while b != 0: a, b = b, a % b return a def main(): a = 28871271685163 b = 17461204521323 start = timer() print(gcd(a, b)) end = timer() print(end - st... | math.gcd() is certainly a Python shim over a library function that is running as machine code (i.e. compiled from "C" code), not a function being run by the Python interpreter. See also: Where are math.py and sys.py? This should be it (for CPython): math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs) i... | 2 | 7 |
78,251,275 | 2024-3-31 | https://stackoverflow.com/questions/78251275/numpy-array-methods-are-faster-than-numpy-functions | I have to work with the learning history of a Keras model. This is a basic task, but I've measured the performance of the Python built-in min() function, the numpy.min() function, and the numpy ndarray.min() function for list and ndarray. The performance of the built-in Python min() function is nothing compared to that... | Basically your observations are correct. Here's my timings and notes Create 2 arrays, one much larger, and a list: In [254]: a = np.random.randint(0,1000,1000); b = a.tolist() In [255]: aa = np.random.randint(0,1000,100000) The method is faster, by about 7µs in both cases - that's basially the overhead of the function... | 3 | 2 |
78,251,320 | 2024-3-31 | https://stackoverflow.com/questions/78251320/asyncio-how-to-read-stdout-from-subprocess | I have stuck with a pretty simple problem - I can't communicate with process' stdout. The process is a simple stopwatch, so I'd be able to start it, stop and get current time. The code of stopwatch is: import argparse import time def main() -> None: parser = argparse.ArgumentParser() parser.add_argument('start', type=i... | In this case "proc.communicate" cannot be used; it's not suitable for the purpose, since the OP wants to interrupt a running process. The sample code in the Python docs also shows how to directly read the piped stdout in these cases, so there is in principle nothing wrong with doing that. The main problem is that the s... | 2 | 2 |
78,244,861 | 2024-3-29 | https://stackoverflow.com/questions/78244861/launching-python-debug-with-arguments-messes-with-file-path | I'm using VSCode on Windows, with the GitBash as integrated terminal. When I launch the Python Debugger with default configurations, it works fine, and I get this command executed on the terminal: /usr/bin/env c:\\Users\\augus\\.Apps\\anaconda3\\envs\\muskit-env\\python.exe \ c:\\Users\\augus\\.vscode\\extensions\\ms-p... | Going through the issues on vscode-python repository, it is being mentioned in multiple issues that git bash is not officially supported. For example here: Note Gitbash isn't supported by Python extension, so use Select default profile to switch to cmd or powershell if need be. Possibly it is a bug and it will be bet... | 3 | 1 |
78,248,526 | 2024-3-30 | https://stackoverflow.com/questions/78248526/how-to-create-vector-embeddings-using-sentencetransformers | I found this code: https://github.com/pixegami/langchain-rag-tutorial/blob/main/create_database.py It takes the document, splits it into chunks, creates vector embeddings for each chunk, and saves those into Chroma Database. However, the source code uses OpenAI key to create embeddings. Since I don't have access to Ope... | Define your embedding model, with HuggingFaceEmbeddings from langchain_community.embeddings import HuggingFaceEmbeddings embedder = HuggingFaceEmbeddings( model_name = "sentence-transformers/all-MiniLM-L6-v2" ) Then embed the chunks into vectorDB db = Chroma.from_documents( documents=chunks, embedding=embedder, p... | 2 | 2 |
78,248,879 | 2024-3-30 | https://stackoverflow.com/questions/78248879/remove-gaps-between-subplots-mosaic-in-matplotlib | How do I remove the gaps between the subplots on a mosaic? The traditional way does not work with mosaics: plt.subplots_adjust(wspace=0, hspace=0) I also tried using gridspec_kw, but no luck. import matplotlib.pyplot as plt import numpy as np ax = plt.figure(layout="constrained").subplot_mosaic( """ abcde fghiX jklXX ... | This is not caused by subplot_mosaic but because a layout was specified. If you use constrained or tight layout, the layout manager will supersede the custom adjustments. Remove the layout manager and either method will work: gridspec_kw fig = plt.figure() # without layout param ax = fig.subplot_mosaic( """ abcde fgh... | 2 | 4 |
78,249,223 | 2024-3-30 | https://stackoverflow.com/questions/78249223/scraping-all-links-using-beautifulsoup | I am trying to scrape all match reports links from the page but there is 'load more' button, and I don't want to use selenium. Is there any solution to collect all links without selenium. Thanks in advance. Here what I tried: from bs4 import BeautifulSoup as bs import requests r=requests.get('https://www.iplt20.com/ne... | Try: import requests from bs4 import BeautifulSoup url = "https://www.iplt20.com/news/match-reports" soup = BeautifulSoup(requests.get(url).content, "html.parser") for a in soup.select("#div-match-report a:has(li)"): print(a["href"]) Prints: https://www.iplt20.com/news/4014/tata-ipl-2024-match-11-lsg-vs-pbks-match-rep... | 2 | 3 |
78,248,599 | 2024-3-30 | https://stackoverflow.com/questions/78248599/export-pandas-to-csv-data-but-before-doing-so-sort-date-by-least-to-greatest | Upon looking and researching online it does seem that there a numerous way of doing this but not sure if it fits the way that I want it for. Personally I would still like my dates as this format "3/30/24". I am extracting data from some which has numerous amount of data and everything works as expected but when I tried... | You should pass a custom key with to_datetime to sort_values, this will use the defined logic to sort while leaving the data unchanged: (df.sort_values(by='Date', key=lambda x: pd.to_datetime(x, format='%m/%d/%y') .to_csv(path, index=False) ) Output csv: Company Name,Delivery Address,Date,Customer Name Burgerking,124 ... | 2 | 1 |
78,247,930 | 2024-3-30 | https://stackoverflow.com/questions/78247930/rotate-a-multipolygon-without-changing-the-inner-spatial-relation | I have a multipolygon shapefile that i want to rotate. I can do the rotation but the problem is that the roatation changes the inner vertices. This creates overlap of polygon which i dont want. This is what i have tried. import geopandas as gpd input_poly_path = "poly3.shp" gdf = gpd.read_file(input_poly_path) explode ... | IIUC, you need to pass the centroid of the unary_union as the origin of the rotation : out = gpd.GeoDataFrame( geometry=gdf.rotate( angle=-90, origin=list(gdf.unary_union.centroid.coords)[0] ) ) NB: There is no need to explode the geometry, because you do not have MultiPolygons. Used input (gdf) : import geopandas as... | 2 | 3 |
78,247,747 | 2024-3-30 | https://stackoverflow.com/questions/78247747/tkinter-menu-spontaneously-adding-extra-item | I'm writing a Tkinter program that so far creates a window with a menu bar, a File menu, and a single item. The menu is successfully created, but with two items, the first being one that I did not specify, whose name is "-----". If I don't add an item, the spontaneous one is still added. This still happens if I specify... | In that way it works. I think u put tearoff=0 in menubar instead of fileMenu. If you put your tearoff=0 in menubar it won't affect fileMenu. So, u need to specifically put tearoff=0 in specific tk.Menu() import tkinter as tk window = tk.Tk() window.geometry("800x600") menubar = tk.Menu(window) window.config(menu=menuba... | 2 | 3 |
78,246,775 | 2024-3-30 | https://stackoverflow.com/questions/78246775/how-can-i-change-the-groupby-column-to-find-the-first-row-that-meets-the-conditi | This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'main': ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'y', 'y', 'y', 'y', 'y', 'y', 'y'], 'sub': ['c', 'c', 'c', 'd', 'd', 'e', 'e', 'e', 'e', 'f', 'f', 'f', 'f', 'g', 'g', 'g'], 'num_1': [10, 9, 80, 80, 99, 101, 110, 222, 90, 1, 7, 10, 2, 10, 95, 10], 'num... | IIUC, you can use numpy broadcasting to form a mask per "main" and use this to find the first num1>num2 while considering only the next groups: def find(g): # get sub as 0,1,2… sub = pd.factorize(g['sub'])[0] # convert inputs to numpy n1 = g['num_1'].to_numpy() n2 = g.loc[~g['sub'].duplicated(), 'num_2'].to_numpy() # f... | 2 | 1 |
78,246,703 | 2024-3-30 | https://stackoverflow.com/questions/78246703/getting-a-function-to-call-an-equation | I am creating a function to create an approximate solution for differential equations using Euler's method. I can get the code to work, but ran into trouble when trying to convert this into a function. Namely, I am having difficulty getting my function to correctly call the formula. This original code worked well: #def... | There are a couple of ways of dealing with your problem. The first (and IMO preferable) solution is just to pass a function to your eulers_method function i.e. def eulers_method(x, y, diff_eq, h, n): #empty solution and x_value lists to be used in the euler function solutions = [] x_values = [] for s in range (0, n): #... | 2 | 3 |
78,245,576 | 2024-3-29 | https://stackoverflow.com/questions/78245576/how-to-make-regex-code-apply-only-to-empty-target-cells | An example of my data StreetAddress City State Zip 1 Main St 01123 Winsted CT 1 Main St Winsted CT 01123 I am trying to use regex and pandas to clean a spreadsheet that I have. The problem I am running into is that my regex code is replacing every cell in the entire column even if there is valid data in it... | I would use a boolean mask, this will avoid overwriting existing data, and also be more efficient since only the relevant rows will be evaluated: add = df['StreetAddress'].str.extract(r'(\d{5})', expand=False) m = add.notna() df.loc[m, 'Zip'] = add[m] df.loc[m, 'StreetAddress'] = (df.loc[m, 'StreetAddress'] .str.replac... | 2 | 2 |
78,240,251 | 2024-3-28 | https://stackoverflow.com/questions/78240251/python-script-using-bluetooth-running-on-windows-11-vs-raspberry-pi4 | I've run into an issue with a python script which performs differently when run on Windows 11 (through VS) versus running on a Raspberry Pi4 The script has been modified from a CLi script found to interact with Victron Energy hardware. Thanks to @ukbaz, the script ran and returned data from a bluetooth connected Victro... | I suspect that what you want to do is only exit after the file has been written. Maybe you could use the asyncio event capability? https://docs.python.org/3/library/asyncio-sync.html#event Create an event in the global scope by placing the following at the top of the file after the imports. file_written_event = asyncio... | 2 | 1 |
78,244,496 | 2024-3-29 | https://stackoverflow.com/questions/78244496/scraping-mlb-daily-lineups-from-rotowire-using-python | I am trying to scrape the MLB daily lineup information from here: https://www.rotowire.com/baseball/daily-lineups.php I am trying to use python with requests, BeautifulSoup and pandas. My ultimate goal is to end up with two pandas data frames. First is a starting pitching data frame: date game_time pitcher_name team... | You have to iterate the boxes and select all your expected features. import pandas as pd import requests from bs4 import BeautifulSoup url = "https://www.rotowire.com/baseball/daily-lineups.php" soup = BeautifulSoup(requests.get(url).content, "html.parser") data_pitiching = [] data_batter = [] team_type = '' for e in s... | 2 | 2 |
78,240,915 | 2024-3-28 | https://stackoverflow.com/questions/78240915/saving-a-scipy-sparse-matrix-directly-as-a-regular-txt-file | I have a scipy.sparse matrix (csr_matrix()). But I need to save it to a file not in the .npz format but as a regular .txt or .csv file. My problem is that I don't have enough memory to convert the sparse matrix into a regular np.array() and then save it to a file. Is there a way to have the data as a sparse matrix in m... | Answer to new question: import numpy as np from scipy import sparse, io A = sparse.eye(5, format='csr') * np.pi np.set_printoptions(precision=16, linewidth=1000) with open('matrix.txt', 'a') as f: for row in A: f.write(str(row.toarray()[0])) f.write('\n') # [3.141592653589793 0. 0. 0. 0. ] # [0. 3.141592653589793 0. 0.... | 2 | 2 |
78,244,582 | 2024-3-29 | https://stackoverflow.com/questions/78244582/parsing-strings-with-numbers-and-si-prefixes-in-polars | Say I have this dataframe: >>> import polars >>> df = polars.DataFrame(dict(j=['1.2', '1.2k', '1.2M', '-1.2B'])) >>> df shape: (4, 1) ┌───────┐ │ j │ │ --- │ │ str │ ╞═══════╡ │ 1.2 │ │ 1.2k │ │ 1.2M │ │ -1.2B │ └───────┘ How would I go about parsing the above to get: >>> df = polars.DataFrame(dict(j=[1.2, 1_200, 1_20... | You can use str.extract() and str.strip_chars() to split the parts and then get the resulting number by using Expr.replace() + Expr.pow(): df.with_columns( pl.col('j').str.strip_chars('KMB').cast(pl.Float32) * pl.lit(10).pow( pl.col('j').str.extract(r'(K|M|B)').replace(['K','M','B'],[3,6,9]).fill_null(0) ) ) ┌─────────... | 4 | 3 |
78,238,201 | 2024-3-28 | https://stackoverflow.com/questions/78238201/why-does-it-provide-two-different-outputs-with-if2-if3 | I am testing the m.if3 function in gekko by using conditional statements of if-else but I get two different outputs. The optimal number i get from below code is 12. I plug that in the next code with if-else statement to ensure that the cost matches up but it does not. Am I using if3/if2 incorrectly? The rate is 0.1 for... | The if2 or if3 function isn't needed because the switching argument duration-5 is a constant value that is not a function of a Gekko variable. Just like the validation script, the two segments can be calculated separately and added together to get a total cost and patient count. from gekko import GEKKO m = GEKKO(remote... | 2 | 0 |
78,233,914 | 2024-3-27 | https://stackoverflow.com/questions/78233914/calculate-relative-volume-ratio-indicator-in-pandas-data-frame-and-add-the-indic | I know there have been a few posts on this, but my case is a little bit different and I wanted to get some help on this. I have a pandas dataframe symbol_df with 1 min bars in the below format for each stock symbol: id Symbol_id Date Open High Low Close Volume 1 1 2023-12-13 09:15:00 4730.95 4744.00 4713.95 4696.40 230... | TL;DR from yfinance import download # Prepare data similar to the original symbol_df = ( download(tickers="AAPL", period="7d", interval="1m") .rename_axis(index='Date') .reset_index() ) # Calculate Relative Volume Ratio volume = symbol_df.set_index('Date')['Volume'] dts = volume.index cum_volume = volume.groupby(dts.da... | 2 | 1 |
78,243,747 | 2024-3-29 | https://stackoverflow.com/questions/78243747/how-to-use-two-key-functions-when-sorting-a-multiindex-dataframe | In this call to df.sort_index() on a MultiIndex dataframe, how to use func_2 for level two? func_1 = lambda s: s.str.lower() func_2 = lambda x: np.abs(x) m_sorted = df_multi.sort_index(level=['one', 'two'], key=func_1) The documentation says "For MultiIndex inputs, the key is applied per level", which is ambiguous. i... | sort_index takes a unique function as key that would be used for all levels. That said, you could use a wrapper function to map the desired sorting function per level name: def sorter(level, default=lambda x: x): return { 'one': lambda s: s.str.lower(), 'two': np.abs, }.get(level.name, default)(level) df_multi.sort_ind... | 5 | 5 |
78,243,115 | 2024-3-29 | https://stackoverflow.com/questions/78243115/calculating-based-on-rows-conditions-in-pandas | I encountered the following problem: I have a pandas dataframe that looks like this. id_tranc sum bid 1 4000 2.3% 1 20000 3.5% 2 100000 if >=100 000 - 1.6%, if < 100 000 - 100$ 3 30000 if >=100 000 - 1.6%, if < 100 000 - 100$ 1 60000 500$ code_to_create_dataset: dataframe = pd.DataFrame({ 'id_tranc': ... | I would write a small parser based on a regex and operator: from operator import ge, lt, gt, le import re def logic(value, bid): # define operators, add other ones if needed ops = {'>=': ge, '>': gt, '<': lt, '<=': le} # remove spaces, split conditions on comma conditions = bid.replace(' ', '').split(',') # then loop o... | 2 | 2 |
78,240,481 | 2024-3-28 | https://stackoverflow.com/questions/78240481/i-am-encountering-an-f2py-dimension-error-when-passing-numpy-array-to-fortran | I have been trying to wrap a fortran module that takes several 1-dimensional arrays and returns calculated values CTP and HILOW. subroutine ctp_hi_low ( nlev_in, tlev_in, qlev_in, plev_in, & t2m_in , q2m_in , psfc_in, CTP, HILOW , missing ) implicit none ! ! Input/Output Variables ! integer, intent(in ) :: nlev_in ! **... | It is better to call fortran subroutine from python with explicit argument name: conv_trig_pot_mod.ctp_hi_low(nlev_in=10, tlev_in=arr, qlev_in=arr, plev_in=arr, t2m_in=1, q2m_in=1, psfc_in=????, missing=1) The order of arguments differs between Fortran and Python. you can check the new arguments list and order __doc__... | 2 | 1 |
78,240,642 | 2024-3-28 | https://stackoverflow.com/questions/78240642/python-global-variables-in-recursion-get-different-result | I have this code, which prints 1: s = 0 def dfs(n): global s if n > 10: return 0 s += dfs(n + 1) return n dfs(0) print(s) If I modify dfs like this: def dfs(n): global s if n > 10: return 0 i = dfs(n + 1) s += i return n it will print 55 I know what is a better way to write the dfs. I just want to know why the value ... | Python is interpreted and executed from top to bottom, so in the first version you have: s += dfs(n + 1) which is exact as: s = s + dfs(n + 1) So when you do this recursively you have on stack these commands: s = 0 + dfs(1) # <-- dfs(1) will return 1 s = 0 + dfs(2) # <-- dfs(2) will return 2 ... s = 0 + dfs(9) # <-- ... | 4 | 8 |
78,238,674 | 2024-3-28 | https://stackoverflow.com/questions/78238674/how-to-convert-rs-tukeys-hsd-table-into-correlation-matrix-in-python-using-pan | I have recently exported a table from R's TukeyHSD test to obtain the p-values for various time groups (0, 5, 10, 20, 30, 40, 50, 60). I'm curious if there's a method to transform this into a correlation matrix, where each axis represents the time groups and corresponds to the respective p-value. The table includes an ... | Try: df[["x", "y"]] = df.index.str.split("-", expand=True).to_frame().astype(int).values print(pd.crosstab(df["x"], df["y"], df["p adj"], aggfunc="first")) Prints: y 0 5 10 20 40 50 x 5 3.816166e-01 NaN NaN NaN NaN NaN 10 6.878476e-03 0.973138 NaN NaN NaN NaN 20 4.764197e-08 0.073809 0.336915 NaN NaN NaN 40 1.270855e-... | 2 | 1 |
78,239,380 | 2024-3-28 | https://stackoverflow.com/questions/78239380/polars-apply-same-custom-function-to-multiple-columns-in-group-by | What's the best way to apply a custom function to multiple columns in Polars? Specifically I need the function to reference another column in the dataframe. Say I have the following: df = pl.DataFrame({ 'group': [1,1,2,2], 'other': ['a', 'b', 'a', 'b'], 'num_obs': [10, 5, 20, 10], 'x': [1,2,3,4], 'y': [5,6,7,8], }) An... | You can just pass list of columns into pl.col(): df.group_by('group').agg( (pl.col('x','y') * pl.col('num_obs')).sum() / pl.col('num_obs').sum(), pl.col('num_obs').sum() ) ┌───────┬──────────┬──────────┬─────────┐ │ group ┆ x ┆ y ┆ num_obs │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ f64 ┆ i64 │ ╞═══════╪══════════╪══════... | 2 | 2 |
78,232,295 | 2024-3-27 | https://stackoverflow.com/questions/78232295/manually-set-values-shown-in-legend-for-continuous-variable-of-seaborn-matplotli | Is there a way to manually set the values shown in the legend of a seaborn (or matplotlib) scatterplot when the legend contains a continuous variable (hue)? For example, in the plot below I might like to show the colors corresponding to values of [0, 1, 2, 3] rather than [1.5, 3, 4.5, 6, 7.5] np.random.seed(123) x = np... | Seaborn creates its scatterplot a bit different than matplotlib. That way, the scatterplot can be customized in more ways. For the legend, Seaborn 0.13 employs custom Line2D elements (older Seaborn versions use PathCollections). The following approach: replaces Seaborn's hue_norm=(0, 3) with an equivalent matplotlib n... | 2 | 2 |
78,237,884 | 2024-3-28 | https://stackoverflow.com/questions/78237884/python-convert-markdown-to-html-with-codeblocks-like-in-stackoverflow | I have been trying to convert a Markdown file into HTML code with Python for a few days - without success. The markdown file contains inline code and code blocks. However, I can't find a solution to display the code blocks in HTML like StackOverflow or GitHub does. In other words, a rectangle containing the code. The M... | The background-color and related styles need to be defined on the pre tag (or its parent div), actually, if you want the same styles applied to both code blocks and code spans, then you will need to define the styles for both. And as the background color is the same, there is no need to undo the styles for the code ele... | 2 | 2 |
78,235,551 | 2024-3-28 | https://stackoverflow.com/questions/78235551/looking-for-regex-pattern-to-return-similar-results-to-my-current-function | I have some pascal-cased text that I'm trying to split into separate tokens/words. For example, "Hello123AIIsCool" would become ["Hello", "123", "AI", "Is", "Cool"]. Some Conditions "Words" will always start with an upper-cased letter. E.g., "Hello" A contiguous sequence of numbers should be left together. E.g., "123"... | Based on your Version 1: import re def extract_v1(string: str) -> list[str]: word_pattern = r"[A-Z][a-z]+" num_pattern = r"\d+" upper_pattern = r"[A-Z]+(?![a-z])" # Fixed pattern = f"{word_pattern}|{num_pattern}|{upper_pattern}" extracts: list[str] = re.findall( pattern=pattern, string=string ) return extracts string =... | 6 | 3 |
78,233,403 | 2024-3-27 | https://stackoverflow.com/questions/78233403/attributeerror-module-keras-tf-keras-keras-has-no-attribute-internal | Trying to install top2vec on colab ,and install everything that other people mentioned, but still get this error, have no idea how to solve,anybody knows? really appreciate! error screenshot !pip install top2vec !pip install top2vec[sentence_transformers] !pip install top2vec[sentence_encoders] from top2vec import Top2... | This is a known issue: The recent release of Keras 3 breaks TensorFlow Probability at import. installation of tensorflow v2.15.0, tensorflow-probability v0.23.0, and keras v3 causes a AttributeError: module 'keras._tf_keras.keras' has no attribute '__internal__' Please see these posts: https://github.com/tensorflow/p... | 3 | 3 |
78,232,294 | 2024-3-27 | https://stackoverflow.com/questions/78232294/why-regular-operations-are-not-based-on-their-in-place-corresponding-operation | To me, the only difference is that the regular operation needs one more instantiation, and the result is held by this new instance. And thus the regular implementation should call the other. But : these (in-place) methods should attempt to do the operation in-place (modifying self) and return the result (which could be... | Inplace operations likely modify their operands. In the example you give, you use A.copy() to avoid that. Some types do not allow modifications (tuples, for example, are immutable). Thus they don't allow inplace operations. Also, inplace operations are not exactly intuitive to someone new to programming, or even to som... | 3 | 1 |
78,231,207 | 2024-3-27 | https://stackoverflow.com/questions/78231207/skip-level-in-nested-json-and-convert-to-pandas-dataframe | I have json data that is structured like this, which I want to turn into a data frame: { "data": { "1": { "Conversion": { "id": "1", "datetime": "2024-03-26 08:30:00" } }, "50": { "Conversion": { "id": "50", "datetime": "2024-03-27 09:00:00" } } } } My usual approach would be to use json_normalize, like this: df = pd.... | You have to manually change data in double list comprehension: L = [b['Conversion'] for k, v in input['data'].items() for a, b in v.items()] print (L) [{'id': '1', 'datetime': '2024-03-26 08:30:00'}, {'id': '50', 'datetime': '2024-03-27 09:00:00'}] out = pd.json_normalize(L) print (out) id datetime 0 1 2024-03-26 08:30... | 2 | 3 |
78,230,664 | 2024-3-27 | https://stackoverflow.com/questions/78230664/python-tkinter-resize-all-ttkbootstrap-or-ttk-button-padding-for-a-specific-styl | I want to alter padding for all buttons using a particular style (danger). For some reason this change is only applied to the currently active theme, switching themes reverts the Button padding to default. You can see the issue by running the following and switching themes ... import tkinter as tk from tkinter import t... | The main reason is this part and configuring tb.Style() within the setup_ui(). It means that the configuration you're setting for danger.TButton is only associated with the instance of tb.Style(), So,when u try to change your theme, a new instance of tb.Style() is created internally by ttkbootstrap, and your custom con... | 3 | 0 |
78,202,760 | 2024-3-21 | https://stackoverflow.com/questions/78202760/polars-groupby-describe-extension | df is a demo Polars DataFrame: df = pl.DataFrame( { "groups": ["A", "A", "A", "B", "B", "B"], "values": [1, 2, 3, 4, 5, 6], } ) The current group_by.agg() apporach is a bit inconvinient for creating descriptive statistics: print( df.group_by("groups").agg( pl.len().alias("count"), pl.col("values").mean().alias("mean")... | Calling this will output as same as you mentioned in the question import polars as pl class DescribeAccessor: def __init__(self, df: pl.DataFrame): self._df = df def __call__( self, by: str, percentiles: list = [0.25, 0.5, 0.75], skew: bool = True, kurt: bool = True, ) -> pl.DataFrame: percentile_exprs = [ pl.col("valu... | 3 | 4 |
78,227,144 | 2024-3-26 | https://stackoverflow.com/questions/78227144/simulation-of-a-pendulum-hanging-on-a-spinning-disk | Can anybody get this code to run? I know, that it is very long and maybe not easy to understand, but what I am trying to do is to write a simulation for a problem, that I have already posted here: https://math.stackexchange.com/questions/4876146/pendulum-hanging-on-a-spinning-disk I try to make a nice simulation, that ... | Edited to include the direct solution in Cartesians, since this was the original direction taken by the OP. See the bottom of this answer. Edited again to provide an alternative derivation of the Cartesian equations from Newton's Second Law (F=ma) rather than Lagrangian Mechanics. (This has the side benefit that it als... | 2 | 7 |
78,215,243 | 2024-3-24 | https://stackoverflow.com/questions/78215243/python-app-keeps-oom-crashing-on-pandas-merge | I have a ligh Python app which should perform a very simple task, but keeps crashing due to OOM. What app should do Loads data from .parquet in to dataframe Calculate indicator using stockstats package Merge freshly calculated data into original dataframe to have both OHCL + SUPERTREND inside one dataframe -> here is ... | In order to close this question, I have figured out that the issue was caused by duplicated datetimes in dataframe. This caused some weird bugs on dataframe merge on datetime column. So I have fixed the data and it works fine now. Duplicated datetimes During investigating data with dask, I have noticed that there are ... | 2 | 1 |
78,225,920 | 2024-3-26 | https://stackoverflow.com/questions/78225920/why-nextitertrain-dataloader-takes-long-execution-time-in-pytorch | I am trying to load a local dataset with images (around 225 images in total) using the following code: # Set the batch size BATCH_SIZE = 32 # Create data loaders train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders( train_dir=train_dir, test_dir=test_dir, transform=manual_transforms, # use man... | The main reason the next(iter(train_dataloader) call is slow is due to multiprocessing - or to the pittfalls of multiprocessing. When num_workers > 0, the call to iter(train_dataloader) will fork the main Python process (the current script), which means that any time-consuming code that occurs during import before the ... | 2 | 2 |
78,192,426 | 2024-3-20 | https://stackoverflow.com/questions/78192426/how-to-use-solr-as-retriever-in-rag | I want to build a RAG (Retrieval Augmented Generation) service with LangChain and for the retriever I want to use Solr. There is already a python package eurelis-langchain-solr-vectorstore where you can use Solr in combination with LangChain but how do I define server credentials? And my embedding model is already runn... | For the first question: For basic credentials you can send them in the url with the login:password@ pattern http://localhost:8983/solr => http://login:password@localhost:8983/solr For the second one: to use your embeddings server you need to provide the Solr vector store with a class inheriting from langchain_core.embe... | 2 | 1 |
78,211,526 | 2024-3-23 | https://stackoverflow.com/questions/78211526/pytorch-attributeerror-torch-dtype-object-has-no-attribute-itemsize | I am trying to follow this article on medium Article. I had a few problems with it so the remain chang eI did was to the TrainingArguments object I added gradient_checkpointing_kwargs={'use_reentrant':False},. So now I have the following objects: peft_training_args = TrainingArguments( output_dir = output_dir, warmup_s... | I was able to recreate your problem on Databricks with the following cluster: Runtime: 14.1 ML (includes Apache Spark 3.5.0, GPU, Scala 2.12) Worker Type: Standard_NC16as_T4_v3 / Standard_NC6s_vs Driver Type: Standard_NC16as_T4_v3 / Standard_NC6s_vs And then building on top of all the answers here already I was able ... | 2 | 1 |
78,221,046 | 2024-3-25 | https://stackoverflow.com/questions/78221046/simultaneous-spacing-and-duration-constraints-with-time-gaps-in-gekko | I'm trying to simultaneously enforce sequential duration and spacing constraints to vector solution output in Gekko. Normally, this would be fairly straightforward using window logic, but my time array (in weeks) has gaps per the "week" array below (e.g., it goes [13, 14, 17...]). I was able to get the spacing requirem... | Below is a minimal example of duration and spacing constraints that may help. The decision variable is when to start the promo. The promo selection is post-processed after st is optimized. from gekko import GEKKO import numpy as np # Initialize the model m = GEKKO(remote=False) # Define weeks and parameters weeks = np.... | 2 | 1 |
78,210,393 | 2024-3-23 | https://stackoverflow.com/questions/78210393/cannot-import-name-linear-util-from-jax | I'm trying to reproduce the experiments of the S5 model, https://github.com/lindermanlab/S5, but I encountered some issues when solving the environment. When I'm running the shell script./run_lra_cifar.sh, I get the following error Traceback (most recent call last): File "/Path/S5/run_train.py", line 3, in <module> fro... | jax.linear_util was deprecated in JAX v0.4.16 and removed in JAX v0.4.24. It appears that flax is the source of the linear_util import, meaning that you are using an older flax version with a newer jax version. To fix your issue, you'll either need to install an older version of JAX which still has jax.linear_util, or ... | 3 | 1 |
78,202,488 | 2024-3-21 | https://stackoverflow.com/questions/78202488/combination-of-non-overlapping-interval-pairs | I recently did a coding challenge where I was tasked to return the number of unique interval pairs that do not overlap when given the starting points in one list and the ending points in one list. I was able to come up with an n^2 solution and eliminated duplicates by using a set to hash each entry tuple of (start, end... | This is a O(n*log n) solution in Ruby (n being the number of intervals). I will include a detailed explanation that should make conversion of the code to Python straightforward. I assume that non-overlapping intervals have no points in common, not even endpoints1. def paperCuttings(starting, ending) # Compute an array ... | 2 | 4 |
78,227,090 | 2024-3-26 | https://stackoverflow.com/questions/78227090/get-own-pyproject-toml-dependencies-programatically | I use a pyproject.toml file to list a package's dependencies: [build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [project] name = "foobar" version = "1.0" requires-python = ">=3.8" dependencies = [ "requests>=2.0", "numpy", "tomli;python_version<'3.11'", ] Is is possible, from within the ... | Something along the lines of the following should do the trick: import importlib.metadata import packaging.requirements def _get_dependencies(name): rd = metadata(name).get_all('Requires-Dist') deps = [] for req in rd: req = packaging.requirements.Requirement(req) if req.marker is not None and not req.marker.evaluate()... | 2 | 1 |
78,228,212 | 2024-3-26 | https://stackoverflow.com/questions/78228212/python-converting-dateprice-list-to-new-rows | I am trying to convert the following column into new rows: Id Prices 001 ["March:59", "April:64", "May:62"] 002 ["Jan:55", ETC] to id date price 001 March 59 001 April 64 001 May 62 002 Jan 55 The date:price pairs aren't stored in a traditional dictionary format like the following solution: ... | If you have valid lists, explode and split: df = pd.DataFrame({'Id': ['001', '002'], 'Prices': [["March:59", "April:64", "May:62"], ["Jan:55"]]}) out = df.explode('Prices') out[['date', 'price']] = out.pop('Prices').str.split(':', expand=True) If you have strings, str.extractall with a regex and join: df = pd.DataFram... | 2 | 3 |
78,227,479 | 2024-3-26 | https://stackoverflow.com/questions/78227479/add-a-column-to-a-polars-lazyframe-based-on-a-group-by-aggregation-of-another-co | I have a LazyFrame of time, symbols and mid_price: Example: time symbols mid_price datetime[ns] str f64 2024-03-01 00:01:00 "PERP_SOL_USDT@… 126.1575 2024-03-01 00:01:00 "PERP_WAVES_USD… 2.71235 2024-03-01 00:01:00 "SOL_USDT@BINAN… 126.005 2024-03-01 00:01:00 "WAVES_USDT@BIN… 2.7085 2024-03-01 00:02:00 "PERP_SOL_USDT@…... | It sounds like you don't want to actually aggregate anything (and get a single value per symbol), but instead want to compute "change" but independently for each symbol. In polars, this kind of behaviour, similar to window functions in PostgreSQL, can be achieved with pl.Expr.over. df.with_columns( pl.col("mid_price").... | 2 | 3 |
78,225,953 | 2024-3-26 | https://stackoverflow.com/questions/78225953/why-is-if-x-is-none-pass-faster-than-x-is-none-alone | Timing results in Python 3.12 (and similar with 3.11 and 3.13 on different machines): When x = None: 13.8 ns x is None 10.1 ns if x is None: pass When x = True: 13.9 ns x is None 11.1 ns if x is None: pass How can doing more take less time? Why is if x is None: pass faster, when it does the same x is None check and th... | Look at the disassembled code: >>> import dis >>> dis.dis('if x is None: pass') 0 0 RESUME 0 1 2 LOAD_NAME 0 (x) 4 POP_JUMP_IF_NOT_NONE 1 (to 8) 6 RETURN_CONST 0 (None) >> 8 RETURN_CONST 0 (None) >>> dis.dis('x is None') 0 0 RESUME 0 1 2 LOAD_NAME 0 (x) 4 LOAD_CONST 0 (None) 6 IS_OP 0 8 RETURN_VALUE The if case has a ... | 5 | 16 |
78,225,397 | 2024-3-26 | https://stackoverflow.com/questions/78225397/replace-chars-in-existing-column-names-without-creating-new-columns | I am reading a csv file and need to normalize the column names as part of a larger function chaining operation. I want to do everything with function chaining. When using the recommended name.map function for replacing chars in columns like: import polars as pl df = pl.DataFrame( {"A (%)": [1, 2, 3], "B": [4, 5, 6], "C... | You could simply replace DataFrame.with_columns() with DataFrame.select() method: df = pl.DataFrame( {"A (%)": [1, 2, 3], "B": [4, 5, 6], "C (Euro)": ["abc", "def", "ghi"]} ).select( pl.all().name.map( lambda c: c.replace(" ", "_") .replace("(%)", "pct") .replace("(Euro)", "euro") .lower() ) ) ┌───────┬─────┬────────┐ ... | 3 | 3 |
78,225,517 | 2024-3-26 | https://stackoverflow.com/questions/78225517/how-do-i-update-a-dataframe-column-with-a-formula-that-uses-values-from-other-co | I have a dataset of investments that shows a value for the investment, a coupon rate, and an annual income. Some investments generate no income, and some investments have a coupon rate but the annual income is not computed. How do I update the income column when there is a valid coupon but no number in the income colum... | You should not use a loop, not use - for missing values. Remove the -, use NaNs, and vectorize your code: df[['coupon', 'income']] = df[['coupon', 'income']].apply(pd.to_numeric, errors='coerce') df['income'] = df['income'].fillna(df['coupon'].mul(df['value']).div(100)) Output: value coupon income 0 100 3.0 3.0 1 150... | 3 | 3 |
78,224,406 | 2024-3-26 | https://stackoverflow.com/questions/78224406/why-is-the-value-and-the-times-which-the-function-is-called-different-and-how-d | Updated: May I know how recursion works for this similar code? def fib( n ): global cnt cnt += 1 #global cnt is assigned and changed if n <= 2: return 1 return fib( n - 1 ) + fib( n - 2 ) cnt = 0 print(fib( 10 )) print("fib is called", cnt, "times") #109 times! Old question: def power_of_two(n): global cnt cnt += 1 if... | it will be 4 times for n=3, Steps for your code. for n==3 your cnt ==1 return 2* #Recursion step 1 for n==2 it will be cnt ==2 return 2*2* #Recursion step 2 for n==1 it will be cnt==3 return 2*2*2* #Recursion step 3 and for last step is the stop recursion with if n==0 statement, so cnt==4 return 2*2*2*1 #Recursion step... | 2 | 1 |
78,224,121 | 2024-3-26 | https://stackoverflow.com/questions/78224121/annotate-at-the-top-of-a-marker-with-varying-sizes-in-matplotlib | Can I get the coordinates of markers to move the annotation to the top of the triangle? import matplotlib.pyplot as plt X = [1,2,3,4,5] Y = [1,1,1,1,1] labels = 'ABCDE' sizes = [1000, 1500, 2000, 2500, 3000] fig, ax = plt.subplots() ax.scatter(X, Y, s= sizes, marker = 10) for x, y, label, size in zip(X, Y, labels, size... | You need to (a) move the y coordinate by something proportional to the height of the marker; (b) root the text at bottom centre ("center" in American!). Note that the "size" of a marker is proportional to its AREA. So its height is proportional to sqrt(size). A certain amount of trial and error produced this. The heigh... | 2 | 3 |
78,194,686 | 2024-3-20 | https://stackoverflow.com/questions/78194686/how-to-web-scrape-google-news-headline-of-a-particular-year-e-g-news-from-2020 | I've been exploring web scraping techniques using Python and RSS feed, but I'm not sure how to narrow down the search results to a particular year on Google News. Ideally, I'd like to retrieve headlines, publication dates, and possibly summaries for news articles from a specific year (such as 2020). With the code provi... | You can use date filters in your rss_url. modify the query part in the below format Format: q=query+after:yyyy-mm-dd+before:yyyy-mm-dd Example: https://news.google.com/rss/search?q=forex%20rate%20news+after:2023-11-01+before:2023-12-01&hl=en-IN&gl=IN&ceid=IN:en The URL above returns articles related to forex rate news ... | 2 | 2 |
78,218,094 | 2024-3-25 | https://stackoverflow.com/questions/78218094/how-to-mock-a-python-function-so-that-it-wont-be-called-during-import | I am writing some unit tests (using pytest) for someone else's code which I am not allowed to change or alter in any way. This code has a global variable, that is initialized with a function return outside of any function and it calls a function which (while run locally) raises an error. I cannot share that code, but I... | As other commenters already noted, the problem that you attempt to solve hints at bigger issues with the code to be tested, so probably giving an answer to how the specific problem can be solved is actually the wrong thing to do. That said, here is a bit of an unorthodox and messy way to do so. It is based on the follo... | 3 | 3 |
78,221,500 | 2024-3-25 | https://stackoverflow.com/questions/78221500/python-pandas-subset-dataframe-based-on-non-missing-values-from-a-column | I have a pd dataframe: import pandas as pd column1 = [None,None,None,4,8,9,None,None,None,2,3,5,None] column2 = [None,None,None,None,5,1,None,None,6,3,3,None,None] column3 = [None,None,None,3,None,7,None,None,7,None,None,1,None] df = pd.DataFrame(np.column_stack([column1, column2,column3]),columns=['column1', 'column2'... | You can find the non-na value, then perform a cumulative sum, then mod 2 to get the "groups" of start and one-less-than stop positions. Shifting this by 1, adding to the original, and clipping to (0, 1) gets clumps of the start and stop points. To label the groups, you can take a diff of 1, then clip to (0, 1) again, a... | 2 | 1 |
78,211,119 | 2024-3-23 | https://stackoverflow.com/questions/78211119/how-to-tackle-statement-is-unreachable-unreachable-with-mypy-when-setting-at | Problem description Suppose a following test class Foo: def __init__(self): self.value: int | None = None def set_value(self, value: int | None): self.value = value def test_foo(): foo = Foo() assert foo.value is None foo.set_value(1) assert isinstance(foo.value, int) assert foo.value == 1 # unreachable The test: Fir... | You can explicitly control type narrowing with the TypeGuard special form (PEP 647). Although normally you would use TypeGuard to farther narrow a type than what has already been inferred, you can use it to 'narrow' to whatever type you choose, even if it is different or broader than the type checker has already inferr... | 3 | 1 |
78,215,074 | 2024-3-24 | https://stackoverflow.com/questions/78215074/stacked-subplots-with-same-legend-color-and-labels | I have been trying to plot a stacked plot with the same legend color and non-duplicate labels, without much of a success. import plotly.graph_objects as go from plotly.subplots import make_subplots # Sample data x = [1, 2, 3, 4, 5] y1 = [1, 2, 4, 8, 16] y2 = [1, 3, 6, 10, 15] y3 = [1, 4, 8, 12, 16] # Create subplot fig... | You can set the fill color directly for each trace like so: from plotly.subplots import make_subplots import plotly.graph_objects as go # Sample data x = [1, 2, 3, 4, 5] y1 = [1, 2, 4, 8, 16] y2 = [1, 3, 6, 10, 15] y3 = [1, 4, 8, 12, 16] # Create subplot figure with two subplots fig = make_subplots(rows=1, cols=2, subp... | 2 | 1 |
78,217,152 | 2024-3-25 | https://stackoverflow.com/questions/78217152/created-nested-json-from-dataframe | data={'category':['Medical','Medical','Research','Medical','Research'], 'countrycode':['US','CAN','US','CAN','US'], 'stateCode':['AK','AB','MO','NT','OK'], 'statecount':[600,100,200,760,90]} df=pd.DataFrame(data) Given is my input dataframe. I want to produce a nested json output as follows : { 'Medical' : { 'US' : {'... | One efficient option using groupby: out = {} for (k1,k2), g in df.groupby(['category', 'countrycode']): out.setdefault(k1, {})[k2] = g.set_index('stateCode')['statecount'].to_dict() Alternatively, less efficient but maybe more flexible: {k1: {k2: g2.set_index('stateCode')['statecount'].to_dict() for k2, g2 in g.groupb... | 2 | 1 |
78,216,573 | 2024-3-25 | https://stackoverflow.com/questions/78216573/question-about-difference-between-two-expressions | if any([x % 2 for x in result]): print("good") and if any(x % 2 for x in result): print("good") I'm studying Python, but not sure what is difference between two expressions shown above. Does the first expression check each element in list? I try to code myself, to solve this problem, but I don't get it why those two ... | To see what's going on, let's run the following program: def test(i): print(i) if i == 5: return True return False if any([test(i) for i in range(10)]): print("Done") if any(test(i) for i in range(10)): print("Done") 0 1 2 3 4 5 6 7 8 9 Done 0 1 2 3 4 5 Done The first version creates a list using list comprehension, ... | 2 | 3 |
78,216,029 | 2024-3-24 | https://stackoverflow.com/questions/78216029/loop-through-each-customer-records-to-get-the-first-last-channel-they-came-from | I have customer visit records with the channel they came from. I want to have one record per customer where I have the first channel they came from and the last channel they came from. Another logic I need to add is that if the first channel is "Direct", then do not take it and look at the next record. If that next rec... | Convert Date to datetime so you can sort by Date (use format="%m/%d/%y" if your dates are in this format instead). Define condition_i and condition_ii to account for your new logic: you want to keep for each Customer ID: (i) all rows if Channel is Direct for all rows; or (ii) only rows where Channel is not Direct, if ... | 2 | 1 |
78,214,477 | 2024-3-24 | https://stackoverflow.com/questions/78214477/how-to-make-black-borders-around-certain-markers-in-a-seaborn-pairplot | I have the following code: import seaborn as sns import pandas as pd import numpy as np Data = pd.DataFrame(columns=['x1','x2','x3','label']) for i in range(100): Data.loc[len(Data.index)] = [np.random.rand(),np.random.rand(),np.random.rand(),'1'] Data.loc[len(Data.index)] = [np.random.rand(),np.random.rand(),np.random... | The scatter dots are stored in ax.collections[0]. To avoid that the colors of later hue values always come on top, seaborn keeps the dots in the order they appear in the dataframe. You can use .set_edgecolors() to set the edge color of each individual dot. For the legend, the dots in stored in its handles as line objec... | 5 | 3 |
78,214,361 | 2024-3-24 | https://stackoverflow.com/questions/78214361/how-to-handle-inf-and-nans-in-great-table | I've got a dataframe that I want to format which includes inf and nan. The dict for it is: df = pd.DataFrame({'Foodbank': {0: 'study', 1: 'generation', 2: 'near', 3: 'sell', 4: 'former', 5: 'line', 6: 'ok', 7: 'field', 8: 'last', 9: 'really', 10: 'particularly', 11: 'must', 12: 'drive', 13: 'herself', 14: 'learn'}, '%(... | A possible solution: df['%(LY)'] = df['%(LY)'].replace(np.inf, np.nan) Output: Foodbank %(LY) 0 study -20.93 1 generation -19.23 2 near -26.09 3 sell 150.00 4 former 90.24 5 line -23.85 6 ok NaN 7 field NaN 8 last NaN 9 really NaN 10 particularly NaN 11 must -35.48 12 drive NaN 13 herself NaN 14 learn -1.30 | 3 | 3 |
78,212,524 | 2024-3-23 | https://stackoverflow.com/questions/78212524/strategies-for-enhancing-algorithm-efficiency | I have this task: Mother Anna opened a package of candies, which she wants to distribute to her children as a reward. So that they are not clashes between them, so of course the one who finished in a better place in the competition cannot get less candies than the one that ended up in a worse place. How many ways can A... | Consider that each assignment of candies is an integer partition of n candies into k parts. Also note that for each partition of n candies, there is a single unique assignment candies to children that is valid (e.g. for n=7 the partition 3 3 1 can only be mapped to children in one way, [0, 3, 3], anything else would be... | 2 | 2 |
78,213,315 | 2024-3-24 | https://stackoverflow.com/questions/78213315/aggregate-in-polars-by-appending-lists | In Python Polars, how can I aggregate by concatenating lists, rather than creating a nested list? For example, I'd like to aggregate this dataframe on id import polars as pl df = pl.DataFrame({ 'id': [1, 1], 'name': [["Bob"], ["Mary", "Sue"]], }) id name 1 ["Bob"] 1 ["Mary", "Sue"] and get this result i... | Try using explode on your name column. result_df = df.group_by('id').agg(pl.col('name').explode()) | 2 | 2 |
78,208,864 | 2024-3-22 | https://stackoverflow.com/questions/78208864/time-based-spacing-constraints-in-gekko | I'm trying to constrain the vector output of "simu_total_volume" below by requiring that solution output elements (x7=1) be spaced apart by s records (weeks) while also controlling for the maximum number of times x7 can be = 1 in total. The code below seems to work but I'm noticing a reduction in the sum of x7 from 10 ... | Enforce a spacing constraint with a summation over a subset of the periods with a moving window such as: m.Equation(sum(x[0:3])<=1) m.Equation(sum(x[1:4])<=1) m.Equation(sum(x[2:5])<=1) Here is a test that shows solutions with different spacing constraints with a maximum of 4 out of the 5 selected. The spacing constra... | 3 | 1 |
78,212,052 | 2024-3-23 | https://stackoverflow.com/questions/78212052/stop-ode-integration-when-a-condition-is-satisfied | I'm simulating double pendulum fliptimes using scipy.integrate.odeint. The way my code is structured, odeint solves the system over a fixed time interval; then I have to check the result to see if a flip occurred. Instead, I want to check after each step whether the condition is satisfied, and if so, stop. Then, there ... | In the language of initial value problems, you want to detect an "event". scipy.integrate.odeint does not provide an interface for that. This is one of the reasons the documentation suggests: For new code, use scipy.integrate.solve_ivp to solve a differential equation. Once you convert your code to use solve_ivp, you... | 2 | 2 |
78,210,383 | 2024-3-23 | https://stackoverflow.com/questions/78210383/odoo16-where-is-the-docs-variable-used-in-the-template-defined | I have created 2 recrods, action report and template for pdf, but I have never defined the docs variable in the model, so how can Odoo understand it, or is it defined by default somewhere? So what if I want to define additional variables like "text1" : "hello" to use in the template? Thanks All | The docs variable is set while rendering the report,in _get_rendering_context function 1/ You can pass them through data to report_action Example: (from employees summary report) def print_report(self): self.ensure_one() [data] = self.read() data['emp'] = self.env.context.get('active_ids', []) employees = self.env['hr.... | 2 | 3 |
78,202,681 | 2024-3-21 | https://stackoverflow.com/questions/78202681/explode-a-dataframe-into-a-range-of-another-dataframe | I have some data in 2 dataframes that look like: import polars as pl data = {"channel": [0, 1, 2, 1, 2, 0, 1], "time": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]} time_df = pl.DataFrame(data) data = { "time": [10.0, 10.5], "event_table": [["start_1", "stop_1", "start_2", "stop_2"], ["start_3"]], } events_df = pl.DataFrame(dat... | Not sure if I'm overcomplicating things here but: The initial approach that comes to mind is to number the events so they align with the row index from the channels. shape: (2, 2) ┌──────────────────────────────────┬───────┐ │ event_table ┆ index │ │ --- ┆ --- │ │ list[str] ┆ u32 │ ╞══════════════════════════════════╪═... | 2 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.