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,074,479 | 2024-2-28 | https://stackoverflow.com/questions/78074479/add-row-of-column-totals-in-polars | I'm trying to move away from pandas to polars, I have a use case where I need to add the column totals as a new row to the polars lazy frame. I've found this answer and it would perfectly solve my problem in pandas, but I haven't found any way or documentation on how to translate this code to polars. | To create a new row with the total of each column, you can first create a row of the column totals using an aggregation and then concatenate it to the dataframe using pl.concat. pl.concat([df, df.select(pl.all().sum())]) Previous answer Disclaimer. My original answer was based on the answer to the linked pandas questi... | 4 | 5 |
78,084,763 | 2024-2-29 | https://stackoverflow.com/questions/78084763/collect-common-groups-on-non-index-column-across-two-dataframes | Here are two dataframes grouped how I want them: last5s = pd.Timestamp.now().replace(microsecond=0) - pd.Timedelta('5s') dates = pd.date_range(last5s, periods = 5, freq='s') N=10 data1 = np.random.randint(0,10,N) data2 = np.random.randint(0,10,N) df1 = pd.DataFrame({'timestamp': np.random.choice(dates, size=N), 'A': da... | You can just do: for t, d1 in g1: d2 = g2.get_group(t) if d2 is None: print("I don't want this") continue print(d1) print('-'*10) print(d2) print('='*30) Output: timestamp A 0 2024-02-29 19:10:14 0 3 2024-02-29 19:10:14 7 7 2024-02-29 19:10:14 1 ---------- timestamp B 1 2024-02-29 19:10:14 0 3 2024-02-29 19:10:14 6 5... | 5 | 3 |
78,083,235 | 2024-2-29 | https://stackoverflow.com/questions/78083235/add-a-constant-to-an-existing-column | Dataframe: rng = np.random.default_rng(42) df = pl.DataFrame( { "nrs": [1, 2, 3, None, 5], "names": ["foo", "ham", "spam", "egg", None], "random": rng.random(5), "A": [True, True, False, False, False], } ) Currently, to add a constant to a column I do: df = df.with_columns(pl.col('random') + 500.0) Questions: Why do... | AI:s tell you to do so, because they are not actually intelligent They try to suggest you how it's done in pandas, because of similar keywords like dataframe and python. But it just does not work the same way with polars by design. Augmented assignment problem With += too, it's really just a matter of syntax. pl.col is... | 3 | 6 |
78,071,328 | 2024-2-28 | https://stackoverflow.com/questions/78071328/get-the-number-of-all-possible-combinations-that-give-a-certain-product | I'm looking for a algorithm that counts number of all possible combinations that gives certain product. I have a list of perfect squares [1,4,9,16,..,n] and I have two values a, b where a - number of elements that we can use in multiplication to get perfect square, b - maximum value of each element that can be used in ... | Here's a mostly straightforward solution using recursive generators. No element larger than b shows up because no element so large is ever considered. Duplicates never show up because, by construction, this yields lists in non-increasing order of elements (i.e., in lexicographically reverse order). I don't know what sq... | 4 | 5 |
78,077,316 | 2024-2-28 | https://stackoverflow.com/questions/78077316/exception-not-found-python-cv2-py-typed-error-failed-building-wheel-for-ope | I am following the env setup in CenterPose repo. However, opencv-python doesn't get installed. (CenterPose) mona@ada:/data/CenterPose/data$ pip install opencv-python I get this error: -- Installing: /tmp/pip-install-wjrf6kvm/opencv-python_e5e6222fa4024d2d8f3e1d1c3bd5fb1f/_skbuild/linux-x86_64-3.6/cmake-install/share/o... | The last OpenCV version to have wheels built for Python 3.6 was v4.6. With that in mind, I was able to get everything installed by explicitly restricting to that version. Here is a standalone YAML that handles everything needed for environment creation (this doesn't require repository cloning): CenterPose_py36.yaml nam... | 4 | 5 |
78,071,815 | 2024-2-28 | https://stackoverflow.com/questions/78071815/design-add-and-search-words-data-structure-leetcode-211 | I am currently trying to solve the problem Add and Search Words Data Structure on leetcode. The question is as follows: Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: WordDictionary() Initializes the object. void a... | One thing searching in a trie shares with binary search is that it keeps shrinking the possibilities between a range; except instead of binary, it's character-by-character, and instead of dividing down the binary middle, it uses the position in the word. (It still performs with log n iid, see Tong2016Smoothed.) However... | 3 | 1 |
78,082,450 | 2024-2-29 | https://stackoverflow.com/questions/78082450/removing-duplicate-sub-dataframes-from-a-pandas-dataframe | I have a pandas dataframe, for example df_dupl = pd.DataFrame({ 'EVENT_TIME': ['00:01', '00:01', '00:01', '00:03', '00:03', '00:03', '00:06', '00:06', '00:06', '00:08', '00:08', '00:10', '00:10', '00:11', '00:11', '00:13', '00:13', '00:13'], 'UNIQUE_ID': [123, 123, 123, 125, 125, 125, 123, 123, 123, 127, 127, 123, 123,... | Another approach is to shift the rows by enumeration, then compare: # the value columns value_cols = df.columns[2:] # groups are identified as `EVENT_TIME` and `UNIQUE_ID` groupby = df_dupl.groupby(['EVENT_TIME','UNIQUE_ID'])['Value1'] # these are the groups groups = groupby.ngroup() # enumeration within the groups enu... | 5 | 5 |
78,080,665 | 2024-2-29 | https://stackoverflow.com/questions/78080665/insert-attibute-in-position | I need to insert an element attribute at the correct position using the lxml library. Here is an example where I am trying to insert the attr2 attribute in front of the attr3 attribute: from lxml import etree xml = '<root attr0="val0" attr1="val1" attr3="val3" attr4="val4" attr5="val5"/>' root = etree.fromstring(xml) i... | One possible solution could be to recreate the element attributes from scratch: from lxml import etree xml = '<root attr0="val0" attr1="val1" attr3="val3" attr4="val4" attr5="val5"/>' root = etree.fromstring(xml) attribs = root.attrib.items() root.attrib.clear() for k, v in attribs: if k == "attr3": root.attrib["attr2"... | 2 | 3 |
78,080,284 | 2024-2-29 | https://stackoverflow.com/questions/78080284/test-for-missing-import-with-pytest | In the __init__.py-file of my project I have the following code, for retrieving the current version of the program from the pyproject.toml-file: from typing import Any from importlib import metadata try: import tomllib with open("pyproject.toml", "rb") as project_file: pyproject: dict[str, Any] = tomllib.load(project_f... | You can monkeypatch sys.modules, so tomllib is not there (see Python testing: Simulate ImportError) Here is a curated example: import sys def func(): try: import tomllib return 1 except ImportError: return 0 def test_with_tomllib(): assert func() == 1 def test_without_tomllib(monkeypatch): monkeypatch.setitem(sys.modul... | 3 | 4 |
78,075,981 | 2024-2-28 | https://stackoverflow.com/questions/78075981/joining-polars-dataframes-while-ignoring-duplicate-values-in-the-on-column | Given the code df1 = pl.DataFrame({"A": [1, 1], "B": [3, 4]}) df2 = pl.DataFrame({"A": [1, 1], "C": [5, 6]}) result = df1.join(df2, on='A') result looks like shape: (4, 3) ┌─────┬─────┬─────┐ │ A ┆ B ┆ C │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╡ │ 1 ┆ 3 ┆ 5 │ │ 1 ┆ 4 ┆ 5 │ │ 1 ┆ 3 ┆ 6 │ │ 1 ┆ 4 ┆ 6... | If the tables are aligned (possibly, after sorting by the on column), you can concatenate them horizontally using pl.concat. pl.concat([df1.sort("A"), df2.sort("A").drop("A")], how="horizontal") shape: (2, 3) ┌─────┬─────┬─────┐ │ A ┆ B ┆ C │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╡ │ 1 ┆ 3 ┆ 5 │ │ ... | 3 | 3 |
78,077,410 | 2024-2-28 | https://stackoverflow.com/questions/78077410/styling-negative-numbers-in-pandas | I have a dataframe that I am exporting to Excel. I would also like to style it before the export. I have this code which changes the background color and text color and works fine, but I would like to add to it: df.style.set_properties(**{'background-color': 'black', 'color': 'lawngreen', 'border-color': 'white'}).to_e... | I'd break it down into three steps (see the comments #) : st = ( df.style # 1-applying the default styles .set_properties(**default_css) # 2-formatting the numeric columns .apply( lambda df_: df_.select_dtypes("number") .lt(0).replace({True: tc(neg), False: tc(pos)}), axis=None, ) .format(precision=2) # this one is opt... | 3 | 1 |
78,076,178 | 2024-2-28 | https://stackoverflow.com/questions/78076178/how-do-i-type-hint-a-return-type-of-one-function-based-init-if-init-is-overloade | I have a class that accepts either ints or floats in it's init but all must be int or float so i am using typing.overload to achieve that and I want to be able to type hint the return of a function based on the given values. class Vector3: @overload def __init__(self, x: int, y: int, z: int) -> None: ... @overload def ... | Don't overload __init__ at all. Make Vector3 generic instead, using a constrained type variable. from typing import Generic, TypeVar T = TypeVar('T', int, float) class Vector3(Generic[T]): def __init__(self, x: T, y: T, z: T) -> None: self._x: T = x self._y: T = y self._z: T = z def __key(self) -> tuple[T, T, T]: retur... | 4 | 5 |
78,075,720 | 2024-2-28 | https://stackoverflow.com/questions/78075720/how-to-write-to-a-sqlite-database-using-polars-in-python | import polars as pl import sqlite3 conn = sqlite3.connect("test.db") df = pl.DataFrame({"col1": [1, 2, 3]}) According to the documentation of pl.write_database, I need to pass a connection URI string e.g. "sqlite:////path/to/database.db" for SQLite database: df.write_database("test_table", f"sqlite:////test.db", if_ta... | When working with SQLite, the number of slashes depends on how you are accessing the sqlite file. If you use two slashes as suggested in the comments, you'll see this: sqlalchemy.exc.ArgumentError: Invalid SQLite URL: sqlite://test.db Valid SQLite URL forms are: sqlite:///:memory: (or, sqlite://) sqlite:///relative/pat... | 7 | 3 |
78,073,286 | 2024-2-28 | https://stackoverflow.com/questions/78073286/how-can-i-have-the-value-of-a-gradio-block-be-passed-to-a-functions-named-param | Example: import gradio as gr def dummy(a, b='Hello', c='!'): return '{0} {1} {2}'.format(b, a, c) with gr.Blocks() as demo: txt = gr.Textbox(value="test", label="Query", lines=1) txt2 = gr.Textbox(value="test2", label="Query2", lines=1) answer = gr.Textbox(value="", label="Answer") btn = gr.Button(value="Submit") btn.c... | As far as I know, Gradio doesn't directly allow it. I.e., it doesn't allow something like this: btn.click(fn=dummy, inputs={"a": txt, "c": txt2}, outputs=answer) In this specific case, if you can't modify the dummy function then I would rearrange the parameters with the following function: def rearrange_args(func): de... | 2 | 3 |
78,072,152 | 2024-2-28 | https://stackoverflow.com/questions/78072152/getting-all-value-that-is-max-occurrence-of-each-row-of-numpy | How to gather all the values that repeated the most in each row of the numpy array, like the result of np.unique. However, I want to avoid loops as the data to be handle will be much larger (much more rows). See the example below Input: a is a 2D array, had the shape of (x, k), where x would be very large. a = np.asarr... | Use statistics.multimode: from statistics import multimode out = list(map(multimode, a)) Output: [[2, 7], [5], [6]] | 2 | 3 |
78,071,920 | 2024-2-28 | https://stackoverflow.com/questions/78071920/add-multiple-columns-from-one-function-call-in-python-polars | I would like to add multiple columns at once to a Polars dataframe, where each column derives from the same object (for a row), by creating the object only once and then returning a method of that object for each column. Here is a simplified example using a range object: import polars as pl df = pl.DataFrame({ 'x': [11... | If you return a dictionary from your function: return dict(count_of_10=c10, count_of_12=c12) You will get a struct column: df.with_columns( count = pl.col('x').map_elements(uses_object) ) shape: (2, 2) ┌─────┬───────────┐ │ x ┆ count │ │ --- ┆ --- │ │ i64 ┆ struct[2] │ ╞═════╪═══════════╡ │ 11 ┆ {1,0} │ │ 22 ┆ {1,1} ... | 3 | 2 |
78,059,324 | 2024-2-26 | https://stackoverflow.com/questions/78059324/attributeerror-styler-object-has-no-attribute-style | This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'a': [2, 2, 2, -4, 4, 4, 4, -3, 2, -2, -6], 'b': [2, 2, 2, 4, 4, 4, 4, 3, 2, 2, 6] } ) I use a function to highlight cells in a when I use to_excel: def highlight_cells(s): if s.name=='a': conds = [s > 0, s < 0, s == 0] labels = ['background-color: lime', ... | style.apply already returns a Styler object, you only need further do operation on this, i.e. df.style.apply(highlight_cells).format(...) # ^ # | # No need .style again | 2 | 4 |
78,047,434 | 2024-2-23 | https://stackoverflow.com/questions/78047434/deserialize-aliased-json-using-pydantic | I am wanting to use the Pydantic (Version: 2.6.1) aliases so that I can use a Python keyword ('from') when creating JSON. I thought this would work: from pydantic import BaseModel, Field class TestModel(BaseModel): from_str: str = Field(serialization_alias="from") test_obj = TestModel(from_str="John") print("TestModel:... | I was able to 'fix' this by setting up the class as follows: class TestModel(BaseModel): model_config = ConfigDict(populate_by_name=True) from_str: str = Field(alias="from") Where populate_by_name allows you to access the class variable via it's name, but serialization and validation use the alias. | 2 | 2 |
78,040,248 | 2024-2-22 | https://stackoverflow.com/questions/78040248/visualize-nodes-and-their-connections-in-clusters-via-networkx | I have a list of Connections between two nodes describing similarities of Entries in a Dataset. I'm thinking of vizualising the Entries and their connections to show that there are clusters of very similar entries. Each tuple stands for a pair of very similar nodes. I've chosen weight as 1 for all of them since it's re... | From an InfoVis perspective there are a few things you can do transparency & node size Transparency can be used to visualize overlapping. You have to choose between these two tradeoffs: A lower transparency level allows you to visualize more layers, for that many nodes need to overlap and you should increase the node ... | 3 | 2 |
78,070,256 | 2024-2-27 | https://stackoverflow.com/questions/78070256/htmx-hx-target-error-fails-when-hx-target-defined-django-python | I am using the htmx extension "response-targets" via "hx-ext" in a python django project. The Problem "hx-target-error" will not work when "hx-target" is also defined, but works when it is the only target. Environment htmx 1.9.10, response-targets 1.9.10, python 3.12, django 5.0.1 Example html: <div hx-ext="response-ta... | Resolved: The solution is to move the "hx-ext" attribute <div hx-ext="response-targets"> to a higher encompassing level than any DOM elements referenced by either "hx-target" or "hx-target-error". In my case, "hx-target-error" pointed to a div 'id' outside of the div containing "hx-ext". Thank you @guigui42 for suggest... | 2 | 7 |
78,057,740 | 2024-2-25 | https://stackoverflow.com/questions/78057740/chrome-122-how-to-allow-insecure-content-insecure-download-blocked | I'm unable to test file download with Selenium (python), after Chrome update to the version '122.0.6261.70'. Previously running Chrome with the '--allow-running-insecure-content' arg did a trick. The same is suggested over the net. On some sites one additional arg is suggested: '--disable-web-security'. But both change... | Okay, so found two solutions: --unsafely-treat-insecure-origin-as-secure=* This is an experimental flag that allows you to list which domains to treat as secure so the download is no longer blocked. --disable-features=InsecureDownloadWarnings This is a more stable flag that disables the insecure download blocking feat... | 10 | 20 |
78,065,058 | 2024-2-27 | https://stackoverflow.com/questions/78065058/knapsack-problem-find-top-k-lower-profit-solutions | In the classic 0-1 knapsack problem, I am using the following (dynamic programming) algorithm to construct a "dp table": def knapsack(weights, values, capacity): n = len(weights) weights = np.concatenate(([0], weights)) # Prepend a zero values = np.concatenate(([0], values)) # Prepend a zero table = np.zeros((n+1, capa... | I'd build a richer DP table. For each cell, you store just the total value of just one item set. I'd instead store information of the top k item sets for that cell: both the total value and the indices. Output of the below program: 22 [0, 1, 3] 22 [1, 2] 21 [0, 1, 4] And that's the information I store in the final tab... | 4 | 1 |
78,048,223 | 2024-2-23 | https://stackoverflow.com/questions/78048223/adding-folder-with-data-with-pyproject-toml | I would like to package some legacy code to a hello Python package containing only one module (hello.py) file in the top-level directory alongside with some data in a folder called my_data without changing the folder structure: hello/ |-hello.py |-pyproject.toml |-my_data/ |-my_data.csv Packaging the Python source cod... | The package-data configuration of setuptools can be used when you have a package. But instead you seem to have a a single file-module. In other words package-data is incompatible with the directory structure that you have. I suggest rearranging the files like the following: hello/ |-pyproject.toml |-hello/ |-__init__.p... | 2 | 2 |
78,056,565 | 2024-2-25 | https://stackoverflow.com/questions/78056565/how-do-i-get-doctest-to-run-with-examples-in-markdown-codeblocks-for-mkdocs | I'm using mkdocs & mkdocstring to build my documentation and including code examples in the docstrings. I'm also using doctest (via pytest --doctest-modules) to test all those examples. Option 1 - format for documentation If I format my docstring like this: """ Recursively flattens a nested iterable (including strings... | Patching the regex that doctest uses to identify codeblocks solved this problem. Documenting it here for those who stumble across this in the future ... As this is not something I want to do regularly in projects(!), I created pytest-doctest-mkdocstrings as a pytest plugin to do this for me and included some additional... | 3 | 0 |
78,048,681 | 2024-2-23 | https://stackoverflow.com/questions/78048681/add-a-new-column-into-an-existing-polars-dataframe | I want to add a column new_column to an existing dataframe df. I know this looks like a duplicate of Add new column to polars DataFrame but the answer to that questions, as well as the answers to many similar questions, don't really add a column to an existing dataframe. They create a new column with another dataframe.... | Your question suggests that you think that when you do df = df.with_columns( new_column = pl.lit('some_text') ) that you're copying everything over to some new df which would be really inefficient. You're right that that would be really inefficient but that isn't what happens. A DataFrame is just a way to organize poi... | 4 | 6 |
78,065,276 | 2024-2-27 | https://stackoverflow.com/questions/78065276/why-python-multiprocessing-process-passes-a-queue-parameter-and-read-faster-th | In python I have implemented 2 types of queue reads The difference: queue is created and executed in the main process queue is created in the main process and executed by other processes. But there is a performance difference, I tried to debug it, but I can't see why! code: queue1.py import multiprocessing import tim... | I don't know if I cam tell you "exactly why" you observe what you see but I have what I believe is a fairly good explanation -- even if it doesn't explain all of what you see. First, if you read the documentation on multiprocessing.Queue, you will see that the call to method qsize is not reliable and should not be used... | 2 | 3 |
78,070,791 | 2024-2-27 | https://stackoverflow.com/questions/78070791/my-floating-point-problem-trial-in-c-python | In what follows, IEEE-754 Double-precision floating-point format is taken for granted to be used. Python: "...almost all machines use IEEE 754 binary floating-point arithmetic, and almost all platforms map Python floats to IEEE 754 binary64 'double precision' values." C++: associates double with IEEE-754 double-precisi... | Yes, it's entirely about round-to-nearest/even. Python's float.hex() can show you the bits directly: >>> 1.0 + 2**-52 + 2**-53 1.0000000000000004 >>> _.hex() '0x1.0000000000002p+0' Although Python and C have little to do with this: it's almost certainly a result of how your CPU/FPU implement float addition (they almos... | 4 | 1 |
78,069,220 | 2024-2-27 | https://stackoverflow.com/questions/78069220/what-sorting-algorithm-is-this-merge-iterator-with-itself | As long as the list isn't sorted, keep replacing it with a merge of an iterator with itself. Is that (equivalent to) one of the commonly known sorting algorithms, just implemented weirdly, or is it something new? from random import shuffle from heapq import merge from itertools import pairwise # Create test data a = li... | It's indeed bubble sort implemented weirdly. Bubble sort repeatedly does this until the list is sorted: Slide a two-item window over the list. At each position, sort the two items in the window, then slide the window one position to the right. This leaves the smaller item behind, the larger item remains in the window,... | 4 | 2 |
78,063,441 | 2024-2-26 | https://stackoverflow.com/questions/78063441/rolling-mean-with-conditions-interview-problem | I encountered this question during an interview and can't think of a solution. This is the problem, suppose you had a dataset as follows (it goes beyond time 2 but this is just a sample to work with): import pandas as pd data = pd.DataFrame({ 'time': [1, 1, 1, 2, 2, 2], 'names': ["Andy", "Bob", "Karen", "Andy", "Matt",... | IIUC, you want to compute the mean of the values up to the current time, while considering only the last seen duplicates (if any). If so, here is one potential option that uses boolean indexing inside a for-loop to build the expanding windows : # uncomment if necessary # data.sort_values("time", inplace=True) to_keep =... | 3 | 1 |
78,069,577 | 2024-2-27 | https://stackoverflow.com/questions/78069577/datetime-now-in-windows-vs-wsl-vs-linux | I see a difference in the datetime.now() function in Windows Python 3.11 vs WSL Python 3.10 and Linux Python 3.10. On Windows, I get duplicate entries. On WSL and Linux, I don't. I am converting a test system from primarily being used with Python in WSL to using Python in Windows natively and hit a kind of weird issue.... | As Python uses underlying operating system features, some of its behaviors will differ depending on what OS fuels your runtime environment. And while your test is bit flawed because you use different Python versions, unifying these would most likely yield to similar results. Windows has historically had issues with tim... | 3 | 4 |
78,068,806 | 2024-2-27 | https://stackoverflow.com/questions/78068806/polars-aggregate-without-a-groupby | Is there a way to call .agg() without grouping first? I want to perform standard aggregations but only want one row in the response, rather than separate rows for separate groups. I could do something like df.with_columns(dummy_col=pl.lit("dummy_col")).group_by('dummy_col').agg(<aggregateion>) but I'm wondering if the... | When all expressions within a select context are aggregations, the resulting dataframe only has a single row. import polars as pl df = pl.DataFrame({ "a": [1, 2, 3, 4, 5], "b": [0, 0, 1, 1, 1], }) df.select(pl.col("a").mean(), pl.col("b").first()) shape: (1, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ f64 ┆ i64 │ ╞═══... | 4 | 5 |
78,068,616 | 2024-2-27 | https://stackoverflow.com/questions/78068616/what-is-the-difference-between-driver-and-webdriver-python-selenium | About Selenium with Python... What is the difference between from seleniumbase import Driver (seleniumbase) and from selenium import webdriver (selenium, seleniumwire)? What is the difference in "use cases"? I see only constructor difference: seleniumbase Driver is harder to set options, then manipulaton with object ar... | It sounds like you're trying to compare this: from seleniumbase import Driver driver = Driver() with: from selenium import webdriver driver = webdriver.Chrome() The seleniumbase driver has more methods than the regular selenium one. The seleniumbase driver methods also have auto-selector detection, smart waiting, spe... | 2 | 2 |
78,057,716 | 2024-2-25 | https://stackoverflow.com/questions/78057716/trying-to-run-gemma-on-kaggle-and-got-issue-keras-nlp-models-has-no-attribute | I'm trying to run Gemma on Keras with this model https://www.kaggle.com/models/keras/gemma/frameworks/keras/variations/gemma_instruct_7b_en And I'm reproducing the Example available on "Model Card" on above page. When I run this code: gemma_lm = keras_nlp.models.GemmaCausalLM.from_preset("gemma_instruct_7b_en") gemma_l... | Try restarting the kernel. Note that the same behavior occurs with the 2B Gemma model, i.e. gemma_lm = keras_nlp.models.GemmaCausalLM.from_preset("gemma_2b_en"). I am not sure why restarting the kernel works, but it's worth noting that this doesn't happen in Google Colab. | 3 | 3 |
78,067,486 | 2024-2-27 | https://stackoverflow.com/questions/78067486/given-a-value-from-a-pandas-column-dataframe-select-n-rows-above-and-below-to-t | I have two pandas DataFrames: import pandas as pd data1 = { 'score': [1, 2], 'seconds': [1140, 2100], } data2 = { 'prize': [5.5, 14.5, 14.6, 21, 23, 24, 26, 38, 39, 40, 50], 'seconds': [840, 1080, 1380, 1620, 1650, 1680, 1700, 1740, 2040, 2100, 2160], } df1 = pd.DataFrame.from_dict(data1) df2 = pd.DataFrame.from_dict(d... | You can use a merge_asof to identify the closest value to each value in df1, then a rolling.max to extend the selection to the neighboring N rows: N = 2 # number of surronding rows to keep s1 = df1['seconds'].sort_values() s2 = df2['seconds'].sort_values().rename('_') keep = pd.merge_asof(s1, s2, left_on='seconds', rig... | 6 | 8 |
78,065,399 | 2024-2-27 | https://stackoverflow.com/questions/78065399/select-consecutive-elements-that-satisfy-a-certain-condition-as-separate-arrays | Given an array of values, I want to select multiple sequences of consecutive elements that satisfy a condition. The result should be one array for each sequence of elements. For example I have an array containing both negative and positive numbers. I need to select sequences of negative numbers, with each sequence in a... | clustering groups of negative numbers If you only want to group the chunks of negative values, irrespective of their relative values, then simply compute a second mask to identify the starts of each negative chunk: mask = values < 0 mask2 = np.r_[True, np.diff(mask)] out = np.array_split(values[mask], np.nonzero(mask2[... | 4 | 4 |
78,065,410 | 2024-2-27 | https://stackoverflow.com/questions/78065410/how-to-get-real-part-of-a-sympy-expression | In Sympy I want to get the real part of an expression, but unable to separate the real part. The steps I have done: from sympy import * a, b = symbols('a b') z1 = a + b*I z2 = simplify(expand(z1**3)) The z2 output is: a**3 + 3*I*a**2*b - 3*a*b**2 - I*b**3 When I try to get the real part, I get this: >>> re(z2) re(a)*... | Sympy doesn't realize that you want a and b to be real variables, so its output assumes they are complex. If a and b are real, then terms containing im(a) and/or im(b) are 0 since there are no imaginary parts to a or b. To fix this, you should define your variables with your assumptions, i.e. tell sympy that a and b ar... | 2 | 3 |
78,063,360 | 2024-2-26 | https://stackoverflow.com/questions/78063360/pandas-modified-rolling-average | Below is my outlier detection code in pandas. I am doing rolling over window of 15, what I want is to do over window of 5 where this window is based on the day of week of the centered date i.e. if the centre is Monday take 2 backwards monday and 2 forward monday. Rolling doesn't have any support for this. How to do? im... | One option using a groupby.rolling and the dayofweek as grouper to ensure only using the identical days in the rolling: r = (df.set_index('Date') .groupby(df['Date'].dt.dayofweek.values) # avoid index alignment .rolling(f'{5*7}D', center=True) ['Price1'] ) avg = r.mean().set_axis(df.index) # restore correct index std =... | 2 | 5 |
78,050,400 | 2024-2-23 | https://stackoverflow.com/questions/78050400/list-of-tuples-combine-two-dataframe-columns-if-first-tuple-elements-match | I have two separate lists each of n elements, with one being ID numbers and the second being pandas dataframes. I will define them as id and dfs. The dataframes in dfs have the same format with columns A, B, and C but with different numerical values. I have zipped the two lists together as such: df_groups = list(zip(id... | You can write a custom summarising function to go through all dataframes in a group and return a sum. I don't entirely love this solution, because in converts C to float, but you can play with it further if needed: from itertools import groupby import pandas as pd ids = ['a','b','c','a','d'] dfs = [ pd.DataFrame({"A": ... | 3 | 4 |
78,057,189 | 2024-2-25 | https://stackoverflow.com/questions/78057189/how-do-i-change-the-mv-status-of-a-gekko-variable-after-solving-for-steady-state | I am trying to find the value for an inlet flow rate that keeps a gravity drained tank at a required level. After the solution is found using IMODE 3, I want to simulate the system at this state for a period of time using IMODE 4. Below is the code I am using: from gekko import GEKKO import numpy as np m = GEKKO(remote... | Set m.options.SPECS = 0 to ignore the calculated / fixed specifications when changing modes (see documentation). Here is a complete script that solves successfully. from gekko import GEKKO import numpy as np m = GEKKO(remote = False) F_in = m.MV(value = 1, name= 'F_in') level = m.CV(value = 1, name = 'level') F_out = m... | 3 | 1 |
78,058,636 | 2024-2-26 | https://stackoverflow.com/questions/78058636/condaverificationerror-when-installing-pytorch | I am trying to install pytorch using either of below command and I got a lot of error. I am using windows CPU only. conda install pytorch::pytorch or conda install pytorch torchvision torchaudio cpuonly -c pytorch some of the error are CondaVerificationError: The package for pytorch located at C:\Users\test\miniconda3... | One of your packages seems to be corrupt. You can try cleaning the packages from cache and reinstalling pytorch: conda clean -p | 3 | 4 |
78,059,445 | 2024-2-26 | https://stackoverflow.com/questions/78059445/how-to-add-plus-sign-for-positive-number-when-using-to-excel | This is my DataFrame: import pandas as pd import numpy as np df = pd.DataFrame( { 'a': [2, 2, 2, -4, np.nan, np.nan, 4, -3, 2, -2, -6], 'b': [2, 2, 2, 4, 4, 4, 4, 3, 2, 2, 6] } ) I want to add a plus sign for positive numbers only for column a when exporting to Excel. For example 1 becomes +1. Note that I have NaN val... | What about using a callable: (df.style.format({'a': lambda x: f'{x:+g}' if np.isfinite(x) else ''}) .to_excel(r'/tmp/df.xlsx', sheet_name='xx', index=False) ) Alternative callable: lambda x: '' if np.isnan(x) else f'{x:+g}' Output (in jupyter): | 3 | 4 |
78,056,934 | 2024-2-25 | https://stackoverflow.com/questions/78056934/pandas-or-polars-find-index-of-previous-element-larger-than-current-one | Suppose my data looks like this: data = { 'value': [1,9,6,7,3, 2,4,5,1,9] } For each row, I would like to find the row number of the latest previous element larger than the current one. So, my expected output is: [None, 0, 1, 2, 1, 1, 3, 4, 1, 0] the first element 1 has no previous element, so I want None in the res... | This iterates only on the range of rows that this should look. It doesn't loop over the rows themselves in python. If your initial bound_range covers all the cases then it won't ever actually do a loop. lb=0 bound_range=3 df=df.with_columns(z=pl.lit(None, dtype=pl.UInt64)) while True: df=df.with_columns( z=pl.when(pl.c... | 18 | 4 |
78,057,705 | 2024-2-25 | https://stackoverflow.com/questions/78057705/is-there-a-simple-way-to-access-a-value-in-a-polars-struct | A basic use of value_counts in a DataFrame is to obtain the count of a specific value. If I have a df such as: DataFrame({"color": ["red", "blue", "red", "green", "blue", "blue"]}) then if I want the count for color = 'red' in Pandas I could simply use: df['color'].value_counts()['red'] which is clear and obvious. In... | If you don't want to use unnest, you can do df.select(pl.col("color").value_counts()).filter( pl.col("color").struct["color"] == "red" ).item()["count"] which gives 2 There's tradeoffs - not having an Index opens up more doors for scalability, but admittedly some operations to become more verbose | 3 | 2 |
78,054,752 | 2024-2-25 | https://stackoverflow.com/questions/78054752/fastapi-sqlmodel-pydantic-not-serializing-datetime | My understanding is that SQLModel uses pydantic BaseModel (checked the _mro_. Why is it that the bellow fails the type comparison. (err provided). class SomeModel(SQLModel,table=True): timestamp: datetime id: UUID = Field(default_factory=lambda: str(uuid4()), primary_key=True) def test_some_model(): m=SomeModel(**{'tim... | Adding validate_assignment fixes the issue. Picked this solution up from https://github.com/tiangolo/sqlmodel/issues/52 after more than a couple days of breaking my head. Hopefully this helps other poor souls. class SomeModel(SQLModel,table=True): class Config: validate_assignment = True timestamp: datetime age:int id... | 2 | 3 |
78,052,641 | 2024-2-24 | https://stackoverflow.com/questions/78052641/tkinter-output-of-function-as-table-and-graph | I have two functions that produce two types of output one is a data frame table and the other is a plot of that dataframe. All functions take one file as input. which we load from the previous tkinter function. I would like to dynamically select a function from the radio box, next, once we select a particular function ... | You have asked for the complete algorithm, in fact complete programming except how to manipulate your data. I don't know whether this kind of questions are allowed in stack overflow. I've given explanation as and where required. I couldn't check the code as you haven't provided the data and function you want to execute... | 2 | 2 |
78,056,851 | 2024-2-25 | https://stackoverflow.com/questions/78056851/how-to-leave-out-all-nans-a-pandas-dataframe | I'm upgrading some code from python2 to python3 and the modern pandas version (I now have pandas 2.0.3 and numpy version 1.26.4) My dataframe is : N NE E SE S SW W NW H12 NaN NaN NaN NaN NaN NaN NaN NaN H13 0.7 NaN NaN NaN NaN NaN 1.0 1.4 H14 0.3 NaN NaN NaN NaN NaN 0.8 1.1 H15 NaN NaN NaN NaN NaN NaN NaN NaN H16 NaN ... | any is now keyword-only, you have to use axis=1. Although you have not shown your original code, the following should work: out = df.loc[df.any(axis=1), df.any()] Output: N W NW H13 0.7 1.0 1.4 H14 0.3 0.8 1.1 | 2 | 2 |
78,057,088 | 2024-2-25 | https://stackoverflow.com/questions/78057088/how-to-keep-a-numeric-sequence-in-a-pandas-dataframe-column-that-only-increase | I have a DataFrame like this: import pandas as pd df = pd.DataFrame({ 'minutes':[1,2,3,4,5,6,7,8,9,10], 'score1': [0,0,1,1,0,0,0,1,1,2], 'score2': [0,1,1,1,1,2,1,1,2,2], 'sum_score': [0,1,2,2,1,2,1,2,3,4] }) Output: minutes score1 score2 sum_score 0 1 0 0 0 1 2 0 1 1 2 3 1 1 2 3 4 1 1 2 4 5 0 1 1 5 6 0 2 2 6 7 0 1 1 ... | Try: x = df[["score1", "score2"]][::-1].cummin()[::-1] mask = (df.score1 == x.score1) & (df.score2 == x.score2) print(df[mask]) Prints: minutes score1 score2 sum_score 0 1 0 0 0 1 2 0 1 1 4 5 0 1 1 6 7 0 1 1 7 8 1 1 2 8 9 1 2 3 9 10 2 2 4 | 2 | 3 |
78,054,482 | 2024-2-25 | https://stackoverflow.com/questions/78054482/optimal-way-of-counting-the-number-of-non-overlapping-pairs-given-a-list-of-inte | I'm trying to count the number of non-overlapping pairs given a list of intervals. For example: [(1, 8), (7, 9), (3, 10), (7, 12), (11, 13), (13, 14), (9, 15)] There are 8 pairs: ((1, 8), (11, 13)) ((1, 8), (13, 14)) ((1, 8), (9, 15)) ((7, 9), (11, 13)) ((7, 9), (13, 14)) ((3, 10), (11, 13)) ((3, 10), (13, 14)) ((7, 1... | Sort the intervals, once by start point, once by end point. Now, given an interval, perform a binary search using the start point in the intervals sorted by end point. The index you get tells you how many non-overlapping intervals come before: All intervals that end before your interval starts are non-overlapping. Do t... | 3 | 1 |
78,054,656 | 2024-2-25 | https://stackoverflow.com/questions/78054656/what-is-the-difference-between-the-various-spline-interpolators-from-scipy | My goal is to calculate a smooth trajectory passing through a set of points as shown below. I have had a look at the available methods of scipy.interpolate, and also the scipy user guide. However, the choice of the right method is not quite clear to me. What is the difference between BSpline, splprep, splrep, Univariat... | What is the difference between BSpline, splprep, splrep, UnivariateSpline, interp1d, make_interp_spline and CubicSpline? a BSpline object represents a spline function in terms of knots t, coefficients c and degree k. It does not know anything about the data x, y. It is a low-level implementation object, on par with ... | 3 | 3 |
78,054,851 | 2024-2-25 | https://stackoverflow.com/questions/78054851/when-using-random-uniforma-b-is-b-inclusive-or-exclusive | I was exploring the random module and can't find a correct answer to whether b is inclusive or exclusive in random.uniform(a, b). In a code like random.uniform(0, 1), some answers say 1 is included while others say 1 is never produced. What's the correct answer? | The documentation for random.uniform(a, b) suggests that you may encounter cases where the upper limit b is included in the range due to how floating-point numbers are represented, but it's not guaranteed: Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a. The end-point... | 3 | 5 |
78,054,093 | 2024-2-24 | https://stackoverflow.com/questions/78054093/why-does-it-take-longer-to-sum-integers-when-theyre-object-attributes | I am learning python after having some java in school back in the day. If there are 2 lists, one with single digit integers and one with objects with a bunch of attributes, they appear to be a different speed to step through them? I was under the understanding that the objects are a memory pointer. Example: int_list = ... | Accessing ints[i][j] needs: lookup for ints variable lookup for i & j variables array boundary check Accessing tiles[i][j].tile_type needs the above plus name lookup for tile_type, so it's slower. Anyway, instead of trying to figure out why all this is slower, you can optimize this code a lot by forgetting about indi... | 2 | 4 |
78,053,222 | 2024-2-24 | https://stackoverflow.com/questions/78053222/optimising-array-addition-y-x-rgba | I have two arrays A, B that are both of the shape (42, 28, 4) where: 42 : y_dim 28 : x_dim 4 : RGBA ## I'm on MacBook Air M1 2020 16Gb btw I want to combine these through a similar process to this: def add(A, B): X = A.shape[1] Y = A.shape[0] alpha = A[..., 3] / 255 B[..., :3] = blend(B[..., :3], A[..., :3], alpha.res... | First, your blending equation looks wrong. Even with alpha being 255, you'd only get a 50:50 mix. You'd want something like B = B * (1-alpha) + A * alpha or rearranged B += (A-B) * alpha but that expression has teeth (integer subtraction will have overflow/underflow). You appear to be drawing "sprites" in a grid on th... | 4 | 3 |
78,052,071 | 2024-2-24 | https://stackoverflow.com/questions/78052071/pyspark-count-over-a-window-with-reset | I have a PySpark DataFrame which looks like this: df = spark.createDataFrame( data=[ (1, "GERMANY", "20230606", True), (2, "GERMANY", "20230620", False), (3, "GERMANY", "20230627", True), (4, "GERMANY", "20230705", True), (5, "GERMANY", "20230714", False), (6, "GERMANY", "20230715", True), ], schema=["ID", "COUNTRY", "... | Partition the dataframe by COUNTRY then calculate the cumulative sum over the inverted FLAG column to assign group numbers in order to distinguish between different blocks of rows which start with false W1 = Window.partitionBy('COUNTRY').orderBy('DATE') df1 = df.withColumn('blocks', F.sum((~F.col('FLAG')).cast('long'))... | 2 | 1 |
78,051,606 | 2024-2-24 | https://stackoverflow.com/questions/78051606/cannot-reproduce-a-bifurcation-diagram-from-article | I have been reading this article A Simple Guide for Plotting a Proper Bifurcation Diagram and I want to reproduce the following figure (Fig. 10, p. 2150011-7): I have created this procedure that works fine with other classical bifurcation diagrams: def model(x, r): return 8.821 * np.tanh(1.487 * x) - r * np.tanh(0.222... | I think that the journal reviewers for that article should have been a little more careful. The model equation is based on an earlier article (Baghdadi et al., 2015 - I had to go through my workplace's institutional access to get at it) the original value of B is 5.821, not 8.821 (see Fig 2 in the 2015 article). def mo... | 2 | 2 |
78,050,439 | 2024-2-23 | https://stackoverflow.com/questions/78050439/selenium-undetected-chromedriver-with-different-chrome-versions | I have the following code which works fine on a computer where chrome 122 is installed currently - import undetected_chromedriver as uc driver = uc.Chrome() driver.get('https://ballzy.eu/en/men/sport/shoes') But when I run this code on a computer where a different chrome-version is installed like 120, I get the follow... | With undetected-chromedriver, you have to update the version_main arg of uc.Chrome() if you don't want to use the latest available driver version to match Chrome. Eg: import undetected_chromedriver as uc driver = uc.Chrome(version_main=120) Alternatively, you can use https://github.com/seleniumbase/SeleniumBase with U... | 2 | 2 |
78,050,000 | 2024-2-23 | https://stackoverflow.com/questions/78050000/how-to-assign-each-item-in-a-list-an-equal-amount-of-items-from-another-list-in | Let's say I have a list of people ['foo','bar','baz'] and a list of items ['hat','bag','ball','bat','shoe','stick','pie','phone'] and I want to randomly assign each person an equal amount of items, like so { 'foo':['hat','bat','stick'], 'bar':['bag','shoe','phone'], 'baz':['ball','pie'] } I think itertools is the jo... | Another solution, using itertools.cycle: import random from itertools import cycle persons = ["foo", "bar", "baz"] items = ["hat", "bag", "ball", "bat", "shoe", "stick", "pie", "phone"] random.shuffle(items) out = {} for p, i in zip(cycle(persons), items): out.setdefault(p, []).append(i) print(out) Prints (for example... | 2 | 4 |
78,050,189 | 2024-2-23 | https://stackoverflow.com/questions/78050189/df-query-in-polars | What is the equivalent of pandas.DataFrame.query in polars? import pandas as pd data= { 'A':["Polars","Python","Pandas"], 'B' :[23000,24000,26000], 'C':['30days', '40days',np.nan], } df = pd.DataFrame(data) A B C 0 Polars 23000 30days 1 Python 24000 40days 2 Pandas 26000 NaN Now, defining a variable item item=24000 df... | indeed, filter is all you need df.filter(pl.col("B") >= item) clean, simple, predictable, without hacks | 5 | 10 |
78,049,793 | 2024-2-23 | https://stackoverflow.com/questions/78049793/inverse-value-with-polars-dataframe | Say, I have a dataset in the following DataFrame: df=pl.DataFrame({ 'x':['a','a','b','b'], 'y':['b','c','c','a'], 'value':[3,5,1,4] }) df shape: (4, 3) ┌─────┬─────┬───────┐ │ x ┆ y ┆ value │ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 │ ╞═════╪═════╪═══════╡ │ a ┆ b ┆ 3 │ │ a ┆ c ┆ 5 │ │ b ┆ c ┆ 1 │ │ b ┆ a ┆ 4 │ └─────┴───... | You could join it to itself with aliases and then do fill_null(0). df.join( df.select( y="x", x="y", inverse="value" ), on=["x","y"], how="left" ).fill_null(0) shape: (4, 4) ┌─────┬─────┬───────┬─────────┐ │ x ┆ y ┆ value ┆ inverse │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 ┆ i64 │ ╞═════╪═════╪═══════╪═════════╡ │ ... | 2 | 4 |
78,048,750 | 2024-2-23 | https://stackoverflow.com/questions/78048750/in-polars-select-all-column-ending-with-pattern-and-add-new-columns-without-patt | I have the following dataframe: import polars as pl import numpy as np df = pl.DataFrame({ "nrs": [1, 2, 3, None, 5], "names_A0": ["foo", "ham", "spam", "egg", None], "random_A0": np.random.rand(5), "A_A2": [True, True, False, False, False], }) digit = 0 For each column X whose name ends with the string suf =f'_A{digi... | You can you Polars Selectors along with some basic strings operations to accomplish this. Depending on what you how you expect this problem to evolve, you can jump straight to regular expressions, or use polars.selectors.ends_with/string.removesuffix String Suffix Operations This approach uses - polars.selectors.ends_w... | 4 | 3 |
78,048,307 | 2024-2-23 | https://stackoverflow.com/questions/78048307/gradient-color-on-broken-barh-plot-in-matplotlib | I am trying to reproduce this: using this code: import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.lines import Line2D colors = ["#CC5A43","#5375D4"]*3 data = { "year": [2004, 2022, 2004, 2022, 2004, 2022], "countries" : ["Sweden", "Sweden", "Denmark", "Denmark", "Norway", "Norway"]... | Refer to the answer of How to fill matplotlib bars with a gradient? I have made some changes of the function gradientbars in which I add some comments. Also I have changed the size of the scatter plot for making it consistent with broken_barh and also for the legend which is disappeared. Here are the full codes: import... | 2 | 1 |
78,043,310 | 2024-2-22 | https://stackoverflow.com/questions/78043310/abstract-property-instantiating-a-partially-implemented-class | I read this very nice documentation on abstract class abc.ABC. It has this example (shortened by me for the purpose of this question): import abc class Base(abc.ABC): @property @abc.abstractmethod def value(self): return 'Should never reach here' @value.setter @abc.abstractmethod def value(self, new_value): return clas... | TL;DR PartialImplementation is not partially implemented; you defined a new property with a concrete getter and a (logically) concrete setter, instead of supplying only a concrete getter. Abstract properties are tricky. Your base class has one property, which defines itself as abstract by the presence of the abstract ... | 2 | 2 |
78,047,164 | 2024-2-23 | https://stackoverflow.com/questions/78047164/optimize-assigning-an-index-to-groups-of-split-data-in-polars | SOLVED: Fastest Function: 995x faster than original function def add_range_index_stack2(data, range_str): range_str = _range_format(range_str) df_range_index = ( data.group_by_dynamic(index_column="date", every=range_str, by="symbol") .agg() .with_columns( pl.int_range(0, pl.len()).over("symbol").alias("range_index") )... | Another solution is to create a separate DataFrame that for each symbol and range index stores the corresponding start date. df_range_index = ( df .group_by_dynamic(index_column="date", every="1w", by="symbol").agg() .with_columns(pl.int_range(0, pl.len()).over("symbol").alias("range_index")) ) shape: (106, 3) ┌──────... | 2 | 2 |
78,046,217 | 2024-2-23 | https://stackoverflow.com/questions/78046217/my-custom-object-is-not-deepcopied-when-it-is-used-as-the-default-parameter-in-p | I know that Pydantic creates a deepcopy of mutable objects for "every new instances" that we create, if they are placed in the default values. It holds true for my lst field, but not for my custom object item. (The code for __deepcopy__ is taken from here) from copy import deepcopy from typing import Self from pydantic... | It works only for not hashable objects, but according to Python documentation Objects which are instances of user-defined classes are hashable by default https://docs.python.org/3/glossary.html#term-hashable (I was also surprised) So, you can use default_factory to achieve your goal: from copy import deepcopy from py... | 2 | 2 |
78,046,145 | 2024-2-23 | https://stackoverflow.com/questions/78046145/why-cant-an-attribute-have-the-same-name-as-a-class-if-its-type-is-a-union-and | There seems to be some ambiguity in how the use of | in attribute type annotations together with attribute default values is parsed. Leading to the following error: >>> class A: pass ... >>> class B: ... A: A | None = None ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2... | A class definition creates a namespace, and by placing A on the left side of an assignment the compiler binds A as a local name to the None object in the namespace of the class B, instead of looking up A outside the scope of the class B and binding A to the class A defined in the module namespace. So A | None gets eval... | 2 | 2 |
78,045,627 | 2024-2-23 | https://stackoverflow.com/questions/78045627/using-dynamic-cut-breaks-for-each-row-of-a-dataframe | I am trying to bin values to prepare data to be later fed into a plotting library. For this I am trying to use polars Expr.cut. The dataframe I operate on contains different groups of values, each of these groups should be binned using different breaks. Ideally I would like to use np.linspace(BinMin, BinMax, 50) for th... | Unfortunately, pl.Expr.cut doesn't support expressions for the breaks argument (yet), but requires a fixed sequence. (This would be a good feature request though). A naive solution that will work for DataFrames, but doesn't use polars' native expression API, would be to use pl.Expr.map_elements together with the corres... | 4 | 2 |
78,044,552 | 2024-2-22 | https://stackoverflow.com/questions/78044552/how-to-add-data-from-one-data-frame-to-another-by-row-only-when-the-value-in-th | I have 2 dataframes. For each row in dataframe2, I want to see if dataframe1 already has a row with the same value in column 'name'. If it does, I want to add the data from the row in dataframe2 to corresponding row in dataframe 1. The value in column 'name' should not be added across. Steve should not be copied across... | Concatenate df1 + df2 minus the rows with names that aren't in df1; Group by name; Sum the values in each group; Reset the index. df = pd.concat([df1, df2.loc[df2["name"].isin(df1["name"])]]).groupby("name").sum().reset_index() Result: name goals minutes 0 Ben 2 178 1 Bob 1 64 2 Kevin 2 93 | 2 | 2 |
78,043,285 | 2024-2-22 | https://stackoverflow.com/questions/78043285/df-drop-duplicates-in-polars | import polars as pl df = pl.DataFrame( { "X": [4, 2, 3, 4], "Y": ["p", "p", "p", "p"], "Z": ["b", "b", "b", "b"], } ) We know the equivalent of pandas's df.drop_duplicates() is df.unique() in python-polars But, each time I execute my query I get a different result? print(df.unique()) X Y Z i64 str str 3 "p" "b" 2 "p... | Yes, this is an intentional behavior. If you need a consistent behavior then do: df.unique(maintain_order=True) polars.DataFrame.unique maintain_order Keep the same order as the original DataFrame. This is more expensive to compute. Settings this to True blocks the possibility to run on the streaming engine. Maintai... | 2 | 5 |
78,043,002 | 2024-2-22 | https://stackoverflow.com/questions/78043002/selecting-a-range-of-columns-using-polars | I have a many-column DF from which I need to process various ranges of columns. In Pandas I could use an expression along the lines of : df.loc[:, 'first_name': 'last_name'] to obtain the required columns between the two end-points. Is there an equivalent in Polars which does not involve listing all the numerous column... | Since df.columns is just a list you can use the .index method to find their locations. Accomplishing this via the eager [] API or the .select interface can be done as follows: import polars as pl def inclusive(target, a, b): start, stop = target.columns.index(a), target.columns.index(b) return pl.col(target.columns[sta... | 3 | 2 |
78,041,555 | 2024-2-22 | https://stackoverflow.com/questions/78041555/python-development-dependencies | I'm familiar with installing dependencies using a requirements.txt or environment.yml, but I've only ever seen syntax in those files like some_package>=1.2.3. What does it mean when dependencies are listed with curly braces, as in: pytest = "^6.2.5" coverage = {extras = ["toml"], version = "^5.5"} safety = "^1.10.3" my... | python-poetry uses that format for defining dependencies in a pyproject.toml file usually under [tool.poetry.dependencies] As explained by PEP 508 packages can have extra dependencies which enables optional features of a given package (package dependent). You could install poetry and use that to manage dependencies or ... | 2 | 3 |
78,039,918 | 2024-2-22 | https://stackoverflow.com/questions/78039918/how-to-use-isin-in-polars-dataframe | I have a polars DataFrame: import polars as pl import numpy as np df = pl.DataFrame({'A': ['red', 'blue', 'green', np.nan, 'orange']}) my_list = ['red','orange'] I want to know which colors are present in my_list. In pandas, I would do something like: df.A.isin(my_list) But, I am getting this error: AttributeError: '... | The following can be used to create a dataset where column A is replaced by a boolean column indicating whether each item was in my_list. df.with_columns(pl.col("A").is_in(my_list)) shape: (5, 1) ┌───────┐ │ A │ │ --- │ │ bool │ ╞═══════╡ │ true │ │ false │ │ false │ │ null │ │ true │ └───────┘ If instead you'd like ... | 3 | 2 |
78,039,427 | 2024-2-22 | https://stackoverflow.com/questions/78039427/how-to-apply-custom-function-with-many-parameters-in-a-pandas-column | I have the following function import math def f(k,a,x): return (1/(1+math.exp(-k*x))^a) And the following pandas dataframe import pandas as pd df = pd.DataFrame({'x': list(range(1,100))}) How can I apply the above function on the x column of the df for lets say k=1 and a=2 ? | Using your function: def f(k,a,x): return (1/(1+math.exp(-k*x))**a) df['out'] = df['x'].apply(lambda x: f(k=1, a=2, x=x)) But better vectorize with numpy: import numpy as np def f_vectorized(k, a, x): return (1/(1+np.exp(-k*x))**a) df['out'] = f_vectorized(k=1, a=2, x=df['x']) Output: x out 0 1 0.534447 1 2 0.775803... | 2 | 2 |
78,036,340 | 2024-2-21 | https://stackoverflow.com/questions/78036340/ansible-get-the-last-character-of-a-fact | I would like to have the last character of a fact. My playbook looks like this: - name: sf set_fact: root_dev: "{{ ansible_mounts|json_query('[?mount == `/`].device') }}" - name: e debug: msg: "{{ root_dev[:-1] }}" The problem is the output in this case always: "msg": [] or if I use the playbook without semicolon: d... | Explanation of the problem: You have to understand how the slicing works. Given the lists l1 and l2 for testing l1: [a] l2: [a, b, c] The index [-1] gives you the last item (which is also the first item) l1[-1]: a The slice [:-1] gives you all items but the last one. The result is an empty list because there is onl... | 2 | 3 |
78,036,231 | 2024-2-21 | https://stackoverflow.com/questions/78036231/how-to-resample-ohlc-dataframe-in-python-without-peeking-into-the-future | I have a Pandas DataFrame with one second frequency datetime index and columns 'Open', 'High', 'Low', 'Close' which represent prices for a financial instrument. I want to resample this DataFrame to 15 min (or any frequency) but without peeking into the future and still keeping the original DataFrame with one second fre... | Here is numba version that computes OHLC your way which is significantly faster: from numba import njit @njit def compute_ohlc(floor_15_min, O, H, L, C, O_out, H_out, L_out, C_out): first, curr_max, curr_min, last = O[0], H[0], L[0], C[0] last_v = floor_15_min[0] for i, v in enumerate(floor_15_min): if v != last_v: fir... | 3 | 1 |
78,034,110 | 2024-2-21 | https://stackoverflow.com/questions/78034110/are-python-c-extensions-faster-than-numba-jit | I am testing the performance of the Numba JIT vs Python C extensions. It seems the C extension is about 3-4 times faster than the Numba equivalent for a for-loop-based function to calculate the sum of all the elements in a 2d array. Update: Based on valuable comments, I realized a mistake that I should have compiled (c... | I would like to complete the good answer of John Bollinger: First of all, C extensions tends to be compiled with GCC on Linux (possibly MSVC on Windows and Clang on MacOS AFAIK), while Numba uses the LLVM compilation toolchain internally. If you want to compare both, then you should use Clang which is based on the LLVM... | 4 | 8 |
78,035,329 | 2024-2-21 | https://stackoverflow.com/questions/78035329/is-it-possible-in-a-pandas-dataframe-to-have-some-multiindexed-columns-and-some | In pandas I would like to have a dataframe whose some columns have a multi index, some don't. Visually I would like something like this: | c | | |--------| d | | a | b | | ================| | 1 | 4 | 0 | | 2 | 5 | 1 | | 3 | 6 | 2 | In pandas I can do something like this: df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6], 'd... | You can use the empty string "" as a placeholder : columns = [ ("c", "a"), ("c", "b"), ("d", ""), # << here ] Output : type(df["d"]) # pandas.core.series.Series type(df["c"]) # pandas.core.frame.DataFrame type(df["c"]["a"]) # pandas.core.series.Series | 3 | 2 |
78,033,371 | 2024-2-21 | https://stackoverflow.com/questions/78033371/how-to-change-the-value-of-a-button-in-python-flask | I want to change the value of a button written in html to "records". I want to adress and change the button in python. This is in order to prevent to tap the record button twice as the request form changes and to get a visual feedback that it works. this is what i have: @app.route('/camera', methods=['GET', 'POST']) de... | What you are looking to do should be done through JavaScript, because the most natural way to change the label of the button is through client-side programming. However, if you insist on doing this from server-side code, you can start by changing the template camera.html. Let's say that you have the following button in... | 3 | 2 |
78,033,462 | 2024-2-21 | https://stackoverflow.com/questions/78033462/compute-the-ratio-between-the-number-of-rows-where-a-true-to-the-number-of-rows | I have a Polars dataframe: df = pl.DataFrame( { "nrs": [1, 2, 3, None, 5], "names": ["foo", "ham", "spam", "egg", None], "random": np.random.rand(5), "A": [True, True, False, False, False], } ) How can I compute the ratio between the number of rows where A==True, to the number of rows where A==False? Note that A is al... | You can leverage polars' expression API as follow. df.select(pl.col("A").sum() / pl.col("A").not_().sum()).item() The summing works as A is a boolean column. If this is not the case, you can exchange pl.col("A") for another corresponding boolean expression. | 4 | 4 |
78,031,550 | 2024-2-21 | https://stackoverflow.com/questions/78031550/how-to-make-a-more-efficient-mapping-function-based-on-a-dataframe-with-the-inde | Say I have a dataframe with column ['Subtype'] and ['Building Condition'], Dataframe 1: Subtype Building Condition A Good B Bad C Bad I want to map dataframe 1 using another dataframe based on the values of those two columns Dataframe 2: Good Bad A Repair Retrofit B Retrofit Reconstruct C Reco... | The documented approach in such case is to use indexing lookup on the underyling numpy array: # factorize the requested name idx, cols = pd.factorize(df1['Building Condition']) # reorder and slice df1['Intervention'] = (df2.reindex(index=df1['Subtype'], columns=cols) .to_numpy()[np.arange(len(df1)), idx] ) Output: Su... | 2 | 1 |
78,017,822 | 2024-2-18 | https://stackoverflow.com/questions/78017822/no-overloads-for-update-match-the-provided-arguments | I'm currently reading FastAPI's tutorial user guide and pylance is throwing the following warning: No overloads for "update" match the provided argumentsPylancereportCallIssue typing.pyi(690, 9): Overload 2 is the closest match Here is the code that is throwing the warning: from fastapi import FastAPI app = FastAPI()... | You're bitten by intelligent type inference. To make it clear, I'll get rid of FastAPI dependency and reproduce on a simpler case: foo = {"foo": ["bar"]} foo["bar"] = "baz" Whoops, mypy (or pylance) error. I don't have Pylance available anywhere nearby, so let's stick with mypy - the issue is the same, wording may dif... | 3 | 4 |
77,992,977 | 2024-2-14 | https://stackoverflow.com/questions/77992977/how-does-tensor-permutation-work-in-pytorch | I'm struggling with understanding the way torch.permute() works. In general, how exactly is an n-D tensor permuted? An example with explaination for a 4-D or higher dimension tensor is highly appreciated. I've search across the web but did not find any clearly explaination. | All tensors are contiguous 1D data lists in memory. What differs is the interface PyTorch provides us with to access them. This all revolves around the notion of stride, which is the way this data is navigated through. Indeed, on a higher level, we prefer to reason our data in higher dimensions by using tensor shapes. ... | 2 | 3 |
77,999,734 | 2024-2-15 | https://stackoverflow.com/questions/77999734/how-can-i-verify-an-emails-dkim-signature-in-python | Given a raw email, how can I validate the DKIM signature with Python? Ideally I’d like more than just a pass / fail result, I’d like to know details of any issues. I’ve found the dkimpy package, but the API isn’t obvious to me. | For a simple pass/fail validation: import dkim # dkimpy # Returns True/False res = dkim.verify(mail_data.encode()) For something more nuanced you can do this: d = dkim.DKIM(mail_data.encode(), logger=None, minkey=1024, timeout=5, tlsrpt=False) try: d.verify() # If it fails, a `dkim.ValidationError` exception will be t... | 2 | 3 |
77,992,104 | 2024-2-14 | https://stackoverflow.com/questions/77992104/why-does-google-vertex-api-blocking-responses-even-with-safety-off | I am attempting to use evaluate how Gemini performs on the Learned Hands dataset, which prompts to see if a given post has a specific legal issue included. My code is the following: from vertexai.preview import generative_models from vertexai.preview.generative_models import GenerativeModel prompt = """ Does the post d... | Please update your SDK version. The new versions have much better output when the result is blocked or has no candidates. It's not possible to completely disable safety blocks. This is not your case, but chat.send_message also raises exception when the response is truncated due to exceeding maximum output tokens. On t... | 3 | 0 |
78,005,435 | 2024-2-16 | https://stackoverflow.com/questions/78005435/how-to-randomly-sample-very-large-pyarrow-dataset | I have a very large arrow dataset (181GB, 30m rows) from the huggingface framework I've been using. I want to randomly sample with replacement 100 rows (20 times), but after looking around, I cannot find a clear way to do this. I've tried converting to a pd.Dataframe so that I can use df.sample(), but python crashes ev... | A bit late, but I just had to write a function to randomly sample a pyarrow Table. It produces the sample directly from a pyarrow Table without converting to a pandas dataframe. def sample_table(table: pa.Table, n_sample_rows: int = None) -> pa.Table: if n_sample_rows is None or n_sample_rows >= table.num_rows: return ... | 2 | 2 |
78,013,301 | 2024-2-17 | https://stackoverflow.com/questions/78013301/python-dataclasses-and-sqlite3-adapters | What is the cleanest way to commit data stored in instances of a dataclass contained in a list to SQLite with sqlite3's executemany? For example: @dataclass class Person: name: str age: int a = Person("Alice", 21) b = Person("Bob", 22) c = Person("Charlie", 23) people = [a, b, c] # ... cursor.executemany(f"INSERT INTO ... | Use the astuple() function to convert the dataclass instances to tuples. from dataclasses import dataclass, fields, astuple headers = ','.join(f.name for f in fields(Person)) people = map(astuple, [a, b, c]) placeholders = ','.join(['?'] * len(headers)) table = 'persons' cursor.executemany(f"INSERT INTO {table} ({heade... | 4 | 2 |
78,019,134 | 2024-2-19 | https://stackoverflow.com/questions/78019134/how-to-properly-save-the-finetuned-transformer-model-in-safetensors-without-losi | I have been trying to finetune a casual LM model by retraining its lm_head layer. I've been training with Deepspeed Zero stage 3 (this part works fine). But I have problem saving my finetuned model and loading it back. I think the problem is that the unwrapped_model.save_pretrained() function automatically ignores the ... | I think I found the solution. The problem is, in ZeRO3 we have to call accelerator.get_state_dict(model) function before saving. Directly saving the model itself won't work because its parameters are stored across different GPUs. Calling accelerator.get_state_dict(model) can force Deepspeed to collect the values of ALL... | 3 | 0 |
78,019,438 | 2024-2-19 | https://stackoverflow.com/questions/78019438/axioserror-request-failed-with-status-code-403-in-streamlit | I am getting this error "AxiosError: Request failed with status code 403" while uploading image on streamlit app. this is my code screenshot of error import streamlit as st from PIL import Image # Title st.title('Image Viewer') #Upload an image uploaded_image = st.file_uploader("Upload an image", type=["jpg", "jpeg", "... | If you are running it locally try: streamlit run app.py --server.enableXsrfProtection false | 3 | 9 |
78,027,325 | 2024-2-20 | https://stackoverflow.com/questions/78027325/stable-baselines-3-throws-valueerror-when-episode-is-truncated | So I'm trying to train an agent on my custom gymnasium environment trough stablebaselines3 and it kept crashing seemingly random and throwing the following ValueError: Traceback (most recent call last): File "C:\Users\bo112\PycharmProjects\ecocharge\code\Simulation Env\prototype_visu.py", line 684, in <module> model.le... | The problem is most likely in your custom environment definition (ChargeEnv). The error says that it has a wrong observation shape (it is empty). You should check your ChargeEnv.observation_space. If you want to create a custom environment, make sure to read the documentation to set it up correctly (https://gymnasium.f... | 2 | 2 |
78,002,829 | 2024-2-15 | https://stackoverflow.com/questions/78002829/lru-cache-vs-dynamic-programming-stackoverflow-with-one-but-not-with-the-other | I'm doing this basic dp (Dynamic Programming) problem on trees (https://cses.fi/problemset/task/1674/). Given the structure of a company (hierarchy is a tree), the task is to calculate for each employee the number of their subordinates. This: import sys from functools import lru_cache # noqa sys.setrecursionlimit(2 * 1... | lru_cache is implemented in C, its calls are interleaved with your function's calls, and your C code recursion is too deep and crashes. Your second program only has deep Python code recursion, not deep C code recursion, avoiding the issue. In Python 3.11 I get a similar bad crash: [Execution complete with exit code -11... | 4 | 7 |
78,024,123 | 2024-2-19 | https://stackoverflow.com/questions/78024123/find-max-value-in-a-range-of-a-given-column-in-polars | I have the following dataframe: df = pl.DataFrame({ "Column A": [2, 3, 1, 4, 1, 3, 3, 2, 1, 0], "Column B": [ "Life", None, None, None, "Death", None, "Life", None, None, "Death" ] }) shape: (10, 2) ┌──────────┬──────────┐ │ Column A ┆ Column B │ │ --- ┆ --- │ │ i64 ┆ str │ ╞══════════╪══════════╡ │ 2 ┆ Life │ │ 3 ┆ n... | I think the general idea is to assign "group ids" to each "range". A common approach for this is to use cumulative sum along with forward filling. ( df.with_columns( start = (pl.col("Column B") == "Life").cum_sum().forward_fill(), end = (pl.col("Column B") == "Death").cum_sum().forward_fill() ) .with_columns( group_id_... | 4 | 6 |
78,005,051 | 2024-2-16 | https://stackoverflow.com/questions/78005051/modulenotfounderror-no-module-named-llama-index-graph-stores | I am trying to use the NebulaGraphStore class from llama_index via from llama_index.graph_stores.nebula import NebulaGraphStore as suggested by the llama_index documentation, but the following error occurred: ModuleNotFoundError Traceback (most recent call last) Cell In[2], line 1 ----> 1 from llama_index.graph_stores.... | According to latest doc of llama-index, all graph-store module are not included in llama-index core packages and needs to install it by pip: %pip install llama-index-llms-openai %pip install llama-index-embeddings-openai %pip install llama-index-graph-stores-nebula %pip install llama-index-llms-azure-openai https://do... | 2 | 2 |
78,030,255 | 2024-2-20 | https://stackoverflow.com/questions/78030255/why-register-next-step-handler-doesnt-call-a-function-immediately-and-waits-for | I'm creating a simple bot using Telebot. The start func offers two buttons to the user (Currency/Weather). I expect the bot to move to the func "where_to_go" when a button is pressed. It happens only when I press the button twice or send any other second message. Then "where_to_go" func reads the first message. So it w... | You can try this : @bot.message_handler(commands = ['start','main']) def start(message): markup = types.ReplyKeyboardMarkup() btn1 = types.KeyboardButton('Currency Calc') markup.row(btn1) btn2 = types.KeyboardButton('Weather Today') markup.row(btn2) file = open('./Start Photo.png', 'rb') bot.send_photo(message.chat.id,... | 2 | 2 |
78,030,813 | 2024-2-20 | https://stackoverflow.com/questions/78030813/fill-between-areas-with-gradient-color-in-matplotlib | I try to plot the following plot with gradient color ramp using matplotlib fill_between. I can manage to get the color below the horizontal line correctly, but I had difficult time to do the same for above horizontal line. The idea is to keep color above and below the horizontal line up to y values boundary, and the re... | You can use fill_between with np.minimum to color below the threshold line. And with np.maximum to color above that line. import numpy as np import matplotlib.pyplot as plt y = [54.38,53.99,65.39,66.22,57.65,49.17,42.72,42.07,44.88,46.56,55.27,57.28,60.54,65.87,37.61,44.21,50.62,56.15,52.65,52.17,57.71,61.21,60.77,50.7... | 3 | 3 |
78,029,515 | 2024-2-20 | https://stackoverflow.com/questions/78029515/managed-dictionary-does-not-behave-as-expected-in-multiprocessing | From what I've managed to figure out so far, this may only be a problem in macOS. Here's my MRE: from multiprocessing import Pool, Manager from functools import partial def foo(d, n): d.setdefault("X", []).append(n) def main(): with Manager() as manager: d = manager.dict() with Pool() as pool: pool.map(partial(foo, d),... | This is a crappy "answer" and I apologize for that and will delete it once you post a comment that you have seen it. I get the distinct impression that the answer is related to the "sub-list" not being managed per that post I mentioned. For example: This seems to work: def foo(d, n): d.setdefault("X", []).append(n) # t... | 2 | 2 |
78,027,751 | 2024-2-20 | https://stackoverflow.com/questions/78027751/keyerror-when-creating-new-column-from-groupby-operation-in-pandas | I am trying to create a new column by performing some operations on the existing columns but it is throwing a key error in my code. I tried to debug it by using df.columns and copy pasted the exact names but still I got the same error. My code is as follows: def calculate_elasticity(group): sales_change = group['Primar... | If use GroupBy.transform is not possible processing 2 columns together, need GroupBy.apply: def calculate_elasticity(group): sales_change = group['Primary Sales Quantity'].pct_change() price_change = group['MRP'].pct_change() group['Variant-based Elasticity'] = sales_change / price_change return group df = df.groupby('... | 2 | 2 |
78,025,976 | 2024-2-20 | https://stackoverflow.com/questions/78025976/create-a-column-for-cumulative-sum-for-each-string-value-in-a-column-pandas | I have the following pandas dataframe import pandas as pd import random random.seed(42) pd.DataFrame({'index': list(range(0,10)), 'cluster': [random.choice(['S', 'C', ]) for l in range(0,10)]}) index cluster 0 0 S 1 1 S 2 2 C 3 3 S 4 4 S 5 5 S 6 6 S 7 7 S 8 8 C 9 9 S I would like to create 5 new columns, one for each ... | Code df is your input dataframe tmp = (pd.get_dummies(df['cluster']) .cumsum()[df['cluster'].unique()] .add_prefix('cumulative_') ) out = pd.concat([df, tmp],axis=1) out index cluster cumulative_S cumulative_C 0 0 S 1 0 1 1 S 2 0 2 2 C 2 1 3 3 S 3 1 4 4 S 4 1 5 5 S 5 1 6 6 S 6 1 7 7 S 7 1 8 8 C 7 2 9 9 S 8 2 | 2 | 2 |
78,025,261 | 2024-2-20 | https://stackoverflow.com/questions/78025261/re-findall-giving-different-results-to-re-compile-regex | Why does re.compile.findall not find "um" if "um" is at the beginning of the string (it works fine is "um" isn't at the beginning of the string, as per the last 2 lines below) >>> s = "um" >>> re.findall(r"\bum\b", s, re.IGNORECASE) ['um'] >>> re.compile(r"\bum\b").findall(s, re.IGNORECASE) [] >>> re.compile(r"\bum\b")... | You intended to pass re.IGNORECASE to the compile() function, but in the failing cases you're actually passing it to the findall() method. There it's interpreted as an integer giving the starting position for the search to begin. Its value as an integer isn't defined, but happens to be 2 today: >>> int(re.IGNORECASE) 2... | 2 | 3 |
78,024,292 | 2024-2-20 | https://stackoverflow.com/questions/78024292/true-python-scatter-function | I am writing this to have a reference post when it comes to plotting circles with a scatter plot but the user wants to provide a real radius for the scattered circles instead of an abstract size. I have been looking around and there are other posts that explain the theory of it, but have not come accross a ready-to-use... | It is not very clear whether you want r to be the radius or the diameter of the circle. The code below supposes it is the radius (just leave out the * 2 if you want the diameter. For a discussion about how the dot size is measured, see this post. The code below converts the radius in data units to pixels, and then to "... | 2 | 2 |
78,022,472 | 2024-2-19 | https://stackoverflow.com/questions/78022472/what-is-windows-equivalent-of-pwd-getpwuid | What is the windows equivalent of pwd.getpwuid? I believe pwd is an UNIX package. Here is the code and the error when using windows import pwd file_owner_name = pwd.getpwuid(file_owner_uid).pw_name import pwd ModuleNotFoundError: No module named 'pwd' | Unfortunately not supported by Python out of the box. Methods like pathlib.Path.owner() always return NotImplementedError on Windows. You'll need to call Windows functions directly. The easiest way is to install PyWin32. Then: import win32security path = './' security_descriptor = win32security.GetFileSecurity(path, w... | 2 | 2 |
78,001,435 | 2024-2-15 | https://stackoverflow.com/questions/78001435/remove-central-noise-from-image | I'm working with biologists, who are imaging DNA strands under a microscope, giving greyscale PNGs. Depending on the experiment, there can be a lot of background noise. On the ones where there is quite little, a simple threshold for pixel intensity is generally enough to remove it. However for some, it's not so simple.... | I am not sure what result you want so I am working somewhat in the dark. I suspect you want a "Local Area Threshold" - see Wikipedia. Also referred to as "Adaptive Threshold". It is available, or can be achieved in many image processing packages, but for brevity and until I (or others) better understand what you want a... | 2 | 2 |
78,021,584 | 2024-2-19 | https://stackoverflow.com/questions/78021584/runtimeerror-await-wasnt-used-with-future-async-dict-comprehension-in-python | I've finished this tutorial about async list comprehension. Now I want to try an async dict comprehension. This is the code to replicate: import asyncio async def div7_tuple(x): return x, x/7 async def main(): lost = [4, 8, 15, 16, 23, 42] awaitables = asyncio.gather(*[div7_tuple(x) for x in lost]) print({k: v for k, v... | gather() gives you a Future object back(this is that Future object that the error message says - await wasn't used with future). If you need the result of the object(in order to iterate over it) you need to await it first: async def main(): lost = [4, 8, 15, 16, 23, 42] awaitables = asyncio.gather(*[div7_tuple(x) for x... | 2 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.