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 |
|---|---|---|---|---|---|---|
76,960,371 | 2023-8-23 | https://stackoverflow.com/questions/76960371/executing-several-python-files-on-the-same-interactive-prompt-on-vs-code | I'm transitioning from Spyder to VS Code, and I'm having an issue executing ad-hoc code on an interactive session. I first save this to a tmp1.py and run the selection on an interactive window: import pandas as pd df = pd.DataFrame({'a': [1,2,3,4], 'b': [1,1,2,3]}) Then on tmp2.py I just write and run: print(df) It o... | For some reason my "Jupyter > Interactive Window: Creation Mode" setting was "perfile", although "multiple" is supposed to be the default. After changing it to "multiple" everything works logically. I can also open sevaral interactive windows, and the selected code gets evaluated in the active one. | 3 | 5 |
76,973,376 | 2023-8-24 | https://stackoverflow.com/questions/76973376/how-to-use-assertraises-in-table-driven-tests-where-some-tests-raise-and-others | How can I avoid calling the function I'm testing in two different places when writing table-driven tests where some of the tests should raise but others should not? This is what I want to do but it fails passing None to assertRaises: tests = [ (0, None), (1, None), (-1, TooFewException), (99, None), (100, TooManyExcept... | contextlib has nullcontext() which can accomplish this. It's not really using fewer lines (without an ugly one-liner branch), but it eliminates the second user-code call: from contextlib import nullcontext for n, exc in tests: if exc is None: cm = nullcontext() else: cm = self.assertRaises(exc) with cm: results = my_co... | 2 | 3 |
76,967,606 | 2023-8-24 | https://stackoverflow.com/questions/76967606/how-to-run-parallel-processes-reading-from-the-same-variable-in-python-efficient | I have a Python script to process one single file (~100 Gb) with many simple statistical operation that do not depend on each other. So I first load the file, then I use Joblib to run the statistical operations on the loaded data in parallel. I can see from htop that all CPU cores are loaded to 100% but most of the tim... | TL;DR: there are several issues in this code making is very inefficient. Put it shortly, it is bound by system overheads like page faults, cache misses, cache-line write allocates, useless memory writes, and even possibly memory swapping (depending on the amount of available RAM). Under the hood To understand why this... | 2 | 3 |
76,964,381 | 2023-8-23 | https://stackoverflow.com/questions/76964381/format-large-number-output-in-pythons-tqdm-module-for-readability | is there any way we can format a big number in tqdm's progress bar for better readability? For example, 1000000row/s must be 1,000,000rows/s . I know about unit scale, but it formats a number like 1,21M rows/s which is not currently what I am trying to achieve Thanks! | A little bit of reverse-engineering how tqdm handles it: from time import sleep from tqdm import tqdm tqdm.format_sizeof = lambda x, divisor=None: f"{x:,}" if divisor else f"{x:5.2f}" with tqdm(total=1_000_000, unit_scale=True) as t: for _ in range(1_000_000): sleep(0.00001) t.update() Prints: 8%|████████████▊ | 78,8... | 4 | 5 |
76,972,113 | 2023-8-24 | https://stackoverflow.com/questions/76972113/expand-a-nested-list-in-a-pandas-datatable-column-and-move-to-their-own-column | I am trying to use panads to manage data that I am pulling from an API. The data has one column that is a nested list and I am trying to extract it out to their own columns. The data looks like this so far: id mail displayName propertiesRegistered createdDateTime 00000000-0000-0000-0000-000000000000 joe.user@em... | You can use str.get_dummies: valid_properties = ['address', 'mobilePhone', 'officePhone', 'homePhone'] df = df.join(df.pop('propertiesRegistered').agg('|'.join).str.get_dummies() .reindex(columns=valid_properties, fill_value=0) # or astype(bool) for real booleans .replace({1: 'TRUE', 0: 'FALSE'}) ) Or a crosstab: s = ... | 3 | 1 |
76,971,984 | 2023-8-24 | https://stackoverflow.com/questions/76971984/how-do-you-convert-data-frame-column-values-to-integer | I need to convert data frame column to int. df['Slot'].unique() displays this: array(['1', '2', '3', '4', 1, 3, 5], dtype=object) some values have '' around it some dont. I tried to convert the data type to int as below: df['Slot']=df['Slot'].astype('Int64') I get this error: TypeError: cannot safely cast non-equiva... | You should first convert to numeric, then cast to Int64: df['Slot'] = pd.to_numeric(df['Slot']).astype('Int64') After casting the type: df.dtypes Slot Int64 dtype: object As noted in comments, if you use numpy's int64 type this works from scratch: df['Slot'].astype('int64') | 3 | 3 |
76,970,781 | 2023-8-24 | https://stackoverflow.com/questions/76970781/capturing-negative-lookahead | I need for https://github.com/mchelem/terminator-editor-plugin to capture different type of path with line number. So far I use this pattern: (?![ab]\/)(([^ \t\n\r\f\v:\"])+?\.(html|py|css|js|txt|xml|json|vue))(\". line |:|\n| )(([0-9]+)*) I'm trying to make it work for git patch format, which adds a 'a/' and 'b/' befo... | You have redundant groups that you can remove and make the starting [ab]/ part optional to leave it out of first capture group. Here is refactored and optimized regex: (?:[ab]/)?([^ \t\n\r\f\v:"]+\.(?:html|py|css|js|txt|xml|json|vue))(?:". line |[:\n ]) Updated RegEx Demo | 2 | 3 |
76,970,380 | 2023-8-24 | https://stackoverflow.com/questions/76970380/random-forest-predicting-neither-class-when-target-is-one-hot-encoded | I fairly know that trees are sensitive to one hot encoded (OHE) targets however I want to understand why it returns the predictions like this: array([[0, 0, 0, 0], [0, 0, 0, 0], . . . [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]]) For most of the samples, it predict neither class. I will encode my targets as... | When the targets are one-hot encoded, sklearn treats the problem as a multi-label one (each row could have any number of labels). As such, you get a predicted probability for each label, and those are independently thresholded at 0.5 in order to make the class predictions. When the targets are ordinally encoded, sklear... | 2 | 3 |
76,966,431 | 2023-8-24 | https://stackoverflow.com/questions/76966431/chaining-functions-with-pipe-pipe-using-not-the-first-argument | In a pipe i want to use the result of previous steps as the second argument to a subsequent step. In R i can use the result of the previous chain using . like so: df %>% b(arg1b) %>% c(arg1c, .) How to do this in python for example using pipe? df.pipe(b, arg1b).pipe(c, arg1c, **) syntax error | I'm not an active user of pandas, but this documentation page on pandas.DataFrame.pipe seems to cover your case df.pipe(b, arg1b) .pipe((c, 'second_arg_name'), arg1c) where 'second_arg_name' should be replaced with actual name of the second argument in function c | 2 | 3 |
76,959,316 | 2023-8-23 | https://stackoverflow.com/questions/76959316/remove-border-contours-from-fingerprint-image | how do i remove the outer contour lines at the edge of this fingerprint image without affecting ridges and valleys contours before processing after segmentation and ROI result after applying CLAHE and enhancement [] (https://i.sstatic.net/TIMu6.jpg) import cv2 image = cv2.imread('fingerprint.jpg') original = image.co... | Here’s a possible solution. I’m working with the binary image. You don’t show how you get this image, you mention segmentation and CLAHE but none of these operations are shown in your snippet. It might be easier to deal with the “borders” there, before actually getting the binary image of the finger ridges. Anyway, my ... | 3 | 3 |
76,964,787 | 2023-8-23 | https://stackoverflow.com/questions/76964787/how-can-i-get-the-start-positions-of-my-regex-matches-from-a-string-without-also | This is kind of a complicated question to explain and easier to just show as an example. So let's say I have this string here: exampleString = "abcauehafj['hello']jfa['hello']jasfjgafadsf" And so we have the regex pattern of: regex = r"\['hello'\]" Now, what I want to do is get the start positions of regex matches wi... | If you prefer a list comprehension, it's easy to do with enumerate, unless I misunderstood what you desired: import re exampleString = "abcauehafj['hello']jfa['hello']jasfjgafadsf" regex = r"\['hello'\]" start_pos = [match.start() - i * len(match.group()) for (i, match) in enumerate(re.finditer(regex, exampleString))] ... | 2 | 2 |
76,965,208 | 2023-8-23 | https://stackoverflow.com/questions/76965208/in-python-how-can-i-type-hint-an-input-that-is-not-str-or-bytes-and-is-a-sequen | In python, how can I type hint an input that is not str or bytes and is a sequence? I have a function that I want to accept a sequence but not accept a string or bytes input. But this code allows in str and bytes: import typing def validate(input_data: typing.Sequence) -> None: # implementation that validate that input... | One can do this by creating a Sequence protocol that implements the sequence interface, and by making the contains method ingest object, str and bytes classes will not implement the new protocol. Answer from: https://github.com/python/typing/issues/256#issuecomment-1687374072 str __contains__ is incompatible with this... | 2 | 3 |
76,962,240 | 2023-8-23 | https://stackoverflow.com/questions/76962240/numpy-turn-hierarchy-of-matrices-into-concatenation | I have the following 4 matrices: >>> a array([[0., 0.], [0., 0.]]) >>> b array([[1., 1.], [1., 1.]]) >>> c array([[2., 2.], [2., 2.]]) >>> d array([[3., 3.], [3., 3.]]) I'm creating another matrix that will contain them: >>> e = np.array([[a,b], [c,d]]) >>> e.shape (2, 2, 2, 2) I want to "cancel the hierarchy" and re... | Try np.block([[a,b],[c,d]]) This concatenates the inner lists horizontally, and does a vertical stack. Alternatively you could swap 2 axes of e and then reshape. In [41]: np.block([[a,b],[c,d]]) Out[41]: array([[0., 0., 1., 1.], [0., 0., 1., 1.], [2., 2., 3., 3.], [2., 2., 3., 3.]]) In [45]: e.transpose(0,2,1,3).resha... | 3 | 2 |
76,964,144 | 2023-8-23 | https://stackoverflow.com/questions/76964144/python-csv-writer-adds-unwanted-characters | I am letting my script read a csv file and I want to save it first into an array, then slice the second element (which is the second line of my csv file) and write the array back to the csv file. csv file looks like this before: first name,username,age,status test1,test1_username,28,2023-08-18 13:41:10+00:00 test2,test... | You're not writing anything to the output file (or it is missing in example). Also, use writer.writerows to write the data: import csv rows = [] with open("in.csv", "r", encoding="UTF-8") as f: data = csv.reader(f, delimiter=",", lineterminator="\n") for row in data: rows.append(row) # <-- append only `row` to the list... | 2 | 3 |
76,963,206 | 2023-8-23 | https://stackoverflow.com/questions/76963206/transform-one-dimensional-numpy-array-into-mask-suitable-for-array-index-update | Given a 2-dimensional array a, I want to update select indices specified by b to a fixed value of 1. test data: import numpy as np a = np.array( [[0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 1], [0, 0, 0, 0]] ) b = np.array([1, 2, 2, 0, 3, 3]) One solution is to transform b into a masked array lik... | No need to build the mask, use indexing directly: a[np.arange(len(b)), b] = 1 Output: array([[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 1], [0, 0, 0, 1]]) That said, the mask could be built using: mask = b[:,None] == np.arange(a.shape[1]) Output: array([[False, True, False, False], [False, Fal... | 3 | 1 |
76,957,766 | 2023-8-23 | https://stackoverflow.com/questions/76957766/save-a-txt-file-with-double-tab-as-separator | How can I save a table in txt file with double separator? I can save a txt file with one tab as below: df.to_csv("file1.txt", sep='\t', index=False) Name 05:58 06:11 06:18 1234DCE -3.43 -3.427 -4.622 18DDD12 11.564 10.883 10.915 453FGH2A 0.351 0.176 0.0 8FF3EFA -0.72 0.888 -0.638 98ACD12 12.574 11.883 13.356 A2DA21 0.... | If you don't pass a filename to to_csv, Pandas will return a string. So you can add a second tab: with open('file1.txt', 'w') as fp: content = df.to_csv(sep='\t', index=False) fp.write(content.replace('\t', '\t\t').strip()) However your data will not be well aligned (row 453FGH2A for example). Maybe you should use to_... | 3 | 1 |
76,938,875 | 2023-8-20 | https://stackoverflow.com/questions/76938875/remove-non-ascii-characters-from-a-polars-dataframe | I have a Polars Dataframe with a mix of Series, which I want to write to a CSV / Upload to a Database. The problem is if any of the UTF8 series have non-ASCII characters, it is failing due to the DB Type I'm using so I would like to filter out the non-ASCII characters, whilst leaving everything else. I created a functi... | .str.replace_all() with a regex to match non-ascii chars: pl.col(pl.String).str.replace_all(r"[^\p{Ascii}]", "") | 3 | 7 |
76,941,782 | 2023-8-21 | https://stackoverflow.com/questions/76941782/pycord-unknown-interaction | import discord from discord.ext import commands, tasks import imageio import os import numpy as np import asyncio @stocks.command(name="graph", description="Generate and display a stock price history graph") async def graph(self, interaction: discord.Interaction, symbol): video_path = "stock_graph.mp4" imageio.mimsave(... | First of all, understand that a Discord interaction has a short lifetime, which is exactly 3 seconds. That is, you must respond to the interaction that called your command within 3 seconds or else it will become unknown. If your command performs a time-consuming task, where you can't respond to the interaction in less ... | 2 | 2 |
76,937,581 | 2023-8-20 | https://stackoverflow.com/questions/76937581/defining-custom-types-in-pydantic-v2 | The code below used to work in Pydantic V1: from pydantic import BaseModel class CustomInt(int): """Custom int.""" pass class CustomModel(BaseModel): """Custom model.""" custom_int: CustomInt Using it with Pydantic V2 will trigger an error. The error can be resolved by including arbitrary_types_allowed=True in model_c... | You can keep using a class which inherits from a type by defining core schema on the class: from typing_extensions import Any from pydantic import GetCoreSchemaHandler, TypeAdapter from pydantic_core import CoreSchema, core_schema class CustomInt(int): """Custom int.""" ... @classmethod def __get_pydantic_core_schema__... | 6 | 3 |
76,956,869 | 2023-8-22 | https://stackoverflow.com/questions/76956869/add-dataframe-rows-based-on-external-condition | I have this dataframe: Env location lob grid row server model make slot Prod USA Market AB3 bc2 Server123 Hitachi dcs 1 Prod USA Market AB3 bc2 Server123 Hitachi dcs 2 Prod USA Market AB3 bc2 Server123 Hitachi dcs 3 Prod USA Market AB3 bc2 Server123 Hitachi dcs 4 Dev EMEA Ins AB6 bc4 Serverabc IBM abc 3 Dev EMEA Ins AB... | I would use groupby.apply to add new rows to each model. The general workflow is as follows. Remove duplicate slots from each model. Group the dataframe by the 'model' column. For each model, do anything at all only if a. it is either IBM or Cisco (identified by whether it is a key in N_slots dictionary) b. the numb... | 4 | 3 |
76,917,508 | 2023-8-16 | https://stackoverflow.com/questions/76917508/calculating-partial-correlation-from-a-shrunken-covariance-matrix-help-port | There's a paper that I found interesting and would like to use some of the methods in Python. Erb et al. 2020 implements partial correlation on compositional data and Jin et al. 2022 implements it in an R package called Propr. I found the function bShrink that I'm simplifying below: library(corpcor) # Load iris dataset... | The problems There are two issues here, the estimation of the covariate matrices are different and the translation of the cor2pcor step is wrong. Let's start with cor2pcor. I honestly did not understand very well how you are computing it so I decided to check the implementation in R. If we go on the corpcor implementat... | 3 | 2 |
76,923,540 | 2023-8-17 | https://stackoverflow.com/questions/76923540/why-does-aws-lambda-experience-a-consistent-10-second-delay-for-an-unresolvable | I'm experiencing a peculiar behavior when trying to make an HTTP request to unresolved domain names from an AWS Lambda function using the requests library in Python. When I attempt to make a request using: response = requests.get('https://benandjerry.com', timeout=(1,1)) In AWS Lambda, it consistently takes around 10 ... | The issue you're seeing is due to the AWS DNS taking up to 10 seconds trying to resolve the domain. If you want more control over the DNS resolution, you can implement a custom requests Transport Adapter to do the DNS resolution yourself—which allows you to better customize the timeout. pip install dnspython import ur... | 5 | 3 |
76,956,654 | 2023-8-22 | https://stackoverflow.com/questions/76956654/can-this-recursive-function-be-turned-into-an-iterative-function-with-similar-pe | I am writing a function in python using numba to label objects in a 2D or 3D array, meaning all orthogonally connected cells with the same value in the input array will be given a unique label from 1 to N in the output array, where N is the number of orthogonally connected groups. It is very similar to functions such a... | Can this recursive function be turned into an iterative function with similar performance? Turning this into an iterative function is straightforward, considering it's just a simple depth-first search (you could also use a breadth-first search using a queue instead of a stack here, both work). Simply use a stack to k... | 2 | 4 |
76,934,579 | 2023-8-19 | https://stackoverflow.com/questions/76934579/pydanticusererror-if-you-use-root-validator-with-pre-false-the-default-you | I want to execute this code in google colab but I get following error: from llama_index.prompts.prompts import SimpleInputPrompt # Create a system prompt system_prompt = """[INST] <> more string here.<> """ query_wrapper_prompt = SimpleInputPrompt("{query_str} [/INST]") Error: /usr/local/lib/python3.10/dist-packages/p... | In my env, I have pip list | grep pydantic pydantic 2.2.1 I fix the problem, by downgrading pydantic version pip install pydantic==1.10.9 | 22 | 36 |
76,910,725 | 2023-8-16 | https://stackoverflow.com/questions/76910725/pyspark-getting-jaccard-similarity-from-co-ocurrence-matrix | I have a co-occurence matrix in pyspark for co-ocurrences of certain keywords A,B,C A B C A 5 1 0 B 1 3 2 C 0 2 3 How can I calculate the jaccard similarity from this matrix in Python for all keywords. Is there any library available to do that or should I simply compute the similarity by using the Jaccard similarity ... | Let's assume the co-occurrence matrix is given as a list of lists: com = [[5, 1, 0], [1, 3, 2], [0, 2, 3]] n_elem = len(com) The Jaccard similarity of two sets A and B is given by |A ∩ B| / |A ∪ B|. The co-occurrence matrix gives the value of |A|, |B|, and |A ∩ B|. The value of |A ∪ B| is simply |A| + |B| - |A ∩ B|, w... | 2 | 5 |
76,957,392 | 2023-8-22 | https://stackoverflow.com/questions/76957392/how-to-sort-the-contents-of-a-text-file | I am trying to sort the content of a text file. Currently, I'm sorting it using excel. I wanted to use python script to automatically sort the contents. The code below does not produce the needed output. Any idea will be very much appreciated. def sorting(filename): infile = open(filename) words = [] for line in infil... | I don't usually argue for pandas as the first solution, but in this case I think it is the right answer: import pandas as pd data = {} for row in open('x.csv'): cols = row.rstrip().split() if cols[2] not in data: data[cols[2]] = {} data[cols[2]][cols[0]] = cols[1] print(data) df = pd.DataFrame(data) print(df) Output: ... | 2 | 3 |
76,956,697 | 2023-8-22 | https://stackoverflow.com/questions/76956697/efficiently-append-csv-files-python | I am trying to append > 1000 csv files (all with the same format) in Python. The files have anything between 1KB and 30GB. All the files have 200GB in total. I want to combine these files into a unique dataframe. Below what I am doing which is very very slow: folder_path = 'Some path here' csv_files = [file for file in... | If all of your files are in the same format, and you are just trying to create a new CSV, then ditch pandas. import csv import pathlib def write_to_writer(writer: csv.writer, path: pathlib.Path, skipheader=False) -> None: with path.open(newline="") as f: reader = csv.reader(f) if skipheader: next(reader) writer.writero... | 2 | 4 |
76,956,328 | 2023-8-22 | https://stackoverflow.com/questions/76956328/pandas-column-containing-a-list-of-matched-strings-found-using-str-contains | I have string data that I am matching to a list of terms and I want to create a new column that shows all words found in each row of the dataframe df = pd.DataFrame({'String': ['Cat Dog Fish', 'Cat Dog', 'Pig Horse', 'DogFish']}) print(df) String 0 Cat Dog Fish 1 Cat Dog 2 Pig Horse 3 DogFish 4 CatHorse words = ['Cat',... | Try: words = ["Cat", "Dog", "Fish"] df["Matched"] = df["String"].apply(lambda s: [w for w in words if w in s]) print(df) Prints: String Matched 0 Cat Dog Fish [Cat, Dog, Fish] 1 Cat Dog [Cat, Dog] 2 Pig Horse [] 3 DogFish [Dog, Fish] | 2 | 3 |
76,947,564 | 2023-8-21 | https://stackoverflow.com/questions/76947564/how-can-i-quickly-sum-over-a-pandas-groupby-object-while-handling-nans | I have a DataFrame with key and value columns. value is sometimes NA: df = pd.DataFrame({ 'key': np.random.randint(0, 1_000_000, 100_000_000), 'value': np.random.randint(0, 1_000, 100_000_000).astype(float), }) df.loc[df.value == 0, 'value'] = np.nan I want to group by key and sum over the value column. If any value i... | One workaround could be to replace the NaNs by Inf: df.fillna({'value': np.inf}).groupby('key')['value'].sum().replace(np.inf, np.nan) Faster alternative: df['value'].fillna(np.inf).groupby(df['key']).sum().replace(np.inf, np.nan) Example output: key 0 45208.0 1 NaN 2 62754.0 3 50001.0 4 51073.0 ... 99995 55102.0 999... | 2 | 3 |
76,949,979 | 2023-8-22 | https://stackoverflow.com/questions/76949979/conda-when-running-give-runtimeerror-openssl-3-0s-legacy-provider-failed-to-lo | I was accidentally go to my miniconda directory and rm -r ca* (just because I using Arch and when update miniconda3 package, it said there are some certificates were there so it can't perform update, so I removed them) Now every time I run conda command, it give me RuntimeError: OpenSSL 3.0's legacy provider failed to ... | my problem was fixed as follow: export CRYPTOGRAPHY_OPENSSL_NO_LEGACY=1 conda install cryptography that's all. | 4 | 9 |
76,950,969 | 2023-8-22 | https://stackoverflow.com/questions/76950969/error-response-from-daemon-failed-to-create-task-for-container | I have a django app. That also has redis, celery and flower. Everything is working on my local machine. But When I am trying to dockerize it The redis and django app is starting. But celery and flower is failing to start. It is giving me this error while starting celery: Error response from daemon: failed to create tas... | I have found the problem in my docker-compose.yml. I had defined entrypoint like this: entrypoint: - "celery -A core worker -P eventlet --autoscale=10,1 -l INFO" But the correct way to define this in one line is this: entrypoint: "celery -A core worker -P eventlet --autoscale=10,1 -l INFO" | 3 | 0 |
76,948,077 | 2023-8-21 | https://stackoverflow.com/questions/76948077/python-automatically-matching-named-parameters | Is there any way to pass parameters to a Python function such that if the variable name matches the parameter name, the function will ensure the input is correct? Let's say I have a function as such: def func(foo, bar): return do_something_with(foo, bar) and I wanted to call it as such: foo = get_foo() bar = get_bar()... | There is no special function call syntax to pass variables as keyword arguments of the same name. If that's how you want to call your function, you must write func(foo=foo, bar=bar). While there are a few ways you could work around the issue, they're all so much worse than just writing the keywords out that I wouldn't ... | 3 | 1 |
76,948,587 | 2023-8-21 | https://stackoverflow.com/questions/76948587/multi-indexed-dataframe-join-keep-updated-data-if-not-nan-and-append-on-new-ind | I have two DataFrames with multiple indices named df_base and df_updates. I want to combine these DataFrames into a single DataFrame and keep the multi indices. >>> import numpy as np >>> import pandas as pd >>> df_base = pd.DataFrame( ... { ... "price": { ... ("2019-01-01", "1001"): 100, ... ("2019-01-01", "1002"): 10... | You shouldn't need to update then combine_first, just combine_first: df_base = df_updates.combine_first(df_base) Output: price date id 2019-01-01 1001 100.0 1002 99.0 1003 99.0 1004 100.0 2019-01-02 1001 100.0 1002 100.0 1003 100.0 2019-01-03 1001 100.0 1002 100.0 1003 100.0 | 2 | 2 |
76,948,670 | 2023-8-21 | https://stackoverflow.com/questions/76948670/regex-match-a-word-but-do-not-match-a-phrase-that-can-appear-anywhere-in-the-p | I have been spending time on this regex but I can't get it to work. So I need to match bunch of words in a phrase but if the same word occurs with a set of words, I do not want that to be captured. For example: phrase: Hi, I am talking about a recall on the product I bought last month. If I recall correctly, I purchase... | If you want to match the 2 words: (?<!\bIf\sI\s)\brecall(?:s|ed)?\b The pattern matches: (?<!\bIf\sI\s) Negative lookbehind, assert not If I to the left \brecall(?:s|ed)? Match one of the words recall recalls recalled \b A word boundary Regex demo | Python demo | 2 | 3 |
76,946,298 | 2023-8-21 | https://stackoverflow.com/questions/76946298/loading-of-gdal-library-impossible-after-an-upgrade | I have a Python environment with Django 3 that has to use GDAL (because the DB engine I use is django.contrib.gis.db.backends.postgis). After an upgrade of GDAL (from 3.6.4_6 to 3.7.1_1), I have this exception on any command to run the django project : File "~/.pyenv/versions/3.8.9/lib/python3.8/ctypes/__init__.py", l... | I faced the same OSError: dlopen(/usr/local/lib/libgdal.dylib, 0x0006): Symbol not found: __ZN3Aws6Client19ClientConfigurationC1Ev . Applied the approach suggested by @bennylope (https://nelson.cloud/how-to-install-older-versions-of-homebrew-packages/) and got it worked: wget https://raw.githubusercontent.com/Homebrew/... | 2 | 2 |
76,945,282 | 2023-8-21 | https://stackoverflow.com/questions/76945282/python-asyncio-run-in-executor-never-done | I running the following code in python 3.10.12. There is a sync function fetch_data, which should return 1 immediately. And in main function, a CPU-bound task like sum(i for i in range(int(1e6))) which cost 4~5s. import asyncio def fetch_data(): print("done") return 1 async def main(): loop = asyncio.get_event_loop() t... | It's happening because you don't give the executor a change to process it's tasks. With await asyncio.sleep(0) you interrupt your main() function and executor process the tasks and the result is as expected. If asyncio.sleep is problem, you can use other executor: import asyncio import concurrent.futures def fetch_data... | 2 | 3 |
76,945,193 | 2023-8-21 | https://stackoverflow.com/questions/76945193/populate-relationship-in-sqlalchemy-with-query-join | Consider the following models class A(Base): __tablename__ = "as" id = mapped_column(Integer, primary_key=True) b_id = mapped_column(ForeignKey("bs.id")) b: Mapped[B] = relationship() class B(Base): __tablename__ = "bs" id = mapped_column(Integer, primary_key=True) c_id = mapped_column(ForeignKey("cs.id")) c: Mapped[C]... | How's this: from sqlalchemy.orm import contains_eager query = ( select(A) .join(A.b) .join(B.c) .where(and_(B.x == 0, C.y == 0)) .options(contains_eager(A.b), contains_eager(A.b, B.c)) ) Original answer: select(A) .join(A.b) .join(B.c) .where(and_(B.x == 0, C.y == 0)) .options(joinedload(A.b).joinedload(B.c)) | 2 | 3 |
76,946,010 | 2023-8-21 | https://stackoverflow.com/questions/76946010/getting-list-of-unique-special-characters | I want to obtain a list of all the unique characters in a text. A particularity of the text is that it includes composed characters like s̈, b̃. So when I split the text, the special characters are separated. For example, this character s̈ is separated into two characters s and ¨. This is an example of the text I want ... | Handling composed characters in Python can be a bit tricky due to the nature of how they are encoded. Try the grapheme library, which specifically deals with grapheme clusters (textual units that are displayed as a single character) Install the grapheme library using pip: pip install grapheme or I prefer this way (to ... | 2 | 4 |
76,916,457 | 2023-8-16 | https://stackoverflow.com/questions/76916457/how-can-i-implement-real-time-sentiment-analysis-on-live-audio-streams-using-pyt | I'm currently working on a project where I need to perform real-time sentiment analysis on live audio streams using Python. The goal is to analyze the sentiment expressed in the spoken words and provide insights in real-time. I've done some research and found resources on text-based sentiment analysis, but I'm unsure a... | The solution I found here by following these steps: Adding middleware to make text from video Running the sentiment analysis for each complete sentence (Using Whisper as @doneforaiur suggested) So, the latency here depends on the length of the words of the sentence. It's a trade-off for getting the analysis for the f... | 4 | 0 |
76,943,502 | 2023-8-21 | https://stackoverflow.com/questions/76943502/reading-a-komoot-xml-file-gpx-with-pandas | I want to read a xml file generated by komoot into a DataFrame. Here is the structure of the xml file: <?xml version='1.0' encoding='UTF-8'?> <gpx version="1.1" creator="https://www.komoot.de" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.... | Following the ValueError guidelines, you need to pass a namespace to read_xml : df = ( pd.read_xml( "testfile.gpx", xpath=".//doc:trkseg/doc:trkpt", namespaces={"doc": "http://www.topografix.com/GPX/1/1"} ) ) Output : print(df) lat lon ele time 0 60.126749 4.250254 455.735013 2023-08-20T17:42:34.674Z 1 60.126580 4.250... | 3 | 3 |
76,932,969 | 2023-8-18 | https://stackoverflow.com/questions/76932969/customizing-p-value-thresholds-for-star-text-format-in-statannotations | The statannotations package provides visualization annotation on the level of statistical significance for pairs of data in plots (in seaborn boxplot or strip plot, for example). These annotation can be in "star" text format, where one or more stars appears on top of the bar between pairs of data: . Is there any way to... | In their repository, specifically inside file [Annotator.py][1]:,we have self._pvalue_format = PValueFormat(). That implies we can change the same. The PValueFormat() class, which can be found here, has the following configurable parameters: CONFIGURABLE_PARAMETERS = [ 'correction_format', 'fontsize', 'pvalue_format_st... | 3 | 3 |
76,941,993 | 2023-8-21 | https://stackoverflow.com/questions/76941993/why-is-list-pop0-not-an-o1-operation-in-python | l = [1,2,3,4] popping the last element would be an O(1) operation since: It returns the last element Changes a few fixed attributes like len of the list Why can't we do the same with pop(0)? Return the first element Change the pointer of the first element (index 0) to that of the second element (index 1) and change ... | Lists could have been implemented to do what you suggest, but it would add complexity and overhead, for an operation better handled by collections.deque. All lists everywhere would need extra metadata to track how much empty space is at the front (important for handling the resize policy, and calling free on the right ... | 4 | 5 |
76,941,870 | 2023-8-21 | https://stackoverflow.com/questions/76941870/valueerror-one-input-key-expected-got-text-one-text-two-in-langchain-wit | I'm trying to run a chain in LangChain with memory and multiple inputs. The closest error I could find was was posted here, but in that one, they are passing only one input. Here is the setup: from langchain.llms import OpenAI from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langc... | While drafting this question, I came across the answer. When defining the memory variable, pass an input_key="human_input" and make sure each prompt has a human_input defined. memory=ConversationBufferMemory( memory_key="chat_history", input_key="human_input" ) Then, in each prompt, make sure there is a human_input in... | 5 | 13 |
76,941,553 | 2023-8-20 | https://stackoverflow.com/questions/76941553/pep-622-can-match-statement-be-used-as-an-expression | PEP 622 introduced match statement as an alternative to if-elif-else. However, one thing I can't find in the proposal or in any of the material online is whether the match statement can be used as an expression and not just as a statement. A couple of examples to make it clear: Example 1: def make_point_2d(pt): match p... | Not in Python. In Rust and Haskell, matches are expressions composed of expressions: let spouse = match name { // expr => expr, "John" => "Jane", // expr => {stmt; stmt; expr}, "David" => {let s = "Alice"; println!("Matched David"); s}, _ => panic!("Unknown name"), }; do spouse <- case name of "John" -> return "Jane" ... | 12 | 6 |
76,936,532 | 2023-8-19 | https://stackoverflow.com/questions/76936532/how-to-manage-legend-tracegroupgap-for-different-row-heights-in-subplots-in-plot | i found this example code for subplot with legend at each subplot. i changed it by adding row_heights and now the legend do not fit to the subplots. import pandas as pd import plotly.express as px df = px.data.gapminder().query("continent=='Americas'") from plotly.subplots import make_subplots import plotly.graph_objec... | As of Plotly v5.15, you can add multiple legends, and position them relative to the height of the plot. In your example, you can add the argument legend='legend', legend='legend2', or legend='legend3' to each go.Scatter to match them with the legendgroup, then add the arguments legend = {"y": 1.0}, legend2 = {"y": 0.42... | 2 | 3 |
76,936,567 | 2023-8-19 | https://stackoverflow.com/questions/76936567/why-are-these-hashes-of-the-same-values-different-between-different-pandas-dataf | When hashing the same email address in two DataFrames, I am returned different hashes. These two dataframes, df1 and df2, each contain a column of email addresses which need to be hashed, so the hashes can be compared when they are inner joined, like this: import pandas as pd ### Boring part to import the data ### # de... | According to the documentation, the default mode of operation is including index in hash computation. So when two same emails have different indices, the hash is different. You can try: df1["hash 1"] = pd.util.hash_pandas_object(df1["email 1"].astype(str), index=False) df2["hash 2"] = pd.util.hash_pandas_object(df2["em... | 2 | 3 |
76,933,933 | 2023-8-19 | https://stackoverflow.com/questions/76933933/langchain-specific-default-response | using LangChain and OpenAI, how can I have the model return a specific default response? for instance, let's say I have these statement/responses Statement: Hi, I need to update my email address. Answer: Thank you for updating us. Please text it here. Statement: Hi, I have a few questions regarding my case. Can you cal... | You can handle this with precise set of examples and role of AI assistant. I am setting verbose = 1 in LLMChain so that you can see the observation/execution.. from langchain.prompts import PromptTemplate from langchain.prompts import FewShotPromptTemplate from langchain.chat_models import ChatOpenAI from langchain.ch... | 4 | 2 |
76,932,528 | 2023-8-18 | https://stackoverflow.com/questions/76932528/how-can-i-sort-a-list-of-args-in-sympy | I have a an expression, i.e. 6*x**3 + 2*x**(1/2) and want to select the item with the lowest exponent, in this case 2*x**(1/2). Is there a simple way to do that? Working with args gives an unsorted list of items and working with Poly is not possible here. | Try using as_ordered_terms and as_coeff_exponent with min: >>> from sympy import symbols >>> x = symbols('x') >>> expr = 6*x**3 + 2*x**(1/2) >>> terms = expr.as_ordered_terms() >>> lowest_term = min(terms, key=lambda term: term.as_coeff_exponent(x)[1]) >>> lowest_term 2*x**0.5 | 2 | 3 |
76,917,629 | 2023-8-16 | https://stackoverflow.com/questions/76917629/copy-file-from-ephemeral-docker-container-to-host | I want to copy a file generated by a docker container, and store inside it to my local host. What is a good way of doing that? The docker container is ephemeral (i.e. it runs for a very short time and then stops.) I am working with the below mentioned scripts: Python (script.py) which generates and saves a file titled ... | Since the container is ephemeral, you may want to run the container and keep it running. And then copy the file. Try the below steps: 1. Keep the container running and run the python command. docker run -it --name temp test:v1 bash -c 'python script.py' Here temp is the name of a temporary container. 2. Copy file from... | 4 | 2 |
76,931,578 | 2023-8-18 | https://stackoverflow.com/questions/76931578/how-can-i-log-into-file-and-on-console-at-the-same-time-with-tee-command | I'm executing a python file with powershell and I would like to get the log in a file and on console also, so tried to use the tee command. cd folder .\program.py | tee log.txt But error was thrown back Cannot run a document in the middle of a pipeline Python file just contains 1 line of code print "test" How can I ... | You have to call python to execute the script. Try executing in the folder where program.py and log.txt is: python program.py | tee log.txt The explanation is that ./program.py without python command tries to run or open the file, but you are not executing it. Then, you try to to pass the ouput to log.txt with the pip... | 2 | 3 |
76,930,775 | 2023-8-18 | https://stackoverflow.com/questions/76930775/how-to-concat-two-rows-by-index-in-a-dataframe-except-for-nan-values | I have a dataset that looks like (with more columns and rows): id type value 0 104 0 7999 1 105 1 196193579 2 108 0 245744 3 NaN 1 NaN Some rows have NaN values, and I already have the indexes for these rows. Now I would like to concat these rows with their previous row, except for NaN values. If I say indexes=[3], t... | If you have an external list of indices to merge with the rows above you can use: indexes=[3] out = (df .astype({'type': str}) .groupby((~df.index.to_series().isin(indexes)).cumsum()) .agg({'id': 'first', 'type': ''.join, 'value': 'first'}) ) If you have many columns build the aggregation dictionary programmatically: ... | 2 | 2 |
76,924,873 | 2023-8-17 | https://stackoverflow.com/questions/76924873/can-i-add-custom-data-to-a-pyproject-toml-file | I am using the toml package to read my pyproject.toml file. I want to add custom data which in this case I will read in my docs/conf.py file. When I try and add a custom section I get errors and warnings from Even Better TOML extension in Vs Code stating that my custom data is no allowed. Example TOML section in pyproj... | Use a [tool.*] table. Quoting PEP 518: The [tool] table is where any tool related to your Python project, not just build tools, can have users specify configuration data as long as they use a sub-table within [tool], e.g. the flit tool would store its configuration in [tool.flit]. Any tools that interpret pyproject.t... | 7 | 9 |
76,928,604 | 2023-8-18 | https://stackoverflow.com/questions/76928604/how-to-make-this-clock-app-always-on-top | I have this clock app written in python. It runs successfully on Windows. Here is the source code. # Source: https://www.geeksforgeeks.org/python-create-a-digital-clock-using-tkinter/ # importing whole module from tkinter import * from tkinter.ttk import * # importing strftime function to # retrieve system's time from ... | By adding the line root.attributes('-topmost', True), you set the window to be always on top of other windows. Update your code as follow: # importing whole module from tkinter import * from tkinter.ttk import * # importing strftime function to # retrieve system's time from time import strftime # creating tkinter windo... | 2 | 2 |
76,927,292 | 2023-8-18 | https://stackoverflow.com/questions/76927292/different-numpy-overflow-behavior-on-mac-vs-linux | I'm encountering different overflow behavior on Mac vs Linux with the same version of numpy. MWE: import numpy as np arr = np.arange(0, 2 * 4e9, 1e9, dtype=float) print(arr.astype(np.uint32)) print(np.__version__) Mac (Python 3.9.13): array([ 0, 1000000000, 2000000000, 3000000000, 4000000000, 705032704, 1705032704, 27... | I believe that this is due to the underlying C implementation of numpy, which probably triggers undefined behaviour, which is handled differently by the compiler used for the linux and mac distributions of numpy. Looking at cast float to unsigned int in C with gcc which deals with a similar topic, we can also see link ... | 3 | 3 |
76,926,839 | 2023-8-18 | https://stackoverflow.com/questions/76926839/polars-casting-a-column-to-decimal | I am trying to read a flat file, assign column names to the dataframe and cast few columns as per my requirements. However while casting a column to Decimal gives me error in Polars. I implemented the same successfully in Spark, but need help if anyone can guide me how to do the same in Polars. sample data data = b""" ... | I believe the scale and precision parameters are invalid. scale specifies the number of digits to the right of the decimal point, while precision specifies the total number of digits in the number. Setting precision = 0 is invalid. If you want 6 decimals, then rewrite precision as: pl.col('EMP_ID').cast(pl.Decimal(scal... | 3 | 0 |
76,924,742 | 2023-8-17 | https://stackoverflow.com/questions/76924742/how-to-sort-tuples-with-floats-using-isclose-comparisons-rather-than-absolute | I want to sort a list of pairs primarily by a float, and secondarily by an integer. The problem is with comparing floats for equality--in many cases we get an arbitrary comparison instead of resorting to the secondary order. Example my_list = [ (0, 1.2), (2, 0.07076863960397783), (1, 0.07076863960397785), (4, 0.02) ] ... | Is this a good solution? No. OP's approach is flawed for sorting purposes. since the two floats are so close that they should really be considered equal Consider if all values are nearly in the vicinity of of the same floating point value. Some pairs are "equal", other not. OP's goal fails as the compare does not f... | 3 | 2 |
76,926,251 | 2023-8-18 | https://stackoverflow.com/questions/76926251/can-a-pytest-test-change-the-value-of-a-session-fixture-and-affect-subsequent-te | Let's say that a pytest session fixture returns a dictionary and this dictionary is then manipulated within a test. Would this affect subsequent tests which use the same fixture? | Yes. And that is trivial to verify. Exactly one of these tests will fail: import pytest @pytest.fixture(scope="session") def d(): return {} def test_one(d): assert not d d["k"] = "v" def test_two(d): assert not d d["k"] = "v" If the fixture scope is changed to "function" (the default scope) then both tests will pass, ... | 3 | 3 |
76,925,094 | 2023-8-17 | https://stackoverflow.com/questions/76925094/selenium-common-exceptions-sessionnotcreatedexception-message-session-not-crea | I am getting the following error: selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 114 Current browser version is 116.0.5845.97 with binary path C:\Program Files\Google\Chrome\Application\chrome.exe Can anyone help me? I've ... | For Chrome 116+ you'll need selenium 4.11.2 at a minimum for the Selenium Manager to download chromedriver 116+ from https://googlechromelabs.github.io/chrome-for-testing/ Then you'll be able to run basic Selenium scripts like this: from selenium import webdriver from selenium.webdriver.chrome.service import Service se... | 2 | 5 |
76,924,449 | 2023-8-17 | https://stackoverflow.com/questions/76924449/how-can-inheritance-change-the-class-signature | I'm finding that inheriting from a base class can change the derived class signature according to inspect.signature, and I would like to understand how that happens. Specifically, the base class in question is tensorflow.keras.layers.Layer: import sys import inspect import tensorflow as tf class Class1(tf.keras.layers.... | This is a bug behavior that is unique to earlier versions of Python, including 3.8 and early patch releases of Python 3.9/3.10 In 3.8 and 3.9.4: Class1 signature: (*args, **kwargs) Class2 signature: (my_arg: int) In newer versions of Python, like 3.9.17 and latest versions of 3.10 and 3.11, the result is how you would... | 3 | 1 |
76,918,044 | 2023-8-17 | https://stackoverflow.com/questions/76918044/cannot-import-mediapipe-typeerror-numpy-dtypemeta-object-is-not-subscripta | The install is successful. I receive this error when trying to import. TypeError: 'numpy._DTypeMeta' object is not subscriptable I have tried higher and lower versions of numpy (1.22.0,1.23.0,1.24.0,1.25.0,1.25.2). I installed mediapipe via pypi as well as a downloaded whl ( mediapipe-0.10.3-cp311-cp311-manylinux_2_1... | Updating numpy to 1.23 works. I was not restarting the kernel after installing versions of numpy. With notebook-scoped libraries, use dbutils.library.restartPython(). If you are using cluster-scoped libraries, then be sure to restart your cluster. There's an issue about this that's documented on the OpenCV repo here: h... | 4 | 5 |
76,923,353 | 2023-8-17 | https://stackoverflow.com/questions/76923353/how-to-add-prefix-suffix-on-a-repeatable-dictionary-key-in-python | Could you please suggest is there any way to keep all the repeatable (duplicate) keys by adding prefix or suffix. In the below example, the address key is duplicated 3 times. It may vary (1 to 3 times). I want to get the output as in the expected output with adding a suffix to make the key unique. Currently the update ... | You can use something like this: list_ = ['name:John','age:25','Address:Chicago','Address:Phoenix','Address:Washington','email:John@email.com'] dic = {} for i in list_: j = i.split(':') key_ = j[0] count = 0 # counts the number of duplicates while key_ in dic: count += 1 key_ = j[0] + str(count) dic[key_] = j[1] Outpu... | 5 | 1 |
76,917,614 | 2023-8-16 | https://stackoverflow.com/questions/76917614/match-element-then-remove-both-elements | My list consists on several items: ["book","rule","eraser","clipboard","pencil",etc] Let say I have an element ["book"] and I want to match with another element ["rule"] with the same len (4). then I want to remove both elements from the list. ["eraser","clipboard","pencil",etc] I tried using a for loop and zip(lists... | Much simpler, think of it as turning on or off a flag. If the flag is on, you turn it off by deleting. If it's off, you turn it on by adding the word. Flags are based on same length: lst = ["book", "rule", "eraser", "clipboard", "pencil", "book"] output = {} for item in lst: length = len(item) popped = output.pop(lengt... | 2 | 5 |
76,913,084 | 2023-8-16 | https://stackoverflow.com/questions/76913084/calling-another-member-decorator-from-another-member-decorator-in-python-3 | I am trying to re-use a member function decorator for other member function decorator but I am getting the following error: 'function' object has no attribute '_MyClass__check_for_valid_token' Basically I have a working decorator that checks if a user is logged in (@LOGIN_REQUIRED) and I would like to call this first ... | I think this is possible, with two caveats; first, the decorator will have to move outside the class, and second, some adaptation will be required in regards to the name mangling. Let's tackle the first - first. Moving some functions Decorating a decorator directly may seem intuitive, but it probably won't result with ... | 3 | 3 |
76,913,677 | 2023-8-16 | https://stackoverflow.com/questions/76913677/python-rounding-error-when-sampling-variable-y-as-a-function-of-x-with-histogram | I'm trying to sample a variable (SST) as a function of another variable (TCWV) using the function histogram, with weights set to the sample variable like this: # average sst over bins num, _ = np.histogram(tcwv, bins=bins) sstsum, _ = np.histogram(tcwv, bins=bins,weights=sst) out=np.zeros_like(sstsum) out[:]=np.nan sst... | I can't think why this is happening, unless it is a rounding error perhaps? It is in fact a rounding error. Specifically, when you're calculating the sum of sst within each bin here: sstsum, _ = np.histogram(tcwv, bins=bins,weights=sst) The results come out wrong by 0.1% versus two alternate methods I tried for calc... | 3 | 4 |
76,912,588 | 2023-8-16 | https://stackoverflow.com/questions/76912588/type-hints-warnings-for-python-in-vs-code | I enjoy using type hinting (annotation) and have used it for some time to help write clean code. I appreciate that they are just hints and as such do not affect the code. But today I saw a video where the linter picked up the hint with a warning (a squiggly yellow underline), which looks really helpful. My VS Code does... | If you are using Pylance, you can add a new line to your settings.json (you need to restart VS Code after updating the file): "python.analysis.typeCheckingMode": "basic" The default value is off, the other possible values are basic and strict. The following screenshot shows warnings for different situations: wrong var... | 8 | 14 |
76,913,406 | 2023-8-16 | https://stackoverflow.com/questions/76913406/how-allow-fastapi-to-handle-multiple-requests-at-the-same-time | For some reason FastAPI doesn't respond to any requests while a request is handled. I would expect FastAPI to be able to handle multiple requests at the same time. I would like to allow multiple calls at the same time as multiple users might be accessing the REST API. Minimal Example: Asynchronous Processes After start... | You need to set the number of workers as shown in the uvicorn settings --workers <int> | 5 | 3 |
76,910,226 | 2023-8-16 | https://stackoverflow.com/questions/76910226/why-isnt-my-class-attribute-preserved-when-using-multiprocessing | I have the following class in a FastAPI application: import asyncio import logging from multiprocessing import Lock, Process from .production_status import Job as ProductionStatusJob class JobScheduler: loop = None logger = logging.getLogger("job_scheduler") process_lock = Lock() JOBS = [ProductionStatusJob] @classmeth... | multiprocessing in Python is funny. It's more powerful than multithreading but also comes with some caveats. The first of those is that you're actually running a different Python interpreter entirely. That means that global variables and the like are going to get a new copy for each process you run. Depending on your o... | 5 | 3 |
76,884,896 | 2023-8-11 | https://stackoverflow.com/questions/76884896/add-row-count-per-group-in-polars | Is there a way to rewrite this: import numpy import polars df = (polars .DataFrame(dict( j=numpy.random.randint(10, 99, 20), )) .with_row_index() .select( g=polars.col('index') // 3, j='j' ) .with_columns(rn=1) .with_columns( rn=polars.col('rn').shift().fill_null(0).cum_sum().over('g') ) ) print(df) g (u32) j (i64) rn ... | It can be done by generating an .int_range() using the length of each group. df.with_columns(rn = pl.int_range(pl.len()).over("g")) shape: (20, 3) ┌─────┬─────┬─────┐ │ g ┆ j ┆ rn │ │ --- ┆ --- ┆ --- │ │ u32 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╡ │ 0 ┆ 14 ┆ 0 │ # group_len = 3, range = [0, 1, 2] │ 0 ┆ 81 ┆ 1 │ │ 0 ┆ 72 ┆ 2... | 6 | 6 |
76,866,139 | 2023-8-9 | https://stackoverflow.com/questions/76866139/rdkit-image-moltoimage-scales-bond-widths-and-element-labels-inconsistently-for | I've noticed that when I create an image from a molecule in RDKit, the size argument leads to inconsistent scaling of the bond width and element labels. The bigger the size, the thinner the lines and the smaller the element labels. I've run a test by generating an image for the same molecule using MolToImage at progres... | OK found , I hope , two solutions ??? First one, using Draw.rdMolDraw2D.MolDraw2DCairo: from glob import glob from rdkit import Chem from rdkit.Chem import Draw from PIL import Image from io import BytesIO def make_frames_from_smi(smi): mol = Chem.MolFromSmiles(smi) for i in range(10): s = (i+3)*100 mol = Chem.MolFromS... | 4 | 1 |
76,883,571 | 2023-8-11 | https://stackoverflow.com/questions/76883571/polars-expression-when-then-otherwise-is-slow | I noticed a thing in python polars. I’m not sure but seems that pl.when().then().otherwise() is slow somewhere. For instance, for dataframe: df = pl.DataFrame({ 'A': [randint(1, 10**15) for _ in range(30_000_000)], 'B': [randint(1, 10**15) for _ in range(30_000_000)], }, schema={ 'A': pl.UInt64, 'B': pl.UInt64, }) Hor... | I've got some comments from Polars developers at discord. I don't see anything out of the ordinary here. Removing otherwise just means .otherwise(pl.lit(None)) is called in the background. It will have to create that column rather than using the existing one. So it will be slower. If you can write your expression as a... | 3 | 4 |
76,888,242 | 2023-8-12 | https://stackoverflow.com/questions/76888242/how-to-set-environment-variables-in-pipelines-in-azure-ml-sdk-v2-with-jobs-creat | I am changing some of our code from Azure ML's SDK v1 to v2. However, when I invoke pipelines with components via ml_client.jobs.create_or_update, I just can't get them to use my environment variables. Here is what I am doing: preprocessing_component = load_component( source=Path(__file__).parent / "preprocessing_compo... | With the introduction of Azure ML SDK v2, the concept of components has been emphasized. These components allow you to define specific environments individually. You can set environment variables for each component as following sample code. You can define environment variables using Python code: environment_variables =... | 3 | 1 |
76,901,874 | 2023-8-14 | https://stackoverflow.com/questions/76901874/userwarning-the-figure-layout-has-changed-to-tight-self-figure-tight-layouta | Why do I keep getting this warning whenever I try to use FacetGrid from seaborn? UserWarning: The figure layout has changed to tight. self._figure.tight_layout(*args, **kwargs) I understand it's a warning and not an error and I also understand it is changing the layout to tight. My question is why does it appear in the... | As mentioned in the comments, this is a matplotlib bug. It was fixed in version 3.7.3, so you can avoid it by upgrading Matplotlib. One of the comments suggests calling plt.figure(..., layout='constrained'), instead of tight_layout(), and that matches a few comments I found in the docs, like the Constrained Layout Guid... | 10 | 5 |
76,898,131 | 2023-8-14 | https://stackoverflow.com/questions/76898131/failedpreconditionerror-runs-is-not-a-directory | I made my own GAN with custom dataset that I collected, I wanted to use Tensorboard, It gives me an error.I asked ChatGPT,Bard and BingAI but they couldn't fix the error. from torch.utils.tensorboard import SummaryWriter writer_fake = SummaryWriter() writer_real = SummaryWriter() I get this error, it creates a new fol... | II just had a similar problem and was able to solve it. In my case the problem was that there were russian letters in the path of the .ipynb file (windows username is written in russian). As soon as I moved the file to a different path with only latin letters, the problem was solved. | 3 | 2 |
76,887,424 | 2023-8-12 | https://stackoverflow.com/questions/76887424/how-solve-python-setup-py-egg-info-did-not-run-successfully-in-anaconda-insta | I recently installed Anaconda and Python (3.11.4). I created my env in Anaconda, and when I tried to install rasa (with "pip install rasa") conda showed me this error. Please help me ERROR when i installed rasa pip Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info d... | In the official Rasa documentation, it says that it is not compactible with modern Python versions. The most current and 100% compact is installing python3.8 wget https://www.python.org/ftp/python/3.8.0/Python-3.8.0.tar.xz tar -xf Python-3.8.0.tar.xz cd Python-3.8.0 ./configure --enable-optimizations make sudo make alt... | 2 | 4 |
76,899,779 | 2023-8-14 | https://stackoverflow.com/questions/76899779/minimum-package-requirements-to-run-a-jupyter-notebook-in-vscode | Recently I keep running into problems with my python notebooks in vscode where vscode doesn't see the installed ipykernel. There are several posts on this issue with suggestions to update certain packages (VSCode not picking up ipykernel, Python requires ipykernel to be installed, vscode not detecting ipykernel, verifi... | The minimum requirement according to the ticket https://github.com/microsoft/vscode-jupyter/issues/14130 is ipykernel The jupyter package is only required when asked to install. It has to do with native zmq modules not working on the platform. | 3 | 0 |
76,901,337 | 2023-8-14 | https://stackoverflow.com/questions/76901337/why-do-f-strings-require-parentheses-around-assignment-expressions | In Python (3.11) why does the use of an assignment expression (the "walrus operator") require wrapping in parentheses when used inside an f-string? For example: #!/usr/bin/env python from pathlib import Path import torch DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") ckpt_dir = Path("/home/path/t... | This behavior was explicitly specified in the original PEP for the assignment expressions (aka the walrus operator). The reason for this was to preserve backward compatibility with formatted string literals. Before assignment expressions were added, you could already write f-strings like f"{x:=y}", which meant "format ... | 16 | 24 |
76,886,257 | 2023-8-11 | https://stackoverflow.com/questions/76886257/how-to-validate-access-token-from-azuread-in-python | What is the recommended way to validate the access token in backend? Any library that handles it? Another team has implemented the frontend they send the access token in the Bearer attributed in the header. I found https://github.com/odwyersoftware/azure-ad-verify-token but it has only 17 Stars. I thought microsoft sho... | Microsoft does not have a Python library to validate access tokens. Nevertheless, I found this official sample. You can check the requires_auth() function, which is used to validate the access token. | 9 | 8 |
76,880,224 | 2023-8-11 | https://stackoverflow.com/questions/76880224/error-using-using-docarrayinmemorysearch-in-langchain-could-not-import-docarray | Here is the full code. It runs perfectly fine on https://learn.deeplearning.ai/ notebook. But when I run it on my local machine, I get an error about ImportError: Could not import docarray python package I have tried reinstalling/force installing langchain and lanchain[docarray] (both pip and pip3). I use mini conda ... | Try to install this way: pip install docarray | 5 | 3 |
76,905,132 | 2023-8-15 | https://stackoverflow.com/questions/76905132/separate-a-string-between-each-two-neighbouring-different-digits-via-re-split | For instance, I'd like to convert "91234 5g5567\t7₇89^" into ["9","1","2","3","4 5g55","67\t7₇8","9^"]. Of course this can be done in a for loop without using any regular expressions, but I want to know if this can be done via a singular regular expression. At present I find two ways to do so: >>> import re >>> def way... | If you want to solve this using re.split without capturing and any further processing in one step, an idea is to use only lookarounds and in the lookbehind disallow two same digits looking ahead. (?=[0-9])(?<=(?!00|11|22|33|44|55|66|77|88|99)[0-9]) See this demo at regex101 or the Python demo at tio.run The way it wor... | 2 | 2 |
76,906,469 | 2023-8-15 | https://stackoverflow.com/questions/76906469/langchain-zero-shot-react-agent-uses-memory-or-not | I'm experimenting with LangChain's AgentType.CHAT_ZERO_SHOT_REACT agent. By its name I'd assume this is an agent intended for chat use and I've given it memory but it doesn't seem able to access its memory. What else do I need to do so that this will access its memory? Or have I incorrectly assumed that this agent can ... | It does not. that's indicated by zero-shot which means just look at the current prompt. from here Zero-shot means the agent functions on the current action only — it has no memory. It uses the ReAct framework to decide which tool to use, based solely on the tool’s description. I think when you work with this agent ty... | 2 | 6 |
76,886,954 | 2023-8-11 | https://stackoverflow.com/questions/76886954/multiple-file-loading-and-embeddings-with-openai | I am trying to load a bunch of pdf files and query them using OpenAI APIs. from langchain.text_splitter import CharacterTextSplitter #from langchain.document_loaders import UnstructuredFileLoader from langchain.document_loaders import UnstructuredPDFLoader from langchain.vectorstores.faiss import FAISS from langchain.e... | The problem is that with each iteration of the loop, you're overwriting the previous vectorstore when you create a new one. Then, when saving to "vectorstore.pkl", you're only saving the last vectorstore. print("Loading data...") pdf_folder_path = "content/" print(os.listdir(pdf_folder_path)) # Load multiple files load... | 2 | 3 |
76,901,063 | 2023-8-14 | https://stackoverflow.com/questions/76901063/issues-with-creating-a-custom-colorbar | I am trying to create a custom colorbar with discrete intervals using this resource (https://matplotlib.org/3.1.1/tutorials/colors/colorbar_only.html), but I am running into this error which references my 'cb2' line in my code: Error: "AttributeError: 'GeoContourSet' object has no attribute 'set'" import xarray as xr... | There's a lot going on in your sample code, and without data to replicate the error it requires some guessing. So perhaps you can simplify it a little and use toy data (or publicly available otherwise)? I suspect the error comes from the fact that you pass the result from ax.contourf to mpl.colorbar.ColorBase. The latt... | 3 | 1 |
76,886,864 | 2023-8-11 | https://stackoverflow.com/questions/76886864/unable-to-install-pyinstaller-in-anaconda-environment | I have an environment in Anaconda called myEnv. I am trying to install pyinstaller to it. I tried all 3 of the options given here https://anaconda.org/conda-forge/pyinstaller for installing pyinstaller, however, none of them worked. This is what the message looks like in Anaconda Prompt: Collecting package metadata (cu... | You can directly install pyinstaller from GitHub python -m pip install git+https://github.com/pyinstaller/pyinstaller If you're using a conda env file, you can also configure the package to be installed in the same way. name: myEnv channels: dependencies: - pip: - "--editable=git+https://github.com/pyinstaller/pyinsta... | 2 | 3 |
76,903,859 | 2023-8-15 | https://stackoverflow.com/questions/76903859/a-quick-way-to-find-the-first-matching-submatrix-from-the-matrix | My matrix is simple, like: # python3 numpy >>> A array([[0., 0., 1., 1., 1.], [0., 0., 1., 1., 1.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]]) >>> P array([[0., 0., 0., 0.]]) I need to find an all-zero region(one is enough) in A with the same size as P (1x4). So the right answer include: (2, 0)... | As @Julien pointed out in the comment, in general, we can use sliding windows for this kind of task. def find_all_zero_region_by_sliding_window(a, shape): x, y = np.nonzero(np.lib.stride_tricks.sliding_window_view(a, shape).max(axis=-1).max(axis=-1) == 0) return np.stack((x, y), axis=-1) find_all_zero_region_by_sliding... | 3 | 2 |
76,907,845 | 2023-8-15 | https://stackoverflow.com/questions/76907845/python-split-function-to-extract-the-first-element-and-last-element | python code --> ",".join("one_two_three".split("_")[0:-1]) I want to take the 0th element and last element of delimited string and create a new string put of it . The code should delimited string of any length Expected output : "one,three" The above code gives me 'one,two' Can some one please help me | [0:-1] is a slice, it returns all the elements from 0 to the 2nd-to-last element. Without the third stride parameter, which is used for getting every Nth element, a slice can only return a contiguous portion of a list, not two separate items. You should select the first and last separately, then concatenate them. items... | 2 | 4 |
76,904,666 | 2023-8-15 | https://stackoverflow.com/questions/76904666/find-all-decompositions-in-two-factors-of-a-number | For a given N, I am trying to find every positive integers a and b such that N = a*b. I start decomposing into prime factors using sympy.ntheory.factorint, it gives me a dict factor -> exponent. I have this code already, but I don't want to get duplicates (a and b play the same role): import itertools from sympy.ntheor... | You're using module sympy, which already has a divisors function: from sympy import divisors print(divisors(12)) # [1, 2, 3, 4, 6, 12] def find_decompositions(n): divs = divisors(n) half = (len(divs) + 1) // 2 # +1 because perfect squares have odd number of divisors return list(zip(divs[:half], divs[::-1])) print(find_... | 4 | 2 |
76,907,660 | 2023-8-15 | https://stackoverflow.com/questions/76907660/sslerror-when-accessing-sidra-ibge-api-using-python-ssl-unsafe-legacy-rene | I've been using a Python script to access the SIDRA (IBGE) API and fetch data. It was working perfectly fine, but recently, without any changes on my part, I started encountering an SSL error. Here's the code I've been using: import requests url = 'https://servicodados.ibge.gov.br/api/v3/agregados' response = requests.... | Try: import ssl import requests class TLSAdapter(requests.adapters.HTTPAdapter): def init_poolmanager(self, *args, **kwargs): ctx = ssl.create_default_context() ctx.set_ciphers("DEFAULT@SECLEVEL=1") ctx.options |= 0x4 # <-- the key part here, OP_LEGACY_SERVER_CONNECT kwargs["ssl_context"] = ctx return super(TLSAdapter,... | 3 | 2 |
76,880,837 | 2023-8-11 | https://stackoverflow.com/questions/76880837/how-do-i-communicate-using-gql-with-apollo-websocket-protocol | I want to connect to the websocket. When I inspect the traffic between the client and the server I see that the first message is the handshake: {"type": "connection_init", "payload": { "accept-language": "en", "ec-version": "5.1.88", "referrer": URL, } } Based on the format (the keys of the dict) I conclude that the w... | The EuropeanTour website does not use the Apollo websocket protocol for its API so you cannot use the standard WebsocketTransport class. What I found out: instead of returning a connection_ack message after the connection_init, it returns a wsIdentity message for a subscription, the client will first send a start mess... | 4 | 3 |
76,906,166 | 2023-8-15 | https://stackoverflow.com/questions/76906166/is-there-a-way-for-me-to-dry-common-imports-in-my-python-files | In C# the concept of global using can be used to DRY (do not repeat yourself) many common using statements across many files. Now we have many similar imports across many Python files. Is there a similar strategy that we can use to reduce our boilerplate code? | You could create a "prelude" module whose only purpose is to be glob imported by other modules. This idea can be found in other programming languages, like std::prelude from Rust and Prelude from Haskell. For example, create a prelude.py file with contents like from .sprockets import LeftSprocket, RightSprocket, make_s... | 7 | 13 |
76,884,972 | 2023-8-11 | https://stackoverflow.com/questions/76884972/let-a-passed-function-object-be-called-as-a-method | EDIT: I extended the example to show the more complex case that I was talking about before. Thanks for the feedback in the comments. Some more context: I am mostly interested in this on a theoretical level. I would be happy with an answer like "This is not possible because ...", giving some detailed insights about pyt... | You can bind the method to the instance manually, since it won't be living in the class __dict__: self.foo = foo.__get__(self) This is assuming you don't want to monkeypatch the entire class. If you do, assign c.foo = my_foo instead of passing to the instance initializer. You could also conceivably use inheritance: cl... | 4 | 2 |
76,892,486 | 2023-8-13 | https://stackoverflow.com/questions/76892486/does-pynacl-release-gil-and-should-it-be-used-with-multithreading | Does PyNaCl release the Global Interpreter Lock? Will it be suitable to use multithreading for encryption using PyNaCl's SecretBox? I want to encrypt relatively large amounts of data (~500 MB) using PyNaCl. For this, I divide it into chunks of around 5MB and encrypt them using ThreadPoolExecutor(). Is this ideal? I don... | PyNaCl uses the Common Foreign Function Interface (CFFI) to provide bindings to the C library Libsodium. We can see that the SecretBox function is basically a binding for the crypto_secretbox() function of the Libsodium library. As per CFFI documentation: [2] C function calls are done with the GIL released. Since mos... | 3 | 5 |
76,904,262 | 2023-8-15 | https://stackoverflow.com/questions/76904262/get-the-value-of-a-column-based-on-min-max-values-of-another-column-of-a-pandas | The pandas dataframe: data = pd.DataFrame ({ 'group': ['A', 'A', 'B', 'B', 'C', 'C'], 'date': ['2023-01-15', '2023-02-20', '2023-01-10', '2023-03-05', '2023-02-01', '2023-04-10'], 'value': [10, 15, 5, 25, 8, 12]} ) Trying to get the values of the 'value' column based on the min and max values of 'date' column for each... | Sort the dataframe by date then groupby and aggregate with nth to get the rows corresponding to min and max dates g = data.sort_values(['date']).groupby('group') g.nth(0).merge(g.nth(-1), on='group', suffixes=['_min', '_max']) date_min value_min date_max value_max group A 2023-01-15 10 2023-02-20 15 B 2023-01-10 5 2... | 2 | 3 |
76,881,483 | 2023-8-11 | https://stackoverflow.com/questions/76881483/whats-the-correct-way-to-type-hint-an-empty-list-as-a-literal-in-python | I have a function that always returns an empty list (it's a long story why), I could type hint as usual with just "list", but it would be useful to indicate that the list is always going to be the same. My first thought was to use literal like this: from typing import Literal def get_empty_list() -> Literal[[]]: return... | If you want a type that expresses "list that doesn't have elements now, but might have elements added later", then that's fundamentally not a static type. Appending elements to such a list would be valid, but would cause the list to stop being an element of that type, which should not happen with static types in a prog... | 4 | 10 |
76,902,113 | 2023-8-14 | https://stackoverflow.com/questions/76902113/why-are-there-no-arrays-of-objects-in-python | The Python module array supports arrays, which are, unlike lists, stored in a contiguous manner, giving performance characteristics which are often more desirable. But the types of elements are limited to those listed in the documentation. I can see why the types have to be ones with constant (or at least bounded from ... | because we have lists, which are exactly an array of pointers. python's array module stores data contiguously, python objects have dynamic sizes and cannot be stored contiguously, so we have lists which store the pointers. the main use of array is for passing around C-style arrays between different C functions, arrays ... | 3 | 4 |
76,901,667 | 2023-8-14 | https://stackoverflow.com/questions/76901667/why-cast-return-value-of-len-to-int-in-python | In the source code of Stable Baselines3, in common/preprocessing.py, on line 158, there is: return (int(len(observation_space.nvec)),). As far as I know, in Python, len can only return an int, and regardless if this is not true, would return an int here (might be wrong on both counts). If this is the case, the cast to ... | The call to int is not necessary. len always returns an int. If a class' __len__ implemention returns something other than an int, Python will attempt to convert it to an int. If that can't be done, a TypeError will be raised. There's no scenario where len can return something other than an int. You can try to violate ... | 2 | 3 |
76,878,713 | 2023-8-10 | https://stackoverflow.com/questions/76878713/tkinter-extension-was-not-compiled-and-gui-subsystem-has-been-detected-missing | I am trying to install (through pyenv) Python-3.11.4 under CentOS-7. It installs but without GUI. I get the following error message: Installing Python-3.11.4... Traceback (most recent call last): File "<string>", line 1, in <module> File "/.../pyenv/versions/3.11.4/lib/python3.11/tkinter/__init__.py", line 38, in <modu... | To build successfully Python-3.11.4 under CentOS-7, one needs to set the following environment variables: export CPPFLAGS="$(pkg-config --cflags openssl11) -I/usr/include" export LDFLAGS="$(pkg-config --libs openssl11) -L/usr/lib64 -ltcl8.5 -ltk8.5" where the openssl11 parts are needed for the _ssl module, and the res... | 9 | 3 |
76,898,926 | 2023-8-14 | https://stackoverflow.com/questions/76898926/polars-exceptions-shapeerror-unable-to-vstack-dtypes-for-column-a-dont-mat | Unable to concatenate the polars dataframes with data types of a column being f64 and i64. I have two pandas dataframes df1, df2 in pandas, where column 'a' in df1 is float and in df2 is int, when I perform pd.concat([df1, df2]) it works. However, when I try the same operation on polars dataframes, it is throwing the f... | You can use the vertical_relaxed strategy. pl.concat([df1, df2], how="vertical_relaxed") shape: (6, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ f64 ┆ i64 │ ╞═════╪═════╡ │ 1.0 ┆ 1 │ │ 2.0 ┆ 2 │ │ 3.0 ┆ 3 │ │ 1.0 ┆ 1 │ │ 2.0 ┆ 2 │ │ 3.0 ┆ 3 │ └─────┴─────┘ | 3 | 4 |
76,898,029 | 2023-8-14 | https://stackoverflow.com/questions/76898029/ultralytics-yolov8-probs-attribute-returning-none-for-object-detection | I'm using the Ultralytics YOLOv8 implementation to perform object detection on an image. However, when I try to retrieve the classification probabilities using the probs attribute from the results object, it returns None. Here's my code: from ultralytics import YOLO # Load a model model = YOLO('yolov8n.pt') # pretraine... | I think you should be able to get the confidences with results[0].boxes.conf. The probs property seems not to be working in Yolov8 | 3 | 2 |
76,897,416 | 2023-8-14 | https://stackoverflow.com/questions/76897416/avoiding-loops-in-dictionary-generation-from-child-parent-relationships | I am trying to create a dictionary tree from child-parent relathionships but the issue here is that the child can contain one of his predecesors generating loops that I would like to avoid. list_child_parent = [(2,1),(3,2),(4,2),(5,3),(6,4),(2,6)] def make_map(list_child_parent): has_parent = set() all_items = {} for c... | You can use a set to keep track of all the children, so that you can make the dict of descendants an empty dict if the current child has previously been a child of another parent: def make_map(list_child_parent): mapping = {} children = set() for child, parent in list_child_parent: mapping.setdefault(parent, {})[child]... | 3 | 2 |
76,896,195 | 2023-8-14 | https://stackoverflow.com/questions/76896195/python-unpack-list-of-dicts-containing-individual-np-arrays | Is there a pure numpy way that I can use to get to this expected outcome? Right now I have to use Pandas and I would like to skip it. import pandas as pd import numpy as np listOfDicts = [{'key1': np.array(10), 'key2': np.array(10), 'key3': np.array(44)}, {'key1': np.array(2), 'key2': np.array(15), 'key3': np.array(22)... | One way to turn your dataframe into a dictionary of numpy arrays, is to transpose it and use DataFrame.agg() to merge the columns: import numpy as np import pandas as pd listOfDicts = [{'key1': np.array(10), 'key2': np.array(10), 'key3': np.array(44)}, {'key1': np.array(2), 'key2': np.array(15), 'key3': np.array(22)}, ... | 2 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.