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,187,827
2023-9-27
https://stackoverflow.com/questions/77187827/xcode-project-originally-python-kivy-not-building-to-iphone
Short summary: The app created by python kivy which was converted to Xcode project using kivy-ios/toolchain runs on the simulator and in some cases can be built to my iPhone. But I don’t understand what I am doing different on the occasions where it does not run on my iPhone -Mac M1 arm64 -Ventura 13.5.2 -Xcode15 -iOS1...
Ok, this is a little hacky but it works… Change Xcode filename. Background All toolchains commands need Xcode to be the same name as targeted when toolchain is built. Or at least there are locations that toolchain expects Xcode to be based on the setup of the toolchain environment. But then after the Xcode project is b...
3
3
77,194,533
2023-9-28
https://stackoverflow.com/questions/77194533/why-is-true-or-false-and-false-true
Why is this printing 'yes'? I don't understand why. I understand that x or y returns true, but x and z should return false, or is the order it compares different? x=True y=False z=False if(x or y and z): print ("yes") else: print("no")
Because and has a higher precedence than or, so it is equivalent to: True or (False and False) Which is: True or False which is: True
2
5
77,194,151
2023-9-28
https://stackoverflow.com/questions/77194151/ignore-path-in-pylint-config-raises-regex-error
I have the pylint config: [MAIN] load-plugins=pylint_django django-settings-module=kernel.settings ignore-paths=^kernel/**$ , ^migrations/*$ But whenever i want to run i get this error for kernel regex: re.error: multiple repeat at position 10 How to make it so it ignores all subdirs and files inside kernel?
It's an re.error. Which means your regular expression syntax is incorrect. so to ignore ALL subdirs and files inside the kernel. simply assign kernel/.* regex value to ignore-paths so it will look like this. [MAIN] load-plugins=pylint_django django-settings-module=kernel.settings ignore-paths=^kernel/.* hope this ...
2
2
77,186,124
2023-9-27
https://stackoverflow.com/questions/77186124/run-a-function-every-time-a-method-in-a-class-is-called
I am trying to make a method that gets called every time a function is called, for every single function in the class. The class is a subclass of another class (in my specific case, it is a subclass of list). class Foo(another_class): def __init__(self, bar): self.bar = bar super().__init__(self.bar) def function_to_be...
You can call the super().__getattribute__ method (which in this case resolves to the object.__getattribute__ method) instead to avoid recursion: class Foo(list): def __init__(self, seq): super().__init__(seq) self.bar = 0 def function_to_be_called(self): self.bar += 1 def function(self): pass def __getattribute__(self,...
2
4
77,185,386
2023-9-27
https://stackoverflow.com/questions/77185386/python-rich-live-not-working-in-intellij-ide
I have the following example of Rich Live from the official examples of Rich. (layout.py) Code from datetime import datetime from time import sleep from rich.align import Align from rich.console import Console from rich.layout import Layout from rich.live import Live from rich.text import Text console = Console() layou...
Toggling the "Emulate terminal in output console" option in the Run configuration should fix the problem. If this option is unavailable in the run configuration, remove it from Run | Edit Configuration and create a new one by right-clicking the file in the editor, More Run/Debug | Modify Configuration. Also, the versio...
2
7
77,191,221
2023-9-27
https://stackoverflow.com/questions/77191221/undetected-chromedriver-attributeerror-chromeoptions-object-has-no-attribute
I'm getting an error when I run a Python Selenium script to open a webpage. I have tried uninstalling and reinstalling selenium, chromeautoinstaller, and undetected chromedriver. I also tried adding option.add_argument('--headless'). None of these were successful and the error remained the same. Here is my code: def d...
As of today, undetected-chromedriver is still using options.headless in their code. That's a problem due to this change in selenium 4.13.0 that was just released: * remove deprecated headless methods Here are some alternatives: Downgrade to an earlier selenium version until fixed. Use SeleniumBase's UC Mode (a modifi...
3
7
77,190,372
2023-9-27
https://stackoverflow.com/questions/77190372/cannot-access-flask-app-running-in-docker-container-in-my-browser
I'm trying to run a Flask app in a docker container and connect to it using my browser. I am not able to see the app and get an error This site can’t be reached when trying to go to http://127.0.0.1:5000. I've already followed the advice in these two questions (1) (2). This is my Dockerfile: FROM python:3.11.5-bookworm...
Make sure to run the container specifying the mapping port: docker run -p 5000:5000 <docker_image_id> The first port stands for the port on the host machine, and the second one is for which port you want to map it in the container. Make sure there aren't any background processes running. Check for any ( linux ): netsta...
3
3
77,190,347
2023-9-27
https://stackoverflow.com/questions/77190347/how-do-i-forward-fill-on-specific-rows-only-in-pandas
I have the following df: col1 col2 col3 0 a 1.0 1.0 1 b NaN NaN 2 c 5.0 3.0 3 d 5.0 NaN I want to do forward fill the rows only where col2 = NaN so the result would be like this col1 col2 col3 0 a 1.0 1.0 1 b 1.0 1.0 2 c 5.0 3.0 3 d 5.0 NaN I was able to get to here but this isn't a smart solution because it ffills...
Code df.fillna(df.ffill().where(df['col2'].isna())) output: col1 col2 col3 0 a 1.0 1.0 1 b 1.0 1.0 2 c 5.0 3.0 3 d 5.0 NaN Example import pandas as pd data = {'col1': ['a', 'b', 'c', 'd'], 'col2': [1, None, 5, 5], 'col3': [1, None, 3, None]} df = pd.DataFrame(data)
2
4
77,186,034
2023-9-27
https://stackoverflow.com/questions/77186034/how-to-replace-string-keeping-associated-info-in-python
Given an ordered list of words with associated info (or a list of tuples). I want to replace some of the strings with others but keep track of the associated info. Let's say that we have a simple case where our input data is two list: words = ["hello", "I", "am", "I", "am", "Jone", "101"] info = ["1", "3", "23", "4", "...
Using partial matching capability of the the regex library, one can keep track of which patterns might still be applicable. def apply_transformations(words_infos: list[tuple[str, Any]], transformations: dict[regex.Pattern, tuple[str, ...]]) \ -> list[tuple[str, Any]]: # Create the list which we modify to create the res...
2
1
77,184,491
2023-9-27
https://stackoverflow.com/questions/77184491/psycopg2-how-to-deal-with-special-characters-in-password
I am trying to connect to a db instance, but my password has the following special characters: backslash, plus, dot, asterisk/star and at symbol. For example, 12@34\56.78*90 (regex nightmare lol) How do I safe pass it to the connection string? My code looks like that: connection_string = f'user={user} password={pass} h...
Based on a reddit thread, I found out that passing variable by variable directly instead of a connection string did the trick: con = psycopg2.connect( dbname=dn, user=du, password=dp, host=dh, port=dbp, )
2
1
77,187,280
2023-9-27
https://stackoverflow.com/questions/77187280/is-there-any-way-to-filter-a-multi-indexed-pandas-dataframe-using-a-dict
Please consider the following DataFrame: mi = pd.MultiIndex( levels = [[1, 2, 3], ['red', 'green', 'blue'], ['a', 'b', 'c']], codes = [[1,0,1,0], [0,1,1,2], [1,0,0,1]], names = ["Key1", "Key2", "Key3"]) df = pd.DataFrame({ "values": [1, 2, 3, 4] }, index = mi) ... which looks like this: Now I know how to filter this ...
You can convert the MultiIndex to_frame, then slice the columns with dictionary keys and check if all are equal within a row to perform boolean indexing: d = {"Key1":1, "Key2":"green"} out = df[df.index.to_frame()[list(d)].eq(d).all(axis=1)] Alternatively, using np.logical_and.reduce and your original approach: out = ...
2
2
77,185,621
2023-9-27
https://stackoverflow.com/questions/77185621/setting-an-item-of-incompatible-dtype-is-deprecated-and-will-raise-in-a-future-e
I have the below code which for instance work as excepted but won't work in the Future : total.name = 'New_Row' total_df = total.to_frame().T total_df.at['New_Row', 'CURRENCY'] = '' total_df.at['New_Row', 'MANDATE'] = Portfolio total_df.at['New_Row', 'COMPOSITE'] = 'GRAND TOTAL' total_df.set_index('COMPOSITE',inplace=...
I think it is bug - BUG: incompatible dtype when creating string column with loc #55025 . In next version of pandas should be solved.
12
9
77,184,058
2023-9-27
https://stackoverflow.com/questions/77184058/save-a-pandas-dataframe-to-a-csv-file-without-adding-extra-double-quotes
I want to save a Pandas dataframe to a CSV file in such a way that no additional double quotes or any other characters are added to these formulas. Here is my attempt: import pandas as pd data = { "Column1": [1, 2, 3], "Column2": ["A", "B", "C"], "Formula": ['"=HYPERLINK(""https://www.yahoo.com"",""See Yahoo"")"', '"=H...
Remove the double quotes "" from the hyperlinks: import pandas as pd data = { "Column1": [1, 2, 3], "Column2": ["A", "B", "C"], "Formula": [ '=HYPERLINK("https://www.yahoo.com", "See Yahoo")', '=HYPERLINK("https://www.google.com", "See Google")', '=HYPERLINK("https://www.bing.com", "See Bing")', ], } df = pd.DataFrame(...
3
4
77,170,542
2023-9-25
https://stackoverflow.com/questions/77170542/how-to-make-pydantic-discriminate-a-nested-object-based-on-a-field
I have this Pydantic model: import typing import pydantic class TypeAData(pydantic.BaseModel): aStr: str class TypeBData(pydantic.BaseModel): bNumber: int class TypeCData(pydantic.BaseModel): cBoolean: bool class MyData(pydantic.BaseModel): type: typing.Literal['A', 'B', 'C'] name: str data: TypeAData | TypeBData | Typ...
Kinda late to the party, but here it goes. Consider the input I1: { "type": "A", "name": "Model A", "data": {"string": "Some string"}, } Using import typing import pydantic class TypeAData(pydantic.BaseModel): string: str class TypeBData(pydantic.BaseModel): integer: int class TypeCData(pydantic.BaseModel): boolean: b...
3
0
77,164,318
2023-9-23
https://stackoverflow.com/questions/77164318/error-with-langchain-chatprompttemplate-from-messages
As shown in LangChain Quickstart, I am trying the following Python code: from langchain.prompts.chat import ChatPromptTemplate template = "You are a helpful assistant that translates {input_language} to {output_language}." human_template = "{text}" chat_prompt = ChatPromptTemplate.from_messages([ ("system", template), ...
Your example is from the Prompt templates section of the LangChain Quickstart tutorial. I did not spot any differences, so it should work as given. I tried out the example myself, with an additional loop to output the messages created by chat_prompt.format_messages: from langchain.prompts.chat import ChatPromptTemplate...
3
10
77,158,196
2023-9-22
https://stackoverflow.com/questions/77158196/get-list-of-column-names-with-values-0-for-every-row-in-polars
I want to add a column result to a polars DataFrame that contains a list of the column names with a value greater than zero at that position. So given this: import polars as pl df = pl.DataFrame({"apple": [1, 0, 2, 0], "banana": [1, 0, 0, 1]}) cols = ["apple", "banana"] How do I get: shape: (4, 3) ┌───────┬────────┬──...
Here's one way: you can use pl.when with pl.lit in the concat_list to get either the literal column names or nulls, then do a list.drop_nulls: df.with_columns( result=pl.concat_list( pl.when(pl.col(col) > 0).then(pl.lit(col)) for col in df.columns ).list.drop_nulls() ) shape: (4, 3) ┌───────┬────────┬─────────────────...
4
4
77,160,103
2023-9-22
https://stackoverflow.com/questions/77160103/exponential-moving-average-ema-calculations-in-polars-dataframe
I have the following list of 20 values: values = [143.15,143.1,143.06,143.01,143.03,143.09,143.14,143.18,143.2,143.2,143.2,143.31,143.38,143.35,143.34,143.25,143.33,143.3,143.33,143.36] In order to find the Exponential Moving Average, across a span of 9 values, I can do the following in Python: def calculate_ema(value...
Two things here: Reading the ewm_mean docs closely, you want adjust=False (default is True). min_periods is still doing the calculations as if you didn't skip any values, it just replaces those calculated values with null up to the min_periodsth row, so to speak. Try removing min_periods and see how the tail values do...
6
7
77,141,633
2023-9-20
https://stackoverflow.com/questions/77141633/prefect-importerror-cannot-import-name-secretfield-from-pydantic
I'm currently using prefect to orchestrate some simple task in python. It's working fine until I get this error : Traceback (most recent call last): File "test.py", line 2, in <module> from prefect import flow File "/Users/.../.venv/lib/python3.8/site-packages/prefect/__init__.py", line 25, in <module> from prefect.sta...
That's because Prefect isn't compatible with pydantic>2 yet. So, they've pinned the reqs to the versions less than 2 (check PR10144 for more details). Try to install the latest version of Perfect or downgrade your pydantic's to 1.10.11 : pip install -U prefect # or pip install pydantic==1.10.11
5
14
77,173,196
2023-9-25
https://stackoverflow.com/questions/77173196/how-to-rename-a-conda-environment-using-micromamba
I now use micromamba instead of conda or mamba. I would like to rename/move an environment. Using conda, I can rename via: conda rename -n CURRENT_ENV_NAME NEW_ENV_NAME But this doesn't work with neither mamba nor micromamba: $ /opt/homebrew/Caskroom/miniforge/base/condabin/mamba rename -n flu_frequencies_test flu_fre...
Micromamba As stated in the answer to Cloning environment with micromamba, --clone is not an option in micromamba. Instead, export the environment yaml and create a new environment using the --file flag. Then remove the old environment. export the env dependencies: micromamba env export oldenv > oldenv.yaml create a n...
4
4
77,159,136
2023-9-22
https://stackoverflow.com/questions/77159136/efficiently-using-hugging-face-transformers-pipelines-on-gpu-with-large-datasets
I'm relatively new to Python and facing some performance issues while using Hugging Face Transformers for sentiment analysis on a relatively large dataset. I've created a DataFrame with 6000 rows of text data in Spanish, and I'm applying a sentiment analysis pipeline to each row of text. Here's a simplified version of ...
I think you can ignore this message. I found it being reported on different websites this year, but if I get it correctly, this Github issue on the Huggingface transformers (https://github.com/huggingface/transformers/issues/22387) shows that the warning can be safely ignored. In addition, batching or using datasets mi...
17
17
77,181,602
2023-9-26
https://stackoverflow.com/questions/77181602/number-of-loop-tokens-used-in-a-function-of-python
def my_func(): t = 10 while(t > 0): t = t - 1 for item in range(10): pass Is there some easy way in Python to know that two loop constructs are getting used in the above code? I am trying to build a coding platform where I want to restrict users to using just one loop to solve a question, so this information can be pr...
As others mentioned, you could use ast. code = """ def my_func(): t = 10 while(t > 0): t = t - 1 for item in range(10): pass """ import ast from typing import List, Union class LoopVisitor(ast.NodeVisitor): def __init__(self): self._loops: List[Union[ast.While, ast.For]] = [] @property def count(self) -> int: return l...
3
5
77,177,457
2023-9-26
https://stackoverflow.com/questions/77177457/how-to-statically-protect-against-str-enum-comparisons
More often than not, I make the following mistake: import enum class StatusValues(enum.Enum): one = "one" two = "two" def status_is_one(status: str): return status == StatusValues.one String will never be an enum class. The problem is that it should be StatusValues.one.value. Is there a strcmp(status, StatusValues.one...
Yes, this can be a gotcha: by default we cannot directly compare strings with enum members: >>> status = "two" >>> status == StatusValues.two False One has to remember to compare a string to the enum member's .value, which is also kind of verbose: >>> "two" == StatusValues.two.value True Fortunately, there is a solut...
4
5
77,165,100
2023-9-23
https://stackoverflow.com/questions/77165100/only-the-first-row-of-annotations-displayed-on-seaborn-heatmap
As it's usually advised, I have managed to reduce my problem to a minimal reproducible example: import numpy as np import seaborn as sns import matplotlib.pyplot as plt matrix = np.array([[0.1234, 1.4567, 0.7890, 0.1234], [0.9876, 0, 0.5432, 0.6789], [0.1111, 0.2222, 0, 0.3333], [0.4444, 0.5555, 0.6666, 0]]) sns.heatma...
Just ran into the issue myself, I was on Seaborn 0.12.2. Ran pip install seaborn --upgrade and now have 0.13.0 Restarted vscode and annotations appeared.
46
42
77,178,370
2023-9-26
https://stackoverflow.com/questions/77178370/how-to-retrieve-source-documents-via-langchains-get-relevant-documents-method-o
I am making a chatbot which accesses an external knowledge base docs. I want to get the relevant documents the bot accessed for its answer, but this shouldn't be the case when the user input is something like "hello", "how are you", "what's 2+2", or any answer that is not retrieved from the external knowledge base docs...
To solve this problem, I had to change the chain type to RetrievalQA and introduce agents and tools. import os from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import FAISS from langchain.chains import RetrievalQA from langchain.memory import ConversationBufferMemory from langchain.c...
3
1
77,146,194
2023-9-20
https://stackoverflow.com/questions/77146194/pyarrow-breaks-pyodbc-mysql
I have a Docker container with MySQL ODBC driver, unixODBC, and a bunch of Python stuff installed. My MySQL driver works through isql, and it works when connecting from Python with pyodbc, if I do so in a fresh Python process: sh-4.4# python Python 3.8.16 (default, May 31 2023, 12:44:21) [GCC 8.5.0 20210514 (Red Hat 8....
In the end, this turned out to be exhaustion of the 2048 bytes allocated to TLS (Thread-Local Storage) for dynamically-loaded libraries. libarrow.so associated with pyarrow is a pig when it comes to this block of memory, and loading it prior to loading the MySQL driver via pyodbc caused libmyodbc8a.so to push usage ove...
3
2
77,173,549
2023-9-25
https://stackoverflow.com/questions/77173549/replacing-a-simplestring-inside-a-libcst-function-definition-dataclasses-froze
Context While trying to use the libcst module, I am experiencing some difficulties updating a documentation of a function. MWE To reproduce the error, the following minimal working example (MWE) is included: from libcst import ( # type: ignore[import] Expr, FunctionDef, IndentedBlock, MaybeSentinel, SimpleStatementLine...
Why were you getting the "FrozenInstanceError" ? As you saw, the CST produced by libcst is a graph made of immutable nodes (each one representing a part of the Python language). If you want to change a node, you actually need to make a new copy of it. This is done using node.with_changes() method. So you could do this ...
4
5
77,181,503
2023-9-26
https://stackoverflow.com/questions/77181503/how-to-understand-the-output-of-scipys-quadratic-assignment-function
I'm trying to use scipy's quadratic_assignment function but I can't understand how the output can describe an optimal solution. Here is a minimal example where I compare a small matrix to itself: import numpy as np from scipy.optimize import quadratic_assignment # Parameters n = 5 p = np.log(n)/n # Approx. 32% # Defini...
The quadratic_assignment function (approximately) solves two types of problem: quadratic assignment and graph matching. These are mathematically very similar: the difference is that quadratic assignment involves minimising an objective function, whereas graph matching involves maximising that same function. (Reference:...
2
6
77,181,517
2023-9-26
https://stackoverflow.com/questions/77181517/python-open-cv-find-lines-in-noisy-image
I want to find the dark gray diagonal line in this the background is quite noisy and has a gradient in brightness. (The line is barely visible when opening the .png but if I read it as grayscale the line becomes more pronounced.) I tried different combinations of bluring, thresholding and canny edge detection. The bes...
You can try to first detect ridges in the image using a Hessian, and then threshold. This seems to work okay on your example image. import cv2 import numpy as np import matplotlib.pyplot as plt from skimage.feature import hessian_matrix, hessian_matrix_eigvals def detect_ridges(img: np.ndarray, sigma: int = 3) -> np.nd...
3
3
77,182,937
2023-9-26
https://stackoverflow.com/questions/77182937/typeerror-get-loc-got-an-unexpected-keyword-argument-method
In pandas 2 with the following code: for time in tfo_dates: dt=pd.to_datetime(time) indx_time.append(df.index.get_loc(dt,method='nearest')) I get this error: TypeError: get_loc() got an unexpected keyword argument 'method' This worked in version 1.5 but if we look at the version 2 documentation there is no method arg...
IIUC, no need for a loop : matches = df.index.get_indexer(pd.to_datetime(tfo_dates), method="nearest") out = df.iloc[matches] Output : print(out) B A 2023-09-01 17:05:30 0.548814 2023-09-03 13:05:30 0.461479 2023-09-04 23:05:30 0.681820 Used inputs : B A 2023-09-01 17:05:30 0.548814 2023-09-01 19:05:30 0.715189 2023...
4
2
77,154,846
2023-9-22
https://stackoverflow.com/questions/77154846/when-using-a-conda-environment-vs-code-terminal-and-the-python-extension-v202
I'm trying to use conda, python with VS Code. The shell I'm using in the integrated terminal is PowerShell. Everything works well in windows terminal, but after I relaunch vscode terminal, every conda commands doesn't work on vscode terminal (except activate and deactivate). conda command works at first activation Fi...
This is a bug: A drive with the name '.C' does not exist #22047. The fix has been made in Make sure PATH ends with a separator before prepending #22046 in the pre-release channel of the Python extension. If you switch to the pre-release channel and reload VS Code and still get this problem, the maintainers have provide...
4
4
77,182,455
2023-9-26
https://stackoverflow.com/questions/77182455/is-there-a-numpy-function-similar-to-np-isin-that-allows-for-a-tolerance-instead
I have two arrays of different sizes and want to determine where elements of one array can be found in the other array. I would like to be able to allow for a tolerance between elements. The goal would be something like this: array1 = [1, 2, 3, 4, 5, 6] array2 = [2, 8, 1.00001, 1.1] places = [mystery function](array1, ...
With custom function to find the absolute difference between 2 arrays and positions which fit the given tolerance: array1 = np.array([1, 2, 3, 4, 5, 6]) array2 = np.array([2, 8, 1.00001, 1.1]) tolerance = 0.001 def argwhere_close(a, b, tol): return np.where(np.any(np.abs(a - b[:, None]) <= tolerance, axis=0))[0] print(...
3
4
77,178,058
2023-9-26
https://stackoverflow.com/questions/77178058/how-to-set-safety-parameters-for-text-generation-model-in-google-cloud-vertex-ai
I am working on a research project where I need to summarize news articles using the Google Palm2 Text Generation Model. I have encountered an issue with certain news articles in my dataset where I'm getting empty responses along with safety attributes that block the output. Here is the code I'm using: from vertexai.la...
I'm not sure about Vertex AI but you can set the safety_settings of the PaLM model (from google generative AI) by the following: import google.generativeai as palm completion = palm.generate_text( model=model, prompt=prompt, safety_settings=[ { "category": safety_types.HarmCategory.HARM_CATEGORY_DEROGATORY, "threshold"...
3
1
77,180,558
2023-9-26
https://stackoverflow.com/questions/77180558/how-can-i-prevent-the-anti-virus-from-detecting-my-app-as-a-virus-or-malware-whe
recently I've made an automated file sorter based on file extension using Python and Tkinter GUI module, after I was done I compiled the the Python code into an executable using PyInstaller via windows terminal, then I put a "README" text file into the executable folder and compiled that folder as a setup executable us...
This is both an interesting question and a question without answer ;-) You indeed have a real problem and correctly explain what happens. Unfortunately converting a Python program to a Windows executable will almost always raises anti-malware warnings. The underlying reason, is that your executable uses a bootstrap cod...
3
2
77,179,993
2023-9-26
https://stackoverflow.com/questions/77179993/transposing-columns-to-rows-pandas
I have a situation like following: ID Old value.Carbon Old value.Dioxide New value.Carbon New Value.Dioxide 123 34.89 13.45 56.66 11.11 456 12.13 55.66 66.88 12.33 My output that i want should be:( i want the column to be transposed to rows like following, i have renamed the fields as Old Value. and New V...
Using stack and a MultiIndex to reshape: tmp = df.set_index('ID') out = (tmp.set_axis(tmp.columns.str.capitalize() .str.split('\.', expand=True), axis=1) .rename_axis(columns=(None, 'Field')) .stack() .reset_index() ) Output: ID Field Old value New value 0 123 carbon 34.89 56.66 1 123 dioxide 13.45 11.11 2 456 carbon...
2
3
77,177,877
2023-9-26
https://stackoverflow.com/questions/77177877/what-is-except-syntax-in-python-trystar-in-ast-module
I came across this documentation in the ast module for a version of the try/except block with an extra asterisk. The documentation doesn't explain what it is, and gives a completely generic example: class ast.TryStar(body, handlers, orelse, finalbody) try blocks which are followed by except* clauses. The attributes ar...
except*(aka except-star) is one of the feature/syntax introduced in Python 3.11 and it is used to handle ExceptionGroup. Quoting from the official documentation except* clause The except* clause(s) are used for handling ExceptionGroups. The exception type for matching is interpreted as in the case of except, but in th...
4
6
77,168,202
2023-9-24
https://stackoverflow.com/questions/77168202/calculating-total-tokens-for-api-request-to-chatgpt-including-functions
Hello Stack Overflow community, I've been working on integrating ChatGPT's API into my project, and I'm having some trouble calculating the total number of tokens for my API requests. Specifically, I'm passing both messages and functions in my API calls. I've managed to figure out how to calculate the token count for t...
I am going to walk you through calculating the tokens for gpt-3.5 and gpt-4. You can apply a similar method to other models you just need to find the right settings. We are going to calculate the tokens used by the messages and the functions separately then adding them together at the end to get the total. Messages Sta...
2
4
77,170,039
2023-9-25
https://stackoverflow.com/questions/77170039/how-would-i-solve-a-linear-diophantine-congruence-in-python
I was given a challenge where the solution involves solving a series of linear modular equations in 14 variables. The following is a selection of these equations: 3a + 3b + 3c + 3d + 3e + 3f + 3g + h + i + j + k + l + m + n = 15 7a + 9b + 17c + 11d + 6e + 5f + g = 3 13a + 2b + 9c + 8d + 12f + 13g = 17 5a + 2b + 16c + 1...
The word diophantine is misleading here. What you want to do is linear algebra over Z_p meaning the integers modulo a prime p. SymPy can do this if you use DomainMatrix instead of Matrix. This is how to do it in SymPy 1.12: In [1]: from sympy import * In [2]: from sympy.polys.matrices import DomainMatrix In [3]: a, b, ...
4
2
77,172,130
2023-9-25
https://stackoverflow.com/questions/77172130/how-to-find-the-distance-to-next-non-nan-value-in-numpy-array
Consider the following array: arr = np.array( [ [10, np.nan], [20, np.nan], [np.nan, 50], [15, 20], [np.nan, 30], [np.nan, np.nan], [10, np.nan], ] ) For every cell in each column in arr I need to find the distance to the next non-NaN value. That is, the expected outcome should look like this: expected = np.array( [ [...
Using pandas, you can compute a reverse cumcount, with mask and shift: out = (pd.DataFrame(arr).notna()[::-1] .apply(lambda s: s.groupby(s.cumsum()).cumcount().add(1) .where(s.cummax()).shift()[::-1]) .to_numpy() ) Output: array([[ 1., 2.], [ 2., 1.], [ 1., 1.], [ 3., 1.], [ 2., nan], [ 1., nan], [nan, nan]])
3
1
77,171,252
2023-9-25
https://stackoverflow.com/questions/77171252/pandas-select-matching-multi-index-with-different-number-of-levels
I have a data frame with 3 index levels: d a b c 1 9 4 1 2 8 2 4 3 7 5 2 4 6 4 5 5 5 6 3 6 4 5 6 7 3 7 4 8 2 6 7 9 1 8 5 and I have a multi index object with only 2 levels: MultiIndex([(1, 9), (2, 8), (3, 7), (4, 6), (9, 1)], names=['a', 'b']) How can I select the entries on the data frame that match this multi inde...
You can filter different levels by Index.difference and filter by boolean indexing with Index.isin: lvl = df1.index.names.difference(multi_idx.names) out = df1[df1.index.droplevel(lvl).isin(multi_idx)] print (out) d a b c 1 9 4 1 2 8 2 4 3 7 5 2 4 6 4 5 9 1 8 5
3
3
77,169,369
2023-9-25
https://stackoverflow.com/questions/77169369/tkinter-menu-bar-goes-invisible-when-checking-topmost-attribute
I have a larger tkinter app that I wanted to dinamically set the topmost attribute. I am able to achieve what I want, but everytime I check the state of topmost, the selected menu bar on the screen goes invisible. To reproduce this, consider the MRE below and upon running the code, click the "menu" button on the menu b...
This is not a fix for your issue, but rather a workaround. It seems like the topmost attribute is really weird... First, it is platform specific. Second, once set, it doesn't just change. If you set "-topmost", 1 for another window both will have the same attribute. From the documentation I found "-topmost gets or sets...
3
2
77,170,645
2023-9-25
https://stackoverflow.com/questions/77170645/pandas-2-1-0-warning-the-method-keyword-in-series-replace-is-deprecated-and
I have a pandas line of code that gives me a future deprecation warning as stated in the title and I can't find in the pandas documentation how to modify it in order to remove the warning. The line of code is the following: df['temp_open']=df['temp_open'].replace('',method='ffill') Any help would be greatly appreciate...
You can do this instead : df["temp_open"] = df["temp_open"].replace("", None).ffill() And if you want to keep the nulls (if any) untouched, you can use : df["temp_open"] = ( df["temp_open"].replace("", None).ffill().where(df["temp_open"].notnull()) ) Output : print(df) temp_open 0 A 1 A 2 NaN 3 B 4 C 5 C Used input ...
7
11
77,169,204
2023-9-24
https://stackoverflow.com/questions/77169204/pythonic-way-of-dropping-columns-used-in-assign-i-e-pandas-equivalent-of-kee
In dplyr package of R, there's the option .keep = "unused" when creating new columns with the function mutate() (which is their equivalent of assign). An example, for those who haven't used it: > head(iris) Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7...
I've never used R but based on the definition of unused and AFIK, to simulate the same behaviour in pandas, you will need to pop each column from a copy of the original DataFrame : "unused" retains only the columns not used in ... to create new columns. This is useful if you generate new columns, but no longer need th...
7
9
77,169,051
2023-9-24
https://stackoverflow.com/questions/77169051/how-to-loop-over-pivot-table-to-create-list-of-dictionaries-taking-the-index-and
I have this table here and i'm trying to take the value and device category from each row in each column so I can have data like below. series: [{ name: 'engaged_sessions', data: [{ name: 'Desktop', y: 7765, }, { name: 'Mobile', y: 388 },... name: 'event_count', data: [{ name: 'Desktop', y: 51325, }, { name: 'Mobile', ...
If df contains the pivoted dataframe from your question you can do: out = [] for c in df: out.append( {"name": c, "data": [{"name": k, "y": v} for k, v in df[c].to_dict().items()]} ) print(out) Prints: [ { "name": "engaged_sessions", "data": [ {"name": "Desktop", "y": 7765}, {"name": "Mobile", "y": 388}, {"name": "Sma...
3
3
77,168,615
2023-9-24
https://stackoverflow.com/questions/77168615/how-to-separate-row-entries-in-a-csv-file-into-distinct-columns-with-duplicate-l
I need to restructure a .csv file that follows this structure: a b 1 2 3 4 5 6 ... Into this new structure: a b a b a b ... 1 2 3 4 5 6 ... I don't know how to do this efficiently without iterating over each row. Is there a more efficient way of doing this in Python?
Here is one possible solution: import pandas as pd # read the .csv to a dataframe df = pd.read_csv('your_file.csv') # create a new df new_df = pd.DataFrame([df.to_numpy().ravel()], columns=df.columns.to_list() * len(df)) print(new_df) Prints: a b a b a b 0 1 2 3 4 5 6 To save the new dataframe: new_df.to_csv("out.c...
2
3
77,167,537
2023-9-24
https://stackoverflow.com/questions/77167537/extract-tuple-items-from-list-without-accessing-index
I am trying to extract the tuple items which consist of another embedded tuple without using the index. items = [(('a', 'b'), 'a'), (('a', 'b'), 'b'), (('a', 'b'), 'c'), (('a', 'b'), 'd')] # Currently accessing using index for xy,z in items: print(xy[0],xy[1],z) # Trying without index but getting error for x, y, z in i...
Yes, you just need to wrap the nested tuple to have an extra layer of unpacking: for (x, y), z in items: print(x,y,z) Note how (x, y) causes the inner tuple to be unpacked.
2
3
77,165,974
2023-9-24
https://stackoverflow.com/questions/77165974/nameerror-name-exceptiongroup-is-not-defined
I work through Python tutorial and ran against a sample in https://docs.python.org/3/tutorial/errors.html in section 8.9. Raising and Handling Multiple Unrelated Exceptions which doesn't work by me: $ python Python 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] on linux Type "help", "copyright", "credits" or "licen...
According to the official docs, ExceptionGroup was only added in Python 3.11. Make sure you check your Python version
3
6
77,162,216
2023-9-23
https://stackoverflow.com/questions/77162216/can-you-resize-overflowdirect-window-in-tkinter-without-flicker-when-adjusting-p
I have an overridredirect window that I need to resize on mouse drag. The example is functioning, but when I drag any of: sw, w, nw, n and ne handles it causes flicker (most noticeable when dragging fast). This is likely due to adjusting position and size simultaneously. I tried update_idletasks to see if that would sm...
Now that you have made it clear what you actually want to do, may I suggest this method. The short explanation is: When "snip" button is pressed, the entire screen is taken over by a semi-transparent tk.Toplevel with a tk.Canvas child. You drag out a square on the canvas (ie, no window resizing), and release to lock it...
3
1
77,162,718
2023-9-23
https://stackoverflow.com/questions/77162718/pandas-dataframe-style-format-not-printing-specified-precision
I am trying to format the dataframe using https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.format.html. But, I am not getting the desired result: >>> df = pd.DataFrame([[np.nan, 1.534231, 'A'], [2.32453251, np.nan, 3.0]]) >>> df.style.format(na_rep='MISS', precision=3) <pandas.io.formats.styl...
Styler.format is used to apply as specific formatting to a pandas DataFrame. So the data present in the dataframe doesn't change but when you display it in a specific environment, the styling will be applied to the data. So when you write the following code, >>> df = pd.DataFrame([[np.nan, 1.534231, 'A'], [2.32453251, ...
3
2
77,158,832
2023-9-22
https://stackoverflow.com/questions/77158832/dash-suppress-error-a-nonexistent-object-was-used-in-an-input-of-a-dash-callb
I have a complex Dash app where different layouts are displayed depending on some inputs. These output layouts (created in callbacks) contain some inputs. Because those inputs are not defined yet in the layout, I have the error "A nonexistent object was used in an Input of a Dash callback." Is there a way nowadays to g...
Building off of @Dmitry's answer (👍+1), I modified and extended a few aspects of the code: The functionality of the pattern-matching is printed live to the app for the sake of easier demonstration Using dcc.Store to persist the dynamically generated dcc.Input components' user-entered text values Contextualizing the c...
2
2
77,154,241
2023-9-22
https://stackoverflow.com/questions/77154241/chunk-a-json-array-of-objects-until-each-array-item-is-of-byte-length-a-static
I have a list of dict that follow a consistent structure where each dict has a list of integers. However, I need to make sure each dict has a bytesize (when converted to a JSON string) less than a specified threshold. If the dict exceeds that bytesize threshold, I need to chunk that dict's integer list. Attempt: impor...
As discussed in the comments, a simple approach to this task is to recursively split the input list until the output dict meets the size requirement. This will give more evenly sized lists in the output, but may result in more dicts than are absolutely necessary (and would be produced by one of the length accumulation ...
2
1
77,152,114
2023-9-21
https://stackoverflow.com/questions/77152114/for-a-function-decorator-how-can-a-single-optional-kwarg-item-be-type-constrain
I have a decorator that looks for an optional kwargs item, foo, with all other *args and **kwargs passed through to the decorated function. I want the typing hints to specify which type that specific item must be, if it is present. For the following snippet, how can I create the typing partial constraint on FnParams s...
It appears this isn't available yet: https://peps.python.org/pep-0612/#concatenating-keyword-parameters However, there is room for this in the future.
3
0
77,153,141
2023-9-21
https://stackoverflow.com/questions/77153141/why-variable-assignment-behaves-differently-in-python
I am new to Python and I am quite confused about the following code: Example 1: n = 1 m = n n = 2 print(n) # 2 print(m) # 1 Example 2: names = ["a", "b", "c"] visitor = names names.pop() print(names) # ['a', 'b'] print(visitor) # ['a', 'b'] Example 1 shows that n is 1 and m is 1. However, example 2 shows that names i...
Integers are not mutable. So the only way to change a variable that is assigned to an integer is through assignment. When you assign m=n, m is assigned to the same address that n currently is assigned. Both m and n refer to the address of the integer 1. m will continue to point to 1 even if n is assigned to a different...
2
1
77,154,762
2023-9-22
https://stackoverflow.com/questions/77154762/fixing-overlapping-time-tick-labels-in-matplotlib-for-a-pandas-dataframe-plot
I have a DataFrame named airtep_df with columns 'AIRTEP' (Int64), 'AIRTEP_qc' (Int64), and 'UTCTime'. I'm trying to create a plot from this data, but the time tick labels on the x-axis are overlapping, making the plot unreadable. I attempted to rotate the tick labels using plt.xticks(rotation=45), but the plot disappea...
Datetime-formatted rotated x-axis tick labels You could try something like: import numpy as np import pandas as pd ​ import matplotlib.dates as mdates import matplotlib.pyplot as plt ​ ​ ### Sample data generation date_rng = pd.date_range(start="2016-01-01", end="2016-01-02", freq="H") ​ temps = np.random.randint(17, 4...
3
1
77,154,695
2023-9-22
https://stackoverflow.com/questions/77154695/are-comparisons-really-allowed-to-return-numbers-instead-of-booleans-and-why
I've found a surprising sentence in the Python documentation under Truth Value Testing: Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. Relational operators seem to have no excepting statements, so IIUC they could return ...
So, it is probably important to understand that bool objects are int objects, since issubclass(bool, int) is true. So isinstance(True, int) and isinstance(False, int) is true. Prior to version 2.3 which was released back in 2002, Python lacked a bool type. PEP 285 was the accepted proposal. Prior to this, these operati...
3
5
77,153,903
2023-9-21
https://stackoverflow.com/questions/77153903/finding-the-largest-power-of-10-that-divides-evenly-into-a-list-of-numbers
I'm trying to scale down a set of numbers to feed into a DP subset-sum algorithm. (It blows up if the numbers are too large.) Specifically, I need to find the largest power of 10 I can divide into the numbers without losing precision. I have a working routine but since it will run often in a loop, I'm hoping there's a ...
This can be done all at once with the math library if your list is all integers. import math def largest_common_power_of_10(numbers): # get the greatest power of 10 that divides all numbers in list gcd_nums = math.gcd(*numbers) gcd = [x for x in range(1, len(str(gcd_nums))) if gcd_nums % math.pow(10, x) == 0] if len(gc...
4
3
77,153,334
2023-9-21
https://stackoverflow.com/questions/77153334/how-to-revert-n-choose-2-combinations
I have a set of pairs that can contain the result of mutliple "N choose 2" combinations: inputs = { ('id1', 'id2'), ('id1', 'id3'), ('id1', 'id4'), ('id2', 'id3'), ('id2', 'id4'), ('id3', 'id4'), ('id3', 'id5'), ('id4', 'id5'), ('id5', 'id6'), } And I would like to reverse those combinations, like this: recombinations...
Using the networkx library, this is quite simple, since it has a function that does exactly what you're asking for: finding all maximal cliques in a graph. Here: import networkx as nx G = nx.Graph() pairs_of_connected_nodes = [ ('id1', 'id2'), ('id1', 'id3'), ('id1', 'id4'), ('id2', 'id3'), ('id2', 'id4'), ('id3', 'id4...
3
5
77,144,665
2023-9-20
https://stackoverflow.com/questions/77144665/how-can-i-run-python-as-root-or-sudo-while-still-using-my-local-pip
pip is recommended to be run under local user, not root. This means if you do sudo python ..., you will not have access to your Python libs installed via pip. How can I run Python (or a pip installed bin/ command) under root / sudo (when needed) while having access to my pip libraries?
So the issue you're likely having is that you have pip installed the packages you want to a user specific site-packages directory, which then isn't being included in the sys.path module search list generated by sites.py when Python starts up for the root user. There are a couple of workaround for this to add the additi...
5
2
77,153,150
2023-9-21
https://stackoverflow.com/questions/77153150/how-to-select-first-n-key-ordered-values-of-column-within-a-grouping-variable-in
I have a dataset: import pandas as pd data = [ ('A', 'X'), ('A', 'X'), ('A', 'Y'), ('A', 'Z'), ('B', 1), ('B', 1), ('B', 2), ('B', 2), ('B', 3), ('B', 3), ('C', 'L-7'), ('C', 'L-9'), ('C', 'L-9'), ('T', 2020), ('T', 2020), ('T', 2025) ] df = pd.DataFrame(data, columns=['ID', 'SEQ']) print(df) I want to create a key gr...
Your approach of using groupby and then head(2) is on the right track for getting the first 2 rows of each different SEQ within each ID group. However, the additional requirement is to get only the first 2 unique SEQ groups within each ID. To achieve this, you can: Create a new column that has the rank of unique SEQ wi...
2
1
77,152,143
2023-9-21
https://stackoverflow.com/questions/77152143/is-it-possible-for-a-snowpark-stored-procedure-to-produce-a-dataframe-as-its-out
I want to create an snowflake stored procedure using snowpark. Inside of the procedure I will create some dataframe and performs some operations like filter, sort, join etc. At the end I just want to return that "dataframe", does snowpark supports that? Can someone provide an example of how to achieve this?
It is supported - Writing Snowpark Code in Python Worksheets Python Worksheet Run + Deploy Code is wrapped as Stored Procedure and ready to be used Call in SQL CALL ProcName(); Call in Python
2
4
77,152,147
2023-9-21
https://stackoverflow.com/questions/77152147/how-to-find-the-position-of-same-rows-from-one-2d-array-to-another-2d-array
import numpy as np # Create two sample dataframes df1 = np.array([[0.000000,0.000000,0.000000], [0.090000,0.000000,0.000000], [0.190000,0.000000,0.000000], [0.280000,0.000000,0.000000], [0.380000,0.000000,0.000000], [0.470000,0.000000,0.000000], [0.570000,0.000000,0.000000], [0.660000,0.000000,0.000000], [0.760000,0.00...
If you only want to match the non-zeros, you can remove them: np.where(np.isclose(np.where(df1!=0, df1, np.nan)[:, None], df2))[0] Output: array([5, 6, 7, 8, 9]) If you want a full match, including zeros (row per row), you can use: out = np.where(np.isclose(df1[:, None], df2).all(2))[0] Output: array([5, 6, 7, 8, 9]...
4
0
77,151,521
2023-9-21
https://stackoverflow.com/questions/77151521/most-pythonic-method-of-conditionally-extracting-data-from-multiple-lists-of-dic
I'm trying to use two lists of dictionaries to build an object, the dictionaries are built from a TAP connection to two different databases. Because of the data sources I cannot guarantee that any of the dictionaries will contain the information I need, so I've chosen a primary dictionary and if the information is not ...
remove code duplication def find_in_eparesults(name, value, epa_key): if math.isnan(value): for r in eparesults: if r['pl_name'] == name: value = r[epa_key] break return value for result in eeuresults: name=result['target_name'] axes=find_in_eparesults(name, result['semi_major_axis'], 'pl_orbper') period=find_in_epares...
2
1
77,150,937
2023-9-21
https://stackoverflow.com/questions/77150937/incorrect-fourier-coefficients-signs-resulting-from-scipy-fft-fft
I analysed a triangle wave using the Fourier series by hand, and then using the scipy.fft package. What I'm getting are the same absolute values of the coefficients, but with opposite signs. By hand: I took the interval [-1,1], calculated the integral to get a0 = 1, then a1, a3 and a5 using the result of integration: ...
Note that when you call fft(), you don’t pass in the time axis (space). So how is the function supposed to know you sampled from -1 to 1? It doesn’t! It assumes you sampled at 0, 1, 2, 3, … N-1. This means that the FFT function sees the signal as shifted compared to your manual calculation, and a shift means the phase ...
2
4
77,148,259
2023-9-21
https://stackoverflow.com/questions/77148259/omitting-middle-characters-if-string-is-too-long-when-display-a-pandas-dataframe
When display a DataFrame in Jupyter Notebook, if the string value is too long, the last characters will be omitted: df = pd.DataFrame({'A':['ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ']}) display(df) output: A 0 ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ...
From the documentation, you can build a custom formatter. def formatter(x): if isinstance(x, str): if len(x) > pd.options.display.max_colwidth: display_width = pd.options.display.max_colwidth split = int((display_width-3) / 2) if display_width % 2: # if odd number return x[:split] + "..." + x[-split:] else: return x[:(...
2
5
77,146,349
2023-9-20
https://stackoverflow.com/questions/77146349/obtaining-grouped-max-or-min-in-pandas-without-skipping-nans
Consider a sample dateframe df = pd.DataFrame({'group' : [1, 2, 2], 'x' : [1, 2, 3], 'y' : [2, 3, np.nan]}) If I want to get the max value of variable 'y' without skipping NANs, I would use the function: df.y.max(skipna = False) The returned results is nan as expected However, if I want to calculate the grouped max v...
You can try to apply pd.Series.max: x = df.groupby("group")["y"].apply(pd.Series.max, skipna=False) print(x) Prints: group 1 2.0 2 NaN Name: y, dtype: float64
3
3
77,142,806
2023-9-20
https://stackoverflow.com/questions/77142806/how-to-read-cursorresult-to-pandas-in-sqlalchemy
How does one convert a CursorResult-object into a Pandas Dataframe? The following code results in a CursorResult-object: from sqlalchemy.orm import Session from sqlalchemy import create_engine engine = create_engine(f"mssql+pyodbc://{db_server}/{db_name}?trusted_connection=yes&driver={db_driver}") q1 = "SELECT * FROM m...
IIUC, just use pd.DataFrame constructor. dtypes are correctly set. # sqlalchemy==2.0.16 # pandas==2.0.2 from sqlalchemy.sql import text with Session(engine) as session: results = session.execute(text(q1)) df = pd.DataFrame(results) # session.commit() # commit is irrelevant if you don't write data Test on my database: ...
2
4
77,142,566
2023-9-20
https://stackoverflow.com/questions/77142566/python-multiprocessing-imap-iterates-over-whole-itarable
In my code I am trying to achieve the following: I get each result as soon as any of the processes finish Next iteration must only be called whenever it is necessary (if it is converted into a list, I will have RAM issues) To my knowledge imap from multiprocessing module should be perfect for this task, but this code...
imap doesn't guarantee consuming the input iterator at the same pace the workers finish their tasks. You can use a threading.BoundedSemaphore (even if you're only using a single thread) to have the input generator wait until the for loop has consumed an item: import multiprocessing import threading import time def txt_...
2
3
77,142,174
2023-9-20
https://stackoverflow.com/questions/77142174/use-both-put-and-post-methods-from-same-api-using-fastapi
I'm about to create an API using FastApi wherein I have to search for 'user_name' in db. If 'user_name' exists then I have to update the user_details. If the 'user_name' doesn't exist, then I have to create entry for the user. In this case, I think both PUT and POST methods need to be applied for the same API endpoint....
Yes, it is possible. You just need to use different decorator for the same path. from fastapi import FastAPI app = FastAPI() @app.put("/") async def put_root(): return {"message": "Hello World from put"} @app.post("/") async def post_root(): return {"message": "Hello World from post"} the code is oversimplify but it s...
3
6
77,115,274
2023-9-15
https://stackoverflow.com/questions/77115274/copy-a-dataframe-to-new-variable-with-method-chaining
Is it possible to copy a dataframe in the middle of a method chain to a new variable? Something like: import pandas as pd df = (pd.DataFrame([[2, 4, 6], [8, 10, 12], [14, 16, 18], ]) .assign(something_else=100) .div(2) .copy_to_new_variable(df_imag) # Imaginated method to copy df to df_imag. .div(10) ) print(df_imag) ...
Actually, this is what I was looking for. Check the link, the idea is from Matt Harrison (who wrote multiple books about pandas) for debugging of method chains. This way is also recommended in this great article 4 Pandas Anti-Patterns to Avoid and How to Fix Them by Aidan Cooper. import pandas as pd def to_df(df, name)...
2
0
77,110,560
2023-9-15
https://stackoverflow.com/questions/77110560/python-polars-calculate-time-difference-from-first-element-in-each-repeating
I have a polars.DataFrame like: df = pl.DataFrame({ "timestamp": ['2009-04-18 11:30:00', '2009-04-18 11:40:00', '2009-04-18 11:50:00', '2009-04-18 12:00:00', '2009-04-18 12:10:00', '2009-04-18 12:20:00', '2009-04-18 12:30:00'], "group": ["group_1", "group_1", "group_1", "group_2", "group_2", "group_1", "group_1"]}) df ...
.rle_id() ("Run-length encoding") can be used to identify the groups. This is especially useful when you want to define groups by runs of identical values df.with_columns(group_id = pl.col("group").rle_id()) shape: (7, 3) ┌─────────────────────────┬─────────┬──────────┐ │ timestamp ┆ group ┆ group_id │ │ --- ┆ --- ┆...
4
4
77,126,001
2023-9-18
https://stackoverflow.com/questions/77126001/calculation-of-expected-value-in-shap-explanations-of-xgboost-classifier
How do we make sense of SHAP explainer.expected_value? Why is it not the same with y_train.mean() after sigmoid transformation? Below is a summary of the code for quick reference. Full code available in this notebook: https://github.com/MenaWANG/ML_toy_examples/blob/main/explain%20models/shap_XGB_classification.ipynb m...
SHAP is guaranteed to be additive in raw space (logits). To understand why additivity in raw scores doesn't extend to additivity in class predictions you may think for a while why exp(x+y) != exp(x) + exp(y) Re: Just keen to understand how was explainer.expected_value calculated for XGBoost classifier. Do you happen to...
2
3
77,134,254
2023-9-19
https://stackoverflow.com/questions/77134254/specify-dependencies-in-pyproject-toml-with-install-url-or-with-index-url
I like to have my package installable with pip install ... and to use the pyproject.toml standard. I can specify dependencies to install from git, with: dependencies = [ 'numpy>=1.21', 'psychopy @ git+https://github.com/psychopy/psychopy', ] But how can I specify a dependency to install from a different indexer, equiv...
I recommend reading the article "install_requires vs. requirements files" in the "Python packaging user guide". This article is partly outdated but the principle of abstract dependencies vs. concrete dependencies is unchanged. Concrete dependencies do not belong in packaging metadata, i.e. concrete dependencies can not...
11
6
77,114,363
2023-9-15
https://stackoverflow.com/questions/77114363/snowpark-udf-with-row-input-type
I would like to define a Snowpark UDF with input type snowflake.snowpark.Row. The reason for this is that I would like to mimic the pandas.apply approach where I can define my business logic in some class, and then apply the logic to each row of the Snowpark dataframe. Each column can be easily mapped to a class attrib...
Solution tested in Snowflake Python worksheet, based on the suggestion by @felipe-hoffa above import snowflake.snowpark as snowpark from snowflake.snowpark.functions import col, udf from snowflake.snowpark.types import IntegerType, VariantType from dataclasses import dataclass import json def main(session: snowpark.Ses...
3
0
77,100,890
2023-9-13
https://stackoverflow.com/questions/77100890/pydantic-v2-custom-type-validators-with-info
I'm trying to update my code to pydantic v2 and having trouble finding a good way to replicate the custom types I had in version 1. I'll use my custom date type as an example. The original implementation and usage looked something like this: from datetime import date from pydantic import BaseModel class CustomDate(date...
As of version 2.4 you can get the field_name and data together. See the updated docs here. Now the first version of my custom data type looks like: class CustomDate: POTENTIAL_FORMATS = [] @classmethod def validate(cls, field_value, info): if type(field_value) is date: return field_value return to_date(info.field_name,...
8
2
77,104,125
2023-9-14
https://stackoverflow.com/questions/77104125/no-module-named-keras-wrappers
I have this code on google colab which allows me to optimise an LSTM model using gridsearchCV, but recently an error message has appeared: ModuleNotFoundError: No module named 'keras.wrappers'. is there another module other than 'keras.wrappers' that allows the code to be restarted? Code: from keras.layers import Dense...
This works for me pip install keras==2.12.0 Another Approach you can try pip uninstall tensorflow pip install tensorflow==2.12.0
9
12
77,124,879
2023-9-18
https://stackoverflow.com/questions/77124879/pip-extras-require-must-be-a-dictionary-whose-values-are-strings-or-lists-of
I tried running pip install gym==0.21.0 but got the cryptic error: Collecting gym==0.21.0 Using cached gym-0.21.0.tar.gz (1.5 MB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [1 lines of output] error in gym setup com...
Based on the comments in the issue section at https://github.com/openai, these are the changes that need to be made - pip install setuptools==65.5.0 pip==21 # gym 0.21 installation is broken with more recent versions pip install wheel==0.38.0 I was facing the same issue and after doing the above, it was resolved. The...
7
27
77,134,535
2023-9-19
https://stackoverflow.com/questions/77134535/migrate-postgresdsn-build-from-pydentic-v1-to-pydantic-v2
I have simple Config class from FastAPI tutorial. But it seems like it uses old pydantic version. I run my code with pydantic v2 version and get a several errors. I fix almost all of them, but the last one I cannot fix yet. This is part of code which does not work: from pydantic import AnyHttpUrl, HttpUrl, PostgresDsn,...
You can use unicode_string() to stringify your URI as follow: from sqlalchemy.ext.asyncio import create_async_engine create_async_engine(settings.POSTGRES_URI.unicode_string()) Check documentation page here for additional explanation.
13
8
77,126,601
2023-9-18
https://stackoverflow.com/questions/77126601/currency-conversion-with-forex-python-converter
I wrote a script that converts currencies based on the current exchange rate. It seems to work fine, except when trying to convert EUR to USD, as it never gets the exchange rate correctly. For example, it tells me 1000 EUR are worth 64 USD, whereas the reality would be around 950...The actual exchange rate is 1.06 but ...
There is no issue with your code or the forex_python.converter library. This is a bug with the :latest version of theforexapi which is used by the forex_python.converter, see link to raised issue: latest/?base=EUR&symbols=USD returns base=ILS #18 The returned "base" is "ILS" instead of "EUR" as expected. This bug only...
4
4
77,132,356
2023-9-19
https://stackoverflow.com/questions/77132356/rq-job-terminated-unexpectedly
I have defined the rq task on module task.py as: import django_rq import logging import requests log = logging.getLogger(__name__) def req_call(): url = 'https://jsonplaceholder.typicode.com/posts' response = requests.get(url) return response @django_rq.job('default') def test_request_call_on_rq_job(): response = req_c...
I think I found the cause of the request being not executed gracefully on rq. I just guess it was due to flow at https://github.com/python/cpython/blob/main/Lib/urllib/request.py#L2619 not being able to pick the proxy setting in the RQ context. So I just skipped the way to reach there by setting NO_PROXY env to the URL...
2
2
77,137,301
2023-9-19
https://stackoverflow.com/questions/77137301/curve-fit-seems-to-overestimate-error-of-estimated-parameters
I have some data from the lab, which I'm fitting to the function f(s, params) = amp * (s/sp) / (1 + s/sp + 1.041) + bg (couldn't figure out how to type set this) I set absolute_sigma=True on curve_fit to get the absolute uncertainties of the parameters (sp, amp, bg), but the calculated error from np.sqrt(np.diag(pcov))...
Why When using absolute_sigma=True your are advised to feed the sigma switch as well, if not they are replaced by 1. making Chi Square loss function behaves as RSS and pcov becomes somehow meaningless if your uncertainty are not unitary. Fix Provides uncertainty or an estimate of it as well to get a meaningful pcov mat...
2
2
77,130,229
2023-9-18
https://stackoverflow.com/questions/77130229/psycopg3-inserting-dict-into-jsonb-field
I have a table with a JSONB field and would like to insert into it using a named dict like so: sql = "INSERT INTO tbl (id, json_fld) VALUES (%(id)s, %(json_fld)s)" conn.execute(sql, {'id':1, 'json_fld': {'a':1,'b':false, 'c': 'yes'}}); I tried the answers in this question but those all apply to psycopg2 and NOT psycop...
Python code to convert dict to jsonb using psycopg JSON adapters described here JSON adaptation section JSON adaptation. import psycopg from psycopg.types.json import Jsonb con = psycopg.connect("dbname=test user=postgres") cur = con.cursor() cur.execute("insert into json_test values(%s, %s)", [1, Jsonb({'a':1,'b': Fal...
4
6
77,137,537
2023-9-19
https://stackoverflow.com/questions/77137537/when-does-using-floating-point-operations-to-calculate-ceiling-integer-log2-fail
I'm curious what the first input is which differentiates these two functions: from math import * def ilog2_ceil_alt(i: int) -> int: # DO NOT USE THIS FUNCTION IT'S WRONG return ceil(log2(i)) def ilog2_ceil(i: int) -> int: # Correct if i <= 0: raise ValueError("math domain error") return (i-1).bit_length() ... Obviousl...
A first issue with ceil(log2(i)) is that the integer i will first be converted to the floating-point type toward 0 (this is the wrong direction!), here with a 53-bit precision. For instance, if i is 253 + 1, it will be converted to 253, and you'll get 53 instead of 54. But another problem may occur even with smaller va...
2
5
77,111,621
2023-9-15
https://stackoverflow.com/questions/77111621/create-google-calendar-invites-using-service-account-securely
I created a service account using my Enterprise Google Workspace account and I need to automate calendar invites creation using Python. I have added the service account email into the calendar's shared people and when I try to get the calendar using service.calendarList().list().execute() it works fine. However, if I t...
AFAIK you have 2 options available to you. Google has removed several other options. Serviceaccount with delegation. You state that this is not an option for you, but technically it is. Give serviceaccount access to Calendar API for specific user, using OAuth 2.0. Option 1 This is actually the best (and the "proper"...
3
3
77,117,250
2023-9-16
https://stackoverflow.com/questions/77117250/how-to-blur-the-edges-of-a-surface-in-pygame
I'd like to blur the edges of a surface in a "gradient fashion", in Pygame. Here is an example of the desired effect where we have : No blur on first image Medium blur on second square High blur on third square image of blur effects desired Pygame has 2 functions to blur surfaces : pygame.transform.box_blur and pygam...
You need to create a Surface with a transparent background (pygame.SRCALPHA) that is slightly larger than your image. Then you can blit your image onto the surface and blur it: rect = pygame.Rect(0, 0, image.get_width()+100, image.get_height()+100) blur_image = pygame.Surface(rect.size, pygame.SRCALPHA) blur_image.blit...
2
2
77,095,776
2023-9-13
https://stackoverflow.com/questions/77095776/fastapi-pydantic-data-validation-for-put-method-if-body-only-contains-the-update
I am learning FastAPI and understanding that its data validation using pydantic is one of its features. But after reading its put method example from its tutorial I have a question if I only want to let the put body contain the updated data(as the URL already has its id), how do I do that? Use the sample code from the ...
Solution 1 You could have a Pydantic model, which would act as the parent one and include every attribute that is shared between both POST and PUT request bodies. You could then create a submodel, containing only the id attribute and inheriting from the parent model (not the BaseModel), which would be used for POST req...
3
1
77,138,178
2023-9-19
https://stackoverflow.com/questions/77138178/fill-in-zero-values-only-in-the-center-of-a-numpy-array
I'm working with a rasterio raster that I've 'read' into python, so it is now a numpy array. The outer edge of the np array are all zeros, and the interior are all ones, except, in the midst of the ones are occasional zeros, see the example array below. I want to leave all the zeros on the outside of the array alone (i...
Perhaps you can use scipy.ndimage.binary_fill_holes: import numpy as np from scipy.ndimage import binary_fill_holes arr = np.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]) filled_arr = binary_fill_holes(...
3
4
77,136,876
2023-9-19
https://stackoverflow.com/questions/77136876/ending-numpy-calculation-early
Given two large arrays, A = np.random.randint(10,size=(10000,2)) B = np.random.randint(10,size=(10000,2)) I would like to determine if any of the vectors have a cross product of zero. We could do C = np.cross(A[:,None,:],B[None,:,:]) and then check if C contains a 0 or not. not C.all() However, this process requires...
Does numpy have such an "early termination" operation that will cut numpy operations early if they reach a condition? Put it simply, no, Numpy does not. In practice, this is a bit more complex than that. In fact, the allfunc and anyfunc function you propose similar to np.all and np.any. Such function does some kind ...
4
2
77,137,092
2023-9-19
https://stackoverflow.com/questions/77137092/how-to-show-all-x-tick-labels-with-seaborn-objects
How do I make it so that it shows all x ticks from 0 to 9? bin diff 1 4 -0.032748 3 9 0.106409 13 7 0.057214 17 3 0.157840 19 0 -0.086567 ... ... ... 1941 0 0.014386 1945 4 0.049601 1947 9 0.059406 1957 1 0.045282 1959 6 -0.033853 ( so.Plot(x='bin', y='diff', data=diff_df) .theme({**axes_style("whitegrid"), "grid.li...
As per Parameterizing scales and Customizing legends and ticks, use seaborn.objects.Continuous.tick inside seaborn.objects.Plot.scale .scale(x=so.Continuous().tick(every=1)) import pandas as pd import numpy as np import seaborn.objects as so # sample data np.random.seed(365) rows = 1100 data = {'diff': np.random.r...
2
5
77,134,662
2023-9-19
https://stackoverflow.com/questions/77134662/how-to-draw-3d-synthesis-of-fourier-series
I saw this by using Tikz: https://tikz.net/fourier_series/ I want to create this 3D synthesis of Fourier Series: with Python 3D plot, there is matplotlib that is able to do that. My MWE / What I have achieved is: # https://pythonnumericalmethods.berkeley.edu/notebooks/chapter24.02-Discrete-Fourier-Transform.html # Gen...
Based on Python Programming and Numerical Methods - A Guide for Engineers and Scientists: Discrete Fourier Transform (DFT) # Generate 3 sine waves with frequencies 1 Hz, 4 Hz, and 7 Hz, # amplitudes 3, 1 and 0.5, and phase all zeros. # Add this 3 sine waves together with a sampling rate 100 Hz import matplotlib.pyplot ...
3
1
77,094,430
2023-9-13
https://stackoverflow.com/questions/77094430/how-to-check-if-a-python-package-is-installed-using-poetry
I'm using Poetry to manage my Python project, and I would like to check if a package is installed. This means the package is actually fetched from the remote repository and is located in the .venv/ folder. I went through the official documentation but didn't find any command that can do that. Any ideas? Thanks. Update:...
Assuming you have activated the virtual environment in the .venv folder (using, for example source .venv/bin/activate), you can use pip list to list all of the installed packages in that virtual environment. There is a poetry show command to list all available packages as well that you might want to look into: https://...
7
7
77,134,706
2023-9-19
https://stackoverflow.com/questions/77134706/event-loop-is-closed-is-playwright-already-stopped
Context After initialisation of a playwright browser object in function initialise_playwright_browsercontroller, I try to use its Page object in another function. However, that yields get error: "Event loop is closed! Is Playwright already stopped?" If I use the Page object in the same function (and with statement) i...
If you want to use context manager, then you should use yield instead of return from playwright.sync_api import sync_playwright from playwright.sync_api._generated import Locator # type: ignore[import] from playwright.sync_api._generated import Browser, Page from typeguard import typechecked import contextlib @typechec...
2
5
77,135,853
2023-9-19
https://stackoverflow.com/questions/77135853/extract-date-from-weirdly-formatted-datetime-polars
import polars as pl df = pl.DataFrame(['2023-08-01T06:13:24.448409', '2023-08-01T07:29:34.491027']) print(df.with_columns(pl.col('column_0').str.strptime(pl.Date,'%Y-%m-%d'))) So I have the following mass of code, and for some ungodly reason I cant for the death of me extract the date from those given strings. In the ...
To parse a datetime upfront you'll need to provide the full format (date & time) initially then retrieve the date part afterwards. Try the following format: '%Y-%m-%dT%H:%M:%S.%f'
2
3
77,128,583
2023-9-18
https://stackoverflow.com/questions/77128583/how-to-find-all-tuple-permutations-in-a-list
I want to create all possible permutations of tuples in a list using python. For example, take the list my_list = [(None, 1), (None,1), (None,1)] I want the generate a list of (2!)^n lists where 2! is the number of combinations of the tuple arrangements and n represents the number of tuples in the list. So the above l...
itertools.product is useful here (if I understand your question correctly). itertools.product is the equivalent to your nested loops and takes as argument multiple iterables. So [permutations(x) for x in my_list] (or map(permutations, my_list)) generically creates a list of iterables from my_list and the asterisk * tur...
2
4
77,098,113
2023-9-13
https://stackoverflow.com/questions/77098113/solving-incompatible-dtype-warning-for-pandas-dataframe-when-setting-new-column
Setting the value of a new dataframe column: df.loc[df["Measure] == metric.label, "source_data_url"] = metric.source_data_url now (as of Pandas version 2.1.0) gives a warning, FutureWarning: Setting an item of incompatible dtype is deprecated and will raise in a future error of pandas. Value ' metric_3' has dtype inco...
I had the same problem. My intuition of this is that when you are setting value for the first time to the column source_data_url, the column does not yet exists, so pandas creates a column source_data_url and assigns value NaN to all of its elements. This makes Pandas think that the column's dtype is float64. Then it r...
11
10
77,131,685
2023-9-19
https://stackoverflow.com/questions/77131685/the-fastest-way-of-pyspark-and-geodataframe-to-check-if-a-point-is-contained-in
A CSV file read through pyspark contains tens of thousands of GPS information (lat, lon) and a feather file read through geodataframe contains millions of polygon information. In the previous question (The best algorithm to get index with specific range at pandas dataframe), I succeeded in creating a geodataframe. Howe...
You can use Apache Sedona for your geospatial analysis. https://sedona.apache.org/latest-snapshot/tutorial/sql/ I adapted this notebook to give you an example of how to do this. All you have to do is readin your Points CSV into point_rdd and polygon data in feather file format into Geopandas dataframe and then convert ...
2
4
77,131,670
2023-9-19
https://stackoverflow.com/questions/77131670/python-pandas-replace-the-values-of-a-dataframe-by-searching-in-another-datafram
I have two dataframes. df1 contains CITIES and the total number of VISITS. df2 contains the VISITS records. Periodically df1 is updated with the data from df2 with the new VISITS. df1 example (before updating) ID NAME VISITS --- 01 CITY1 01 02 CITY2 01 ... 06 CITYZ 12 df2 example CITY NUMBER --- ... CITY1 01 CITY2 01 ...
You can remove duplicates from df2 and keep only the last updated values (if your cities are already sorted by 'NUMBER', you can remove sort_values): df1['VISITS'] = df1['NAME'].map(df2.sort_values('NUMBER', ascending=True) .drop_duplicates('CITY', keep='last') .set_index('CITY')['NUMBER']) print(df1) # Output ID NAME ...
2
3
77,118,099
2023-9-16
https://stackoverflow.com/questions/77118099/typeerror-updater-init-got-an-unexpected-keyword-argument-token
I have this code which is suppose to look for /help command in telegram. So once you type /help in the telegram channel it will give you options. The code is as follows. from telegram import Update from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackContext from telegram.ext import filters # Defin...
I used telegram.Bot class and then I passed it to the Updater like this: from telegram import Update, Bot from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackContext from telegram.ext import filters #defining your bot token here TOKEN = "YOUR_BOT_TOKEN" def start(update: Update, context: CallbackC...
4
2
77,130,750
2023-9-18
https://stackoverflow.com/questions/77130750/gitlab-ci-job-token-does-not-authenticate-with-private-python-repository
I tried to use the CI_JOB_TOKEN in a GitLab CI pipeline to install a Python Package from a different project's package registry. According to the documentation i should just have to add my project to the allowlist of the corresponding project and run the pipeline. However i always get the following 401 error when runni...
According to the GitLab PyPI registry authentication documentation, you should use the username gitlab-ci-token when authenticating with a job token. This might be confusing because some other examples use __token__ even though GitLab does not accept this username unless you are using an access token literally named __...
6
10
77,109,279
2023-9-15
https://stackoverflow.com/questions/77109279/how-do-i-locate-minima-in-an-array
I have a code to plot a heatmap for a set of data, represented as (x, y, f(x, y)), and I want to find the local minimum points. import numpy as np import math import matplotlib.pyplot as plt import matplotlib as mpl from scipy.interpolate import griddata data = np.genfromtxt('data.dat', skip_header=1, delimiter=' ') x,...
To find local minima, we usually used some gradient based optimizations like gradient descent. However, it is not easy to find all local minima unless doing a lot of "restart" (generally people are happy with one local minimum). One straightforward method to your problem is using grid search: if the current point is le...
5
3
77,130,056
2023-9-18
https://stackoverflow.com/questions/77130056/converting-a-list-to-pandas-dataframe-where-list-contains-dictionary
I wanted to convert a list to pandas dataframe, where the first element of the list is a dictionary. I have below code import pandas as pd import numpy as np pd.DataFrame([{'aa' : 10}, np.nan]) However this fails with below message Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local...
Enclose your list into np.array: pd.DataFrame(np.array([{'aa' : 10}, np.nan])) 0 0 {'aa': 10} 1 NaN Though you list is quite small, here's timings comparison just for the case: In [777]: %timeit pd.DataFrame(np.array([{'aa' : 10}, np.nan])) 26.6 µs ± 220 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) ...
2
1
77,101,344
2023-9-14
https://stackoverflow.com/questions/77101344/selenium-headless-not-functioning-with-buttons-properly
I have some code to open a search url for a site, click the first result, and click a button. This all works fine until I try to use headless Chrome. Code (working -> not using headless Chrome): from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_co...
You have to use the new headless mode to get the same results as normal mode: chrome_options.add_argument("--headless=new") You'll see that if you search for --headless=new in the Selenium documentation on https://www.selenium.dev/documentation/webdriver/browsers/chrome/ If you're still having issues, try SeleniumBas...
3
1