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 |
|---|---|---|---|---|---|---|
74,562,541 | 2022-11-24 | https://stackoverflow.com/questions/74562541/append-new-column-to-a-snowpark-dataframe-with-simple-string | I've started using python Snowpark and no doubt missing obvious answers based on being unfamiliar to the syntax and documentation. I would like to do a very simple operation: append a new column to an existing Snowpark DataFrame and assign with a simple string. Any pointers to the documentation to what I presume is rea... | You can do this by using the function with_column in combination with the lit function. The with_column function needs a Column expression and for a literal value this can be made with the lit function. see documentation here: https://docs.snowflake.com/en/developer-guide/snowpark/reference/python/api/snowflake.snowpar... | 3 | 4 |
74,607,741 | 2022-11-28 | https://stackoverflow.com/questions/74607741/how-to-create-an-array-of-na-or-null-values-in-python | This is easy to do in R and I am wondering if it is straight forward in Python and I am just missing something, but how do you create a vector of NaN values and Null values in Python? I am trying to do this using the np.full function. R Code: vec <- vector("character", 15) vec[1:15] <- NA vec Python Code unknowns = np... | you could use either None or np.nan to create an array of just missing values in Python like so: np.full(shape=5, fill_value=None) np.full(shape=5, fill_value=np.nan) back to your example, this works just fine: import numpy as np import pandas as pd unknowns = np.full(shape=5, fill_value=None) categories = np.random.c... | 3 | 5 |
74,591,552 | 2022-11-27 | https://stackoverflow.com/questions/74591552/hypothesis-create-column-with-pd-datetime-dtype-in-given-test-dataframe | I want to test whether a certain method can handle different dates in a pandas dataframe, which it takes as an argument. The following example should clarify what kind of setup I want. In the example column('Date', dtype=pd.datetime) does not work for creating a date column in the test dataframe: from hypothesis import... | Use dtype="datetime64[ns]" instead of dtype=pd.datetime. I've opened an issue to look into this in more detail and give helpful error messages when passed pd.datetime, datetime, or a unitless datetime dtype; this kind of confusion isn't the user experience we want to offer! | 3 | 5 |
74,589,665 | 2022-11-27 | https://stackoverflow.com/questions/74589665/how-to-print-rgb-colour-to-the-terminal | Can ANSI escape code SGR 38 - Set foreground color with argument 2;r;g;b be used with print function? Example of use with code 33 is of course OKBLUE = '\033[94m' I would like to use 038 instead to be able to use any RGB color. Is that posible? I tried GREEN = '\038[2;0;153;0m' ENDC = '\033[0m' print(f"{GREEN} some te... | To use an RGB color space within the terminal* the following escape sequence can be used: # Print Hello! in lime green text. print('\033[38;2;146;255;12mHello!\033[0m') # ^ # | # \ The 38 goes here, to indicate a foreground colour. # Print Hello! in white text on a fuschia background. print('\033[48;2;246;45;112mHello!... | 5 | 9 |
74,563,548 | 2022-11-24 | https://stackoverflow.com/questions/74563548/selenium-driver-hanging-on-os-alert | I'm using Selenium in Python (3.11) with a Firefox (107) driver. With the driver I navigate to a page which, after several actions, triggers an OS alert (prompting me to launch a program). When this alert pops up, the driver hangs, and only once it is closed manually does my script continue to run. I have tried driver.... | There are some prefs you can try profile = webdriver.FirefoxProfile() profile.set_preference('dom.push.enabled', False) # or profile = webdriver.FirefoxProfile() profile.set_preference('dom.webnotifications.enabled', False) profile.set_preference('dom.webnotifications.serviceworker.enabled', False) | 5 | 3 |
74,599,665 | 2022-11-28 | https://stackoverflow.com/questions/74599665/how-to-use-template-when-creating-new-python-file-on-vscode | In my python file I always start with the following lines import sys import matplotlib as mpl sys.append('C:\\MyPackages') rc_fonts = { "text.usetex": True, 'font.size': 20, 'text.latex.preamble': r"\usepackage{bm}", } mpl.rcParams.update(rc_fonts) Is there a way to indicate to VScode that each time I create a new fil... | For Doing this kind of repetitive task we can use snippets in VSCode. Step 1 : Hit > shift+ctrl+p open command palette. Step 2 : Select Snippets: Configure User Snippets Step 3 : Select Python Step 4 : paste below code in python.json file. change prefix value. like "prefix": "hedwin" so now when you type hedwin vscode ... | 5 | 6 |
74,599,713 | 2022-11-28 | https://stackoverflow.com/questions/74599713/merge-two-dictionaries-in-python | I'm trying to merge two dictionaries based on key value. However, I'm not able to achieve it. Below is the way I tried solving. dict1 = {4: [741, 114, 306, 70], 2: [77, 325, 505, 144], 3: [937, 339, 612, 100], 1: [52, 811, 1593, 350]} dict2 = {1: 'A', 2: 'B', 3: 'C', 4: 'D'} My resultant dictionary should be output = ... | Use a simple dictionary comprehension: output = {dict2[k]: v for k,v in dict1.items()} Output: {'D': [741, 114, 306, 70], 'B': [77, 325, 505, 144], 'C': [937, 339, 612, 100], 'A': [52, 811, 1593, 350]} | 15 | 14 |
74,599,116 | 2022-11-28 | https://stackoverflow.com/questions/74599116/pandas-dataframe-assign-how-to-refer-to-newly-created-columns | I'm trying to use pandas.DataFrame.assign in Pandas 1.5.2. Let's consider this code, for instance: df = pd.DataFrame({"col1":[1,2,3], "col2": [4,5,6]}) df.assign( test1="hello", test2=df.test1 + " world" ) I'm facing this error: AttributeError: 'DataFrame' object has no attribute 'test1' However, it's explicitly sta... | You can pass a callable to assign. Here use a lambda to reference the DataFrame. Parameters **kwargsdict of {str: callable or Series} The column names are keywords. If the values are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change input DataFrame (though panda... | 3 | 3 |
74,567,219 | 2022-11-24 | https://stackoverflow.com/questions/74567219/how-do-i-get-python-to-send-as-many-concurrent-http-requests-as-possible | I'm trying to send HTTPS requests as quickly as possible. I know this would have to be concurrent requests due to my goal being 150 to 500+ requests a second. I've searched everywhere, but get no Python 3.11+ answer or one that doesn't give me errors. I'm trying to avoid AIOHTTP as the rigmarole of setting it up was a ... | This works, getting around 250+ requests a second. This solution does work on Windows 10. You may have to pip install for concurrent and requests. import time import requests import concurrent.futures start = int(time.time()) # get time before the requests are sent urls = [] # input URLs/IPs array responses = [] # outp... | 7 | 4 |
74,579,273 | 2022-11-26 | https://stackoverflow.com/questions/74579273/indexerror-tuple-index-out-of-range-when-creating-pyspark-dataframe | I want to create test data in a pyspark dataframe but I always get the same "tuple index out of range" error. I do not get this error when reading a csv. Would appreciate any thoughts on why I'm getting this error. The first thing I tried was create a pandas dataframe and convert it to a pyspark dataframe: columns = ["... | After doing some reading I checked https://pyreadiness.org/3.11 and it looks like the latest version of python is not supported by pyspark. I was able to resolve this problem by downgrading to python 3.9 | 7 | 17 |
74,595,035 | 2022-11-28 | https://stackoverflow.com/questions/74595035/filling-nan-on-conditions | I have the following input data: df = pd.DataFrame({"ID" : [1, 1, 1, 2, 2, 2, 2], "length" : [0.7, 0.7, 0.7, 0.8, 0.6, 0.6, 0.7], "height" : [7, 9, np.nan, 4, 8, np.nan, 5]}) df ID length height 0 1 0.7 7 1 1 0.7 9 2 1 0.7 np.nan 3 2 0.8 4 4 2 0.6 8 5 2 0.6 np.nan 6 2 0.7 5 I want to be able to fill the NaN if a group... | You could try with sort_value then we use groupby find the last #last will find the last not NaN value df.height.fillna(df.sort_values(['length','height']).groupby(['ID'])['height'].transform('last'),inplace=True) df Out[296]: ID length height 0 1 0.7 7.0 1 1 0.7 9.0 2 1 0.7 9.0 3 2 0.8 4.0 4 2 0.6 8.0 5 2 0.6 4.0 6 2 ... | 4 | 2 |
74,585,126 | 2022-11-26 | https://stackoverflow.com/questions/74585126/no-output-in-vs-code-using-python-logging-module | I'm on Windows 10 using VS Code 1.73.1 and am retrofitting my program with the Python logging module. My program is generally functioning. The main thing I did is change all the print statements to logger.debug and I know the variable formatting needs to be changed from {} to %s. I also added the encoding flag to my fi... | After using a different logger example, I realized the problem was the Level setting in the first example I used had "INFO" and not "DEBUG" so nothing was showing up. Oops... import logging logger = logging.getLogger('simple_example') logger.setLevel(logging.DEBUG) console = logging.StreamHandler() console.setLevel(lev... | 4 | 5 |
74,546,287 | 2022-11-23 | https://stackoverflow.com/questions/74546287/overlaying-the-ground-truth-mask-on-an-image | In my project, I extracted frames from a video and in another folder I have ground truth for each frame. I want to map the ground truth image of each frame of a video (in my case, it is saliency prediction ground truth) on its related frame image. As an example I have the following frame: And the following is ground t... | I need to do similar things pretty often. In my favorite StackOverflow fashion, here is a script that you can copy and paste. I hope the code itself is self-explanatory. There are a few things that you can tune and try (e.g., color maps, overlay styles). It uses multiprocessing.Pool for faster batch-processing, resizes... | 4 | 8 |
74,592,062 | 2022-11-27 | https://stackoverflow.com/questions/74592062/why-rust-hashmap-is-slower-than-python-dict | I wrote scripts performing the same computations with dict and hashmap in Rust and in Python. Somehow the Python version is more than 10x faster. How is that happens? Rust script: ` use std::collections::HashMap; use std::time::Instant; fn main() { let now = Instant::now(); let mut h = HashMap::new(); for i in 0..10000... | Rust by default doesn't have optimizations enabled, because it's annoying for debugging. That makes it, in debug mode, slower than Python. Enabling optimizations should fix that problem. This behaviour is not specific to Rust, it's the default for most compilers (like gcc/g++ or clang for C/C++, both require the -O3 fl... | 4 | 6 |
74,586,892 | 2022-11-27 | https://stackoverflow.com/questions/74586892/no-module-named-keras-saving-hdf5-format | After pip3 installing tensorflow and the transformers library, I'm receiving the titular error when I try loading this from transformers import pipeline classifier = pipeline("text-classification",model='bhadresh-savani/distilbert-base-uncased-emotion') The error traceback looks like: RuntimeError: Failed to import tr... | If you are using the latest version of TensorFlow and Keras then you have to try this code and you have got this error as shown below RuntimeError: Failed to import transformers.models.distilbert.modeling_tf_distilbert because of the following error (look up to see its traceback): No module named 'keras.saving.hdf5_for... | 9 | 13 |
74,578,175 | 2022-11-25 | https://stackoverflow.com/questions/74578175/getting-video-links-from-youtube-channel-in-python-selenium | I am using Selenium in Python to scrape the videos from Youtube channels' websites. Below is a set of code. The line videos = driver.find_elements(By.CLASS_NAME, 'style-scope ytd-grid-video-renderer') repeatedly returns no links to the videos (a.k.a. the print(videos) after it outputs an empty list). How would you modi... | Implementation using Selenium: First of all, I wanna solve the problem meaning wanted to pull data with the help of YouTube API and I'm about to reach the goal but for some API's restrictions like API KEY's rquests restrict and some other complexities, I couldn't grab complete data that's why I go with super powerful S... | 4 | 5 |
74,585,622 | 2022-11-26 | https://stackoverflow.com/questions/74585622/pyfirmata-gives-error-module-inspect-has-no-attribute-getargspec | I'm trying to use pyFirmata, but I can't get it to work. Even the most basic of the library does not work. I guess there is something wrong with the library code. from pyfirmata import Arduino,util import time port = 'COM5' board = Arduino(port) I get this error: Traceback (most recent call last): File "c:\Users\Publi... | According to the first line of pyFirmata docs: It runs on Python 2.7, 3.6 and 3.7 You are using Python 3.11. The inspect (core library module) has changed since Python 3.7. | 9 | 4 |
74,583,630 | 2022-11-26 | https://stackoverflow.com/questions/74583630/why-is-python-saying-modules-are-imported-when-they-are-not | Python 3.6.5 Using this answer as a guide, I attempted to see whether some modules, such as math were imported. But Python tells me they are all imported when they are not. >>> import sys >>> 'math' in sys.modules True >>> 'math' not in sys.modules False >>> math.pi Traceback (most recent call last): File "<stdin>", li... | to explain this, let's define this function: def import_math(): import math import_math() the above function will import the module math, but only in its local scope, anyone that tries to reference math outside of it will get a name error, because math is not defined in the global scope. any module that is imported is... | 8 | 9 |
74,582,213 | 2022-11-26 | https://stackoverflow.com/questions/74582213/access-token-scope-insufficient-error-with-updating-sheet-using-google-sheets-ap | I've been making a program in python that is intended to have each user be able to use it to access a single google sheet and read and update data on it only in the allowed ways, so ive used google api on the google developer console and managed to get test accounts reading the information that ive manually put in, how... | You are using the sheets.values.update method. If you check the documentation. you will see that this method requires one of the following scopes of authorization Your code apears to only request 'https://www.googleapis.com/auth/spreadsheets.readonly' read only access is not going to let you write to the file. You nee... | 5 | 6 |
74,581,912 | 2022-11-26 | https://stackoverflow.com/questions/74581912/how-to-extract-multiple-strings-from-list-spaced-apart | I have the following list: lst = ['L38A', '38', 'L', 'A', '-6.7742', '-3.5671', '0.00226028', '0.4888', 'L38C', '38', 'L', 'C', '-7.7904', '-6.6306', '0.0', '0.4888', 'L38D', '38', 'L', 'D', '-6.3475', '-3.0068', '0.00398551', '0.4888', 'L38E', '38', 'L', 'E', '-6.4752', '-3.4645', '0.00250913', '0.4888'] I'm looking t... | We can handle this via a zip operation and list comprehension: lst = ['L38A', '38', 'L', 'A', '-6.7742', '-3.5671', '0.00226028', '0.4888', 'L38C', '38', 'L', 'C', '-7.7904', '-6.6306', '0.0', '0.4888', 'L38D', '38', 'L', 'D', '-6.3475', '-3.0068', '0.00398551', '0.4888', 'L38E', '38', 'L', 'E', '-6.4752', '-3.4645', '... | 3 | 2 |
74,575,385 | 2022-11-25 | https://stackoverflow.com/questions/74575385/adding-different-colors-for-markers-in-plotly | I have a graph that looks like this: I want to sort the color combinations for the dots on this, to achieve something like one color for all the versions that start with 17, different one for 18 and lastly the 20. I don't know if I can do this in plotly since it is very specific and found no information on this. Is it... | Currently you are assigning marker color based on the 'day' column in your argument marker=dict(color=data1['day'], colorscale='plasma', size=10), but it sounds like you want to assign the color based on the major version. You can extract the major version from the info_version column, and store it in a new column call... | 4 | 3 |
74,575,744 | 2022-11-25 | https://stackoverflow.com/questions/74575744/github-action-to-execute-a-python-script-that-create-a-file-then-commit-and-pus | My repo contains a main.py that generates a html map and save results in a csv. I want the action to: execute the python script (-> this seems to be ok) that the file generated would then be in the repo, hence having the file generated to be added, commited and pushed to the main branch to be available in the page ass... | If you want to run a script, then you don't need an additional checkout step for that. There is a difference between steps that use workflows and those that execute shell scripts directly. You can read more about it here. In your configuration file, you kind of mix the two in the last step. You don't need an additional... | 5 | 7 |
74,573,624 | 2022-11-25 | https://stackoverflow.com/questions/74573624/why-does-the-dtype-of-a-numpy-array-automatically-change-to-object-if-you-mult | Given an arbitrary numpy array (its size and shape don't seem to play a role) import numpy as np a = np.array([1.]) print(a.dtype) # float64 it changes its dtype if you multiply it with a number equal or larger than 10**20 print((a*10**19).dtype) # float64 print((a*10**20).dtype) # object a *= 10**20 # Throws TypeErro... | I expect it is the size a "natural" integer can take on the system. print(sys.maxsize, sys.getsizeof(sys.maxsize)) => 9223372036854775807 36 print(10**19, sys.getsizeof(10**19)) => 10000000000000000000 36 And this is where on my system the conversion to object starts, when I do for i in range(1, 24): print(f'type of a... | 3 | 4 |
74,556,349 | 2022-11-24 | https://stackoverflow.com/questions/74556349/no-module-named-huggingface-hub-snapshot-download | When I try to run the quick start notebook of this repo, I get the error ModuleNotFoundError: No module named 'huggingface_hub.snapshot_download'. How can I fix it? I already installed huggingface_hub using pip. I get the error after compiling the following cell: !CUDA_VISIBLE_DEVICES=0 python -u ../scripts/main.py --s... | Updating to the latest version of sentence-transformers fixes it (no need to install huggingface-hub explicitly): pip install -U sentence-transformers I've proposed a pull request for this in the original repo. | 17 | 22 |
74,572,953 | 2022-11-25 | https://stackoverflow.com/questions/74572953/pydantic-attributeerror-object-has-no-attribute-fields-set | from pydantic import BaseModel class A(BaseModel): date = '' class B(A): person: float def __init__(self): self.person = 0 B() tried to initiate class B but raised error AttributeError: 'B' object has no attribute '__fields_set__', why is it? | It's because you override the __init__ and do not call super there so Pydantic cannot do it's magic with setting proper fields. With pydantic it's rare you need to implement your __init__ most cases can be solved different way: from pydantic import BaseModel class A(BaseModel): date = "" class B(A): person: float = 0 B... | 8 | 7 |
74,568,115 | 2022-11-25 | https://stackoverflow.com/questions/74568115/is-lightgbm-available-for-mac-m1 | My goal is to learn a notebook. It has recall 97% while I am struggling with F1 Score 'Attrited Customer' 77.9%. The problem is the notebook uses LightGBM. I am unable to install LightGBM. What I've tried: pip install lightgbm -> it throws error python setup.py egg_info did not run successfully. Then, I did pip instal... | As of this writing, no official release of lightgbm (the Python package for LightGBM) supports the M1 Macs (which us ARM chips). osx-arm64 builds of lightgbm are supported by the lightgbm conda-forge feedstock, so you can install lightgbm on an M1 Mac using conda. conda install \ --yes \ -c conda-forge \ 'lightgbm>=3.3... | 5 | 8 |
74,567,273 | 2022-11-25 | https://stackoverflow.com/questions/74567273/for-a-new-python-project-using-the-latest-version-of-python-should-i-declare-my | According to pep-0585 for the latest versions of Python, it appears we can use List and list interchangeably for type declarations. So which should I use? Assume: no requirement for backward compatibility using the latest version of python from typing import List def hello_world_1(animals: list[str]) -> list[str]: re... | According to the current Python docs, typing.List and similar are deprecated. The docs further state The deprecated types will be removed from the typing module in the first Python version released 5 years after the release of Python 3.9.0. See details in PEP 585—Type Hinting Generics In Standard Collections. Concern... | 3 | 3 |
74,566,704 | 2022-11-24 | https://stackoverflow.com/questions/74566704/cannot-install-lightgbm-3-3-3-on-apple-silicon | Here the full log of pip3 install lightgbm==3.3.3. me % pip3 install lightgbm==3.3.3 Collecting lightgbm==3.3.3 Using cached lightgbm-3.3.3.tar.gz (1.5 MB) Preparing metadata (setup.py) ... done Requirement already satisfied: wheel in /opt/homebrew/lib/python3.10/site-packages (from lightgbm==3.3.3) (0.37.1) Collecting... | When you run pip install lightgbm and see this message in logs: Building wheels for collected packages: lightgbm it means that there is not a pre-compiled binary (i.e. wheel) available matching your platform (operating system + architecture + Python version), and that LightGBM needs to be built from source. lightgbm ... | 13 | 30 |
74,566,749 | 2022-11-24 | https://stackoverflow.com/questions/74566749/no-module-names-src-when-importing-from-parent-folder-in-jupyter-notebook | I have the following folder structure in my project my_project notebook |-- some_notebook.ipynb src |-- preprocess |-- __init__.py |-- some_processing.py __init__.py Now, inside some_notebook.ipynb I simply want to get the methods from some_processing.py. Now we I run from src.preprocess import some_processing from s... | I found the answer. Running sys.path.insert(1, os.path.join(sys.path[0], '../src')) made it possible to import anything from parent module src. | 4 | 3 |
74,557,655 | 2022-11-24 | https://stackoverflow.com/questions/74557655/python-type-hints-how-to-use-literal-with-strings-to-conform-with-mypy | I want to restrict the possible input arguments by using typing.Literal. The following code works just fine, however, mypy is complaining. from typing import Literal def literal_func(string_input: Literal["best", "worst"]) -> int: if string_input == "best": return 1 elif string_input == "worst": return 0 literal_func(s... | Unfortunately, mypy does not narrow the type of input_string to Literal["best"]. You can help it with a proper type annotation: input_string: Literal["best"] = "best" literal_func(string_input=input_string) Perhaps worth mentioning that pyright works just fine with your example. Alternatively, the same can be achieve... | 11 | 9 |
74,557,297 | 2022-11-24 | https://stackoverflow.com/questions/74557297/f-string-with-percent-and-fixed-decimals | I know that I can to the following. But is it possible to combine them to give me a percent with fixed decimal? >>> print(f'{0.123:%}') 12.300000% >>> print(f'{0.123:.2f}') 0.12 But what I want is this output: 12.30% | You can specify the number of decimal places before %: >>> f'{0.123:.2%}' '12.30%' | 9 | 19 |
74,554,325 | 2022-11-24 | https://stackoverflow.com/questions/74554325/how-to-disable-the-header-with-filename-and-date-when-converting-ipynb-to-pdf-w | I am using nbconvert for converting my .ipynb into an .pdf file. When doing so the resulting .pdf file contains a header with the filename and the current date below. How can I disable that? I was looking in the docs but cannot find how to do it. CLI command jupyter nbconvert --to pdf filename.ipynb Actual Wanted | I found some helpful pointer in the docs. Just follow these steps: Run jupyter --paths in your command-line. Copy the path who looks like /Users/username/.venv/venvName/share/jupyter (I run nbconvert from a venv. Could be different for you). Go to the path and duplicate the folder latex Name the folder hide_header or ... | 5 | 8 |
74,553,366 | 2022-11-23 | https://stackoverflow.com/questions/74553366/yarl-quoting-c19612-fatal-error-longintrepr-h-file-not-found-1-error-ge | Python version: 3.11 Installing dependencies for an application by pip install -r requirements.txt gives the error below. This error is specific to Python 3.11 version. On Python with 3.10.6 version installation goes fine. Related question: ERROR: Could not build wheels for aiohttp, which is required to install pyproje... | Solution for this error: need to update requirements.txt. Not working versions of modules with Python 3.11: yarl==1.4.2 frozenlist==1.3.0 aiohttp==3.8.1 Working versions: yarl==1.8.1 frozenlist==1.3.1 aiohttp==3.8.2 Links to the corresponding issues with fixes: https://github.com/aio-libs/yarl/issues/706 https://git... | 5 | 4 |
74,551,529 | 2022-11-23 | https://stackoverflow.com/questions/74551529/raspi-pico-w-errno-98-eaddrinuse-despite-using-socket-so-reuseaddr | I'm trying to set up a simple server/client connection using the socket module on a Raspberry Pi Pico W running the latest nightly build image rp2-pico-w-20221123-unstable-v1.19.1-713-g7fe7c55bb.uf2 which I've downloaded from https://micropython.org/download/rp2-pico-w/ The following code runs fine for the first connec... | While I was able to mitigate the reconnection crash by adding a sock.close() statement after the con.close(), the main issue with my code was the structure itself, as Steffen Ullrich pointed out. The actual fix was to move the operations on the sock object out of the loop. import socket def await_connection(): print(' ... | 3 | 4 |
74,550,830 | 2022-11-23 | https://stackoverflow.com/questions/74550830/error-could-not-build-wheels-for-aiohttp-which-is-required-to-install-pyprojec | Python version: 3.11 Installing dependencies for an application by pip install -r requirements.txt gives the following error: socket.c -o build/temp.linux-armv8l-cpython-311/aiohttp/_websocket.o aiohttp/_websocket.c:198:12: fatal error: 'longintrepr.h' file not found #include "longintrepr.h" ^~~~~~~ 1 error generated. ... | Solution for this error: need to update requirements.txt. Not working versions of modules with Python 3.11: aiohttp==3.8.1 yarl==1.4.2 frozenlist==1.3.0 Working versions: aiohttp==3.8.2 yarl==1.8.1 frozenlist==1.3.1 Links to the corresponding issues with fixes: https://github.com/aio-libs/aiohttp/issues/6600 https:/... | 30 | 20 |
74,548,693 | 2022-11-23 | https://stackoverflow.com/questions/74548693/why-do-python-variables-of-same-value-point-to-the-same-memory-address | I ran into an interesting case today wherein a = 10 b = 10 print (a is b) logged out True. I did some searching and came across the concept of interning. Now that explains why True is correct for the range [-5, 256]. However, I get the same results even while using floats. Please help me understand why. Here is the pa... | What you are looking at in your case is called "constant folding". That's an implementation detail, not a language specification - meaning there is no guarantee that this behaviour will remain the same and you should not rely on it in your code. But, in general it comes down to the fact that things that can be calculat... | 3 | 5 |
74,548,343 | 2022-11-23 | https://stackoverflow.com/questions/74548343/inner-merge-two-dataframes-on-string-partial-match | We have the following two data frames temp = pd.DataFrame(np.array([['I am feeling very well',1],['It is hard to believe this happened',0], ['What is love?',1], ['No new friends',0], ['I love this show',1],['Amazing day today',1]]), columns = ['message','sentiment']) temp_truncated = pd.DataFrame(np.array([['I am feeli... | You can use: import re pattern = '|'.join(map(re.escape, temp_truncated['message'])) key = temp['message'].str.extract(f'({pattern})', expand=False) out = (temp .merge(temp_truncated.rename(columns={'message': 'sub'}), left_on=key, right_on='sub') .drop(columns='sub') ) Output: message sentiment cutoff 0 I am feeling... | 4 | 5 |
74,547,365 | 2022-11-23 | https://stackoverflow.com/questions/74547365/how-to-reduce-cognitive-complexity-in-this-python-method | I am faced with a challenge. I have an Python method implemented and the SonarLint plugin of my PyCharm warns me with the message: "Refactor this function to reduce its Cognitive Complexity from 19 to the 15 allowed." but I can't see how to reduce the complexity. My Python method is: def position(key): if key == 'a': r... | I've found what's happening. The Plugin SonarLint has a maximum number of Cognitive Complexity, as you can see in this capture: So SonarLint doesn't say you that you can simplify your method, it tells you that this method is more complex than the prefixed limit that SonarLint has setted. This is the reason because if ... | 3 | 1 |
74,544,539 | 2022-11-23 | https://stackoverflow.com/questions/74544539/python-how-to-check-what-types-are-in-defined-types-uniontype | I am using Python 3.11 and I would need to detect if an optional class attribute is type of Enum (i.e. type of a subclass of Enum). With typing.get_type_hints() I can get the type hints as a dict, but how to check if a field's type is optional Enum (subclass)? Even better if I could get the type of any optional field r... | When you are dealing with a parameterized type (generic or special like typing.Optional), you can inspect it via get_args/get_origin. Doing that you'll see that T | S is implemented slightly differently than typing.Union[T, S]. The origin of the former is types.UnionType, while that of the latter is typing.Union. Unfor... | 3 | 5 |
74,543,989 | 2022-11-23 | https://stackoverflow.com/questions/74543989/why-do-we-need-try-finally-when-using-contextmanager-decorator | I wonder why we need to use a try-finally when using a the @contextmanager decorator. The provided example suggests: from contextlib import contextmanager @contextmanager def managed_resource(*args, **kwds): resource = acquire_resource(*args, **kwds) try: yield resource finally: release_resource(resource) It seems to ... | Because a finally statement is guaranteed to run no matter what (except a power outage), before the code can terminate. So writing it like this guarantees that the resource is always released | 3 | 3 |
74,511,042 | 2022-11-20 | https://stackoverflow.com/questions/74511042/one-connection-to-db-for-app-or-a-connection-on-every-execution | I'm using psycopg2 library to connection to my postgresql database. Every time I want to execute any query, I make a make a new connection like this: import psycopg2 def run_query(query): with psycopg2.connect("dbname=test user=postgres") as connection: cursor = connection.cursor() cursor.execute(query) cursor.close() ... | You should strongly consider using a connection pool, as other answers have suggested, this will be less costly than creating a connection every time you query, as well as deal with workloads that one connection alone couldn't deal with. Create a file called something like mydb.py, and include the following: import psy... | 3 | 6 |
74,537,026 | 2022-11-22 | https://stackoverflow.com/questions/74537026/execute-function-specifically-on-cpu-in-jax | I have a function that will instantiate a huge array and do other things. I am running my code on TPUs so my memory is limited. How can I execute my function specifically on the CPU? If I do: y = jax.device_put(my_function(), device=jax.devices("cpu")[0]) I guess that my_function() is first executed on TPU and the res... | To directly specify the device on which a function should be executed, use the device argument of jax.jit. For example (using a GPU runtime because it's the accelerator I have access to at the moment): import jax gpu_device = jax.devices('gpu')[0] cpu_device = jax.devices('cpu')[0] def my_function(x): return x.sum() x ... | 4 | 4 |
74,534,284 | 2022-11-22 | https://stackoverflow.com/questions/74534284/anotate-return-type-with-psycopg2-type-stub | I have a function which returns a psycopg2 connection, if a connection can be established. So the return type should be Optional[psycopg2.connection], or psycopg2.connection | None. However I am unable to import psycopg2.connection at runtime. I've tried the workaround mentioned in How can I import type-definitions fro... | The question you linked proposes some extremely dirty hack which doesn't seem to work any more. There is absolutely no need for it under such simple circumstances. Moreover, to be honest, I cannot reproduce that solution on any mypy version starting from 0.800 (old enough, given that the linked answer is recent), so th... | 3 | 6 |
74,529,728 | 2022-11-22 | https://stackoverflow.com/questions/74529728/shapelydeprecationwarnings-and-the-use-of-geoms | Some lines to look up geographical information by given pair of coordinates, referenced from https://gis.stackexchange.com/questions/254869/projecting-google-maps-coordinate-to-lookup-country-in-shapefile. import geopandas as gpd from shapely.geometry import Point pt = Point(8.7333333, 53.1333333) # countries shapefile... | The data contains POLYGONs and MULTIPOLYGONs. Apparently there have been changes to Shapely's MULTIPOLYGON API which have not been fully integrated into GeoPandas yet. data.geometry > 0 MULTIPOLYGON (((-61.68667 17.02444, -61.88722 ... > 1 POLYGON ((2.96361 36.80222, 4.78583 36.89472, ... > ... The mentioned errors a... | 3 | 3 |
74,467,521 | 2022-11-16 | https://stackoverflow.com/questions/74467521/how-to-get-foreign-key-attribute-and-many-to-many-attribute-of-a-model-instanc | In asynchronous queries, I want to get foreign key and many to many attributes of a model instance. In a simple example, I want to print university and courses for all instances of the model Student. models.py: from django.db import models class University(models.Model): name = models.CharField(max_length=64) class Cou... | For getting foreign key and many to many attributes (for django 4.1 or higher) in async queries: Foreign key attribute: There are two options for getting foreign key attribute: 1- async for student in Student.objects.all(): university = await University.objects.aget(id=student.university_id) print(university.name) 2- ... | 3 | 2 |
74,507,306 | 2022-11-20 | https://stackoverflow.com/questions/74507306/fastapi-returns-error-422-unprocessable-entity-when-i-send-multipart-form-dat | I have some issue with using Fetch API JavaScript method when sending some simple formData like so: function register() { var formData = new FormData(); var textInputName = document.getElementById('textInputName'); var sexButtonActive = document.querySelector('#buttonsMW > .btn.active'); var imagesInput = document.getE... | The 422 error response body will contain an error message about which field(s) is missing or doesn’t match the expected format. Since you haven't provided that (please do so), my guess is that the error is triggered due to how you defined the images parameter in your endpoint. Since images is expected to be a List of F... | 3 | 2 |
74,481,613 | 2022-11-17 | https://stackoverflow.com/questions/74481613/how-to-unstack-a-dataset-to-a-certain-dataframe | I have a dataset like this data = {'weight': ['NaN',2,3,4,'NaN',6,7,8,9,'NaN',11,12,13,14,15], 'MI': ['NaN', 21, 19, 18, 'NaN',16,15,14,13,'NaN',11,10,9,8,7]} df = pd.DataFrame(data, index= ['group1', "gene1", "gene2", 'gene3', 'group2', "gene1", 'gene21', 'gene4', 'gene7', 'group3', 'gene2', 'gene10', 'gene3', 'gene43... | You can use: m = df['weight'].ne('NaN') (df[m] .set_index((~m).cumsum()[m], append=True)['MI'] .unstack('weight', fill_value=0.1) .add_prefix('group') ) Variant with pivot: m = df['weight'].ne('NaN') (df.assign(col=(~m).cumsum()) .loc[m] .pivot(columns='col', values='MI') .fillna(0.1) .add_prefix('group') ) Output: w... | 3 | 5 |
74,502,898 | 2022-11-19 | https://stackoverflow.com/questions/74502898/polars-select-columns-not-exist-with-no-error | Is it possible to select a potentially non-existent column from a polars dataframe without exceptions (return a column with default values or null/None)? The behavior I really want can be shown in the example as follows: import polars as pl df1 = pl.DataFrame({"id": [1, 2, 3], "bar": ["sugar", "ham", "spam"]}) df2 = pl... | I mean as already in the comment mentioned above this functionality doesn't exist in polars, but we can construct a function which would fullfil your needs import glob def scan_csv_with_columns(file: str, needed_colnames: list[str]) -> pl.LazyFrame: file_collector = [] for filename in glob.glob(file): df_scan = pl.scan... | 3 | 2 |
74,498,191 | 2022-11-19 | https://stackoverflow.com/questions/74498191/how-to-define-multiple-api-endpoints-in-fastapi-with-different-paths-but-the-sam | I'm working on a project which uses FastAPI. My router file looks like the following: # GET API Endpoint 1 @router.get("/project/{project_id}/{employee_id}") async def method_one( project_id: str, organization_id: str, session: AsyncSession = Depends(get_db) ): try: return await CustomController.method_one( session, pr... | In FastAPI, as described in this answer, because endpoints are evaluated in order (see FastAPI's about how order matters), it makes sure that the endpoint you defined first in your app—in this case, that is, /project/{project_id}/...—will be evaluated first. Hence, every time you call one of the other two endpoints, i.... | 4 | 5 |
74,510,279 | 2022-11-20 | https://stackoverflow.com/questions/74510279/pyright-cant-see-poetry-dependencies | In a poetry project the local dependencies are installed in the ~/.cache/pypoetry/virtualenvs/ folder. Pyright in nvim is complaining that import package lines can't be resolved. What should I include into pyproject.toml? Or how to show pyright the path to the dependencies? Thanks My pyrightconfig.json looks like this:... | I spent days troubleshooting this. In the end, the only thing that worked was including this in my pyproject.toml: [tool.pyright] venvPath = "/Users/user/Library/Caches/pypoetry/virtualenvs" venv = "bfrl-93mGb6aN-py3.11" I'm also using this nvim plugin: poet-v I guess you could accomplish this through a proper LSP con... | 4 | 9 |
74,512,005 | 2022-11-20 | https://stackoverflow.com/questions/74512005/fast-bitwise-get-column-in-python | Is there an efficient way to get an array of boolean values that are in the n-th position in bitwise array in Python? Create numpy array with values 0 or 1: import numpy as np array = np.array( [ [1, 0, 1], [1, 1, 1], [0, 0, 1], ] ) Compress size by np.packbits: pack_array = np.packbits(array, axis=1) Expected r... | Besides some micro-optimisations, I dont believe that there is much that can be optimised here. There are also a few small mistakes in your code: @njit(nopython=True) is saying the same thing twice (the n in njit already stands for nopython mode.) simply @njit or @jit(nopython=True) should be used fastMath is for "cut... | 3 | 2 |
74,483,457 | 2022-11-17 | https://stackoverflow.com/questions/74483457/check-column-names-and-column-types-in-great-expectations | Currently, I am validating the table schema with expect_table_columns_to_match_set by feeding in a list of columns. However, I want to validate the schema associated with each column such as string. The only available Great Expectations rule expect_column_values_to_be_of_type has to be written for each column name and ... | You can use expect_column_values_to_match_json_schema (or regex / pattern - depending on what you are more comfortable with). Here is the list of expectations that are possible to use. With expect_column_values_to_match_json_schema you can define your schema in a json format: schema = { "column_name_a": {"type": "strin... | 4 | 2 |
74,493,571 | 2022-11-18 | https://stackoverflow.com/questions/74493571/asyncio-sleep0-does-not-yield-control-to-the-event-loop | I have a simple async setup which includes two coroutines: light_job and heavy_job. light_job halts in the middle and heavy_job starts. I want heavy_job to yield the control in the middle and allow light_job to finish but asyncio.sleep(0) is not working as I expect. this is the setup: import asyncio import time loop = ... | I think this subject needs some more discussion. I intend this post as an appendix to Daniel T's excellent and very clever answer - that's a fine piece of work. But Dan Getz's comment made me think that some more detail would be helpful. Dan suggests that there is no general way to yield to another task. This is correc... | 12 | 19 |
74,508,024 | 2022-11-20 | https://stackoverflow.com/questions/74508024/is-requirements-txt-still-needed-when-using-pyproject-toml | Since mid 2022 it is now possible to get rid of setup.py, setup.cfg in favor of pyproject.toml. Editable installs work with recent versions of setuptools and pip and even the official packaging tutorial switched away from setup.py to pyproject.toml. However, documentation regarding requirements.txt seems to be have bee... | Quoting myself from here My current assumption is: [...] you put your (mostly unpinned) dependencies to pyproject.toml instead of setup.py, so you library can be installed as a dependency of something else without causing much troubles because of issues resolving version constraints. On top of that, for "deployable ... | 78 | 30 |
74,524,530 | 2022-11-21 | https://stackoverflow.com/questions/74524530/how-to-get-the-items-inside-of-an-openaiobject-in-python | I would like to get the text inside this data structure that is outputted via GPT3 OpenAI. I'm using Python. When I print the object I get: <OpenAIObject text_completion id=cmpl-6F7ScZDu2UKKJGPXTiTPNKgfrikZ at 0x7f7648cacef0> JSON: { "choices": [ { "finish_reason": "stop", "index": 0, "logprobs": null, "text": "\nWhat ... | x = {"choices": [{"finish_reason": "length", "text": ", everyone, and welcome to the first installment of the new opening"}], } text = x['choices'][0]['text'] print(text) # , everyone, and welcome to the first installment of the new opening | 7 | 3 |
74,496,411 | 2022-11-18 | https://stackoverflow.com/questions/74496411/does-python-have-a-maximum-group-refer-for-regex-like-perl | Context: When running a regex match in Perl, $1, $2 can be used as references to captured regex references from the match, similarly in Python \g<0>,\g<1> can be used Perl also has a $+ special reference which refers to the captured group with highest numerical value My question: Does Python have an equivalent of $+ ? ... | The method captures in the regex module provides the same functionality: it "returns a list of all the captures of a group." So get the last one >>> import regex >>> str = 'fza' >>> m = regex.search(r'(a)|(f)', str) >>> print(m.captures()[-1]) f When the str has a before f this code prints a. This is the exact equival... | 3 | 3 |
74,538,831 | 2022-11-22 | https://stackoverflow.com/questions/74538831/how-to-send-push-notifications-to-ios-using-a-python-api | I have create a webscraper that sends notifications to my phone whenever certain events are detected. So far I have achieved this by sending emails through the sendgrid api. Its a pretty nice service, and it is free, but it clutters up the mailbox quite a bit. In stead I’d like to send messages directly to the iOS noti... | Maybe you should check out pushover.net. They have a simple WebAPI to send customized notifications to iOS devices. See https://support.pushover.net/i44-example-code-and-pushover-libraries#python for code samples. | 3 | 4 |
74,536,056 | 2022-11-22 | https://stackoverflow.com/questions/74536056/why-is-plotly-express-so-much-more-performant-than-plotly-graph-objects | I'm visualizing a scatterplots with between 400K and 2.5M points. I expectected to need to downsample before visualizing but to see just how much I ran a pilot test with a 400k dataset in plotly express, and the plot popped up quickly, beautifully, and responsively. In order to make the interractive figure I really nee... | Running the following simple example: import numpy as np import plotly.graph_objects as go import plotly.express as px x = np.linspace(-2, 2, 100000) y = np.cos(x) fig = go.Figure(data=[go.Scatter(x=x, y=y)]) fig2 = px.scatter(x=x, y=y) type(fig.data[0]), type(fig2.data[0]) # out: (plotly.graph_objs._scatter.Scatter, p... | 5 | 7 |
74,532,061 | 2022-11-22 | https://stackoverflow.com/questions/74532061/how-to-get-todays-date-in-sparql | I use Python and SPARQL to make a scheduled query for a database. I tried to use the python f-string and doc-string to inject today's date in the query, but when I try so, a conflict occurs with SPARQL syntax and the python string. The better way would be to use SPARQL to get today's date. In my python file my query lo... | now() returns the datetime (as xsd:dateTime) of the query execution: BIND( now() AS ?currentDateTime ) . To get only the date (as xsd:string), you could use CONCAT() with year(), month(), and day(): BIND( CONCAT( year(?currentDateTime), "-", month(?currentDateTime), "-", day(?currentDateTime) ) AS ?currentDateString )... | 5 | 3 |
74,525,250 | 2022-11-21 | https://stackoverflow.com/questions/74525250/how-to-use-multiple-urls-with-pip-extra-index-url | I want to configure my pip using environmental variables. I already have two pip index urls. So I'm already using PIP_INDEX_URL and PIP_EXTRA_INDEX_URL variables. PIP_INDEX_URL="https://example.com" PIP_EXTRA_INDEX_URL="https://example2.com" But I want to add one more index url. I don't know how I tried to add it with... | Pip expects an empty space ( ) to separate the values in environment variables. In this case, for example: PIP_EXTRA_INDEX_URL="https://example2.com https://example3.com" See pip's documentation section "Environment variables". | 5 | 8 |
74,527,775 | 2022-11-22 | https://stackoverflow.com/questions/74527775/how-to-convert-avif-to-png-with-python | I have an image file in avif format How can I convert this file to png format? I found some code to convert jpg files to avif, but I didn't find any code to reconvert them. | You need to install this modules: pip install pillow-avif-plugin Pillow Then: from PIL import Image import pillow_avif img = Image.open('input.avif') img.save('output.png') | 4 | 13 |
74,479,890 | 2022-11-17 | https://stackoverflow.com/questions/74479890/tracking-claims-using-date-timestamp-columns-and-creating-a-final-count-using-pa | I have an issue where I need to track the progression of patients insurance claim statuses based on the dates of those statuses. I also need to create a count of status based on certain conditions. DF: ClaimID New Accepted Denied Pending Expired Group 001 2021-01-01T09:58:35:335Z 2021-01-01T10:05:43:000Z A ... | First convert the date columns with something like for i in ['New', 'Accepted', 'Denied', 'Pending', 'Expired']: df[i] = pd.to_datetime(df[i], format="%Y-%m-%dT%H:%M:%S:%f%z") Then develop the date range applicable based on your column conditions. In this logic if Denied is there the range is new --> denied, or if acc... | 3 | 2 |
74,517,390 | 2022-11-21 | https://stackoverflow.com/questions/74517390/python-playwright-is-there-a-way-to-introspect-and-or-run-commands-interactivel | I'm trying to move from Selenium to Playwright for some webscraping tasks. Perhaps I got stuck into this bad habit of having Selenium running the browser on the side while testing the commands and selectors on the run. Is there any way to achieve something similar using Playwright? What I achieved so far was running pl... | I'd use the technique from can i run playwright outside of 'with'? and How to start playwright outside 'with' without context managers on the interactive repl: PS C:\Users\foo\Desktop> py Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits"... | 3 | 2 |
74,523,327 | 2022-11-21 | https://stackoverflow.com/questions/74523327/color-problem-with-log-transform-to-brighten-dark-area-why-and-how-to-fix | So I try to enhance this image by applying log transform on it original image The area where there are bright white color turns into color blue on the enhanced image. enhanced image path = '...JPG' image = cv2.imread(path) c = 255 / np.log(1 + np.max(image)) log_image = c * (np.log(image + 1)) # Specify the data type s... | Same cause for the two problems Namely this line log_image = c * (np.log(image + 1)) image+1 is an array of np.uint8, as image is. But if there are 255 components in image, then image+1 overflows. 256 are turned into 0. Which lead to np.log(imag+1) to be log(0) at this points. Hence the error. And hence the fact that ... | 3 | 3 |
74,519,974 | 2022-11-21 | https://stackoverflow.com/questions/74519974/fancy-indexing-calculation-of-adjacency-matrix-from-adjacency-list | Problem: I want to calculate at several times the adjacency matrix A_ij given the adjacency list E_ij, where E_ij[t,i] = j gives the edge from i to j at time t. I can do it with the following code: import numpy as np nTimes = 100 nParticles = 10 A_ij = np.full((nTimes, nParticles, nParticles), False) E_ij = np.random.r... | I think this might work: import numpy as np nTimes = 100 nParticles = 10 A_ij = np.full((nTimes, nParticles, nParticles), False) E_ij = np.random.randint(0, 9, (100, 10)) np.put_along_axis(A_ij, E_ij[..., None], True, axis=2) | 3 | 2 |
74,515,286 | 2022-11-21 | https://stackoverflow.com/questions/74515286/prophet-forecasting | My dataframe is in weekly level as below: I was trying to implement a prophet model using this code: df.columns = ['ds', 'y'] # define the model model = Prophet(seasonality_mode='multiplicative') # fit the model model1 = model.fit(df) model1.predict(10) I need to predict the output in a weekly level for the next 10 w... | You need to use model.make_future_dataframe to create new dates: model = Prophet() model.fit(df) future = model.make_future_dataframe(periods=10, freq='W') predictions = model.predict(future) predictions will give predicted values for the whole dataframe, you can reach to the forecasted values for the next 10 weeks wi... | 3 | 4 |
74,516,642 | 2022-11-21 | https://stackoverflow.com/questions/74516642/how-do-i-get-specific-keys-and-their-values-from-nested-dict-in-python | I need help, please be kind I'm a beginner. I have a nested dict like this: dict_ = { "timestamp": "2022-11-18T10: 10: 49.301Z", "name" : "example", "person":{ "birthyear": "2002" "birthname": "Examply" }, "order":{ "orderId": "1234" "ordername": "onetwothreefour" } } How do I get a new dict like: new_dict = {"timesta... | A general approach: dict_ = { "timestamp": "2022-11-18T10: 10: 49.301Z", "name": "example", "person": { "birthyear": "2002", "birthname": "Examply" }, "order": { "orderId": "1234", "ordername": "onetwothreefour" } } def nested_getitem(d, keys): current = d for key in keys: current = current[key] return current new_dict... | 3 | 2 |
74,510,820 | 2022-11-20 | https://stackoverflow.com/questions/74510820/add-two-legends-in-the-same-plot | I've a x and y. Both are flattened 2D arrays. I've two similar arrays, one for determining the colour of datapoint, another for determining detection method ("transit" or "radial"), which is used for determining the marker shape. a=np.random.uniform(0,100,(10,10)).ravel() #My x b=np.random.uniform(0,100,(10,10)).ravel... | You could just manually add the first legend to the Axes: leg1 = ax.legend(*scatter1.legend_elements(), bbox_to_anchor=(1.04, 1), loc="upper left", title="Legend") ax.add_artist(leg1) However, this is not every clear as the color legend uses the marker for Radial and the Detection legend uses just two arbitrary color... | 3 | 5 |
74,500,614 | 2022-11-19 | https://stackoverflow.com/questions/74500614/python-decimal-multiplication-by-zero | Why does the following code: from decimal import Decimal result = Decimal('0') * Decimal('0.8881783462119193534061639577') print(result) return 0E-28 ? I've traced it to the following code in the module: if not self or not other: ans = _dec_from_triple(resultsign, '0', resultexp) # Fixing in case the exponent is out o... | Raymond Hettinger has given a comprehensive explanation at cpython github: In Arithmetic Operations, the section on Arithmetic operations rules tells us: Trailing zeros are not removed after operations. There are test cases covering multiplication by zero. Here are some from multiply.decTest: -- zeros, etc. mulx021 m... | 9 | 3 |
74,509,113 | 2022-11-20 | https://stackoverflow.com/questions/74509113/switch-change-the-version-of-python-in-pyscript | I am just started looking/experimenting pyscript as per the current python code which is running on Python 3.6.0. But looks like pyscript loads the python version along with Pyodide and it is retuning the latest stable version based on the Pyodide version. Problem Statement : Is there any way we can change/switch the p... | YOu cannot as Python is built into Pyodide. You would need to rebuild Pyodide to change the version of Python. I also do not think that Python 3.6 will work with the current version of PyScript and Pyodide. Your only practical option is to make your application work with the Pyodide version of Python. | 3 | 2 |
74,510,664 | 2022-11-20 | https://stackoverflow.com/questions/74510664/does-strict-typing-increase-python-program-performance | Based on questions like this What makes C faster than Python? I've learned that dynamic/static typing isn't the main reason that C is faster than Python. It appears to be largely because python programs are interpreted, and c programs are compiled. I'm wondering if strict typing would close the gap in performance for i... | With current versions of Python, type annotations are mostly hints for the programmer and possibly some validation tools but are ignored by the compiler and not used at runtime by the byte-code interpreter, which is similar to the behavior of Typescript. It might be possible to change the semantics of Python to take ad... | 5 | 5 |
74,508,774 | 2022-11-20 | https://stackoverflow.com/questions/74508774/whats-the-difference-between-fastapi-background-tasks-and-celery-tasks | Recently I read something about this and the point was that celery is more productive. Now, I can't find detailed information about the difference between these two and what should be the best way to use them. | Straight from the documentation: If you need to perform heavy background computation and you don't necessarily need it to be run by the same process (for example, you don't need to share memory, variables, etc), you might benefit from using other bigger tools like Celery. They tend to require more complex configuratio... | 3 | 8 |
74,499,590 | 2022-11-19 | https://stackoverflow.com/questions/74499590/valueerror-number-of-labels-34866-does-not-match-number-of-samples-2 | I am trying to run Decision Tree Classifier but I face this problem.Please can you explain me how do I fix this Error?My English isn’t very good but I will try to understand!I'm just starting to learn the program, so please point me out if there's anything that isn't good enough.thank you! import matplotlib.pyplot as p... | There is just a small error with: x=sale['年紀'],sale['單位售價'] Rather than selecting the columns you want, this creates a tuple of the columns, hence the end of the error message ... does not match number of samples=2 One way to create a new pd.DataFrame with your selected columns: x=sale[['年紀', '單位售價']] | 4 | 2 |
74,508,088 | 2022-11-20 | https://stackoverflow.com/questions/74508088/python-pandas-calculate-standard-deviation-excluding-current-group-with-vectori | So i want to calculate standard deviation excluding current group using groupby. Here an example of the data: import pandas as pd df = pd.DataFrame ({ 'group' : ['A','A','A','A','A','A','B','B','B','B','B','B'], 'team' : ['1','1','2','2','3','3','1','1','2','2','3','3',] 'value' : [1,2,5,7,2,3,7,8,8,9,6,4] }) For exam... | You can use transform after combining group and team as a list: df['std'] = (df.assign(new=df[['group', 'team']].values.tolist())['new'].transform( lambda x: df[df['group'].eq(x[0]) & df['team'].ne(x[1])]['value'].std())) Output: group team value std 0 A 1 1 2.217356 1 A 1 2 2.217356 2 A 2 5 0.816497 3 A 2 7 0.816497 ... | 3 | 1 |
74,502,929 | 2022-11-19 | https://stackoverflow.com/questions/74502929/using-pandas-to-dynamically-replace-values-found-in-other-columns | I have a dataset looks like this: Car Make Model Engine Toyota Rav 4 8cyl6L Toyota 8cyl6L Mitsubishi Eclipse 2.1T Mitsubishi 2.1T Monster Gravedigger 25Lsc Monster 25Lsc The data was clearly concatenated from Make + Model + Engine at some point but the car Model was not provided to me. I've been tryi... | you can use: df['Model']=df.apply(lambda x: x['Car'].replace(x['Make'],"").replace(x['Engine'],""),axis=1) print(df) ''' Car Make Model Engine 0 Toyota Rav 4 8cyl6L Toyota Rav 4 8cyl6L 1 Mitsubishi Eclipse 2.1T Mitsubishi Eclipse 2.1T 2 Monster Gravedigger 25Lsc Monster Gravedigger 25Lsc ''' | 3 | 2 |
74,495,598 | 2022-11-18 | https://stackoverflow.com/questions/74495598/sqlalchemy-attributeerror-connection-object-has-no-attribute-commit | When using SQLAlchemy (version 1.4.44) to create, drop or otherwise modify tables, the updates don't appear to be committing. Attempting to solve this, I'm following the docs and using the commit() function. Here's a simple example from sqlalchemy import create_engine, text engine = create_engine("postgresql://user:pas... | The comment on the question is correct you are looking at the 2.0 docs but all you need to do is set future=True when calling create_engine() to use the "commit as you go" functionality provided in 2.0. SEE migration-core-connection-transaction When using 2.0 style with the create_engine.future flag, “commit as you go... | 10 | 20 |
74,495,636 | 2022-11-18 | https://stackoverflow.com/questions/74495636/converting-from-np-float64-to-np-float32-completely-changes-the-value-of-some-nu | I have a numpy array of dtype=float64, when attempting to convert it the types to float 32, some values change completely. for example, i have the following array: `test_64 = np.array([20110927.00000,20110928.00000,20110929.00000,20110930.00000,20111003.00000,20111004.00000,20111005.00000,20111006.00000,20111007.00000,... | Well, yes, that is what float32 are. Shortest way to see it, float32 have 24 bits significand (1 bit of sign, and 8 bits of exponents). That is 33 bits in all. But the 1st significand bit is not stored, because it is assumed to be 1. np.log2(20110927.) # 24.2614762474699 So, see the problem. You would need 25 bits to ... | 3 | 3 |
74,495,814 | 2022-11-18 | https://stackoverflow.com/questions/74495814/best-method-to-measure-execution-time-of-a-python-snippet | I want to compare execution time of two snippets and see which one is faster. So, I want an accurate method to measure execution time of my python snippets. I already tried using time.time(), time.process_time(), time.perf_counter_ns() as well as timeit.timeit(), but I am facing the same issues with all of the them. Th... | The execution time of a given code snippet will almost always be different every time you run it. Most tools that are available for profiling a single function/snippet of code take this into account, and run the code multiple times to be able to provide an average execution time. The reason for this is that there are o... | 7 | 5 |
74,469,039 | 2022-11-17 | https://stackoverflow.com/questions/74469039/is-it-possible-to-change-the-seed-of-a-random-generator-in-numpy | Say I instantiated a random generator with import numpy as np rng = np.random.default_rng(seed=42) and I want to change its seed. Is it possible to update the seed of the generator instead of instantiating a new generator with the new seed? I managed to find that you can see the state of the generator with rng.__getst... | N.B. The other answer (https://stackoverflow.com/a/74474377/2954547) is better. Use that one, not this one. This is maybe a silly hack, but one solution is to create a new RNG instance using the desired new seed, then replace the state of the existing RNG instance with the state of the new instance: import numpy as np... | 4 | 1 |
74,463,116 | 2022-11-16 | https://stackoverflow.com/questions/74463116/how-to-create-multi-part-paths-with-fastapi | I'm working on a FastAPI application, and I want to create multi-part paths. What I mean by this is I know how to create a path like this for all the REST methods: /api/people/{person_id} but what's a good way to create this: /api/people/{person_id}/accounts/{account_id} I could just keep adding routes in the "people... | In addition to what I have mentioned in the comments, would something like this be of use? from fastapi import FastAPI, APIRouter app = FastAPI() people_router = APIRouter(prefix='/people') account_router = APIRouter(prefix='/{person_id}/accounts') @people_router.get('/{person_id}') def get_person_id(person_id: int) ->... | 4 | 5 |
74,482,742 | 2022-11-17 | https://stackoverflow.com/questions/74482742/how-to-use-pytest-to-confirm-proper-exception-is-raised | I have the following code to create an Object account. I raise an error if the account meets certain conditions, e.g. is too long. I want to use pytest to test that that functionality works. class Account: def __init__(self, acct): self.tagged = {} self.untagged = {} self.acct_stats = {} try: if len(str(acct)) < 12: pr... | Have you tried with pytest.raises()? with pytest.raises(ValueError, match='invalid'): account = Account(account_id) Source | 3 | 2 |
74,489,594 | 2022-11-18 | https://stackoverflow.com/questions/74489594/torchvision-using-pretrained-weights-for-entire-model-vs-backbone | TorchVision Detection models have a weights and a weights_backbone parameter. Does using pretrained weights imply that the model uses pretrained weights_backbone under the hood? I am training a RetinaNet model and I'm not sure which of the two options I should use and what the differences are. | The difference is pretty simple: you can either choose to do transfer learning on the backbone only or on the whole network. RetinaNet from Torchvision has a Resnet50 backbone. You should be able to do both of: retinanet_resnet50_fpn(weights=RetinaNet_ResNet50_FPN_Weights.COCO_V1) retinanet_resnet50_fpn(backbone_weigh... | 4 | 2 |
74,467,875 | 2022-11-16 | https://stackoverflow.com/questions/74467875/vs-code-the-isort-server-crashed-5-times-in-the-last-3-minutes | I may have messed up some environmental path variables. I was tinkering around VS Code while learning about Django and virtual environments, and changing the directory path of my Python install. While figuring out how to point VS Code's default Python path, I deleted some User path variables. Then, isort began to refus... | I ended up refreshing my Windows install. Was for the best because I'm repurposing an older machine anyway. | 17 | -3 |
74,488,759 | 2022-11-18 | https://stackoverflow.com/questions/74488759/tkinter-tclerror-cant-delete-tcl-command-customtkinter-custom-prompt | What do I need I am trying to implement a custom Yes / No prompt box with help of tkinter. However I don't want to use the default messagebox, because I require the following two functionalites: a default value a countdown after which the widget destroys itself and takes the default value as answer What are the unpre... | While I don't have Ctk to give you the exact code. I can tell you exactly what is wrong and how you need to solve it. You have self repeating function via after here: def countdown(self): """Sets the timer for the question.""" if self.answer is not None: self.terminate() elif self.remaining_seconds < 0: self.answer = s... | 5 | 4 |
74,484,933 | 2022-11-18 | https://stackoverflow.com/questions/74484933/how-can-i-break-out-of-telegram-bot-loop-application-run-polling | def bot_start(): application = ApplicationBuilder().token("api_key").build() async def stop(update, context): await context.bot.send_message(chat_id=update.message.chat_id, text='Terminating Bot...') await application.stop() await Updater.shutdown(application.bot) await application.shutdown() async def error(update, co... | Application.run_polling is a convenience methods that starts everything and keeps the bot running until you signal the process to shut down. It's mainly intended to be used if the Application is the only long-running thing in your python process. If you want to run other things alongside your bot, you can instead manua... | 5 | 5 |
74,486,877 | 2022-11-18 | https://stackoverflow.com/questions/74486877/is-there-any-way-to-make-an-anti-aliased-circle-in-opencv | I'm trying to draw a circle in a picture using open CV with Python. Here is the picture I wish I can make : Here is the code I write : import cv2 import numpy as np import imutils text1 = "10x" text2 = "20gr" # Load image in OpenCV image = cv2.imread('Sasa.jfif') resized = imutils.resize(image, width=500) cv2.circle(r... | You can use anti aliasing to make the circle look better as described here: cv2.circle(resized,(350,150),65,(102,51,17),thickness=-1,lineType=cv2.LINE_AA) | 3 | 6 |
74,486,315 | 2022-11-18 | https://stackoverflow.com/questions/74486315/compare-2-list-columns-in-a-pandas-dataframe-remove-value-from-one-list-if-pres | Say I have 2 list columns like below: group1 = [['John', 'Mark'], ['Ben', 'Johnny'], ['Sarah', 'Daniel']] group2 = [['Aya', 'Boa'], ['Mab', 'Johnny'], ['Sarah', 'Peter']] df = pd.DataFrame({'group1':group1, 'group2':group2}) I want to compare the two list columns and remove the list elements from group1 if they are pr... | You need to zip the two Series. I'm using a set here for efficiency (this is not critical if you have only a few items per list): df['group1'] = [[x for x in a if x not in S] for a, S in zip(df['group1'], df['group2'].apply(set))] Output: group1 group2 0 [John, Mark] [Aya, Boa] 1 [Ben] [Mab, Johnny] 2 [Daniel] [Sarah... | 3 | 3 |
74,483,119 | 2022-11-17 | https://stackoverflow.com/questions/74483119/simpleimputer-object-has-no-attribute-fit-dtype | I have a trained scikit-learn model pipeline (including a SimpleImputer) that I'm trying to put into production. However, I get the following error when running it in the production environment. SimpleImputer object has no attribute _fit_dtype How do I solve this? | This is a result of using different versions of scikit-learn in the development and production environments. The model has been trained using one version and then it's used with a different version. This can be solved by storing the current library versions in the development environment in a requirements.txt file usin... | 3 | 3 |
74,454,587 | 2022-11-16 | https://stackoverflow.com/questions/74454587/sentry-sdk-custom-performance-integration-for-python-app | Sentry can track performance for celery tasks and API endpoints https://docs.sentry.io/product/performance/ I have custom script that are lunching by crone and do set of similar tasks I want to incorporated sentry_sdk into my script to get performance tracing of my tasks Any advise how to do it with https://getsentry.g... | You don't need use capture_event I would suggest to use sentry_sdk.start_transaction instead. It also allows track your function performance. Look at my example from time import sleep from sentry_sdk import Hub, init, start_transaction init( dsn="dsn", traces_sample_rate=1.0, ) def sentry_trace(func): def wrapper(*args... | 7 | 6 |
74,479,770 | 2022-11-17 | https://stackoverflow.com/questions/74479770/replace-nested-for-loops-combined-with-conditions-to-boost-performance | In order to speed up my code I want to exchange my for loops by vectorization or other recommended tools. I found plenty of examples with replacing simple for loops but nothing for replacing nested for loops in combination with conditions, which I was able to comprehend / would have helped me... With my code I want to ... | You can quite easily vectorize the most computationally intensive part: the innermost loop. The idea is to compute the points_list all at once. np.cross can be applied on each lines, np.where can be used to filter the result (and get the IDs). Here is the (barely tested) modified main loop: for point in tqdm(points): i... | 3 | 2 |
74,476,392 | 2022-11-17 | https://stackoverflow.com/questions/74476392/python-plotly-display-other-information-on-hover | Here is the code that I have tried: # import pandas as pd import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots df = pd.read_csv("resultant_data.txt", index_col = 0, sep = ",") display=df[["Velocity", "WinLoss"]] pos = lambda col : col[col > 0].sum() neg = lambda col : col[col <... | Essentially, this code ungroups the data frame before plotting to create the hovertemplate you're looking for. As stated in the comments, the data has to have the same number of rows to be shown in the hovertemplate. At the end of my answer, I added the code all in one chunk. Since you have hovermode as x unified, you... | 3 | 4 |
74,468,285 | 2022-11-16 | https://stackoverflow.com/questions/74468285/how-to-fix-runtimewarning-running-interpreter-doesnt-sufficiently-support-cod | Every time I run any pipenv command I'm getting this: C:\Users\user_name\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\attr_make.py:876: RuntimeWarning: Running interpreter doesn't sufficiently support code object introspection. Some features like bare super() or accessing class will not work... | I was fighting the same issue on MacOS. The problem seems to be when pipenv is installed with brew. I fixed it by uninstalling the brew version of pipenv, then installing pipenv using pip. Here are the commands: brew uninstall pipenv pip install pipenv Worked like a charm for me. Hope it helps you. | 3 | 8 |
74,476,226 | 2022-11-17 | https://stackoverflow.com/questions/74476226/add-values-to-new-column-from-a-dict-with-keys-matching-the-index-of-a-dataframe | I have a dictionary that for examples sake, looks like {'a': 1, 'b': 4, 'c': 7} I have a dataframe that has the same index values as the keys in this dict. I want to add each value from the dict to the dataframe. I feel like doing a check for every row of the DF, checking the index value, matching it to the one in the... | You can use map and assign back to a new column: d = {'a': 1, 'b': 4, 'c': 7} df = pd.DataFrame({'c':[1,2,3]},index=['a','b','c']) df['new_col'] = df.index.map(d) prints: c new_col a 1 1 b 2 4 c 3 7 | 3 | 4 |
74,470,382 | 2022-11-17 | https://stackoverflow.com/questions/74470382/plotly-3d-surface-plot-not-appearing | Hi I am trying to plot Plotly 3D surface plot, but unfortunately it doesnt appear. When I try with Scatter3D it works though not with Surface3D. Any ideas why? # Scatter 3D p = go.Figure() p.add_trace(go.Scatter3d( x = df.X1, y = df.X2, z = df.Y3, mode = "markers", marker = dict(size = 3), name = "actual" )) from plo... | A surface is not just a bunch of points. To draw a surface, Plotly needs to know how to split it in elementary triangles. Sure, you may think that, seeing your scatter plot, it seems obvious how to do so. But, well, it would be way less obvious if your points were not that planar. Plus, even in obvious cases, that woul... | 3 | 4 |
74,466,414 | 2022-11-16 | https://stackoverflow.com/questions/74466414/how-to-stop-browser-closing-in-python-selenium-without-calling-quit-or-close | Description of the problem: The problem I'm stuck on is when I run a code, it first opens the chrome browser and opens the google.com website and then it closes it for no reason. This is my code: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service ... | Add this code and try: options = Options() options.add_experimental_option("detach", True) driver = webdriver.Chrome(service=driver_service,options=options) Don't forget to add double slash '\\' in the chromedriver.exe path. | 5 | 10 |
74,461,394 | 2022-11-16 | https://stackoverflow.com/questions/74461394/issue-with-new-isort-extension-installed-as-from-vs-code-update-october-2022-ve | I'm using VS-Code version 1.73.1, with MS Python extension v2022.18.2, on Windows 10 Pro, Build 10.0.19045. After installing the October 2022 update of VS Code, when writing Python code I noticed nagging error diagnostics being issued by the isort extension about the import order of modules. Previously, I had never enc... | Upgrade the isort extension version to latest(v2022.8.0). | 3 | 3 |
74,460,663 | 2022-11-16 | https://stackoverflow.com/questions/74460663/context-manager-error-handling-inside-init-method | A bit of context I am working with a package that allows you to calculate several things about planets (such as their speed, or position), using information stored in files. The package includes methods to load, and unload files, so its basic usage would look like this: load(["File_1", "File_2"]) try: function() finall... | You can wrap your original code using contextlib.contextmanager. from contextlib import contextmanager @contextmanager def file_manager(file_list): try: load(file_list) yield None # after this the code inside the with block is executed finally: # this is called when the with block has finished # or when load raises an ... | 5 | 4 |
74,460,495 | 2022-11-16 | https://stackoverflow.com/questions/74460495/how-to-use-two-variable-types-in-a-pydantic-basemodel-with-typing-union | I need my model to accept either a bytes type variable or a string type variable and to raise an exception if any other type was passed. from typing import Union from pydantic import BaseModel class MyModel(BaseModel): a: Union[bytes, str] m1 = MyModel(a='123') m2 = MyModel(a=b'123') print(type(m1.a)) print(type(m2.a))... | The problem you are facing is that the str type does some automatic conversions (here in the docs): strings are accepted as-is, int float and Decimal are coerced using str(v), bytes and bytearray are converted using v.decode(), enums inheriting from str are converted using v.value, and all other types cause an error ... | 5 | 7 |
74,460,294 | 2022-11-16 | https://stackoverflow.com/questions/74460294/creating-sum-of-date-ranges-in-pandas | I have the following DataFrame, with over 3 million rows: VALID_FROM VALID_TO VALUE 0 2022-01-01 2022-01-02 5 1 2022-01-01 2022-01-03 2 2 2022-01-02 2022-01-04 7 3 2022-01-03 2022-01-06 3 I want to create one large date_range with a sum of the values for each timestamp. For the DataFrame above that would come out to: ... | If performance is important use Index.repeat with DataFrame.loc for new rows, create date colun with counter by GroupBy.cumcount and last aggregate sum: df['VALID_FROM'] = pd.to_datetime(df['VALID_FROM']) df['VALID_TO'] = pd.to_datetime(df['VALID_TO']) df1 = df.loc[df.index.repeat(df['VALID_TO'].sub(df['VALID_FROM']).d... | 3 | 3 |
74,456,529 | 2022-11-16 | https://stackoverflow.com/questions/74456529/python-typing-nested-dictionary-of-unknown-depth | I am using Python 3.11. Type hinting for dict of dicts of strs will look like this: dict[dict[str, str]] But what if I want to make hints for dict of unknown depth? For example, I want to write a function, which construct tree in dict form from list of tuples (parent, offspring): source = [('a', 'b'), ('b', 'c'), ('d'... | You can use a type alias with a forward reference to itself: from typing import TypeAlias NestedDict: TypeAlias = dict[str, str | 'NestedDict'] def tree_form(source: list[tuple[str, str]]) -> NestedDict: return {'a': {'b': {'c': {}}}, 'd': {'e': {}}} print(tree_form([('a', 'b'), ('b', 'c'), ('d', 'e')])) Demo of this ... | 4 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.