question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
78,797,526 | 2024-7-26 | https://stackoverflow.com/questions/78797526/is-using-a-pandas-dataframe-as-a-read-only-table-scalable-in-a-flask-app | I'm developing a small website in Flask that relies on data from a CSV file to output data to a table on the frontend using JQuery. The user would select an ID from a drop-down on the front-end, then a function would run on the back-end where the ID would be used as a filter on the table to return data. The data return... | This line of code can be made much faster without adding any new dependencies, just by using the tools that Pandas gives you. data_list = sorted(set(query_df[query_df['ID'] == id]['Name'].tolist())) The following optimizations can be made: sorted() can be replaced by pre-sorting the dataframe. set() can be replaced b... | 2 | 2 |
78,809,821 | 2024-7-30 | https://stackoverflow.com/questions/78809821/why-does-gekko-not-provide-optimal-commands-even-though-the-output-does-not-matc | The following is related to this question: predictive control model using GEKKO I am trying to apply the MPC to maintain the temperature of a room within a defined range, but GEKKO gives me null commands even if the output diverges. I run the corrected code from my previous question: # Import library import numpy as np... | The gain is listed as K = array([[ 0.93705481, -12.24012156]]) so an increase in beta by +1 leads to a decrease in the T by -12.24. An increase in T_ext by +1 leads to an increase in T by +0.937. The steady-state value of T is 13.32 so to get a starting value of 17, a common practice is to create an additive (or multip... | 2 | 1 |
78,792,688 | 2024-7-25 | https://stackoverflow.com/questions/78792688/unpickling-error-magic-number-pickle-module-loadf-pickle-load-args-pick | When I am trying to load a .pt file i am seeing the following error, str1='Dataset/ALL_feats_cgqa.pt' m = torch.load(str1) the error is as follows, File "/home/Storage1/pythonCodeArea/train.py", line 21, in load_embeddings m = torch.load(str1) File "/home/.local/lib/python3.10/site-packages/torch/serialization.py", l... | My guess is: your .pt file is most likely broken/corrupted. Most of the references that you posted in your question hint at the same cause. One can reproduce the problem as follows (that isn't to say that your .pt file was produced this way, but rather is intended to show that a corrupted file can trigger exactly the m... | 3 | 1 |
78,795,722 | 2024-7-25 | https://stackoverflow.com/questions/78795722/gcloud-mistakes-event-trigger-for-storage-trigger | There's a cloud function in Python that processes some data when a file is uploaded to firebase's bucket: @storage_fn.on_object_finalized(bucket = "my-bucket", timeout_sec = timeout_sec, memory = memory, cpu = cpu, region='us-central1') def validate_file_upload(event: storage_fn.CloudEvent[storage_fn.StorageObjectData]... | The answer is to use double-decorators: import functions_framework from cloudevents.http import CloudEvent from firebase_functions import storage_fn, options @functions_framework.cloud_event @storage_fn.on_object_finalized(bucket = "my-bucket", timeout_sec = timeout_sec, memory = memory, cpu = cpu, region='us-central1'... | 3 | 0 |
78,813,619 | 2024-7-30 | https://stackoverflow.com/questions/78813619/regex-to-interpret-awkward-scientific-notation | Ok, so I'm working with this ENDF data, see here. Sometimes in the files they have what is quite possibly the most annoying encoding of scientific notation floating point numbers I have ever seen1. There it is often used that instead of 1.234e-3 it would be something like 1.234-3 (omitting the "e"). Now I've seen a lib... | Probably wouldn't reach for regex for this, when some simple string ops should work: s.replace("-", "e-").replace("+", "e+").lstrip("e") | 2 | 3 |
78,808,725 | 2024-7-29 | https://stackoverflow.com/questions/78808725/python-regex-to-match-multiple-words-in-a-line-without-going-to-the-next-line | I'm writing a parser to parse the below output: admin@str-s6000-on-5:~$ show interface status Ethernet4 Interface Lanes Speed MTU Alias Vlan Oper Admin Type Asym PFC --------------- ----------- ------- ----- ------------ ------ ------ ------- -------------- ---------- Ethernet4 29,30,31,32 40G 9100 fortyGigE0/4 trunk ... | Suppose, for simplicity, the data were as follows. str = """ admin@str-s6000-on-5:~$ show interface status Ethernet4 Interface Lanes MTU Alias Ad Type Asym PFC --------------- -------- ---- ------ ---- ----------- ---------- Ethernet4 29,30,31 9100 fG0/4 up Q+ or later off PortChannel0001 N/A 9100 N/A up N/A N/A """ I... | 3 | 3 |
78,798,267 | 2024-7-26 | https://stackoverflow.com/questions/78798267/hysteresis-modelling-as-a-control-constraint-for-mpc-in-python-gekko | I am trying to introduce a hysteresis constraint in an MPC optimization problem for control signal dispatch using Python GEKKO. This has become a daunting task as I am unable to transform the following problem into equations that GEKKO understands. The problem: If ON time < minimum ON time, control dispatch for a give... | The easiest way to prevent the controller from turning off or on MVs too frequently is to use the u.MV_STEP_HOR option to specify the number of steps that it must be constant before it can move again. More details are in the documentation. Implementing a time-based condition is more complicated, but still possible. Bel... | 2 | 1 |
78,813,399 | 2024-7-30 | https://stackoverflow.com/questions/78813399/using-apply-in-polars | I am trying to create a new column using apply in polars. For this, I tried the following operation: df = df.with_columns( pl.col("AH_PROC_REALIZADO") .apply(get_procedure_description) .alias("proced_descr") ) But I'm getting the error: AttributeError: 'Expr' object has no attribute 'apply' The function I am trying ... | pl.Expr.apply was deprecated in favour of pl.Expr.map_elements in Polars release 0.19.0. Recently, pl.Expr.apply was removed in the release of Polars 1.0.0. You can adapt your code to the new version as follows. df.with_columns( pl.col("AH_PROC_REALIZADO") .map_elements(get_procedure_description, return_dtype=pl.String... | 2 | 6 |
78,810,432 | 2024-7-30 | https://stackoverflow.com/questions/78810432/how-to-explode-multiple-list-columns-with-missing-values-in-python-polars | Given a Polars dataframe like below, how can I call explode() on both columns while expanding the null entry to the correct length to match up with its row? shape: (3, 2) ┌───────────┬─────────────────────┐ │ x ┆ y │ │ --- ┆ --- │ │ list[i64] ┆ list[bool] │ ╞═══════════╪═════════════════════╡ │ [1] ┆ [true] │ │ [1, 2] ... | You were on the right track, trying to fill the missing values with a list of null values of correct length. To make pl.Expr.repeat_by work with null, we need to ensure that the base expression is of a non-null type. This can be achieved by setting the dtype argument of pl.lit explicity. Then, the list column of (lists... | 7 | 5 |
78,813,024 | 2024-7-30 | https://stackoverflow.com/questions/78813024/fastest-way-to-process-an-expanding-linear-sequence-in-python | I have the following conditions: The number u(0) = 1 is the first one in u. For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u also. There are no other numbers in u. No duplicates should be present. The numbers must be in ascending sequential order Ex: u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, .... | Generating and merging the ys and zs: from heapq import merge from itertools import groupby def twotimeslinear(n): u = [1] ys = (2*x+1 for x in u) zs = (3*x+1 for x in u) for x, _ in groupby(merge(ys, zs)): u.append(x) if n < len(u): return u[n] print(*map(twotimeslinear, range(20))) Attempt This Online! Takes ~0.05 s... | 2 | 5 |
78,802,454 | 2024-7-27 | https://stackoverflow.com/questions/78802454/static-files-not-loading-in-production-in-django-react-application | I'm running a Django application in a Docker container, and I'm having trouble serving static files in production. Everything works fine locally, but when I deploy to production, the static files don't load, and I get 404 errors. Here are the relevant parts of my setup: Django settings.py: TEMPLATES = [ { 'BACKEND': 'd... | I think the error lies in your nginx config. You are setting the alias for the static route to /vol/static, instead of /vol/web/static: server { listen ${LISTEN_PORT}; location /static { alias /vol/web/static; } ... } | 2 | 1 |
78,811,382 | 2024-7-30 | https://stackoverflow.com/questions/78811382/random-samplepopulation-x-sometimes-not-contained-in-random-samplepopulation | EDIT: Edited original post replacing my code with an MRE from user @no comment. I noticed a seemingly non-intuitive behaviour using a seeded random.sample(population, k) call to sample from a list of files in a directory. I would expect that sampling 100 items with k=100 while using a seed, guarantees that when I subse... | The exact algorithm isn't documented/guaranteed. You're likely using CPython, which chooses one of two slightly different algorithms for efficiency, depending on whether you want a small or large percentage of the population. Both algorithms select one element at a time and append it to the sample, but they differ in h... | 3 | 5 |
78,812,183 | 2024-7-30 | https://stackoverflow.com/questions/78812183/split-strings-in-a-series-convert-to-array-and-average-the-values | I have a Pandas Series that has these unique values: array(['17', '19', '21', '20', '22', '23', '12', '13', '15', '24', '25', '18', '16', '14', '26', '11', '10', '12/16', '27', '10/14', '16/22', '16/21', '13/17', '14/19', '11/15', '10/15', '15/21', '13/19', '13/18', '32', '28', '12/15', '29', '42', '30', '31', '34', '4... | I would use extractall and groupby.mean: s = pd.Series(['10', '12/16', '27', '10/14', '16/22', '16/21', '13/17']) out = (s.str.extractall(r'(\d+)')[0].astype(int).groupby(level=0).mean() .round().astype(int) ) You could also go with split and mean, but this generates a more expensive intermediate and will not scale as... | 3 | 2 |
78,811,781 | 2024-7-30 | https://stackoverflow.com/questions/78811781/rolling-kpi-calculations-in-polars-index-not-visible | How to add rolling KPI's to original dataframe in polars? when I do group by, I am not seeing an index and so cant join? I want to keep all original columns in dataframe intact but add rolling kpi to the dataframe? Pandas code: groups_df = df[mask_for_filter].groupby(['group_identifier']) rolling_kpi = groups_df[['col_... | It looks like you don't need to group by, but to run rolling_median() over window instead. over() to limit calculation to be within group_identifier. name.suffix() to assign names to the new columns. If you only need filtered rows: ( df .filter(mask_for_filter) .with_columns( pl.col("col_1", "col_2") .rolling_median(... | 4 | 1 |
78,811,505 | 2024-7-30 | https://stackoverflow.com/questions/78811505/why-does-order-of-the-data-matter-for-neural-network | Recently, I discovered the really weird behaviour of my an AI model. I wanted to build AI model that would try and guess the implicit functions based on the data I gave it. For example, the equation of the flower is: And this is how I wrote it in the Numpy array: K = 0.75 a = 9 def f(x): return x - 2 - 2*np.floor((x -... | Actually, it's a plotting issue. The order in a plot matters while the one of a scatter don't : import matplotlib.pyplot as plt shuffled_points = np.random.permutation(points) plt.scatter(*points.T) # in .scatter()-method POINT-s are depicted plt.scatter(*shuffled_points.T) # in .scatter()-method order does NOT matter... | 4 | 1 |
78,811,969 | 2024-7-30 | https://stackoverflow.com/questions/78811969/small-algorithm-to-create-a-list-of-y-axes-in-python | On python, I have a function called get_list_axes which takes 2 parameters : A list of unique captors - let's call them ["A", "B", "C", D"]. A list of captors from the unique captors above which should share the same y-axis - For instance ["A", "D"] or ["A", "C"] or ["A", "B", "D"], etc. The goal of the function is... | Your original get_list_axes function fails when merge_captors is not in the same order as list_ana_captors. This is because it relies on the specific order of captors, causing incorrect y-axis assignments. To fix this, we map each captor to its y-axis, ensuring captors in merge_captors share the same y-axis regardless ... | 2 | 1 |
78,810,300 | 2024-7-30 | https://stackoverflow.com/questions/78810300/pythonic-approach-to-avoid-nested-loops-for-string-concatenation | I want to find all 5-digit strings, for which the first three digits are in my first list, the second trough fourth are in my second and the third to fifth are in my last list: l0=["123","567","451"] l1=["234","239","881"] l2=["348","551","399"] should thus yield: ['12348', '12399']. I have therefore written a funct... | I would use itertools product to define a function that will perform the check annd append the data: import itertools def get_list(l1,l2): #THIS FUNCTION WILL TEST ALL THE PRODUCTS AND RETURN ONLY THE CORRECT ONES return [a+b[2:] for a,b in list(itertools.product(l1,l2)) if a[1:] == b[:2]] then you can nest the functi... | 3 | 1 |
78,802,780 | 2024-7-28 | https://stackoverflow.com/questions/78802780/python-beautiful-soup-not-loading-table-values | I am unsure how to extra the 'Settle' column for each state (New South Wales, Victoria, Queensland, South Australia) from this website: https://www.asxenergy.com.au/futures_au It seems the numerical data isn't showing. My starting code is: from bs4 import BeautifulSoup from urllib.request import urlopen url = "https://... | As stated, the data comes from asxenergy.com.au/futures_au/dataset Use pandas to get the <table> tags. It's not ideally structured, so need a bit of processing here. import pandas as pd url = 'https://www.asxenergy.com.au/futures_au/dataset' dfs = pd.read_html(url) states = dfs[0].iloc[0].to_list() table_names = list(d... | 2 | 1 |
78,810,121 | 2024-7-30 | https://stackoverflow.com/questions/78810121/python-regex-to-match-the-first-repetition-of-a-digit | Examples: For 0123123123, 1 should be matched since the 2nd 1 appears before the repetition of any other digit. For 01234554321, 5 should be matched since the 2nd 5 appears before the repetition of any other digit. Some regexes that I have tried: The below works for the 1st but not the 2nd example. It matches 1 inst... | One idea: capture the end of the string and add it in the negative lookahead (group 2 here): (\d)(?=.*?\1(.*))(?!.*?(\d).*?\3.+?\2$) This way you can control where the subpattern .*?(\d).*?\3 in the negative lookahead ends. If .+?\2$ succeeds, that means there's an other digit that is repeated before the one in group ... | 19 | 12 |
78,807,662 | 2024-7-29 | https://stackoverflow.com/questions/78807662/how-to-implement-pixel-shuffle | In tensorflow, there is a pixel-shuffle method called depth_to_space. What it does is the following: Suppose we have an image (an array) with dimensions (4,4,4). The above method shuffles the values of this array so that we get an array of size (16,16,1) in a way depicted in the image below: I tried now for a few hour... | Here is a "channels-first" solution (i.e. assuming your array dimensions are ordered channels×height×width): import numpy as np # Create some data ("channels-first" version) a = (np.ones((1, 3, 3), dtype=int) * np.arange(1,5)[:, np.newaxis, np.newaxis]) # 4×3×3 c, h, w = a.shape # channels, height, width p = int(np.sqr... | 2 | 4 |
78,807,798 | 2024-7-29 | https://stackoverflow.com/questions/78807798/mypy-1-10-reports-error-when-functools-wraps-is-used-on-a-generic-function | TLDR; I have a decorator that: changes the function signature the wrapped function uses some generic type arguments Other than the signature I would like to use funtools.wraps to preserve the rest of the information. Is there any way to achieve that without mypy complaining? More context A minimal working example wo... | This is, in some sense, a regression, though it's more of a limitation. Your code should have worked as-is, and Mypy 1.9 does pass your code, which means the behaviour change was added in 1.10. According to this similar issue (which was reported as a bug three months ago, but hasn't been triaged), the cause is this PR,... | 2 | 2 |
78,808,868 | 2024-7-29 | https://stackoverflow.com/questions/78808868/how-to-download-a-geopackage-file-from-geodataframe-in-a-shiny-app | I have a shiny app that displays a number of layers on a map using folium. I want to give the user the possibility to download one of the layers (a linestring geodataframe) as a geopackage file. Here is the code I have so far: # relevant imported packages from shiny import App, render, ui, reactive import pandas as pd ... | As a side note, the @output decorator is no longer necessary since v0.6.0. And regarding the download issue, you (must?) yield the value of the buffer in the render.download, something like below : from io import BytesIO from shiny import App, render, ui import geopandas as gpd from shapely import LineString app_ui = u... | 2 | 1 |
78,807,256 | 2024-7-29 | https://stackoverflow.com/questions/78807256/pandas-merge-without-copying-the-data | I have a dataframe (df1) with unique IDs (col1) but also duplicated IDs for each row (col2). On another dataframe (df2) I have unique IDs of col2. I want to somehow link the two dataframes together without copying the data of df2 (col3) (linking instead of copying). Here is an simplified example of what I try to achiev... | I would suggest to convert the non-key columns to Categorical, which should save a lot of memory if you have many duplicates: out = pd.merge(df1.astype({'col1': 'category'}), df2.astype({'col3': 'category'}), on='col2', how='left') Or, for simplicity: out = pd.merge(df1.astype('category'), df2.astype('category'), on='... | 2 | 3 |
78,807,069 | 2024-7-29 | https://stackoverflow.com/questions/78807069/how-to-implement-in-pytorch-numpys-unique-with-return-index-true | In numpy.unique there is an option return_index=True - which returns positions of unique elements (first occurrence - if several). Unfortunately, there is no such option in torch.unique ! Question: What are the fast and torch-style ways to get indexes of the unique elements ? ===================== More generally my iss... | You can achieve this in PyTorch with the following approach: def get_unique_elements_first_idx(tensor): # sort tensor sorted_tensor, indices = torch.sort(tensor) # find position of jumps unique_mask = torch.cat((torch.tensor([True]), sorted_tensor[1:] != sorted_tensor[:-1])) return indices[unique_mask] Example usage: ... | 3 | 4 |
78,798,514 | 2024-7-26 | https://stackoverflow.com/questions/78798514/typeerror-the-first-argument-must-be-callable-self-job-func-functools-parti | I seem to be experiencing an issue with the following Python Scheduler tasks. I have the below code which has a function to refresh all workbooks in a set bunch of directories. I have attempted to test the code only refreshing the one directory before moving onto the others and I am receiving the titled error. Is anyon... | do() accepts a function object and its arguments. Your code calls it with the result of excel_update(directory_2) call, which is not a function, but a good old None. Here's how to fix it: schedule.every(30).minutes.do(excel_update, directory_2)) See Pass arguments to a job | 2 | 2 |
78,806,818 | 2024-7-29 | https://stackoverflow.com/questions/78806818/join-same-name-dataframe-column-values-into-list | I create a dataframe with distinct column names and use rename to create columns with same name. import pandas as pd df = pd.DataFrame({ "a_1": ["x", "x"], "a_2": ["", ""], "b_1": ["", ""], "a_3": ["", "y"], "c_1": ["z", "z"], }) names = { "a_1": "a", "a_2": "a", "a_3": "a", "b_1": "b", "c_1": "c", } df2 = df.rename(co... | You could transpose and groupby.agg with a custom lambda: df2.T.groupby(level=0).agg(lambda x: x[x!=''].tolist()).T Output: a b c 0 [x] [] [z] 1 [x, y] [] [z] | 2 | 1 |
78,787,332 | 2024-7-24 | https://stackoverflow.com/questions/78787332/selecting-default-search-engine-is-needed-for-chrome-version-127 | All of my Selenium scripts are raising errors after Chrome updated to version 127 because I always have to select a default search engine when the browser is being launched. I use ChromeDriver 127.0.6533.72. How to fix it? | You need to add this Chrome Option to disable the 'choose your search engine' screen: options.addArguments("--disable-search-engine-choice-screen"); If you are using selenium with Python, you'll have to use: options.add_argument("--disable-search-engine-choice-screen") | 33 | 61 |
78,805,127 | 2024-7-29 | https://stackoverflow.com/questions/78805127/how-extract-regex-with-variable-from-string-in-pandas | I have a dataframe column containing text, and I'd like to make a new column which contains the sentences with names, but no other sentences. Hoping for an end result that looks like this: I am able to identify cells containing names from the list of names, but I'm stumbling on the part that extracts the sentence cont... | Code pat = '|'.join(last_names_list) df['col_3'] = df['ColumnA'].str.extract(rf'([^.]*?\b(?:{pat})\b.*?\.)') df: | 2 | 1 |
78,804,321 | 2024-7-28 | https://stackoverflow.com/questions/78804321/run-ps1-scripts-without-specifying-the-executor | In Python, we can use subprocess to run bat (cmd) scripts natively, like import subprocess as sp sp.run(["D:/Temp/hello.bat"]) works fine. However, it cannot run ps1 scripts natively, codes like import subprocess as sp sp.run(["D:/Temp/hello.ps1"]) will cause `WinError 193: %1 is not a valid Win32 application" to be ... | Batch files are special in that they are the only type of interpreter-based script files directly recognized as executables by the system. For any other script files, including PowerShell scripts (*.ps1), the only way you can achieve their execution when directly invoked is: Redefine the command that is used by the ... | 2 | 2 |
78,799,973 | 2024-7-26 | https://stackoverflow.com/questions/78799973/how-to-use-pydantic-model-as-query-parameter-in-litestar-get-route | I’m trying to create a GET route with Litestar that utilizes a Pydantic model as a query parameter. However, the serialization does not work as expected. Here is a minimal example that reproduces my issue: from pydantic import BaseModel from litestar import Litestar, get, Controller class Input(BaseModel): foo: str bar... | There are actually problems with both how you make and how you process your request. First, I wasn't be able to find in the docs a possibility to use Pydantic model for query params as FastAPI has. However you can implement similar logic yourself via DI mechanism: def build_input(foo: str, bar: str) -> Input: """Prepar... | 2 | 1 |
78,802,415 | 2024-7-27 | https://stackoverflow.com/questions/78802415/web-scraping-for-getting-data-with-python-nonetype-error | I'm trying to get dollar, prices for my school project. So I decide to use web scraping for this but I have a problem about it. When I try to use my code on server it gives me NoneType ERROR. It works on google colab but I can't use on my pc or server. How can I solve this guys? Web Scrape code ; def dolar(): headers =... | You should probably use this import requests import time def dolar(): now = time.time() - 10 headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15" } url = f"https://query1.finance.yahoo.com/v8/finance/chart/TRY=X?period1={int(no... | 3 | 3 |
78,802,365 | 2024-7-27 | https://stackoverflow.com/questions/78802365/how-to-filter-pandas-dataframe-for-strings-that-contain-all-substrings-in-a-give | I'm trying to filter out rows of a dataframe where a column of strings under the name 'question' contains all the substrings in a given list. That is, if the given list of substrings is ['King', 'England'], then I need to retain all the rows in the dataframe where the string in the df.question contains both King and En... | You can use .str.contains to check each word and then np.all over axis=0 to combine all boolean values for each row: import numpy as np import pandas as pd df = pd.DataFrame( { "question": [ "Who is the King of England?", "Where is England?", "England King", "King", ] } ) df2 = df[ np.all([df['question'].str.contains(w... | 2 | 3 |
78,802,108 | 2024-7-27 | https://stackoverflow.com/questions/78802108/literal-type-hint-unavailable-outside-of-the-init-method | I am using VScode 1.91.1. It seems like it doesn't want to recognize Literal outside of the __init__ method. Is there a way to have the right type throughout the class? class MyDict(TypedDict): my_var: Literal["a", "b"] class MyClass: def __init__(self, my_dict: MyDict): self.my_var = my_dict["my_var"] # hovering over ... | Another way you could try is the following: from typing import Literal, TypedDict class MyDict(TypedDict): my_var: Literal["a", "b"] class MyClass: def __init__(self, my_dict: MyDict): self._my_var: Literal["a", "b"] = my_dict["my_var"] @property def my_var(self) -> Literal["a", "b"]: return self._my_var def other_meth... | 4 | 1 |
78,801,520 | 2024-7-27 | https://stackoverflow.com/questions/78801520/why-is-pycharm-asking-for-old-version-of-pandas-and-how-can-i-make-it-stop | I am trying to learn Pandas, and am doing a simple project in PyCharm, but PyCharm is saying there is an error because I am not using specific out-of-date versions of Pandas, NumPy, and Faker. I do not know what Faker is. You can see the error message and my code below, though my code doesn't matter much to my question... | From what I've encountered in the past, this usually means that there is either a requirements.txt or a pyproject.toml, or a similar file in your project directory. These files define what versions of required packages the project was built for to let the user know that if they have a version different than that, the d... | 2 | 1 |
78,795,606 | 2024-7-25 | https://stackoverflow.com/questions/78795606/ffprobe-not-reflecting-mp4-dimension-edits | I'm trying to edit MP4 width & height without scaling. I'm doing that by editing tkhd & stsd boxes of the MP4 header. exiftool will show the new width & height but ffprobe will not. Before editing: Exif: $ exiftool $f | egrep -i 'width|height' Image Width : 100 Image Height : 100 Source Image Width : 100 Source Image... | FFprobe analyzes at stream level (eg: H.264) , but you are editing at the container level (eg: MP4). You would need to edit the SPS (Sequence Parameter Settings) bytes. Specifically you'll be editing: pic_width_in_mbs_minus1 and pic_height_in_map_units_minus1. Double-check the following using a hex editor. Try some man... | 2 | 2 |
78,799,576 | 2024-7-26 | https://stackoverflow.com/questions/78799576/how-can-i-save-quantum-gates-as-a-graphic-in-png-svg-format-using-qiskit | I am working with Qiskit for programming quantum circuits. Everything works fine but there is one thing which I didn't find out. Here is my Python code: from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.draw(output = "mpl") This is my output: I am only interested into the graphical repre... | This worked with me: from qiskit import QuantumCircuit from qiskit.visualization import circuit_drawer qc = QuantumCircuit(1) qc.h(0) circuit_img = circuit_drawer(qc, output='mpl', scale=2) circuit_img.savefig('hadamard_gate.png') # save figure as PNG circuit_img.savefig('hadamard_gate.svg') # save figure as SVG cf. h... | 3 | 0 |
78,797,590 | 2024-7-26 | https://stackoverflow.com/questions/78797590/adding-a-flag-to-the-end-of-a-bar-chart-in-python | I was trying to follow an example outlined here https://stackoverflow.com/a/61973946 The code, after small adjustments looks like this: def pos_image(x, y, pays, haut): pays = countries.get(pays).alpha2.lower() fichier = "iso-flag-png" fichier += f"/{pays}.png" im = mpimg.imread(fichier) ratio = 4 / 3 w = ratio * haut ... | I can reproduce your result. I am not exactly sure what's going wrong here: Either the answer that you refer to never worked in the first place or some matplotlib internals have changed since it was posted. That said, here is the problem: Once you call pos_image(), the internal call to ax.imshow() has the effect that t... | 2 | 1 |
78,798,250 | 2024-7-26 | https://stackoverflow.com/questions/78798250/plotly-updatemenus-only-update-specific-parameters | I'm looking for a way to have two updatemenu buttons on a plotly figure. One changes the data and the y-axis title and one switches from linear to log scale. Broadly the code below works but I lose something depending on which method I use. If the buttons method is update then when I switch parameters it defaults back ... | You need to use the update method for the first dropdown (restyle only updates data, update updates both data and layout - nb. those methods refer to their respective Plotly.js function, see Plotly.relayout and Plotly.update). Now to fix the issue, the key is to use "attribute strings", that is, 'yaxis.title': option i... | 2 | 1 |
78,796,974 | 2024-7-26 | https://stackoverflow.com/questions/78796974/shap-values-for-linear-model-different-from-those-calculated-manually | I train a linear model to predict house price, and then I compare the Shapley values calculation manually vs the values returned by the SHAP library and they are slightly different. My understanding is that for linear models the Shapley value is given by: coeff * features for obs - coeffs * mean(features in training se... | TL;DR: The definition of training set matters. Longer answer: Your understanding is right. However, what's not quite right is SHAP's hidden data transformations silently applied behind the scenes, which can be traced like this: import pandas as pd from sklearn.datasets import fetch_california_housing from sklearn.linea... | 2 | 2 |
78,794,966 | 2024-7-25 | https://stackoverflow.com/questions/78794966/how-to-customize-the-caption-text-in-folium-colorbar-i-want-to-increase-the-fon | I am trying to use colorbar for an output variable circle plot in Folium colormap = cm.LinearColormap(colors=['green','red'], index=[min(df['output']), max(df['output'])], vmin=min(df['output']),vmax=max(df['output']), caption='output in units') folium.Circle(location=[row['Latitude'], row['Longitude']], radius=800*row... | AFAIK, there is no direct way to do it but, you can inject CSS using the font-size property. By inspecting the html's folium Map (with CTRL+SHIFT+I) on Chrome, the caption's text seems to be at #legend > g > text : import folium import pandas as pd import branca.colormap as cm df = pd.DataFrame({"output": range(10, 11... | 2 | 1 |
78,797,421 | 2024-7-26 | https://stackoverflow.com/questions/78797421/python-pandas-difference-in-boolean-indexing-between-and | I am confused about different results of boolean indexing when using ~ after != versus when using just == I have a pandas df with 4 columns: dic = { "a": [1,1,1,0,0,1,1], "b": [0,0,1,1,0,0,0], "c": [1,0,1,0,0,1,0], "d": [0,0,1,0,0,1,0], } df = pd.DataFrame(data=dic) print(df) a b c d 0 1 0 1 0 1 1 0 0 0 2 1 1 1 1 3 0 1... | You're not correctly following De Morgan's law. not (A or B) = (not A) and (not B) not (A and B) = (not A) or (not B) If you use the opposite condition as input, you have to replace all (AND) by any (OR): df_B = df.loc[(df[names] != 0.0).any(axis=1)] In English this would be: I want to REMOVE (~) rows for which ALL... | 3 | 3 |
78,796,866 | 2024-7-26 | https://stackoverflow.com/questions/78796866/polars-when-then-conditions-form-dict | I would like to have a function that accept list of conditions as parameter and filter given dataframe by all of them. Pseudocode should look like this: def Filter(df, conditions = ["a","b"]): conditions_dict = { "a": pl.col("x") < 5, "b": pl.col("x") > -3, "c": pl.col("z") < 7 } return df.with_columns( pl.when( any [c... | In general, you can create a generator for the filter expressions of interest and pass it to pl.any_horizontal to check whether any of them evaluates to True. This can be used within a pl.when().then().otherwise() construct. def custom_filter(df: pl.DataFrame, conditions: list[str]) -> pl.DataFrame: conditions_dict = {... | 2 | 3 |
78,795,749 | 2024-7-25 | https://stackoverflow.com/questions/78795749/how-can-i-invert-dataclass-astuple | I am trying to construct a hierarchy of dataclasses from a tuple, like so: from dataclasses import astuple, dataclass @dataclass class Child: name: str @dataclass class Parent: child: Child # this is what I want p = Parent(Child("Tim")) print(p) # this is what I get t = astuple(p) print(Parent(*t)) However, while this... | You can use a helper function that constructs an instance of a dataclass from a given tuple of values and recursively constructs child instances for fields that are dataclasses: from dataclasses import astuple, dataclass, fields, is_dataclass @dataclass class Child: name: str @dataclass class Parent: child: Child def f... | 2 | 4 |
78,795,739 | 2024-7-25 | https://stackoverflow.com/questions/78795739/speed-up-parallelize-multivariate-normal-pdf | I have multiple Nx3 points, and I sequentially generate a new value for each from its corresponding multivariate Gaussian, each with 1x3 mean and 3x3 cov. So, together, I have arrays: Nx3 array of points, Nx3 array of means and Nx3x3 array of covs. I only see how to do it with the classic for-loop: import numpy as np f... | Here is a solution involving Cholesky decomposition. method 1: import numpy as np x = points - means p = x.shape[1] res = np.exp(-0.5*(x*np.linalg.solve(covs, x)).sum(1)) res/(2*np.pi)**(p/2)/np.linalg.det(covs)**0.5 array([0.03356053, 0.03167125, 0.08042358, 0.04351325, 0.1328082 ]) method 2: y = np.linalg.solve(LU ... | 2 | 3 |
78,795,741 | 2024-7-25 | https://stackoverflow.com/questions/78795741/python-detecting-a-letter-pattern-without-iterating-through-all-possible-combin | Apologies for the possibly not-very-useful title; I couldn't figure out how to summarise this problem into one sentence. I'm trying to count how many "units" long a word is in Python 3.10. One "unit" is (C for consonant and V for vowel) either CV or VC or C or V (the latter two only being used when no pair can be made)... | Just convert everything to 'V' or 'C', respectively, in a list. Then check the first 2 letters in a loop. If it's 'CV' or 'VC' pop the list, and no matter what, pop it again. Count the iterations it takes to exhaust the list. def units(word) -> int: word = ["V" if c in "aeiou" else "C" for c in word] cnt = 0 while word... | 2 | 1 |
78,794,752 | 2024-7-25 | https://stackoverflow.com/questions/78794752/how-to-re-order-duplicates-answers-on-polars-dataframe | I have a Polars dataframe that contains multiple questions and answers. The problem is that each answer is contained in its own column, which means that I have a lot of redundant information. Therefore, I would like to have only one column for the questions and another for the answers. Here is an example of the data: d... | TLDR. import polars.selectors as cs ( df .unpivot( on=cs.starts_with("Answer"), index=["ID", "Question"], variable_name="Source", value_name="Answer", ) .filter( pl.col("Question") == pl.col("Source").str.strip_prefix("Answer ") ) .drop("Source") ) shape: (3, 3) ┌─────┬──────────┬───────────────────┐ │ ID ┆ Question ┆... | 3 | 3 |
78,793,639 | 2024-7-25 | https://stackoverflow.com/questions/78793639/why-my-np-gradient-calculation-in-r2-doesnt-fit-with-the-analytical-gradient-c | I'm trying to compute a gradient on a map using np.gradient, but I'm encountering issues. To simplify my problem I am trying on an analytical function z = f(x,y) = -(x - 2)**2 - (y - 2)**2 np.gradient is not providing the expected results; the vectors should point towards the center. What am I doing wrong? Here is the... | the problem is not in the gradient function, it is in the different indexing order of np.meshgrid and np.gradient. by default np.gradient assumes the indexing is the same order as the arguments, ie: Z[x,y] -> np.gradient(Z, x, y) whereas np.meshgrid default indexing results in the opposite indexing, Z[y,x] -> np.meshg... | 4 | 4 |
78,793,287 | 2024-7-25 | https://stackoverflow.com/questions/78793287/how-to-compare-lists-in-two-pandas-dataframes-to-get-the-common-elements | I want to compare lists from columns set_1 and set_2 in df_2 with ins column in df_1 to find all common elements. I've started doing it for one row and one column but I have no idea how to compare all rows between two dfs to get the desired result. Here is my code comparing set_1 and ins in the first row: import pandas... | Since you have objects you'll need to loop. I would first perform a cross-merge, then use a set for efficiency: out = df1.merge(df2, how='cross') cols = list(df2) ins = out.pop('ins').apply(set) for c in cols: out[c] = [[x for x in lst if x in ref] for ref, lst in zip(ins, out[c])] Variant that should be a bit more ef... | 2 | 5 |
78,792,386 | 2024-7-25 | https://stackoverflow.com/questions/78792386/get-cumulative-weight-of-edges-without-repeating-already-traversed-paths | I have a water pipe network where each node is a house and each edge is a pipe connecting houses. The edges have a water volume as an attribute. I want to calculate the total volume reaching node 13. It should sum to 5+2+1+6+0+3+14+4+12+5+8+10+6+9=85 I've tried something like this, but it will repeat already traversed... | IIUC, just get a subgraph of all ancestors of 13 (and including 13), then compute the weighted size (= sum of all edge weights): target = 13 G.subgraph(nx.ancestors(G, target)|{target}).size(weight='volume') Output: 85 | 3 | 1 |
78,789,622 | 2024-7-24 | https://stackoverflow.com/questions/78789622/get-max-date-column-name-on-polars | I'm trying to get the column name containing the maximum date value in my Polars DataFrame. I found a similar question that was already answered here. However, in my case, I have many columns, and adding them manually would be tedious. I would like to use column selectors cs.datetime() and have tried the following: imp... | You were one step away and simply needed to select the column names of interest using df.select(cs.datetime()).columns. Then, we can unpack the list in the function call. Note. I've adapted the type hint of arg_max_horizontal accordingly. Moreover, (thanks to @Cameron Riddell), we can simplify conversion to a string re... | 4 | 3 |
78,789,944 | 2024-7-24 | https://stackoverflow.com/questions/78789944/how-do-you-sort-column-names-in-date-in-descending-order-in-pandas | I have this DataFrame: Node Interface Speed Band_In carrier Date Server1 wan1 100 80 ATT 2024-05-09 Server1 wan1 100 50 Sprint 2024-06-21 Server1 wan1 100 30 Verizon 2024-07-01 Server2 wan1 100 90 ATT 2024-05-01 Server2 wan1 100 88 Sprint 2024-06-02 Server2 wan1 100 22 Verizon 2024-07-19 I need to convert Date field t... | Don't convert your dates to string until after the pivot_table, so can do so easily with rename: df['Date'] = pd.to_datetime(df['Date']) df['is'] = df['Band_In'] / df['Speed'] * 100 out = (df.pivot_table(index=['Node', 'Interface', 'carrier'], columns='Date', values='is') .rename(columns=lambda x: x.strftime('%-d-%b'))... | 2 | 2 |
78,786,324 | 2024-7-24 | https://stackoverflow.com/questions/78786324/how-to-plot-justify-bar-labels-to-the-right-side-and-add-a-title-to-the-bar-labe | I have created a chart in matplotlib in python, but the last line in the following code doesn't allow alignment of the bar labels outside of the graph. import matplotlib.pyplot as plt g=df.plot.barh(x=name,y=days) g.set_title("Days people showed up") g.bar_label(g.containers[0], label_type='edge') I get a graph that l... | You can use a "secondary y axis" (this is similar to the more often used "twin" axis, but is only used to add ticks and labels, not for plotting). The example below uses ax as the name for the return value or df.plot.barh() to make the code easier to match with matplotlib documentation and tutorials. For more finetunin... | 3 | 1 |
78,786,100 | 2024-7-24 | https://stackoverflow.com/questions/78786100/how-can-i-simplify-this-method-to-replace-punctuation-while-keeping-special-word | I am making a modulatory function that will take keywords with special characters (@&\*%) and keep them intact while all other punctuation is deleted from a sentence. I have devised a solution, but it is very bulky and probably more complicated than it needs to be. Is there a way to do this, but in a much simpler way? ... | probably not the best, but really simple protected = ["Q&A", "stack@exchange"] protected_dict = {f'protected{i}': p_word for i, p_word in enumerate(protected)} sentence = "I am going to run over to Q&A stack@exchange and ask them a ton of questions about this & that & that & this while surfacing the internet! with my r... | 2 | 1 |
78,786,208 | 2024-7-24 | https://stackoverflow.com/questions/78786208/polars-replace-elements-in-list-of-list-column | Consider the following example series. s = pl.Series('s', [[1, 2, 3], [3, 4, 5]]) I'd like to replace all 3s with 10s to obtain the following. res = pl.Series('s', [[1, 2, 10], [10, 4, 5]]) Is it possible to efficiently replace elements in the lists of a List column in polars? Note. I've already tried converting to a... | In the case of a simple replacement, you can also consider using pl.Expr.replace within a pl.Series.list.eval context. This approach is a bit less general, but more concise than a pl.when().then().otherwise() construct. s.list.eval(pl.element().replace({3: 10})) shape: (2,) Series: 's' [list[i64]] [ [1, 2, 10] [10, 4,... | 3 | 3 |
78,765,604 | 2024-7-18 | https://stackoverflow.com/questions/78765604/how-to-enable-vi-mode-for-the-python-3-13-interactive-interpreter | One of the new features in python 3.13 is a more sophisticated interactive interpreter. However, it seems that this interpreter is no longer based on readline, and therefore no longer respects ~/.inputrc. I particularly miss the set editing-mode vi behavior. Is there a way to get this same "vi mode" behavior with the p... | According to this CPython issue and this comment on another issue, vi editing mode is not coming any time soon to the new REPL. It is still possible to use the old REPL by setting the PYTHON_BASIC_REPL=1 environmental variable. | 3 | 4 |
78,767,823 | 2024-7-19 | https://stackoverflow.com/questions/78767823/how-to-immediately-cancel-an-asyncio-task-that-uses-the-ollama-python-library-to | I'm using Ollama to generate answers from large language models (LLMs) with the Ollama Python API. I want to cancel the response generation by clicking the stop button. The problem is that the task cancellation works only if the response generation has already started printing. If the task is still processing and getti... | Update Ollama to the newest version with curl https://ollama.ai/install.sh | sh on Linux. It will automatically fix this issue. The code works exactly as it is. Just have to update Ollama. | 2 | 0 |
78,760,560 | 2024-7-17 | https://stackoverflow.com/questions/78760560/how-to-read-restore-a-checkpointed-dataframe-across-batches | I need to "checkpoint" certain information during my batch processing with pyspark that are needed in the next batches. For this use case, DataFrame.checkpoint seems to fit. While I found many places that explain how to create the one, I did not find any how to restore or read a checkpoint. For this to be tested, I cre... | While in theory, checkpoints are retained across Spark jobs and can be accessed from other Spark jobs by reading the files directly without having to recompute the entire lineage, they have not made it easy to read checkpoints directly from the stored files from other Spark jobs. If you are interested, here is an answe... | 4 | 1 |
78,778,926 | 2024-7-22 | https://stackoverflow.com/questions/78778926/creating-a-metaclass-that-inherits-from-abcmeta-and-qobject | I am building an app in PySide6 that will involve dynamic loading of plugins. To facilitate this, I am using ABCMeta to define a custom metaclass for the plugin interface, and I would like this custom metaclass to inherit from ABC and from QObject so that I can abstract as much of the behavior as possible, including th... | Doing some tests here: PySide6 Qobjetc inheritance modifies the usual Python behavior for classes, including attribute lookup - and this renders the mechanisms for abstractmethods in Python's ABC inoperative. Metclasses are a complicated subject, and cooperative metaclasses between different projects are even more comp... | 2 | 2 |
78,783,799 | 2024-7-23 | https://stackoverflow.com/questions/78783799/pylance-reports-code-is-unreachable-when-my-test-shows-otherwise | Pylance claims that code under if not dfs: is unreachable and greys it out in VS Code. import pandas as pd def concat_dfs(dfs: tuple[pd.DataFrame | None], logger) -> pd.DataFrame | None: # filter out dfs that are None, if any dfs = [df for df in dfs if df is not None] # concatenate dfs, if any are not None: if not dfs:... | The reason the code is considered unreachable is that the type hint for the argument dfs is tuple[pd.DataFrame | None]. Type hints take precedence over code interpretation, and this type hint means that the tuple has one element, so not dfs can never be true. Perhaps the type you really want to express is tuple[pd.Data... | 3 | 2 |
78,785,590 | 2024-7-23 | https://stackoverflow.com/questions/78785590/numpy-apply-mask-to-values-then-take-mean-but-in-parallel | I have an 1d numpy array of values: v = np.array([0, 1, 4, 0, 5]) Furthermore, I have a 2d numpy array of boolean masks (in production, there are millions of masks): m = np.array([ [True, True, False, False, False], [True, False, True, False, True], [True, True, True, True, True], ]) I want to apply each row from the... | Faster Numpy code A faster Numpy way to do that is to perform a matrix multiplication: (m @ v) / m.sum(axis=1) We can optimize this further by avoiding implicit conversion and perform the summation with 8-bit integer (this is safe only because v.shape[1] is small -- ie. less than 127): (m @ v) / m.view(np.int8).sum(dt... | 5 | 3 |
78,762,876 | 2024-7-18 | https://stackoverflow.com/questions/78762876/numba-indexing-on-record-type-structured-array-in-numpy | I have a numpy structured array and pass one element in it to a function as below. from numba import njit import numpy as np dtype = np.dtype([ ("id", "i4"), ("qtrnm0", "S4"), ("qtr0", "f4"), ]) a = np.array([(1, b"24q1", 1.0)], dtype=dtype) @njit def upsert_numba(a, sid, qtrnm, val): a[1] = qtrnm a[2] = val #i = 0 #a[... | Consider the following functions. from numba import njit @njit def func(): i = 777 t = i return t @njit def func2(): i = 776 t = i + 1 return t You can check how each variable's type is inferred using the following method. func() func.inspect_types() This is the key lines: # i = const(int, 777) :: Literal[int](777) ... | 2 | 1 |
78,778,792 | 2024-7-22 | https://stackoverflow.com/questions/78778792/plotting-star-maps-with-equatorial-coordinates-system | I'm trying to generate star maps with the equatorial coordinates system (RAJ2000 and DEJ2000). However, I only get a grid system where meridians and parallels are in parallel, while parallels should be curved and meridians should converge to the north celestial pole and the south ceestial pole. I'm using some Python mo... | I could find the solution in another forum. So I'm gonna post the answer. It was easier than it seems! The essential problem was in my WCS coordinate scales, they were defined incorrectly. Actually, using the FOV 30, the image didn't have a FOV of 30 degrees, it was smaller. This point helped to find the answer. There ... | 2 | 0 |
78,776,035 | 2024-7-21 | https://stackoverflow.com/questions/78776035/nlst-times-out-while-connecting-ftps-server-with-python | I can login to with Total Commander to server: ftps://publishedprices.co.il username: "XXXX" password empty And with lftp -u XXXX: publishedprices.co.il But when I tried to login and get the file list with Python on the same machine the nlst function returns time out. Code: from ftplib import FTP_TLS ftp_server = "pub... | The server is very unusual in using different IP address (...22) for the primary FTP port and data connections (...21). As it is common that servers return invalid IP addresses in PASV responses, ftplib in recent versions of Python (3.6 and newer) ignore the returned IP address and always connect to the primary address... | 2 | 5 |
78,785,661 | 2024-7-23 | https://stackoverflow.com/questions/78785661/parsing-formulas-efficiently-using-regex-and-polars | I am trying to parse a series of mathematical formulas and need to extract variable names efficiently using Polars in Python. Regex support in Polars seems to be limited, particularly with look-around assertions. Is there a simple, efficient way to parse symbols from formulas? Here's the snippet of my code: import re i... | As mentioned in the comment, you could drop the negative lookahead and optionally include the open parenthesis in the match. In a post-processing step, you could then filter out any matches containing an open parenthesis (using pl.Series.list.eval). This could look as follows. # avoid negative lookahead and optionally ... | 3 | 2 |
78,784,964 | 2024-7-23 | https://stackoverflow.com/questions/78784964/how-to-add-legend-to-df-plot-legend-not-showing-up-df-plot | I am currently creating a scatter plot with the results of some evaluation I am doing. To get a dataframe of the same structure as mine you can run: import pandas as pd models = ["60000_25_6", "60000_26_6"] results = [] for i in range(10): for model in models: results.append({"simulation": i, "model_id": model, "count_... | The data need assigned a label for the legend, so one option is: fig, ax = plt.subplots() for model in df['model_id'].unique(): df[df["model_id"].eq(model)].plot.scatter('count_at_1', 'count_at_5', c='color', label=model, ax=ax) ax.legend(markerfirst=False) With your sample data: | 4 | 1 |
78,784,292 | 2024-7-23 | https://stackoverflow.com/questions/78784292/use-list-comprehension-with-if-else-and-for-loop-while-only-keeping-list-items | I use list comprehension to load only the images from a folder that meet a certain condition. In the same operation, I would also like to keep track of those that do not meet the condition. This is where I am having trouble. If the if and else conditions are at the beginning, each iteration yields a resulting element. ... | Consider not using a list comprehension at all, precisely because you want to create two lists, not just one. exclude_imgs = [1, 3] excluded = [] final = [] for ix, n in enumerate(sorted(["img1", "img4", "img3", "img5", "img2"]), start=1): (excluded if ix in excluded_imgs else final).append(n) | 1 | 5 |
78,783,365 | 2024-7-23 | https://stackoverflow.com/questions/78783365/expand-numpy-array-to-be-able-to-broadcast-with-second-array-of-variable-depth | I have a function which can take an np.ndarray of shape (3,) or (3, N), or (3, N, M), etc.. I want to add to the input array an array of shape (3,). At the moment, I have to manually check the shape of the incoming array and if neccessary, expand the array that is added to it, so that I don't get a broadcasting error. ... | One option would be to transpose before and after the addition: (input_array.T + array_to_add).T You could also use expand_dims to add the extra dimensions: (np.expand_dims(array_to_add, tuple(range(1, input_array.ndim))) + input_array ) Alternatively with broadcast_to on the reversed shape of input_array + transpose... | 3 | 1 |
78,783,405 | 2024-7-23 | https://stackoverflow.com/questions/78783405/appending-multiple-dictionaries-to-specific-key-of-a-nested-dictionary | I want to append different dictionaries having the key as the meal_name and having total_calories and total_protein as a tuple being the value of the dictionary without overwriting the original dictionaries under the main dictionary having date as the key value. I tried using the code below to add the new dictionary bu... | You can use the if-else statement to check whether the current date is in the dictionary. date = input("Enter the date in (Day-Month-Year) format: ") name = input("Enter the name of the meal: ") if date in meal_data: # If date is already in meal_date then set the current_meal to existing meal current_meal = meal_data[d... | 2 | 2 |
78,766,494 | 2024-7-18 | https://stackoverflow.com/questions/78766494/predictive-control-model-using-gekko | I am modeling an MPC to maintain the temperature in a building within a given interval while minimizing the energy consumption. I am using GEKKO to model my algorithm. I wrote the following code. First, I identified my model using data with the input (the disturbance: external temperature and the control), and the outp... | When creating a question, please include example data that reproduces the error. It appears that the code is correct with this randomly generated data: # Example data for data_1 np.random.seed(42) # For reproducibility n = 100 # Number of data points # Generating example data T_ext = np.random.uniform(low=5, high=25, s... | 2 | 1 |
78,780,961 | 2024-7-22 | https://stackoverflow.com/questions/78780961/using-getattr-with-sqlalchemy-orm-leads-to-recursionerror | Simple self-contained example below, presupposing SQLite. I'm using the SQLAlchemy (v1.3) ORM, where I have a table of world-given whatsits that should not be changed. I also have another table with the same whatsits, in a form more usable to the developer. For instance, this table of dev-whatsits has fields to keep ca... | SQLAlchemy keeps the session state of an instance in the _sa_instance_state attribute, which is set on an instance if the instance doesn't yet have one. To test if an instance has the attribute, however, it has to call __getattr__ of the instance to query the name _sa_instance_state, so your overridden __getattr__ shou... | 2 | 1 |
78,780,896 | 2024-7-22 | https://stackoverflow.com/questions/78780896/customtkinter-grid-buttons-not-centered | I am trying to make a control panel GUI using customtkinter which essentially consits of different pages with different buttons, however when I go to a different page, the buttons aren't centered. As you can see, the first page is centered: However when I navigate to the Music Player, the buttons are aligned to the le... | The fourth column still has a weight of 1 so still takes up space, causing the widgets to appear aligned to the left. Set its weight to 0 when showing the music player: def open_music_controls(self): for widget in self.winfo_children(): widget.destroy() self.grid_columnconfigure((0, 2), weight=1) self.grid_columnconfig... | 2 | 4 |
78,780,567 | 2024-7-22 | https://stackoverflow.com/questions/78780567/why-are-nodes-not-found-in-a-graph-in-osmnx-when-the-graph-is-all-of-new-york-an | Here is my code: import osmnx as ox # Use the following commands to download the graph file of NYC G = ox.graph_from_place('New York City', network_type='drive', simplify=True) # Coordinates for origin and destination orig_x = 40.6662 orig_y = -73.9340 dest_x = 40.6576 dest_y = -73.9208 # Find the nearest nodes orig_no... | That's because of two problems : You swapped the x/y (i.e, New York is at -73.935242/40.730610) and considered the osmid/dist as pair of coordinates when asking for the shortest_path : import osmnx as ox G = ox.graph_from_place("New York City", network_type="drive", simplify=True) orig_x, orig_y = -73.9340, 40.6662 des... | 2 | 1 |
78,780,070 | 2024-7-22 | https://stackoverflow.com/questions/78780070/how-do-i-fix-this-reg-ex-so-that-it-matches-hyphenated-words-where-the-final-seg | I want to match all cases where a hyphenated string (which could be made up of one or multiple hyphenated segments) ends in a consonant that is not the letter m. In other words, it needs to match strings such as: 'crack-l', 'crac-ken', 'cr-ca-cr-cr' etc. but not 'crack' (not hyphenated), 'br-oom' (ends in m), br -oo (l... | You could add a negative lookahead to prevent having a hyphen after and also an idea to shorten [bcdfghjklnpqrstvwxyz](?<!m) to [a-z](?<![aeioum]). Update: Further as @Thefourthbird mentioned in the comments, as well putting the lookbehind after the word-boundary \b will result in better performance (fewer steps). \b(?... | 2 | 5 |
78,780,093 | 2024-7-22 | https://stackoverflow.com/questions/78780093/trouble-figuring-out-input-arguments-to-scipy-regulargridinterpolator-for-2d-int | I'm trying to interpolate 2D data to find the value of Z at point (X,Y) as if it were a 2D lookup table. import numpy as np import pandas as pd from scipy.interpolate import RegularGridInterpolator import io xi, yi = 100, 100; # test points I want to evaluate the interpolator object at # the 2D data copied from google ... | The documentation you point to is using an array. You are using a dataframe. Based on 'How to perform interpolation on 2d grid from dataframe in python?', you can use the values attribute of the dataframe: import numpy as np import pandas as pd from scipy.interpolate import RegularGridInterpolator import io xi, yi = 10... | 2 | 0 |
78,780,118 | 2024-7-22 | https://stackoverflow.com/questions/78780118/how-can-i-stop-the-alembic-logger-from-deactivating-my-own-loggers-after-using-a | I'm using alembic in my code to apply database migrations at application start. I'm also using Python's builtin logging lib to log to the terminal. After applying the migrations (or running any alembic command that prints to stdout it seems) my loggers stop working, though. Code: import logging import alembic.command f... | The answer will be found in your alembic.ini file. You're running a command which was intended to be a script, not an API call, so alembic is configuring its own logging using logging.fileConfig, which by default uses disable_existing_loggers=True. That option will disable any existing non-root loggers unless they or t... | 5 | 3 |
78,778,894 | 2024-7-22 | https://stackoverflow.com/questions/78778894/how-to-make-a-clickable-url-in-shiny-for-python | I tried this: app_ui = ui.page_fluid( ui.output_text("the_txt") ) def server(input, output, session): @render.text def the_txt(): url = 'https://stackoverflow.com' clickable_url = f'<a> href="{url}" target="_blank">Click here</a>' return ui.HTML(clickable_url) But the displayed text is the raw HTML: <a> href="https://... | In your app you have a small syntax error within the tag, you need <a ...> instead of <a> .... Below are two variants, depending on a static case or a situation where you have to render something. Static case You don't need a render function here since this is only HTML. Below are two alternatives: Either use ui.tags f... | 2 | 2 |
78,776,268 | 2024-7-21 | https://stackoverflow.com/questions/78776268/how-can-i-efficiently-fill-null-only-certain-columns-of-a-dataframe | For example, let us say I want to fill_null(strategy="zero") only the numeric columns of my DataFrame. My current strategy is to do this: import polars as pl import polars.selectors as cs df = pl.DataFrame( [ pl.Series("id", ["alpha", None, "gamma"]), pl.Series("xs", [None, 100, 2]), ] ) final_df = df.select(cs.exclude... | pl.DataFrame.select returns a dataframe that contains only the columns listed as arguments. Alternatively, pl.DataFrame.with_columns adds columns to the dataframe (and replaces columns with the same name). Especially, this provides you with the tools to perform the filling without an intermediate dataframe. You can sim... | 2 | 3 |
78,757,169 | 2024-7-17 | https://stackoverflow.com/questions/78757169/python-pandas-read-sas-with-chunk-size-option-fails-with-value-error-on-index-mi | I have a very large SAS file that won't fit in memory of my server. I simply need to convert to parquet formatted file. To do so, I am reading it in chunks using the chunksize option of the read_sas method in pandas. It is mostly working / doing its job. Except, it fails with the following error after a while. This par... | Perhaps try this code: import pandas as pd import pyarrow as pa import pyarrow.parquet as pq filename = 'mysasfile.sas7bdat' output_filename = 'output.parquet' SAS_CHUNK_SIZE = 2000000 writer = None # initialize writer sas_chunks = pd.read_sas(filename, chunksize=SAS_CHUNK_SIZE, iterator=True) for i, sasDf in enumerate... | 4 | 2 |
78,778,698 | 2024-7-22 | https://stackoverflow.com/questions/78778698/random-stratified-sampling-in-pandas | I have created a pandas dataframe as follows: import pandas as pd import numpy as np ds = {'col1' : [1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,4,4,4], 'col2' : [12,3,4,5,4,3,2,3,4,6,7,8,3,3,65,4,3,2,32,1,2,3,4,5,32], } df = pd.DataFrame(data=ds) The dataframe looks as follows: print(df) col1 col2 0 1 12 1 1 3 2 1 4 ... | I would shuffle the whole input with sample(frac=1), then compute a groupby.cumcount to select the first N samples per group (with map and boolean indexing) where N is defined in a dictionary: # {col1: number of samples} n = {1: 3, 2: 2, 3: 2, 4: 3} out = df[df[['col1']].sample(frac=1) .groupby('col1').cumcount() .lt(d... | 2 | 2 |
78,777,910 | 2024-7-22 | https://stackoverflow.com/questions/78777910/how-to-make-import-statements-to-import-from-another-path | I want to "hack" python's import so that it will first search in the path I specified and fallback to the original if not found. The traditional way of using sys.path will not work if there is a __init__.py, see below. CASE 1: The following works: Files: . ├── a │ ├── b.py # content: x='x' │ └── c.py # content: y='y' ... | The solution is to overwrite the default __import__ function (which is used by import statements) so that it first tries to import from the hack folder. __import = __import__ # save the original def _import(name, *a, **b): try: return __import('hack.'+name, *a, **b) except ImportError: return __import(name, *a, **b) __... | 2 | 0 |
78,773,004 | 2024-7-20 | https://stackoverflow.com/questions/78773004/why-do-numpy-scalars-multiply-with-custom-sequences-but-not-with-lists | I have a question to NumPy experts. Consider a NumPy scalar: c = np.arange(3.0).sum(). If I try to multiply it with a custom sequence like e.g. class S: def __init__(self, lst): self.lst = lst def __len__(self): return len(self.lst) def __getitem__(self, s): return self.lst[s] c = np.arange(3.0).sum() s = S([1, 2, 3]) ... | As pointed out by @hpaulj (thanks a lot!) this question was already around: Array and __rmul__ operator in Python Numpy. The mechanics of the problem was explained very well in this answer: stackoverflow.com/a/38230576/901925. However, the proposed solution of inheriting from np.ndarray is certainly a "dirty" one. In t... | 2 | 1 |
78,776,597 | 2024-7-22 | https://stackoverflow.com/questions/78776597/using-callable-iterator-re-finditer-causes-python-to-freeze | I have a function that is called for every line of a text. def tokenize_line(line: str, cmd = ''): matches = re.finditer(Patterns.SUPPORTED_TOKENS, line) tokens_found, not_found, start_idx = [], [], 0 print(matches) for match in matches: pass # Rest of code The result of print(matches) is something like: <callable_ite... | As pointed out in the comments, the hang is caused by a catastrophic backtracking, as you're wrapping the pattern [^;()\'""]*, which can match the entirety of your input or any part of it, in a group that can repeat zero to many times, followed by a ;, which is not matching your input. Upon failure, the regex engine ba... | 3 | 6 |
78,775,206 | 2024-7-21 | https://stackoverflow.com/questions/78775206/how-to-plot-a-line-on-the-second-axis-over-a-horizontal-not-vertical-bar-chart | I know how to plot a line on the second axis over a VERTICAL bar chart. Now I want the bars HORIZONTAL and the line top-to-bottom, just like the whole chart rotates 90°. If I simply replace bar with barh, the line is still left-to-right... Can I do this with Matplotlib? Here is a sample for VERTICAL bar chart: import m... | Pandas plotting doesn't readily support a secondary x axis. Instead, you can directly plot via matplotlib. (Note that df.plot(...) plots via pandas. Pandas plotting is a pandas specific interface towards matplotlib, and only supports a subset of matplotlib's functionality.) import matplotlib.pyplot as plt import pandas... | 2 | 3 |
78,774,606 | 2024-7-21 | https://stackoverflow.com/questions/78774606/exit-on-click-no-longer-works-after-using-clearscreen | I'm working on a Python Turtle graphics program and I'm trying to use the exitonclick method to close the window when it's clicked. However, it doesn't seem to be working. from turtle import Turtle, Screen rem = Turtle() screen = Screen() rem.fd(70) def clear(): screen.clearscreen() screen.listen() screen.onkey(fun=cle... | screen.clearscreen() completely resets the window. That includes removing all modifications to it made through exitonclick. The easiest solution is just to call exitonclick again in your custom function: from turtle import Turtle, Screen rem = Turtle() screen = Screen() rem.fd(70) def clear(): screen.clearscreen() scre... | 3 | 3 |
78,770,763 | 2024-7-19 | https://stackoverflow.com/questions/78770763/how-to-compare-rows-within-the-same-csv-file-faster | I have a csv file containing 720,000 rows with and 10 columns, the columns that are relevant to the problem are ['timestamp_utc', 'looted_by__name', 'item_id', 'quantity'] This file is logs of items people loot of the ground in a game, the problem is that sometimes the loot logger of the ground bugs and types in the p... | Pandas was not designed to iterate rows: Don't iterate rows in Pandas. That answer really goes down the rabbit hole in terms of performance and alternatives, but I think a good takeaway for you would be, that you need a better tool for the job. Enter Python's csv module and its humble but very fast reader: nothing beat... | 3 | 2 |
78,774,364 | 2024-7-21 | https://stackoverflow.com/questions/78774364/why-does-pyautogui-throw-an-imagenotfoundexception-instead-of-returning-none | I am trying to make image recognition program using pyautogui. I want the program to print "I can see it!" when it can see a particular image and "Nope nothing there" when it can't. I'm testing for this by using pyautogui.locateOnScreen. If the call returns anything but None, I print the first message. Otherwise, I pri... | From the pyautogui docs: NOTE: As of version 0.9.41, if the locate functions can’t find the provided image, they’ll raise ImageNotFoundException instead of returning None. Your program assumes pre-0.9.41 behavior. To update it for the most recent version, replace your if-else blocks with try-except: from pyautogui im... | 2 | 2 |
78,773,189 | 2024-7-20 | https://stackoverflow.com/questions/78773189/pulling-labels-for-def-defined-functions-from-a-list-of-strings-in-python | I would like to create functions using the normal def procedure in Python with labels assigned to the namespace that are pulled from a list of strings. How can this be achieved? An example problem: given an arbitrary list of strings exampleList=['label1','label2','label3',...] of length k, initialize k def defined func... | you could use a class with a factory function class MyLabels: def __init__(self, label_list): for label in label_list: setattr(self, label, self.label_factory(label)) def label_factory(self, label): def my_func(arg: str): if len(arg) > len(label): print(f'the word {arg} has more letters than the word {label}') return m... | 2 | 1 |
78,770,796 | 2024-7-19 | https://stackoverflow.com/questions/78770796/how-do-i-get-variable-length-slices-of-values-using-pandas | I have data that includes a full name and first name, and I need to make a new column with the last name. I can assume full - first = last. I've been trying to use slice with an index the length of the first name + 1. But that index is a series, not an integer. So it's returning NaN. The commented lines show the things... | Edit: Use removeprefix instead of replace to deal with cases where first and last names are the same: df['Last'] = df.apply(lambda row: row['Full'].removeprefix(row['First']).strip(), axis=1) Full First Last 0 Joe Smith Joe Smith 1 Bobby Sue Ford Bobby Sue Ford 2 Current Resident Current Resident 3 4 Joe Joe Joe Joe ... | 3 | 2 |
78,770,134 | 2024-7-19 | https://stackoverflow.com/questions/78770134/why-is-the-limit-limit-of-maximum-recursion-depth-in-python-232-2-31 | In Python, some programs create the error RecursionError: maximum recursion depth exceeded in comparison or similar. This is because there is a limit set for how deep the recursion can be nested. To get the current value for maximum recursion depth, use import sys sys.getrecursionlimit() The default value seems to be ... | Usually the limit "limit" would be 2**31 - 1, i.e. the max value for a signed C integer (although the highest possible limit is documented as being platform-dependent). The lower usable range you get within IDLE is because it wraps the built-in function to impose a lower limit: >>> import sys >>> sys.setrecursionlimit ... | 2 | 4 |
78,765,462 | 2024-7-18 | https://stackoverflow.com/questions/78765462/how-to-get-the-available-python-versions-on-remote-node | I have some machines with different properties and different installed versions of Python. Now I want to write a task that returns all available Python versions on every machine (some have 2.7.x, some 3.8.x and others are in between). Depending on that I want to register the highest version for later tasks. I tried to ... | On a RHEL 9.4 System with Python 3.9.18 a minimal example playbook --- - hosts: localhost become: true gather_facts: true pre_tasks: - package_facts: tasks: - debug: var: ansible_python_version - debug: msg: "{{ ansible_facts.packages[item] }}" loop: "{{ ansible_facts.packages | select('search', regex) }}" vars: regex:... | 2 | 3 |
78,768,306 | 2024-7-19 | https://stackoverflow.com/questions/78768306/compare-strings-from-a-very-large-text-file-over-100-gb-with-a-small-text-file | I have two text files. One contains a very long list of strings (100 GB), the other contains about 30 strings. I need to find which lines in the second file are also in the first file and write them to another,third text file. Manually searching for each line is a pain, so I wanted to write a script to do it automatica... | The file.readlines method reads the entirety of a file into memory, which you should avoid when the file is that large. You can instead read the lines of the smaller file into a set, and then iterate over the lines of the larger file to find the common lines by testing if a line is in the set: def common_lines(small_fi... | 2 | 2 |
78,767,542 | 2024-7-19 | https://stackoverflow.com/questions/78767542/is-there-a-way-to-read-sequentially-pretty-printed-json-objects-in-python | Suppose you have a JSON file like this: { "a": 0 } { "a": 1 } It's not JSONL, because each object takes more than one line. But it's not a single valid JSON object either. It's sequentially listed pretty-printed JSON objects. json.loads in Python gives an error about invalid formatting if you attempt to load this, and... | You can partially decode text as JSON with json.JSONDecoder.raw_decode. This method returns a 2-tuple of the parsed object and the ending index of the object in the string, which you can then use as the starting index to partially decode the text for the next JSON object: import json def iter_jsons(jsons, decoder=json.... | 3 | 7 |
78,767,142 | 2024-7-19 | https://stackoverflow.com/questions/78767142/dictionary-indexing-with-numpy-jax | I'm writing an interpolation routine and have a dictionary which stores the function values at the fitting points. Ideally, the dictionary keys would be 2D Numpy arrays of the fitting point coordinates, np.array([x, y]), but since Numpy arrays aren't hashable these are converted to tuples for the keys. # fit_pt_coords:... | There is no way to use traced JAX values as dictionary keys. The problem is that the key values will not be known until runtime within the XLA compiler, and XLA has no dictionary-like data structure that such lookups can be lowered to. There are imperfect solutions, such as keeping the dictionary on the host and using ... | 2 | 2 |
78,766,657 | 2024-7-18 | https://stackoverflow.com/questions/78766657/number-every-first-unique-piece-in-each-group | In each group, each 1st unique item should be given a different number in new column 'num'. I can form the groups but I don't know how to number the unique pieces. Is there a way to do that ? Unique numbers are: AF=1 / CT=2 / RT=4 / CTS=4 data = {'ATEXT': ['AF', 'AF', '', '', 'CT', 'RT', '', 'AF', 'AF', 'CTS', 'AF', 'A... | IIUC, I using a few intermediate columns to help with logic. Instead of using factorize you could use map to assign your unique numbers. Try: df['CODE'] = df['ATEXT'].mask(df['ATEXT'] == '').factorize()[0] + 1 df.loc[df['ATEXT'] == '', 'CODE'] = np.nan df['grp'] = df['ATEXT'].eq('').cumsum() df['Num'] = df.groupby('grp... | 2 | 2 |
78,758,516 | 2024-7-17 | https://stackoverflow.com/questions/78758516/where-to-put-checks-on-the-inputs-of-a-class | Where should I put checks on the inputs of a class. Right now I'm putting it in __init__ as follows, but I'm not sure if that's correct. See example below. import numpy as np class MedianTwoSortedArrays: def __init__(self, sorted_array1, sorted_array2): # check inputs ---------------------------------------------------... | General Validation You generally have two opportunities to inspect the arguments passed to a constructor expression: In the __new__ method, used for instance creation In the __init__ method, used for instance initialization You should generally use __init__ for initialization and validation. Only use __new__ in cases... | 2 | 3 |
78,757,191 | 2024-7-17 | https://stackoverflow.com/questions/78757191/multiprocessing-shared-memory-to-pass-large-arrays-between-processes | Context: I need to analyse some weather data for every hour of the year. For each hour, I need to read in some inputs for each hour before performing some calculation. One of these inputs is a very large numpy array x , which does not change and is the same for every hour of the year. The output is then a vector (1D nu... | Either Spyder itself or the IPython shell is trying to access one of your shared numpy arrays after the shared memory file has been closed. My first guess is that Spyder is trying to populate it's "Variable Explorer" pane by enumerating local variables. This causes an access to the numpy array, but the memory location ... | 2 | 2 |
78,766,426 | 2024-7-18 | https://stackoverflow.com/questions/78766426/export-pydantic-model-classes-not-instances-to-json | I understand that Pydantic can export models to JSON, see ref. But in practice, this means instances of a model: from datetime import datetime from pydantic import BaseModel class BarModel(BaseModel): whatever: int class FooBarModel(BaseModel): foo: datetime bar: BarModel m = FooBarModel(foo=datetime(2032, 6, 1, 12, 13... | Pydantic has built-in functionality to generate the JSON Schema of your models. This is a standardised format that other languages will have tooling to deal with. For example, with your definitions, running: import json print(json.dumps(FooBarModel.model_json_schema(), indent=2)) would output: { "$defs": { "BarModel":... | 2 | 3 |
78,763,342 | 2024-7-18 | https://stackoverflow.com/questions/78763342/compromise-between-quality-and-file-size-how-to-save-a-very-detailed-image-into | I am facing a small (big) problem: I want to generate a high resolution speckle pattern and save it as a file that I can import into a laser engraver. Can be PNG, JPEG, PDF, SVG, or TIFF. My script does a decent job of generating the pattern that I want: The user needs to first define the inputs, these are: ###########... | Let's make some observations of the effects of changing the DPI: DPI 1000 Height=1970 Width=1970 # Spots=140625 Raw pixels: 3880900 DPI 10000 Height=19690 Width=19690 # Spots=140625 Raw pixels: 387696100 We can see that while the number of spots drawn remains quite consistent (it does vary due to the various rounding ... | 5 | 7 |
78,765,505 | 2024-7-18 | https://stackoverflow.com/questions/78765505/how-to-use-overload-from-the-typing-package-within-a-higher-order-function-in-py | Returning an overloaded function from a higher-order callable does not produce expected results with respect to type hints: namely, the resulting function behaves as if it was unannotated at all. Here a minimal example: from typing import Optional, overload def get_f(b: int): @overload def f(x: int) -> str: ... @overlo... | You can create a type denoting an overloaded callable using typing.Protocol (read the PEP to learn more about structural subtyping): from typing import Optional, Protocol, overload class FProtocol(Protocol): @overload def __call__(self, x: int) -> str: ... @overload def __call__(self, x: int, c: bool) -> int: ... def g... | 2 | 4 |
78,764,991 | 2024-7-18 | https://stackoverflow.com/questions/78764991/how-do-i-merge-multiple-dataframes-and-sum-common-values-into-column | I have many dataframe like: df1 df2 and so on... gene | counts gene | counts KRAS 136 KRAS 96 DNAH5 3 DNAH5 4 TP53 105 TP53 20 I want to merge them and sum the column 'counts' so I end with only one dataframe merged_df gene | counts KRAS 232 DNAH5 7 TP53 125 I have tried to use pd.merge but it only accepts 2 datafram... | Indeed, pd.merge only merges 2 dataframes. But pd.join can join many, if they have the same index: # Some example data. Note the None in `df3`. We want our code to handle that well. df1 = pd.DataFrame({'gene': ['KRAS', 'DNAH5', 'TP53'], 'counts': [136, 3, 105]}) df2 = pd.DataFrame({'gene': ['KRAS', 'DNAH5', 'TP53'], 'c... | 3 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.