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 |
|---|---|---|---|---|---|---|
77,051,620 | 2023-9-6 | https://stackoverflow.com/questions/77051620/nanobind-trampoline-method-name-issue | I have a trampoline class that I am trying to wrap in nanobind like so: class PyT : T { public: NB_TRAMPOLINE(T, 1); void F() override { NB_OVERRIDE(F); } }; // ... nb::class_<T, PyT>(m, "T") .def(nb::init<>()) .def("f", &PyT::F) It compiles fine, but when i go to use it in python, it only works if I call the function... | You can solve this by using NB_OVERRIDE_NAME and specifying the name you want it to be overriding, so in this case it would be: void F() override { NB_OVERRIDE_NAME("f", F); } | 2 | 2 |
77,051,212 | 2023-9-6 | https://stackoverflow.com/questions/77051212/python-extract-words-surround-a-word-from-another-column | I have the following dataframe: id text word 1 i am working with john he is my colleague john 2 i watched the bond movie and the bond actor was amazing bond 3 mary is my friend and we work together mary 4 hello world hello python peter I would like to create another column where I retain the 3 words at the left and ri... | You could try: import re df['retain'] = [m.group() if (m:=re.search(fr'(?:(?:\w+\W+){{,3}}){w}(?:.*{w})?\W+(?:(?:\w+\W+){{,2}}\w+)?', t)) else '' for t, w in zip(df['text'], df['word'])] Output: id text word retain 0 1 i am working with john he is my colleague john am working with john he is my 1 2 i watched the bond... | 2 | 2 |
77,026,971 | 2023-9-2 | https://stackoverflow.com/questions/77026971/how-to-wrap-a-vectort-in-nanobind | In boost::python, to wrap a vector<T> you would do something like this: boost::python::class_< std::vector < T > >("T") .def(boost::python::vector_indexing_suite<std::vector< T > >()); How do I accomplish the same thing in nanobind? | Include the header <nanobind/stl/bind_vector.h> and then its just: nb::bind_vector<std::vector<T> >(m, "TVector"); | 3 | 2 |
77,008,824 | 2023-8-30 | https://stackoverflow.com/questions/77008824/how-to-set-cookies-on-jinja2-templateresponse-in-fastapi | I am using Python FastAPI and Jinja2, all of which I am new to. I am able to set cookies alone or return html templates on their own, but I cannot work out how to do both at once. Setting cookies only works as expected, but returning a template seems to overwrite that and just returns html with no cookies. @app.get("/o... | You should set the cookie on the TemplateResponse instead—which is returned from that endpoint—not the Response object defined in the endpoint's parameters, which could be used when returing a simple (JSON) message, e.g., return {'msg': 'OK'}. Related answers that you might find helpful can be found here, here and here... | 4 | 4 |
77,038,132 | 2023-9-4 | https://stackoverflow.com/questions/77038132/python-pillow-pil-doesnt-recognize-the-attribute-textsize-of-the-object-imag | I already checked python version on my environment (sublime text) and it is 3.11.0, the latest, I checked pillow version which is 10.0.0, the latest, and my code looks similar to other examples online. the code has a part in Italian, but its pretty understandable. the problem is at "disegno.textsize(testo, font=font) a... | textsize was deprecated, the correct attribute is textlength which gives you the width of the text. for the height use the fontsize * how many rows of text you wrote. Example code: w = draw.textlength(text, font=font) h = fontSize * rows | 15 | 24 |
77,008,165 | 2023-8-30 | https://stackoverflow.com/questions/77008165/official-api-for-typing-generic-orig-bases | I have a generic type for which I'd like to retrieve at runtime the type of its type variable. The following snippet runs well, but it uses Generic.__orig_bases__ which is not an official API (its use is discouraged in PEP 560 that defines it). Is there an official API to retrieve it? And if not, is there another (offi... | I think with Python 3.12 we can safely say that __orig_bases__ is now documented and there's a function that can retrieve it: from types import get_original_bases print(get_original_bases(IntImplementation)) # (__main__. MyGeneric[int],) Reference: https://docs.python.org/3/library/types.html#types.get_original_bases | 3 | 4 |
77,025,354 | 2023-9-1 | https://stackoverflow.com/questions/77025354/with-pydantic-v2-and-model-validate-how-can-i-create-a-computed-field-from-an | This context here is that I am using FastAPI and have a response_model defined for each of the paths. The endpoint code returns a SQLAlchemy ORM instance which is then passed, I believe, to model_validate. The response_model is a Pydantic model that filters out many of the ORM model attributes (internal ids and etc...)... | What you could consider is having all the ORM attributes in your schema, but labelling them as excluded. Then you have access to all your ORM attributes when you want to use them in a computed field: from pydantic import BaseModel, Field, property, computed_field, ConfigDict from sqlalchemy.orm import declaritive_base ... | 11 | 10 |
77,006,745 | 2023-8-30 | https://stackoverflow.com/questions/77006745/oserror-meta-llama-llama-2-7b-chat-hf-is-not-a-local-folder | I'm trying to replied the code from this Hugging Face blog. At first I installed the transformers and created a token to login to hugging face hub: pip install transformers huggingface-cli login After that it is said to use use_auth_token=True when you have set a token. Unfortunately after running the code I get an er... | def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): the pretrained_model_name_or_path may the model repo or the model path in your case the model repo is "meta-llama/Llama-2-7b-chat-hf" which is right. according to https://huggingface.co/meta-llama/Llama-2-7b-chat-hf/tree/main you must agree to... | 4 | 6 |
77,020,278 | 2023-9-1 | https://stackoverflow.com/questions/77020278/how-to-load-a-huggingface-dataset-from-local-path | Take a simple example in this website, https://huggingface.co/datasets/Dahoas/rm-static: if I want to load this dataset online, I just directly use, from datasets import load_dataset dataset = load_dataset("Dahoas/rm-static") What if I want to load dataset from local path, so I download the files and keep the same fol... | Save the data with save_to_disk then load it with load_from_disk. For example: import datasets ds = datasets.load_dataset("Dahoas/rm-static") ds.save_to_disk("Path/to/save") and later if you wanna re-utilize it just normal load_dataset will work ds = datasets.load_from_disk("Path/to/save") you can verify the same by ... | 6 | 6 |
77,017,804 | 2023-8-31 | https://stackoverflow.com/questions/77017804/polars-valueerror-could-not-convert-value-unknown-as-a-literal | I have a line of code in polars that worked prior to my most recent update of the polars package to '0.19.0'. This example ran before: import polars as pl df = pl.DataFrame( { "a": [5, 6, 7, 8, 9], "b": [5, 6, 7, 8, 9], "c": [5, 6, 7, 8, None],}) cols_1 = ["a", "b"] cols_2 = ["c"] df = df.filter(pl.all(pl.col(cols_1 + ... | Disclaimer. I am just summarising the comments of @jqurious and @keraion. As of the polars release 0.19.0, you'll need to use dedicated horizontal aggregation functions, such as all_horizontal or any_horizontal. import polars as pl df = pl.DataFrame({ "a": [5, 6, 7, 8, 9], "b": [5, 6, 7, 8, 9], "c": [5, 6, 7, 8, None] ... | 5 | 3 |
77,024,460 | 2023-9-1 | https://stackoverflow.com/questions/77024460/got-python-unexpected-failure-in-python-in-excel | I have Excel Version 2309 (Build 16827.20000) through the Beta Channel of 365 Insider Program. The Python (Preview) icons do appear in the Formulas ribbon. I can also type Python code by =PY [tab] However, none of the code works, including the built-in samples. All I got is a #PYTHON! error. When I click show error mes... | Same problem and finally solved. My 365 subscription is managed by my organization and I have two accounts: the first is my email with "company.com" domain, the second is my email with "company.onmicrosoft.com" domain. When I login with the first the PY function returns #PYTHON! error, while using the second with "onmi... | 3 | 0 |
77,043,020 | 2023-9-5 | https://stackoverflow.com/questions/77043020/compare-2-pdf-files-langchain | import streamlit as st import os import tempfile from pathlib import Path from pydantic import BaseModel, Field import streamlit as st from langchain.chat_models import ChatOpenAI from langchain.agents import Tool from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterText... | I've run into this issue, I solved it using from pydantic.v1 import BaseModel or install last v1 version pip install pydantic==1.10.12 Pydantic has released v2 version on June 30, 2023 and langchain integration is not compatible | 2 | 3 |
77,034,675 | 2023-9-4 | https://stackoverflow.com/questions/77034675/finding-the-minimum-cost-for-m-compatible-elements-for-group-1-and-group-2-al | Here is a problem statement. I recently had an interview question regarding this: given arrays compatible1, compatible2, and cost of length n >= 1. cost[i] represents the cost of element i. the respective compatible[i] == 1 if compatible with that group and 0 otherwise. also given min_compatible, which is the minimum ... | ...pick the minimum cost that's compatible with both if both still need an element... I can't see your test cases so this may or may not be the issue, but you should pick a dual-compatible item even if only one of the minimum requirements still needs to be fulfilled as long as it's more economical than picking a sing... | 2 | 4 |
77,048,073 | 2023-9-5 | https://stackoverflow.com/questions/77048073/how-to-iterate-through-paginated-results-in-the-python-sdk-for-microsoft-graph | I'm getting to grips with the Python SDK, having never used GraphQL before (but I'm familiar with the basic concept). I'm able to retrieve the odata_next_link value from responses, but I'm not sure how to use it. I note from here that: You should include the entire URL in the @odata.nextLink property in your request f... | We do not have a page iterator for the Python SDK yet, however there is added support for using a raw url for the request. In the case of pagination, a user can use the odata_next_link property value to make a fresh request using with_url and get items in the next page. Here's a working example: from msgraph.generated... | 5 | 11 |
77,018,288 | 2023-8-31 | https://stackoverflow.com/questions/77018288/sqlalchemy-how-to-customize-standard-type-like-datetime-param-binding-process | Given the following snippet t = Table( "foo", MetaData(), Column("bar", DateTime()), ) engine.execute(t.insert((datetime(1900, 1, 1),))) engine.execute(t.insert(("1900-01-01",))) the last statement works well for postgresql, while failing for Spark e.g. Cannot safely cast 'bar': string to timestamp [SQL: INSERT INTO T... | There is no built-in way to customize the parameter binding processing for a standard SQLAlchemy type, such as DateTime(), for a specific dialect. However, there are a few workarounds that you can use. One workaround is to create a custom type that wraps the standard type and overrides the process_bind_param() method. ... | 3 | 3 |
77,047,476 | 2023-9-5 | https://stackoverflow.com/questions/77047476/pandas-dataframe-write-parquet-and-setting-the-zstd-compression-level | I am writing out a compressed Parquet file from DataFrame as following: result_df.to_parquet("my-data.parquet", compression="zstd") How can I instruct Pandas on the compression level of zstd coding? | Using pyarrow engine you can send compression_level in kwargs to to_parquet result_df.to_parquet(path, engine='pyarrow', compression='zstd', compression_level=1) Test: import pandas as pd import pyarrow.parquet as pq path = 'my-data.parquet' result_df = pd.DataFrame({'a': range(100000)}) for i in range(10): # create t... | 2 | 1 |
77,028,925 | 2023-9-2 | https://stackoverflow.com/questions/77028925/docker-compose-fails-error-externally-managed-environment | I am using a windows machine and have installed wsl to be able to use Docker desktop. Of course the build failed and then I observed python3 and pip3 in the dockerfile. So I installed ubuntu and debian via wsl and then tried to run the app (docker-compose up). It still fails and throws the following error: ERROR [test... | This error occurs due to this: PEP0668. I found the resolution for local machines while going through this answer. Specifically for docker, using the pip install command with the flag --break-system-packages worked for me. In your script update the line: RUN pip3 install daff==1.3.46 with RUN pip3 install daff==1.3.46... | 9 | 19 |
77,016,132 | 2023-8-31 | https://stackoverflow.com/questions/77016132/import-from-another-file-inside-the-same-module-and-running-from-a-main-py-outsi | Given the following tree: ├── main.py └── my_module ├── a.py ├── b.py └── __init__.py a.py: def f(): print('Hello World.') b.py: from a import f def f2(): f() if __name__ == '__main__': f2() main.py: from my_module.b import f2 if __name__ == '__main__': f2() When I run b.py, "Hello World." is printed successfully. ... | Because you have an __init__.py file in the my_module directory, Python sees the entirety of my_module as a package. That also means that all imports within my_module must be relative imports. This is easily fixed by changing your import in b.py to be a relative import. b.py from .a import f def f2(): f() if __name__ =... | 2 | 3 |
77,037,560 | 2023-9-4 | https://stackoverflow.com/questions/77037560/how-to-count-work-days-between-date-columns-with-polars | I have the following DataFrame. df = pl.from_repr(""" ┌────────────┬───────────────┐ │ date ┆ maturity_date │ │ --- ┆ --- │ │ date ┆ date │ ╞════════════╪═══════════════╡ │ 2000-01-04 ┆ 2000-01-17 │ │ 2000-01-04 ┆ 2000-02-15 │ │ 2000-01-04 ┆ 2000-03-15 │ │ 2000-01-04 ┆ 2000-04-17 │ │ 2000-01-04 ┆ 2000-05-15 │ └────────... | @Dean MacGregor's excellent answer using pure Polars wasn't quite performant enough for my use case. Using Numpy's built in busday_count function turned out to be much faster in my case and can easily be converted back to a polars with pl.from_numpy. nyse_holidays=pl.Series([ date(2000,1,17), date(2000,2,21), date(2000... | 3 | 3 |
77,045,427 | 2023-9-5 | https://stackoverflow.com/questions/77045427/using-python-to-automate-creation-of-jira-tickets | I have been trying to write a python script to automatically raise Jira tickets, and have been running into some trouble. To be more specific, I tried to use both the issue_create and create_issue methods as outlined in the atlassian-python API reference. In the code provided below, I successfully obtain the correct pr... | I wanted to provide an answer here, for which I want to provide most of the credit to @matszwecja who hinted how to properly raise an exception so I can find out what's going on. After adding an exception handler, I was able to catch the two issues that were preventing my script from working as intended: The url param... | 3 | 3 |
77,047,680 | 2023-9-5 | https://stackoverflow.com/questions/77047680/imshow-with-x-axis-as-log-scale-is-not-equally-spaced | I am using pcolor to generate the following plot (code below). It has a colorbar in log scale and the x-values are in log-scale too. The problem is that the rectangles in this plot have different widths (I've put a red grid to show the rectangles better, suggestion of Trenton). Is there any way in which I can make sure... | You need to specify the bin edges. Probably a better way to do this in numpy, but the idea is simple - transform to log space, get the bin edges by linear interpolation, and then transform back to normal space. import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import numpy as np # Generate Values x_... | 3 | 3 |
77,025,860 | 2023-9-1 | https://stackoverflow.com/questions/77025860/setuptools-replacing-manifest-in-with-pyproject-toml | Does setuptools support replacing the Manifest.in file, which specifies files that should only be included in the sdist distribution with a declaration in pyproject.toml? | Setuptools does not currently support replacing the MANIFEST.in with a declaration in pyproject.toml. There is also currently no specification for how to control the files included in an sdist. There are other build backends which do support this, by using their own tool subsection of pyproject.toml. For example, hatch... | 2 | 3 |
77,044,403 | 2023-9-5 | https://stackoverflow.com/questions/77044403/type-hint-function-accepting-a-union | Here is my (much simplified) code: def myfun(X:list[str|int]): for x in X: print(x) X = [1,2,3] myfun(X) Pyright complains on the last line because I provide a list of int while the function requires list[int|str]. What is the best way to deal with that case? Is there a way to say pyright to accept "subtypes"? Const... | Program to interfaces, not implementations -- Gang of Four This has been a staple chesnut of OOP lore for a long time (it dates back about 35 years now). But if you've never worked in a statically typed system before, it can be confusing what that means. After all, Python has been object oriented since its inception,... | 3 | 3 |
77,046,536 | 2023-9-5 | https://stackoverflow.com/questions/77046536/split-numpy-array-into-segments-where-condition-is-met | I have an array like so: arr = np.array([1, 2, 3, 4, -5, -6, 3, 5, 1, -2, 5, -1, -1, 10]) I want to get rid of all negative values, and split the array at each index where there was a negative value. The result should look like this: split_list = [[1, 2, 3, 4], [3, 5, 1], [5], [10]] I know how to do this using list c... | Note that instead of numpy, you could make use of itertools.groupby this way (though, judging on this: NumPy grouping using itertools.groupby performance, pure numpy will likely be more efficient): import numpy as np from itertools import groupby arr = np.array([1, 2, 3, 4, -5, -6, 3, 5, 1, -2, 5, -1, -1, 10]) split_li... | 2 | 6 |
77,045,947 | 2023-9-5 | https://stackoverflow.com/questions/77045947/polars-join-with-or-condition | I have two dataset coming from two very different data sources. Dataframe 1 ┌────────────┬─────────────────┬─────────────────┬─────────────────┬────────────────┬──────────────┐ │ date ┆ label ┆ org_slug ┆ org_id ┆ org_name ┆ issues_count │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ date ┆ str ┆ str ┆ str ┆ str ┆ i64 │ ╞══... | Assuming your data per date is small, you might get away with an inner join to a filter. However, this can quickly explode the result set and may run out of memory. print( df1.join(df2, on=["date"], how="inner") .filter( pl.any_horizontal( pl.col("org_id") == pl.col("org_id_right"), pl.col("org_slug") == pl.col("org_sl... | 2 | 2 |
77,044,491 | 2023-9-5 | https://stackoverflow.com/questions/77044491/python-dash-how-to-use-input-from-a-dynamically-created-dropdown | I got an app that contains a button with callback function to create an unlimited amount of dropdowns which will be automatically id'ed as 'dropdown-i'. The struggle is that I don't seem to be able to actually use the values I input in these Dropdowns in another callback function (that's only trying to print them). How... | This is the typical use case for leveraging pattern-matching callback selectors. The pattern-matching callback selectors MATCH, ALL, & ALLSMALLER allow you to write callbacks that respond to or update an arbitrary or dynamic number of components. The idea is to use composite id's (type+index) using dictionaries rathe... | 2 | 3 |
77,045,763 | 2023-9-5 | https://stackoverflow.com/questions/77045763/filter-a-pandas-dataframe-if-cell-values-exist-in-another-dataframe-but-with-a-r | I have two pandas DataFrame, with the same structure. Dataframe B is a subset of DataFrame A. I want to filter DataFrame B, only if the Price value appears in DataFrame A, or it is within 1% of a value in DataFrame A. For example, even if the exact price is not present, I want to keep the value if there is a row in A w... | Here is another take, using .merge_asof (note: dfA and dfB needs to be sorted by price): dfA = dfA.sort_values("price") dfB = dfB.sort_values("price") x = pd.merge_asof(dfB, dfA, on="price", direction="nearest") Creates x: index_x price index_y 0 0 0.23 2 1 2 5.26 2 2 1 10.34 1 Then calculating the percentage diffe... | 3 | 4 |
77,045,573 | 2023-9-5 | https://stackoverflow.com/questions/77045573/converting-list-function-to-generator-using-yield | I am trying to convert a for loop into an iterator using yield, but I have failed in my attempts. I don't understand exactly why the yield isn't giving me the expected output. Does anyone know what the problem is? Attempt at using yield: def iteration_order(dimensions): for dim in range(dimensions): order = [0, dim, 0]... | The problem you see is because you are using that same list for everything. You might yield it with different value, but the generator still has reference to that list and it modifies it, giving you weird output. If you add .copy() for each yield, they will be unique lists and will behave as expected: def iteration_ord... | 2 | 2 |
77,043,946 | 2023-9-5 | https://stackoverflow.com/questions/77043946/how-to-calculate-binomial-probabilities-in-python-with-very-small-numbers | I'm trying to calculate the likelihood of successfully guessing a password in Python. For example, if we take a 10 character lowercase password (26**10 possible passwords) and we can make 1 billion guesses a second, we can calculate the probability of successfully guessing the password in one hour with: from scipy.stat... | I think this is about the limitations of floating-point arithmetic which I also often face (i.e, float overflow). you can use the mpmath library, which provides arbitrary-precision arithmetic: from mpmath import mp mp.dps = 50 # Set the desired precision (adjust as needed) total_passwords = 26**12 guesses_per_second = ... | 2 | 4 |
77,043,496 | 2023-9-5 | https://stackoverflow.com/questions/77043496/is-there-a-split-function-that-returns-in-this-case | Of course we have: "1,2,3".split(",") # ["1", "2", "3"] "1".split(",") # ["1"] but also this, which is sometimes problematic in some situations (*): "".split(",") # [""] Is there a built-in way (maybe with a parameter, or a specific function) to have: "".split(",", allow_empty=True) # [] ? This would (sometimes) mak... | Not to my knowledge but you could use a regex with re.findall: import re re.findall(r'[^,]+', '1,2,3') # ['1', '2', '3'] re.findall(r'[^,]+', '1') # ['1'] re.findall(r'[^,]+', '') # [] Note that this would also discard empty strings within the input string: re.findall(r'[^,]+', '1,,3') # ['1', '3'] | 3 | 5 |
77,041,507 | 2023-9-5 | https://stackoverflow.com/questions/77041507/input-field-validation-with-two-possible-names | I'm migrating an API that was originally written in Python. The Python API allows you to send your request as camelCase or snake_case like this: This is allowed { "someInput": "nice" } This is allowed { "some_input": "nice" } This is done using a great Python library: Pydantic from pydantic import BaseModel def to_ca... | In Go, you cannot provide two JSON tags together for a single struct field. JSON tags are specified using a single string, and they are used to define how a field should be marshaled (serialized to JSON) or unmarshaled (deserialized from JSON). You cannot specify multiple tags for a single field within a struct directl... | 2 | 2 |
77,041,235 | 2023-9-5 | https://stackoverflow.com/questions/77041235/functional-difference-between-coverage-run-m-pytest-and-pytest-cov | The Coverage tool supports generating code coverage data from Pytest tests with coverage run -m pytest .... However, there is also the Pytest-Cov plugin, which invokes Coverage and generates coverage data by adding the --cov= option to Pytest. However the Pytest-Cov documentation doesn't seem to explain anywhere how th... | The differences/advantages are mentioned on their Github README and docs Compared to just using coverage run this plugin does some extras: Subprocess support: you can fork or run stuff in a subprocess and will get covered without any fuss. Xdist support: you can use all of pytest-xdist's features and still get covera... | 2 | 3 |
77,041,143 | 2023-9-5 | https://stackoverflow.com/questions/77041143/best-approach-to-split-explode-and-tidy-data-using-regex-in-python-and-pandas | I have a dataset that requires splitting, exploding, and tidying using regular expressions (regex) in Python and Pandas. The dataset consists of logs from multiple users sent through an old machine to a server API. Each cell may contain multiple messages, and my goal is to transform the data into a structured and tidy ... | Try (regex demo): out = ( df["text_plain"] .str.extractall( r"(?P<timestamp>\d+:\d+:\d+)\S*\s+(?P<user>[^:]+?)\s*:\s*(?P<msg>.*?)(?=\s*\S*\d+:\d+:\d+|\Z)" ) .droplevel(level=1) ) print(pd.merge(df[["id"]], out, left_index=True, right_index=True)) Prints: id timestamp user msg 0 1 5:57:11 H2045 Estatus OK updated 0 1 ... | 2 | 3 |
77,037,891 | 2023-9-4 | https://stackoverflow.com/questions/77037891/typeerror-issubclass-arg-1-must-be-a-class | I am trying to use the Spacy library again for my NPL task. somedays back it was working totally fine with spacy.load("en_core_web_sm"). I thought of using medium instead of small, but now nothing is working. I play around with spacy versions from the latest (3.6.1) to older (3.2.0). I am able to install SpaCy 3.2.0 an... | You can add below to your requirements: typing-inspect==0.8.0 typing_extensions==4.5.0 There appears to be a bug in Pydantic v1.10.7 and earlier related to the recent release of typing_extensions v4.6.0 that causes errors for import spacy and any other spacy commands for python 3.8 and python 3.9 For spacy v3.2 and v... | 7 | 10 |
77,033,528 | 2023-9-3 | https://stackoverflow.com/questions/77033528/why-cant-we-use-a-fill-value-when-reshaping-a-dataframe-array | I have this dataframe : df = pd.DataFrame([list("ABCDEFGHIJ")]) 0 1 2 3 4 5 6 7 8 9 0 A B C D E F G H I J I got an error when trying to reshape the dataframe/array : np.reshape(df, (-1, 3)) ValueError: cannot reshape array of size 10 into shape (3) I'm expecting this array (or a dataframe with the same shape) : arr... | Another possible solution, based on numpy.pad, which inserts the needed np.nan into the array: n = 3 s = df.shape[1] m = s // n + 1*(s % n != 0) np.pad(df.values.flatten(), (0, m*n - s), mode='constant', constant_values=np.nan).reshape(m,n) Explanation: s // n is the integer division of the length of the original arr... | 3 | 2 |
77,033,740 | 2023-9-3 | https://stackoverflow.com/questions/77033740/whats-the-difference-between-astypecategory-categorical-and-factorize | Python offers many ways to convert a variable to categorical. import numpy as np import pandas as pd mydata = pd.Series(['A', 'B', 'B', 'C']) mydata 0 A 1 B 2 B 3 C dtype: object pd.factorize(mydata) # Outputs a tuple with an array and an index (array([0, 1, 1, 2], dtype=int64), Index(['A', 'B', 'C'], dtype='object')) ... | The methods factorize(), categorical(), and astype("category") in Python offer different ways to convert variables to categorical data: pandas.factorize docs : This method is useful for obtaining a numeric representation of an array when all that matters is identifying distinct values. It returns a tuple containing an... | 5 | 2 |
77,032,448 | 2023-9-3 | https://stackoverflow.com/questions/77032448/pytorch-lightning-how-to-save-a-checkpoint-for-every-validation-epoch | It is not clear from the docs how to save a checkpoint for every epoch, and have it actually saved and not instantly deleted, with no followed metric. How to do it? | max_epochs = 100 val_every_n_epochs = 1 checkpoint_callback = ModelCheckpoint( # dirpath=checkpoints_path, # <--- specify this on the trainer itself for version control filename="fa_classifier_{epoch:02d}", every_n_epochs=val_every_n_epochs, save_top_k=-1, # <--- this is important! ) trainer = Trainer( callbacks=[check... | 4 | 6 |
77,031,847 | 2023-9-3 | https://stackoverflow.com/questions/77031847/sending-request-from-react-to-fastapi-causes-origin-http-localhost5173-has-b | I was making a POST request which sends an image file from my UI to the backend server. Backend Server: from fastapi import FastAPI, UploadFile from fastapi.middleware.cors import CORSMiddleware import numpy as np import tensorflow as tf from io import BytesIO from PIL import Image app = FastAPI() origins = ["http://lo... | You should remove the trailing slash from the origin URL in: http://localhost:5173/ ^ The origin URL should instead look like this http://localhost:5173. Hence: origins = ["http://localhost:5173"] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"... | 4 | 4 |
77,031,177 | 2023-9-3 | https://stackoverflow.com/questions/77031177/how-to-reverse-a-singly-linked-list-using-recursive-approach-in-python | I wonder how to reverse a singly linked list using recursive approach in Python. This is LeetCode problem 206. Reverse Linked List: Given the head of a singly linked list, reverse the list, and return the reversed list. Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Most people use an iterative approach, w... | Here is how you could visualise the reversal of linked list 1→2→3: We start with: head │ ┌─┴─────────┐ ┌───────────┐ ┌───────────┐ │ val: 1 │ │ val: 2 │ │ val: 3 │ │ next: ────────┤ next: ────────┤ next: None│ └───────────┘ └───────────┘ └───────────┘ The first recursive call receives head.next, and will have its own... | 2 | 3 |
77,023,710 | 2023-9-1 | https://stackoverflow.com/questions/77023710/how-can-i-get-only-text-in-scrapy-selector-in-python | I hope you are doing well. <ul> <li> <s>Title:</s> De Aardappeleters </li> <li> <s>Dimensions:</s> 82 x 114 cm </li> <li> <s>Media:</s> canvas </li> <li> <s>Style:</s> Realism </li> <li> <s>Date:</s> 1885 </li> ______ <li> | <s>Genre:</s> | It is located on a page of the website here Modern | </li> ______| </ul> I hav... | With a css selector you can use: 'li:has(s):contains("Genre:")::text' With an xpath selector you can use: "//li[s[contains(text(), 'Genre')]]/text()" I have demonstrated using both with your example below: In [1]: html = """<ul> ...: <li> ...: <s>Title:</s> ...: De Aardappeleters ...: </li> ...: <li> ...: <s>Dimensions... | 3 | 1 |
77,009,691 | 2023-8-30 | https://stackoverflow.com/questions/77009691/how-to-maximize-the-cache-hit-rate-of-the-2-element-combinations | My question is simple, but I find it difficult to get the point straight, so please allow me to explain step by step. Suppose I have N items and N corresponding indices. Each item can be loaded using the corresponding index. def load_item(index: int) -> ItemType: # Mostly just reading, but very slow. return item Also ... | Here is a simple approach that depends on the cache and gets 230 on your benchmark. def diagonal_block (lower, upper): for i in range(lower, upper + 1): for j in range(i, upper + 1): yield (i, j) def strip (i_lower, i_upper, j_lower, j_upper): for i in range(i_lower, i_upper+1): for j in range (j_lower, j_upper + 1): y... | 17 | 12 |
77,009,144 | 2023-8-30 | https://stackoverflow.com/questions/77009144/asyncio-this-event-loop-is-already-running-issue | is it a good idea to run the asyncio eventloop inside a thread? import asyncio import time from sample_threading import parallel loop = asyncio.new_event_loop() async def fn(p): for i in range(5): print(i) time.sleep(5) print("done") @parallel def th(p): loop.run_until_complete(fn(p)) th(1) th(2) th(3) above code givi... | error message you are haveing, This event loop is already running, is beacuse when you attempt to run an asyncio event loop that is already running. In your code, you are creating a new event loop using asyncio.new_event_loop(), but you are not explicitly setting it as the current event loop. import asyncio import time... | 4 | 1 |
77,022,582 | 2023-9-1 | https://stackoverflow.com/questions/77022582/type-hint-for-a-special-argument | Consider the following function: from datetime import date def days_between(start_date: date, end_date: date) -> int: if start_date == "initial": start_date = date(2023, 9, 1) delta = end_date - start_date return delta.days The type hint of start date is mostly fine, but it does not cover the case where "initial" is p... | You should use typing.Literal from typing import Literal def days_between(start_date: date | Literal['initial'], end_date: date) -> int: ... This is included starting from python 3.8. Literal can be used to indicate to type checkers that the annotated object has a value equivalent to one of the provided literals. | 2 | 3 |
77,021,106 | 2023-9-1 | https://stackoverflow.com/questions/77021106/is-there-anyway-to-generate-doc-strings-for-python-code-using-github-copilot-vs | Is there anyway to generate doc string using Github Copilot I have code and I want to generate doc string for it. def make_chat_content(self,chat_uuid,text,db_session): import uuid all_content = ChatContent.query.filter_by(chat_uuid=chat_uuid).all() chat_json = dump(all_content) chat_json.append({"role":"user","content... | Looks like it can be done: Only test the sample code in the post. | 2 | 4 |
77,019,925 | 2023-9-1 | https://stackoverflow.com/questions/77019925/numpy-vectorized-logic-giving-unexpected-output | I could swear this should be returning three rows that meet the logic, and I cannot for the life of me figure out why only one is coming back.. Can someone please explain this? import numpy as np data = np.array([[1, 2, 3], [2, 5, 6], [7, 8, 9], [4, 3, 4]]) target_sum = 7 x = (((data[:, 0] + data[:, 1])==target_sum) | ... | I think you mean: x = ((data[:, 0] + data[:, 1])==target_sum) | (data[:, 0] ==7) Notice the parenthesis position. As stated in the doc: Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic. That means a | b == c is evaluated as (a | b) == c, not a | (b==c). | 4 | 6 |
77,019,628 | 2023-8-31 | https://stackoverflow.com/questions/77019628/how-to-order-facets-when-using-the-seaborn-objects-interface | I am trying to order facets in a plot produced by the seaborn objects interface. import numpy as np import seaborn as sns import seaborn.objects as so import matplotlib.pyplot as plt df = sns.load_dataset("iris") df["species"] = df["species"].astype("category") df["species"] = df["species"].cat.codes rng = np.random.de... | Plot.facet has a single order parameter. When only col or row are used a single list can be passed and it will be used by the appropriate variable. When both col and row are used, order can be a dictionary with col/row keys: ( so.Plot(df, x="sepal_length", y="sepal_width") .facet(row="species", col="subset", order={"ro... | 2 | 3 |
77,017,948 | 2023-8-31 | https://stackoverflow.com/questions/77017948/how-to-filter-duplicates-based-on-multiple-columns-in-polars | I was earlier able to filter duplicates based on multiple columns using df.filter(pl.col(['A','C']).is_duplicated()) but after the latest version update this is not working. import polars as pl df = pl.DataFrame( { "A": [1,4,4,7,7,10,10,13,16], "B": [2,5,5,8,18,11,11,14,17], "C": [3,6,6,9,9,12,12,15,18] } ) df.filter(... | This behavior was noted as ambiguous in 0.16.10 and would return this error: exceptions.ComputeError: The predicate passed to 'LazyFrame.filter' expanded to multiple expressions: col("A").is_duplicated(), col("C").is_duplicated(), This is ambiguous. Try to combine the predicates with the 'all' or `any' expression. How... | 3 | 2 |
77,017,290 | 2023-8-31 | https://stackoverflow.com/questions/77017290/optimized-way-to-find-index-pairs-of-two-values-in-a-pandas-column | I have a dataframe of predictions on text data which gives a column named "prediction". here is the code to recreate it. import pandas as pd # initialize list elements data = ['others', 'others', 'prediction1', 'others', 'others', 'others', 'others', 'others', 'others', 'others', 'prediction2', 'others', 'prediction2',... | original question You can use zip: pred_pairs = list(zip(df.index[df['prediction'].eq('prediction1')], df.index[df['prediction'].eq('prediction2')])) Output: [(8, 20), (28, 36)] Or, if the pairs always alternate, with numpy: out = (df.index[df['prediction'].isin(['prediction1', 'prediction2'])] .to_numpy().reshape(-1... | 2 | 1 |
77,016,287 | 2023-8-31 | https://stackoverflow.com/questions/77016287/sorting-list-of-tuples-by-multiple-keys-that-can-be-empty | I try to sort list of tuples first by 1st element, than by 2nd (if it exists), than by 3rd (if it exists). Since the tuples are of different length, some of them does not have 2nd or/and 3rd element, so the error appears: IndexError: list index out of range on line undefined. list_to_sort = [(1, 11), (2, 0, 0), (1, 2)... | I think you are looking for the basic, default sorting for a list a tuples however one of the items in your list might look like a tuple (2) but is an int. For it to be a tuple it would look more like (2,). If that item was a tuple then you could just do: print(sorted(list_to_sort)) So, that gives us a clue as to how ... | 3 | 1 |
77,014,428 | 2023-8-31 | https://stackoverflow.com/questions/77014428/what-is-the-meaning-of-a-files-key-in-poetry-lock | I just installed a newer version of a package in a poetry project. Now, for every package listed in the poetry.lock file, there's an added files key, like this: [[package]] name = "..." version = "..." files = [ {...}, {...} ] This wasn't there before, only after I installed the new version of the package, and introdu... | There is little documentation on Poetry's lock file format and its changes from version to version. Regarding your question, there is a discussion on Github that briefly describes what's going on: Before lock file format version 2.0 The files entry was its own section in the lock file, so one could find, for example, t... | 2 | 3 |
77,012,106 | 2023-8-30 | https://stackoverflow.com/questions/77012106/django-allauth-modulenotfounderror-no-module-named-allauth-account-middlewar | "ModuleNotFoundError: No module named 'allauth.account.middleware'" I keep getting this error in my django project even when django-allauth is all installed and setup??? I tried even reinstalling and changing my python to python3 but didn't change anything, can't figure out why all other imports are working but the MID... | The middleware is only present in the unreleased 0.56.0-dev, likely you are using 0.55.2 and following 0.56 documentation. | 10 | 11 |
77,009,676 | 2023-8-30 | https://stackoverflow.com/questions/77009676/why-is-a-property-on-a-subclass-that-returns-a-type-consistent-with-the-same-at | class Foo: bar: str class Bat(Foo): @property def bar(self) -> str: ... Given the above code, my typechecker (mypy) raises the following complaint: error: Signature of "bar" incompatible with supertype "Foo" [override] This surprises me given that an instance of Foo or Bat will behave the same from the perspective of... | Expanding on the comments to the OP: Older versions of Mypy had some sort of issue/bug somehow tangentially related to this that led to some discussions on the project's GitHub: Mypy disallows overriding an attribute with a property and that should have be fixed on versions >=v0.990 There's also a discussion which feel... | 5 | 6 |
77,012,002 | 2023-8-30 | https://stackoverflow.com/questions/77012002/unexpected-behaviour-when-using-put-with-multidimensional-numpy-array | I have an array A defined as: [[0, 0], [0, 0]] I have a list I containing indices of A, for example [(0, 1), (1, 0), (1, 1)], and a list v with as many values as in I, for example [1, 2, 3]. I want to replace entries of A at indices contained in I with corresponding values stored in v. The expected result is therefore... | IIUC, you can do: I = np.array(I) A[I[:, 0], I[:, 1]] = v print(A) Prints: [[0 1] [2 3]] | 2 | 1 |
77,006,611 | 2023-8-30 | https://stackoverflow.com/questions/77006611/how-to-make-all-values-in-an-array-fall-into-a-range | Say I have a NumPy array of floats, there are positive values and negative values. I have two numbers, say they are a and b, a <= b and [a, b] is a (closed) number range. I want to make all of the array fall into the range [a, b], more specifically I want to replace all values outside of the range with the correspondin... | You can use the np.clip Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1. It is faster than the broadcasts way. Code Example: import numpy as np arr = np.array([-3, 5,... | 2 | 5 |
77,004,957 | 2023-8-30 | https://stackoverflow.com/questions/77004957/what-datatype-is-considered-list-like-in-python | In the Pandas documentation here for Series.isin(values), they state: values : set or list-like What is considered list-like? For a Python dictionary temp_dict, would temp_dict.keys() and temp_dict.values() be considered list-like? | "List-like" isn't a standard Python term. Googling pandas list-like turns up pandas.api.types.is_list_like, but the documentation for that just says Check if the object is list-like. Objects that are considered list-like are for example Python lists, tuples, sets, NumPy arrays, and Pandas Series. Strings and datetime ... | 10 | 15 |
77,004,785 | 2023-8-30 | https://stackoverflow.com/questions/77004785/why-is-the-input-still-a-string-type-after-running-it-through-a-function-to-turn | I type a time like 7:30 run it through the convert() function to turn that into a float that would equal 7.5. Then call it back to main() and check what type it is now, and it gives me it's still a str not a float. def main(): meal_time = input("What time is it?").strip() convert(meal_time) print(type(meal_time)) def c... | You're not updating meal_time in main() with the float returned from convert(). Functions in Python don't modify the original variable unless it's mutable and you're explicitly changing it. Instead of: convert(meal_time) Try: meal_time = convert(meal_time) Output you should observe after the above change: <class 'flo... | 2 | 5 |
76,970,173 | 2023-8-24 | https://stackoverflow.com/questions/76970173/how-to-get-files-and-form-data-using-the-request-object-in-fastapi | I am developing a webhook in which a third-party service will hit my URL and will provide some files, now I can not use FastAPI's UploadFile = File (...) because it throws an error of the required field File I want to read the payload and files from the request object as we can do in Flask by simply doing this from fla... | The proper approach would be to define File/UploadFile and Form type parameters in your endpoint, as demonstrated in Method 1 of this answer, as well as here, here and here (for a faster file and data uploading approach, see this answer and this answer as well). For instance: @app.post("/submit") async def register(nam... | 5 | 6 |
77,001,129 | 2023-8-29 | https://stackoverflow.com/questions/77001129/how-to-configure-fastapi-logging-so-that-it-works-both-with-uvicorn-locally-and | I have the following FastAPI application: from fastapi import FastAPI import logging import uvicorn app = FastAPI(title="api") LOG = logging.getLogger(__name__) LOG.info("API is starting up") LOG.info(uvicorn.Config.asgi_version) @app.get("/") async def get_index(): LOG.info("GET /") return {"Hello": "Api"} The applic... | 1. Setting up the uvicorn logger Straight from the documentation: Logging --log-config <path> - Logging configuration file. Options: dictConfig() formats: .json, .yaml. Any other format will be processed with fileConfig(). Set the formatters.default.use_colors and formatters.access.use_colors values to override the a... | 27 | 31 |
76,963,311 | 2023-8-23 | https://stackoverflow.com/questions/76963311/llama-cpp-python-not-using-nvidia-gpu-cuda | I have been playing around with oobabooga text-generation-webui on my Ubuntu 20.04 with my NVIDIA GTX 1060 6GB for some weeks without problems. I have been using llama2-chat models sharing memory between my RAM and NVIDIA VRAM. I installed without much problems following the intructions on its repository. So what I wa... | After searching around and suffering quite for 3 weeks I found out this issue on its repository. The llama-cpp-python needs to known where is the libllama.so shared library. So exporting it before running my python interpreter, jupyter notebook etc. did the trick. For using the miniconda3 installation used by oobabooga... | 12 | 13 |
76,976,114 | 2023-8-25 | https://stackoverflow.com/questions/76976114/how-to-get-the-days-between-today-and-a-polars-date | I'm having a bit of trouble with my python code. I originally wrote it using pandas, but I need something a bit faster, so I'm converting it to polars. After reading the mongodb into polars dataframes with race = pl.DataFrame(list(race_coll.find())) and converting the 'date_of_race' column into pl.Date type using race... | use a Python datetime object for the reference date, and .dt.total_days() to get the days difference. EX: import polars as pl import pandas as pd s = pl.Series([ "2022-10-30T00:00:00", "2022-10-30T01:00:00", "2022-10-30T02:00:00", "2022-10-30T03:00:00", "2022-10-30T04:00:00", "2022-10-30T05:00:00", ]).cast(pl.Datetime)... | 3 | 4 |
76,988,796 | 2023-8-27 | https://stackoverflow.com/questions/76988796/python-polars-number-of-rows-since-last-value-0 | Given a polars DataFrame column like df = pl.DataFrame({"a": [0, 29, 28, 4, 0, 0, 13, 0]}) how to get a new column like shape: (8, 2) ┌─────┬──────┐ │ a ┆ dist │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪══════╡ │ 0 ┆ 1 │ │ 29 ┆ 0 │ │ 28 ┆ 0 │ │ 4 ┆ 0 │ │ 0 ┆ 1 │ │ 0 ┆ 2 │ │ 13 ┆ 0 │ │ 0 ┆ 1 │ └─────┴──────┘ The solution sh... | Here's one way with rle_id to identify the groups to project over, and only doing so on the 0 groups with a when/then: df = pl.DataFrame({"a": [0, 29, 28, 4, 0, 0, 13, 0]}) df.with_columns( dist=pl.when(pl.col('a') == 0) .then(pl.col('a').cum_count().over(pl.col('a').ne(0).rle_id())) .otherwise(0) ) shape: (8, 2) ┌───... | 3 | 2 |
76,984,212 | 2023-8-26 | https://stackoverflow.com/questions/76984212/how-to-apply-ip-lookup-using-polars | Given two tables I'd like to conduct a lookup over all ips and find the network it belongs to: I have two large tables: and the following networks: Regarding the ClientIP (First table) I thought of casting the whole column with ip_address Regarding the second column (second table) I thought of casting the whole colum... | Assuming the network dataframe's IpCidr blocks are not overlapping, you could convert the IPv4 addresses to a pl.Int64 and get the max value within the CIDR block. A function using only a pl.Expr to convert an IPv4 address to pl.Int64 import polars as pl def ip_addr4_int64_expr(ipv4_str_expr: pl.Expr): return ( ipv4_st... | 3 | 5 |
76,959,447 | 2023-8-23 | https://stackoverflow.com/questions/76959447/how-can-i-reduce-the-amount-of-data-in-a-polars-dataframe | I have a csv file with a size of 28 GB, which I want to plot. Those are way too many data points obviously, so how can I reduce the data? I would like to merge about 1000 data points into one by calculating the mean. This is the sturcture of my DataFrame: df = pl.from_repr(""" ┌─────────────────┬────────────┐ │ Time in... | You can also group by an integer column to create groups of size N: In case of a group_by_dynamic on an integer column, the windows are defined by: “1i” # length 1 “10i” # length 10 We can add a row index and cast to pl.Int64 to use it. (df.with_row_index() .group_by_dynamic(pl.col.index.cast(pl.Int64), every="2i") .... | 3 | 1 |
76,973,907 | 2023-8-25 | https://stackoverflow.com/questions/76973907/type-hint-for-a-matplotlib-color | I'm type-hinting functions in Python, and not sure what type a matplotlib color should be. I have a function like this: def plot_my_thing(data: np.ndarray, color: ???): # function def here What should the type be in ???, when it is meant to be a matplotlib color that you can feed into plt.plot() for the type hint? Rig... | Matplotlib introduced type hints in 3.8.0. Now, you can use matplotlib.typing.ColorType which is just an alias for all valid matplotlib colors. For more information, see the matplotlib typing api reference. | 3 | 6 |
76,967,187 | 2023-8-24 | https://stackoverflow.com/questions/76967187/what-is-alternative-of-deleted-moneydecimal-places-display | I stuck a bit with hiding decimals of Money object. Ex: In [51]: str(Money(123, 'USD')) Out[51]: 'US$123.00' returns with 00 in the end. Before it was resolved by money_obj.decimal_places_display = 0 but it is deleted in the last version on djmoney https://django-money.readthedocs.io/en/latest/changes.html#id3 I have ... | babel's format_currency allows us to display the rounded amount by passing a format string and currency_digits=False. However, by using a format string we lose the ability to localize the amount and the placement of the currency sign. Example: # Python 3.12.2 # Babel==2.14.0 from babel.numbers import format_currency # ... | 3 | 2 |
77,000,435 | 2023-8-29 | https://stackoverflow.com/questions/77000435/how-to-create-search-options | I'm currently working on having my Discord music bot create a keyword search menu, similar to the one depicted in the image. I'm utilizing the ytsearch from the ytdlp library to retrieve the top five results for a keyword search. The search process often takes longer than 3 seconds, resulting in unsuccessful responses.... | How to create options in pycord Here's an example that I have below: breed_types = ['German Shepherd', 'Bulldog', 'etc'] # list of breed types to autocomplete dog_breeds = discord.Option(str, autocomplete=discord.utils.basic_autocomplete(breed_types), required=False) # create options using autocomplete util @bot.slash_... | 3 | 0 |
76,997,449 | 2023-8-29 | https://stackoverflow.com/questions/76997449/invalidate-django-cached-property-in-signal-handler-without-introducing-unnecess | Let's say I have the following Django models: class Team(models.Model): users = models.ManyToManyField(User, through="TeamUser") @cached_property def total_points(self): return self.teamuser_set.aggregate(models.Sum("points"))["points__sum"] or 0 class TeamUser(models.Model): team = models.ForeignKey(Team, on_delete=mo... | I think there is a misconception here. cached_property isn't actually a persisting database cache or a Redis cache. It lives and dies within one instance. This usually means a single request. It will be already refreshed in the next request. It's reason for existence is to not call an expensive method more than once, w... | 5 | 3 |
76,996,496 | 2023-8-28 | https://stackoverflow.com/questions/76996496/0-360-longitude-labels-in-cartopy-orthographic-projection | I'm trying to produce an orthographic figure using Cartopy. I have basically the entire thing working exactly the way I want it to...except for the labels on the longitude gridlines. While the convention for longitude is often to use 0 - 180 E or 0 - 180 W, the convention on other bodies can sometimes be 0 - 360 degree... | Q: How do I plot 0 to 360 longitude labels? A: You can replace the labels with new ones that meet your needs. The code given below should do the trick. Place it in before the line ax1.invert_xaxis(). fig1, ax1 = plt.subplots(1, 1, figsize=(10.0, 10.0), constrained_layout=True, subplot_kw={"projection": plotproj}) ax1.... | 2 | 2 |
76,989,170 | 2023-8-27 | https://stackoverflow.com/questions/76989170/change-column-value-depending-on-how-many-times-value-appears-in-other-column | I have a dataframe that looks like this: Container Event A Clean B Dry A Clean A Dry B Clean C Clean C Clean C Clean I want to introduce a new column called 'Temperature', which has the value 4 the first time a container has the event 'Clean' and value 3 for all subsequent 'Clean' events. Dry would always have value 1... | make conditions and use np.select import numpy as np cond1 = ~df.duplicated() cond2 = df['Event'].eq('Clean') cond3 = df['Event'].eq('Dry') df['Temperature'] = np.select([cond1 & cond2, cond2, cond3], [4, 3, 1]) df Container Event Temperature 0 A Clean 4 1 B Dry 1 2 A Clean 3 3 A Dry 1 4 B Clean 4 5 C Clean 4 6 C Clea... | 2 | 3 |
76,985,067 | 2023-8-26 | https://stackoverflow.com/questions/76985067/i-am-having-an-import-error-with-the-fitz-library-in-pycharm | I am having this issue of importing the fitz library in PyCharm. I pip installed PyMuPDF and in my code I added "import fitz" but it is giving me this error: ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/fitz/_fitz.so, 0x0002): tried: '/Library/Frameworks/Python.fra... | The problem with this not working on my mac mini m2 chip was because there wasn't any wheel that supported it but there is a new wheel. Just use this in your terminal if you're having the same problem. pip install --upgrade pymupdf | 2 | 3 |
77,002,238 | 2023-8-29 | https://stackoverflow.com/questions/77002238/type-checking-python-function-signatures-of-protocol-subclass-with-mypy | Is there a way to safely type-check a python class which subclasses a protocol? If I define a protocol with a certain method function signature, then implicit subclasses must define a method with a compatible signature: # protocols.py from abc import abstractmethod from dataclasses import dataclass from typing import P... | I just want to point out, as was established in the comments, it is not in fact true that if you explicitly subtype SupportsPublish, mypy does not report a type error. The problem is that you weren't type annotating your method, which essentially tells mypy "don't check this". If you do, for example: from dataclasses i... | 7 | 3 |
76,997,401 | 2023-8-29 | https://stackoverflow.com/questions/76997401/how-to-use-mplcursors-to-annotate-with-a-complete-dataframe-row-in-a-multigrid-p | I'm trying to plot a multi-dimensional scatterplot across several visual properties (facets, hue, shape, x, y). I'm also trying to get a tooltip on cursor hover to show additional properties of the point. (I'm using seaborn + mplcursors, but I'm not married to this solution.) The problem is that the hover has the wrong... | sns.relplot returns a FacetGrid which contains an axes_dict. That's a dictionary that for each column and row tells which is the corresponding subplot (ax). Based on this, you can create a new dictionary that maps the ax to the corresponding subset of the dataframe. (Note that this might occupy a lot of extra memory fo... | 2 | 2 |
77,002,835 | 2023-8-29 | https://stackoverflow.com/questions/77002835/im-learning-python-web-scraping-it-shows-attributeerror-when-i-scrapy-crawl-a | I'm learning python scraping with scrapy. I did exacly the same thing as the tutorial teaches. But I got an error. Please help! My Python code: import scrapy class BookSpider(scrapy.Spider): name = "books" allowed_domains = ["books.toscrape.com"] start_urls = ["https://books.toscrape.com"] def parse(self, response): bo... | As pointed out in my comment, the issue you are describing is already being tackled by scrapy here and has to do with one of its dependencies, twisted (a day ago, a new version was released, 23.8.0, which seems to cause the issue). Another user fixed the issue by installing a previous version of twisted (see here). Bas... | 8 | 22 |
77,002,315 | 2023-8-29 | https://stackoverflow.com/questions/77002315/get-2d-gauss-legendre-quadrature-points-and-weights-using-numpy | NumPy provides the np.polynomial.legendre.leggauss() function to compute the sample points and weights for Gauss-Legendre quadrature. I'm trying to use this function to get the 2D points and weights for a quadrilateral. I am able to use the function as shown here: def gauss2D(n): x, w = np.polynomial.legendre.leggauss(... | This would be: x, w = np.polynomial.legendre.leggauss(n) gauss_pts = np.array(np.meshgrid(x,x,indexing='ij')).reshape(2,-1).T weights = (w*w[:,None]).ravel() | 2 | 4 |
77,001,865 | 2023-8-29 | https://stackoverflow.com/questions/77001865/python-call-class-function-as-other-classes-attribute | Is it possible to create a construction like this, where a method foo of a class A is used to set the value of an attribute of another class B. Then this method should be called on an instance of A without calling A.foo() directly. class A: def foo(self): print("Hello") class B: def __init__(self): self.func = A.foo de... | In this case, you could just pass the instance explicitly: class A: def foo(self): print("Hallo") class B: def __init__(self): self.func = A.foo def bar(self): obj = A() self.func(obj) | 2 | 3 |
76,996,584 | 2023-8-28 | https://stackoverflow.com/questions/76996584/multiple-tags-for-beatifulsoup | import os from bs4 import BeautifulSoup # Get a list of all .htm files in the HTML_bak folder html_files = [file for file in os.listdir('HTML_bak') if file.endswith('.htm')] # Loop through each HTML file for file_name in html_files: input_file_path = os.path.join('HTML_bak', file_name) output_file_path = os.path.join('... | You can modify your code to remove the div tags with the gmail_quote class by using the decompose() method of the BeautifulSoup library. This method removes a tag from the tree and then completely destroys it and its contents. # Find and remove all div tags with class gmail_quote for tag in main_content.find_all('div'... | 2 | 2 |
76,998,938 | 2023-8-29 | https://stackoverflow.com/questions/76998938/select-closest-element-between-2-numpy-arrays-of-differing-sizes | I have 2 numpy arrays of different sizes. One of them 'a' contains int values, while the other (larger) np array 'b' contains float values with (say) 3-4 values per element/value in 'a'. a = np.random.randint(low = 1, high = 100, size = (7)) a # array([35, 11, 48, 20, 13, 31, 49]) b = np.array([34.78, 34.8, 35.1, 34.99... | If you have a lot of values to check you could also try using a kdTree. For few values the overhead of building the tree won't make this worth it, but for large n and especially for searching for nearest neighbors in a multidimensional space it's a lot quicker than computing the distance for all pairs: import numpy as ... | 2 | 1 |
76,995,416 | 2023-8-28 | https://stackoverflow.com/questions/76995416/why-does-pandas-multiindex-slice-require-a-column-placeholder-when-selecting-all | Consider this Pandas data frame with a MultiIndex: df = pd.DataFrame({'x': [1, 2, 3, 4]}) arrays = [[1, 1, 2, 2], [False, True, False, True]] df.index = pd.MultiIndex.from_arrays(arrays, names=('grp', 'is_even')) df x grp is_even 1 False 1 True 2 2 False 3 True 4 I can select a specific entry - say, grp == 1 & is_even... | idx[:, True] is actually just a wrapper to create: (slice(None, None, None), True) So when you pass it to slice, this uses the first part for the index and the second for the columns. By doing df.loc[idx[:, True], :] you make it explicit that the columns slicer is : A further demonstration is trying to run df.loc[idx[... | 2 | 3 |
76,994,428 | 2023-8-28 | https://stackoverflow.com/questions/76994428/why-limit-to-last-not-working-in-firestore | When running the code below I get the first item not the last. Why is that? async def example(): db: google.cloud.firestore.AsyncClient = AsyncClient() await db.document("1/1").set({"a": "1"}) await db.document("1/2").set({"a": "2"}) last = ( await ( db.collection("1") .order_by("a") .limit_to_last(1) # <= not working ... | If your database schema looks like this: db | --- 1 (collection) | --- 1 (document) | | | --- a: "1" | --- 2 (document) | --- a: "2" Then the following query: db.collection("1").order_by("a").limit_to_last(1) Will indeed return: {'a': '2'} Because the last element in the results is the second document. I tested and ... | 2 | 3 |
76,989,290 | 2023-8-27 | https://stackoverflow.com/questions/76989290/how-to-fool-issubclass-checks-with-a-magicmock | I have something like this: from unittest.mock import MagicMock class A: pass class B(A): pass mock_B = MagicMock(spec_set=B) assert issubclass(mock_B, A) # TypeError: issubclass() arg 1 must be a class How can I get this to pass? isinstance and Mocking had a lot of stuff various answers, but from there I can't figure... | The problem here is that you want to treat mock_B, an instance of MagicMock, as a class, but an object in Python can only be considered as a class if it is an instance of type, which mock_B is simply not. So instead of trying to make a Mock object class-like, which is technically impossible since Python does not allow ... | 2 | 3 |
76,996,744 | 2023-8-29 | https://stackoverflow.com/questions/76996744/using-a-list-comprehension-with-if-to-create-a-list-of-items-without-duplicati | I have a list word_list = ['cat', 'dog', 'rabbit']. I want to use list comprehension to print each individual character from the list but removes any duplicate character. This is my code: word_list = ['cat', 'dog', 'rabbit'] letter_list = [""] letter_list = [letter for word in word_list for letter in word if letter not... | It is technically possible to implement deduplication with a list comprehension if initialization of some variables are allowed. You can use a set seen to keep track of letters already encountered, and a set include to record whether the current letter was already seen before it is added to the set seen: seen = set() i... | 5 | 4 |
76,992,029 | 2023-8-28 | https://stackoverflow.com/questions/76992029/python-regex-matching-with-optional-prefix-and-suffix | I have a regular expression that matches parts of a string (specifically peptide sequences with modifications) and I want to use re.findall to get all parts of the string: The sequence can start with an optional suffix that is anything non-capital letter string followed by -. And the sequence can also have a prefix tha... | This question already have three answers, all about how to write a regex that works, but none about how to fix your regex. Yours is almost correct: It just needs a tiny modification. [...] why is the $ matched twice? This is the relevant part: (?:-[^A-Z]+)?$ As you see, you are matching an optional pattern before $,... | 4 | 4 |
76,980,340 | 2023-8-25 | https://stackoverflow.com/questions/76980340/how-to-calculate-the-shap-values-for-the-probability-of-a-lightgbm-binary-classi | I modeled a LGBM binary classification model, however I am not interested in the classification itself, I am interested in the probabilities of a given set of observations to output a positive classification. I wanted to see how my model works using SHAP values, but I am struggling to find how to find the SHAP values f... | Try link="logit" for the force_plot: import pandas as pd import numpy as np import shap import lightgbm as lgbm from sklearn.model_selection import train_test_split from sklearn.datasets import load_breast_cancer from scipy.special import expit shap.initjs() data = load_breast_cancer() X = pd.DataFrame(data.data, colum... | 2 | 4 |
76,993,621 | 2023-8-28 | https://stackoverflow.com/questions/76993621/generate-fake-valid-data-with-pydantic | I would like to create automated examples of valid data based on my pydantic models. How can I do this? Example: import pydantic from typing import Any class ExampleData(pydantic.BaseModel): a: int b: str = pydantic.Field(min_length=10, max_length=10) @staticmethod def example() -> dict[str, Any]: # some logic return {... | Here's how you can do it using pydantic and Faker: Installation pip install Faker pip install pydantic Script import uuid from datetime import date, datetime, timedelta from typing import List, Union from pydantic import BaseModel, UUID4 from faker import Faker # your pydantic model class Person(BaseModel): id: UU... | 6 | 6 |
76,993,635 | 2023-8-28 | https://stackoverflow.com/questions/76993635/python-itertools-zip-longest-with-mutable-fillvalue | In a code that evaluates a web response, I would like to zip elements from several lists. However, the elements of the iterators are dict's. Therefore, I would like to fill up the missing values also with dict's, but each generated element should have it's own dict instance. The following code groups elements from each... | You can use a sentinel value and wrap zip_longest in another pipeline. For example: sentinel = object() l = list(tuple({} if x is sentinel else x for x in items) for items in zip_longest(l1, l2, fillvalue=sentinel)) For this example, you can probably use None rather than a custom sentinel object. | 2 | 3 |
76,992,453 | 2023-8-28 | https://stackoverflow.com/questions/76992453/pandas-describe-for-datetime-column | I am using pandas to perform data analysis, I have a datetime column and I am using describe() as below. s = pd.Series([np.datetime64("2000-01-01"), np.datetime64("2010-01-01"), np.datetime64("2010-01-01")]) print('--------------------') print(s) print('--------------------') print(s.dtype) print('--------------------'... | Yes, internally datetime objects are stored as integers (number of nanoseconds since epoch), making them inherently numeric data. For the reported data, all values (['count', 'mean', 'min', '25%', '50%', '75%', 'max']) are valid as they represent the count or a date in the min-max range. You can note that std is absent... | 3 | 3 |
76,992,421 | 2023-8-28 | https://stackoverflow.com/questions/76992421/attributeerror-module-ssl-has-no-attribute-protocol-tlsv1-3 | I am trying to setup a tls context in python. I want to force TLSv1.3 usng: context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_3) This does not work as I receive the following error: AttributeError: module 'ssl' has no attribute 'PROTOCOL_TLSv1_3' I am on Ubuntu 20.04 and am using python version 3.8 and openssl version 1.1.... | TLS 1.3 protocol will be available with PROTOCOL_TLS in OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just TLS 1.3. https://docs.python.org/3.11/library/ssl.html#ssl.SSLContext Footnote 3. According to the protocol version description, this is how you set TLS 1.3 as the minimum version supported: client... | 2 | 5 |
76,989,937 | 2023-8-28 | https://stackoverflow.com/questions/76989937/mongoengine-aggregate-lookup-on-id-not-working | Campaign Record { "_id": { "$oid": "64eb81337f7d9f6e1107fc3a" }, "_cls": "CampaignModel", "campaignNumber": "CMPN-00005", "account": { "$oid": "64d80694fe75052b39c0e615" }, "campaignName": "title", "campaignDescription": "wdesc", "campaignStartDate": { "$date": "2023-08-17T00:00:00.000Z" }, "campaignEndDate": { "$date"... | The problem was you were storing the campaignId as a string type in the Booking collection. Make sure that both values to be compared must be same type before comparing. Thus, you need to convert the campaignId for the document in the Booking collection as ObjectId type as below: db.Campaign.aggregate([ { "$lookup": { ... | 2 | 3 |
76,986,516 | 2023-8-27 | https://stackoverflow.com/questions/76986516/how-to-retrieve-all-spark-session-config-variables | In databricks I can set a config variable at session level, but it is not found in the context variables: spark.conf.set(f"dataset.bookstore", '123') #dataset_bookstore spark.conf.get(f"dataset.bookstore")#123 scf = spark.sparkContext.getConf() allc = scf.getAll() scf.contains(f"dataset.bookstore") # False I understan... | Pyspark's RuntimeConfig indeed seems to be limited compared to its Scala counterpart. However if we peek at its source code... class RuntimeConfig: def __init__(self, jconf: JavaObject) -> None: """Create a new RuntimeConfig that wraps the underlying JVM object.""" self._jconf = jconf we will be able to retrieve its u... | 5 | 6 |
76,988,753 | 2023-8-27 | https://stackoverflow.com/questions/76988753/inner-classes-cant-reference-eachother-is-there-a-more-pythonic-way | I want to use inner classes (mainly dataclass and Enums) to keep things encapsulated. They hold data and defines that are only relevant to the main class, so I'd like to keep them inside it. I get the sense that this is not the most Pythonic way to do things, but I'm not sure how to make it better. The real problem is ... | The problem you are encountering is because class bodies do not create enclosing scopes. Nesting class definitions isn't a common pattern in Python. You are going to be working against the language to get it to work. Here is a minimal example of your problem: >>> class Foo: ... class Bar: ... pass ... class Baz: ... ba... | 2 | 3 |
76,963,279 | 2023-8-23 | https://stackoverflow.com/questions/76963279/parallelize-accelerate-loops-of-tensor-additions | Background: I am working on a program that first shifts the different channels of a tensor along the "column" dimension with different distances, and then performs a summation along the "channel" dimension to merge the different dimensions into one. Specifically, given a tensor x of size (B,C,H,W) and step size S, wher... | Large-kernel convolutions are not necessarily efficient. torch.scatter_add_ can sum over the shifted elements directly. I didn't write the pseudo inverse (I think it was to check for correctness? I compared this new method with your Method1/Method2). out_W = W + (C-1)*S i_list = torch.arange(C, dtype=torch.long, device... | 2 | 2 |
76,985,136 | 2023-8-26 | https://stackoverflow.com/questions/76985136/change-the-logic-of-custom-type-from-extra-types-phonenumber | There is the PhoneNumber type to validate phone numbers: from pydantic import BaseModel from pydantic_extra_types.phone_numbers import PhoneNumber class User(BaseModel): name: str phone_number: PhoneNumber user = User(name='John', phone_number='+447911123456') print(user.phone_number) #> tel:+44-7911-123456 I'm satisf... | The PhoneNumber class has these class variables: #https://github.com/pydantic/pydantic-extra-types/blob/092251d226edcf4e06bbe4f904da177fad20a6de/pydantic_extra_types/phone_numbers.py#L26 default_region_code: str | None = None phone_format: str = 'RFC3966' min_length: int = 7 max_length: int = 64 If we follow a bunch o... | 2 | 4 |
76,983,253 | 2023-8-26 | https://stackoverflow.com/questions/76983253/randomly-sampling-points-within-an-octagon-using-python | How do I randomly sample 2d points uniformly from within an octagon using Python / Numpy? We can say that the octagon is centered at the origin (0, 0). The following is what I've done: import numpy as np import matplotlib.pyplot as plt def sample_within_octagon(num_points): points = np.zeros((num_points, 2)) # Generate... | In your code, the formula for max_radii needs a little modification, try the following: import matplotlib.pyplot as plt import numpy as np from scipy import interpolate def sample_within_octagon(num_points, inv_transform_evals=10000): points = np.zeros((num_points, 2)) # Angle offset for each octagon segment offset = n... | 3 | 2 |
76,981,933 | 2023-8-26 | https://stackoverflow.com/questions/76981933/cannot-type-password-in-pypi | I'm trying to publish a module to PyPi and when I run the command twine upload dist/* everything works fine, I can type in my name, but then I cannot type anything in the password field, other than clicking enter, I've tried googling it but found none of the solutions worked, there isn't much information on this anyway... | Um, this might be a really basic answer here (I can't comment on posts yet), but, are you sure you're not just dealing with the fact that by default in most command line interfaces/shells, you won't see any kind of "activity" (not even censored/starred out characters) when typing in a password? So yeah, you should just... | 2 | 3 |
76,970,335 | 2023-8-24 | https://stackoverflow.com/questions/76970335/how-to-convert-this-python-code-with-a-ssl-client-certificate-to-kotlin-ktor | I have some Python code that makes a HTTP request: import requests response = requests.get( url, cert = tuple(clientCertPath, pkeyPath), // paths to crt.pem and pkey.pem verify = serverCertPath // path to server-ca.crt file ) I'd like to rewrite this to Kotlin using ktor. This is what I've come up with so far: val ser... | There are couple of ways to load pem files and creating a sslcontext out of it. However it is a bit verbose with traditional java. If you just want to go with that without the need for additional libraries, you can give the following stackoverflow topic a try How to build a SSLSocketFactory from PEM certificate and key... | 3 | 1 |
76,981,232 | 2023-8-26 | https://stackoverflow.com/questions/76981232/unpacking-for-list-indices | I often find I have something like this: cur = [0, 0] # the indices into array matrix = [[1,1,1]] where I do matrix[cur[0]][cur[1]] Is there any sort of unpacking syntax here? Like: matrix[*cur] | If you switch to NumPy and you're using Python 3.11+, then yes, that works. import numpy as np cur = [0, 0] matrix = np.array([[1, 2, 3]]) print(matrix[*cur]) # -> 1 Before Python 3.11, you can just convert to tuple: print(matrix[tuple(cur)]) # -> 1 Based on the name matrix, NumPy might be a better solution in other ... | 3 | 6 |
76,980,525 | 2023-8-25 | https://stackoverflow.com/questions/76980525/what-is-wrong-with-this-matrix-multiplication-in-python | In the below code (Jupiter notebook), output is given wrong, how to correct the code? import numpy as np A = [1,22,231,1540] B = [[-1,1,0],[1,-1,1],[0,6,0],[0,6,0]] C = [[113401201],[10649],[1]] result = np.dot(np.dot(A, B),C) print(result) output [-1800609408] The actual answer is I want to find the error and corr... | You're probably running this code on 32-bit platform (where integers are 32 bit): A = np.array(A, dtype=np.int32) B = np.array(B, dtype=np.int32) C = np.array(C, dtype=np.int32) result = np.dot(np.dot(A, B), C) print(result) Prints (incorrectly, because the value overflows): [-1800609408] To correct it, use 64-bit v... | 2 | 6 |
76,980,315 | 2023-8-25 | https://stackoverflow.com/questions/76980315/sorting-dataframe-contents-based-on-last-column-values | I am trying to sort and display the contents of a file. The code I have does not produce the expected output. I have set ascending=True or ascending=False but it still does not work. Thank in advance. sampledata.txt # Source file ADS43 11.468 02:45 982AS2S 5.657 02:45 K72KSU3 -3.398 02:45 JJS7AS 3.238 02:45 LO92SA 2.2... | I've executed your code near-verbatim and don't receive the error you report. data = {} for row in ''' ADS43 11.468 02:45 982AS2S 5.657 02:45 K72KSU3 -3.398 02:45 JJS7AS 3.238 02:45 LO92SA 2.221 02:45 22SA8A -1.931 02:45 ADS43 11.468 03:00 982AS2S -5.657 03:00 K72KSU3 3.398 03:00 JJS7AS -2.238 03:00 LO92SA 7.221 03:00 ... | 2 | 2 |
76,980,131 | 2023-8-25 | https://stackoverflow.com/questions/76980131/how-to-filter-pandas-dataframe-so-that-the-first-and-last-rows-within-a-group-ar | I have a dataframe like below: data = [ [123456, "2017", 150.235], [123456, "2017", 160], [123456, "2017", 135], [123456, "2017", 135], [123456, "2017", 135], [123456, "2018", 202.5], [123456, "2019", 168.526], [123456, "2020", 175.559], [123456, "2020", 176], [123456, "2021", 206.667], [789101, "2017", 228.9], [789101... | Try: out = df.groupby("ID", group_keys=False).apply( lambda x: x[(x.year == x.year.min()) | (x.year == x.year.max())] ) print(out) Prints: ID year value 0 123456 2017 150.235 1 123456 2017 160.000 2 123456 2017 135.000 3 123456 2017 135.000 4 123456 2017 135.000 9 123456 2021 206.667 10 789101 2017 228.900 11 789101 ... | 2 | 1 |
76,979,303 | 2023-8-25 | https://stackoverflow.com/questions/76979303/pandas-filter-dataframe-by-column-of-sets-using-multiple-conditions-regarding-s | I have a problem whereby I want to filter the following dataframe such that I only return the rows where we have both a pie and a non-pie item: ID set 1 apple pie, banana loaf 2 banana pie, apple pie 3 banana loaf, apple tart Thus, the expected output would be: ID set 1 apple pie, banana loaf ... | You could use apply on your dataframe: df[df.set.apply(lambda x: len([s for s in x if "pie" in s]) == 1)] Results: ID set 0 1 [apple pie, banana loaf] | 3 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.