question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
77,418,144 | 2023-11-3 | https://stackoverflow.com/questions/77418144/for-each-element-of-2d-array-sum-higher-elements-in-the-row-and-column | My input dataframe (or 2D numpy array) shape is 11kx12k For each element, I check how many values are higher in the given row and column. For example: array([[1, 3, 1, 5, 3], [3, 7, 3, 2, 1], [2, 3, 1, 8, 9]]) row-wise: 3 1 3 0 1 1 0 1 3 4 3 2 4 1 0 column-wise: 2 1 1 1 1 0 0 0 2 2 1 1 1 0 0 total higher values for ... | I came up with the following: from scipy.stats import rankdata def element_wise_bigger_than(x, axis): return x.shape[axis] - rankdata(x, method='max', axis=axis) What you want is similar to a ranking of elements, which basically tells you how many items are smaller than a given element (maybe with subtracting 1 if you... | 3 | 2 |
77,416,929 | 2023-11-3 | https://stackoverflow.com/questions/77416929/can-i-use-the-same-lock-on-multiple-threads-if-they-do-not-access-the-same-varia | Imagine I have two threads, each modifying a different variable. Can I pass the same lock object to them, or shall I use two separate locks? In general, when shall I use multiple locks? Here is a toy example: from threading import Thread, Lock from time import sleep def task(lock, var): with lock: var = 1 sleep(5) lock... | Only one thread can hold a lock at a time, and a lock is used to provide mutually-exclusive access to a piece of data (or variable). Based on your example, where each thread accesses separate variables, you want two separate locks—one per variable. Note that if only one thread accesses a variable, though, you do not ne... | 2 | 2 |
77,416,725 | 2023-11-3 | https://stackoverflow.com/questions/77416725/unable-to-launch-selenium-encountering-deprecationwarning-and-webdriverexceptio | Suddenly today, Selenium could not be launched in my project. The error messages are as follows: main.py:11: DeprecationWarning: executable_path has been deprecated, please pass in a Service object driver = webdriver.Chrome(options=options,executable_path='drivers/chromedriver-linux64/chromedriver') Traceback (most rec... | In Selenium 4 executable_path is deprecated you have to use an instance of the Service() class with ChromeDriverManager().install() Deprecate all but Options and Service arguments in driver instantiation. (#9125,#9128) https://github.com/SeleniumHQ/selenium/blob/d6acda7c0254f9681574bf4078ff2001705bf940/py/CHANGES#L... | 2 | 2 |
77,415,734 | 2023-11-3 | https://stackoverflow.com/questions/77415734/cant-write-try-else-without-except-in-python | I want to write something shaped like this this except the invalid_task and work functions are of course written inline. unfinished_tasks = 0 async def worker(task): nonlocal unfinished_tasks unfinished_tasks += 1 try: if is_invalid(task): return None result = work(task) if is_error(result): raise Exception() return re... | For this case specifically you can use: unfinished_tasks = 0 async def worker(task): nonlocal unfinished_tasks try: if is_invalid(task): return None result = work(task) if is_error(result): raise Exception() return result except: unfinished_tasks += 1 For general cases pass can be used: try: ... except: pass else: ...... | 4 | 2 |
77,414,942 | 2023-11-3 | https://stackoverflow.com/questions/77414942/pandas-groupby-before-merge | I have dataframe like this. But there are about ten thousand rows. import pandas as pd import numpy as np data = {'gameId': [1, 1, 1, 1, 1, 2, 2, 2, 2, 2], 'eventId': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5], 'player': ['A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E'], 'related_eventId': [2, 1, 4, 3, np.nan, 2, 1, 4, 3, np.nan]... | Add column to list ['eventId', 'player','gameId'] and to parameters left_on and right_on: result = df.merge(df[['eventId', 'player','gameId']], left_on=['gameId','related_eventId'], right_on=['gameId','eventId'], how='left', suffixes=('', '_related')) result.rename(columns={'player_related': 'related_player', 'eventId_... | 4 | 6 |
77,410,905 | 2023-11-2 | https://stackoverflow.com/questions/77410905/visual-studio-code-terminal-shows-multiple-conda-envs | I have VSCode in Windows 11. I have WSL (Ubuntu 22.04) and launch VSCode from the terminal like code . from the project folder. When I open the built-in terminal it shows two conda (Anaconda) environments in parentheses, so I have no idea which one is active, if any. On subsequent conda deactivate you can see in the at... | It turns out that I had to delete ~/.vscode-server directory and let it being autogenerated again on the next code . run. I also had to click the "Inherit Env" setting of the built-in Terminal (I forgot, it may not be the default). With these steps, a newly launched VSCode behaves almost exactly like I expected: If th... | 20 | 2 |
77,412,437 | 2023-11-2 | https://stackoverflow.com/questions/77412437/pandas-dataframe-from-unique-numpy-elements | I want to construct a pandas dataframe where columns have elements from specified arrays with unique elements only. I want to find the most efficient pythonic way of doing this. For example, I have the following numpy arrays as input: a = np.array(["a1"]) b = np.array(["b1", "b2"]) c = np.array(["c1", "c2", "c3"]) Bel... | Use itertools.product: from itertools import product df = pd.DataFrame(product(a, b, c), columns=['a', 'b', 'c']) Output: a b c 0 a1 b1 c1 1 a1 b1 c2 2 a1 b1 c3 3 a1 b2 c1 4 a1 b2 c2 5 a1 b2 c3 Alternative with MultiIndex.from_product: df = pd.MultiIndex.from_product([a, b, c], names=['a', 'b', 'c'] ).to_frame(index... | 2 | 1 |
77,412,205 | 2023-11-2 | https://stackoverflow.com/questions/77412205/count-number-of-values-less-than-value-in-another-column-in-dataframe | Given a dataframe like the one below, for each date in Enrol Date, how can I count the number of values in preceding rows in Close Date that are earlier? Ideally I would like to add the results as a new column. Class Enrol Date Close Date A 30/10/2003 05/12/2003 A 22/12/2003 23/09/2005 A 06/09/2005 29/09/200... | A possible option using triu : cols = ["Enrol Date", "Close Date"] df[cols] = df[cols].apply(pd.to_datetime, dayfirst=True) enrol = df["Enrol Date"].to_numpy() close = df["Close Date"].to_numpy()[:, None] df["Prior Dates"] = np.triu(enrol>close).sum(0) Output : print(df) Class Enrol Date Close Date Prior Dates 0 A 200... | 3 | 5 |
77,410,366 | 2023-11-2 | https://stackoverflow.com/questions/77410366/apple-silicon-m2-error-could-not-build-wheels-for-lightgbm-which-is-required-t | I am experiencing an issue with installing lighgbm on Apple Silicon, the full installation process is as follows: python3 -m pip install lightgbm Defaulting to user installation because normal site-packages is not writeable Collecting lightgbm Using cached lightgbm-4.1.0.tar.gz (1.7 MB) Installing build dependencies ..... | I found the solution, basically I deleted the python that was installed and installed the python with homebrew then everything worked. | 2 | 0 |
77,409,035 | 2023-11-2 | https://stackoverflow.com/questions/77409035/get-layer-of-shape-in-visio-in-python | I'm trying to select all shapes within an existing Visio-file that are i. e. in layer "help" to delete them. Is there a way to achive that using python package "vsdx"? | You can use CreateSelection method with parameter visSelTypeByLayer = 3. Right now I haven't Python environment there, my simple VBA code Sub SOF_77409035() Dim Sh As Shape Dim sl As Selection ActiveWindow.DeselectAll ' deselect all Set sl = ActivePage.CreateSelection(3, 0, "help") ' create selection in memory For Each... | 2 | 3 |
77,410,154 | 2023-11-2 | https://stackoverflow.com/questions/77410154/how-to-format-currency-column-in-streamlit-for-dataframes | I have the following piece of code: import pandas as pd import streamlit as st cashflow = pd.DataFrame(data=[ (2023, 10000), (2022, 95000), (2021, 90000), (2020, 80000), ], columns=['year', 'cashflow']) st.dataframe( data=cashflow, column_config={ 'year': st.column_config.NumberColumn(format='%d'), 'cashflow': st.colum... | Prefer use the Styler instead of the DataFrame: import pandas as pd import streamlit as st cashflow = pd.DataFrame(data=[ (2023, 10000), (2022, 95000), (2021, 90000), (2020, 80000), ], columns=['year', 'cashflow']) st.dataframe( data=cashflow.style.format({'cashflow': '${:,}'}), # <- HERE ) Output: | 3 | 2 |
77,403,707 | 2023-11-1 | https://stackoverflow.com/questions/77403707/how-to-combine-filter-conditions-in-polars | In this example Pokémon data, let's say we want to exclude any Pokémon that is both Type 1 = Dragon and Total = 600. That means we want to exclude just one record (highlighted below): import polars as pl df = pl.read_csv("https://gist.githubusercontent.com/ritchie46/cac6b337ea52281aa23c049250a4ff03/raw/89a957ff3919d90e... | The error is happening because when you use multiple conditions you need to wrap then in parenthesis. Nevertheless to get rid of that single line the proper way is: df.filter((pl.col("Type 1") != "Dragon") | (pl.col("Total") != 600)) Using a parenthesis over both conditions, and use instead of & the operator | (OR) op... | 2 | 4 |
77,405,100 | 2023-11-1 | https://stackoverflow.com/questions/77405100/immortal-objects-in-python-how-do-they-work | Recently I came across PEP 683 – Immortal Objects, Using a Fixed Refcount https://peps.python.org/pep-0683/ What I figured out that objects like None, True, False will be shared across interpreter instead of creating copies. These were already immutable, weren't they? Can someone please explain in easy terms. Thanks. | That PEP is about CPython, which is the reference implementation of Python. As such, it talks about things on a very different level than what most of us are thinking about. CPython keeps track of how many references there are to any given object (the refcount). If you do something like a = some_expression(), the objec... | 2 | 3 |
77,403,801 | 2023-11-1 | https://stackoverflow.com/questions/77403801/make-a-httpx-get-request-with-data-body | When I do a curl request for GET endpoint of a REST API, I would go it like this curl -X 'GET' \ 'http://localhost:8000/user/?limit=10' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '[ { "item_type": "user", "skip": 0 } ]' Directly translated into requests, I would get import requests head... | According to the httpx docs, .get doesn't support request bodies. It suggests you use the more generic .request function instead. The HTTP GET, DELETE, HEAD, and OPTIONS methods are specified as not supporting a request body. To stay in line with this, the .get, .delete, .head and .options functions do not support con... | 2 | 3 |
77,403,294 | 2023-11-1 | https://stackoverflow.com/questions/77403294/how-can-i-use-commas-inside-a-csv-column-to-separate-multiple-floating-point-val | I have a question that is closely related to this question here: How to convert .wav files into a Pandas DataFrame in order to feed it to a neural network? I have created a pandas DataFrame with the following code: df = pd.DataFrame(data={"wavsamples": pd.Series(wavsamples), "wavsamplerate": pd.Series(wavsamplerate), "... | The CSV format will not support list types in a column, you need scalar values. What happens here is that pandas will implicitly cast that column containing the list type to a string. It has nothing to do with your chosen delimiter. One possible way to handle this if you have to have CSV format is to parse it back to a... | 3 | 2 |
77,400,070 | 2023-11-1 | https://stackoverflow.com/questions/77400070/add-missing-value-of-pair | I have a dataframe: [{'Date': Timestamp('2023-01-01 00:00:00'),'Sex':'M', 'Value':11, 'Target':5, 'A':48}, {'Date': Timestamp('2023-01-01 00:00:00'),'Sex':'F', 'Value':25, 'Target':7, 'A':20}, {'Date': Timestamp('2023-01-10 00:00:00'),'Sex':'M', 'Value':45, 'Target':6, 'A':20}, {'Date': Timestamp('2023-01-10 00:00:00')... | You can perform a double merge, once to combine the dates and M/F, then to add the missing combinations to the original data. out = (df[['Date']] .drop_duplicates() .merge(pd.Series(['M', 'F'], name='Sex'), how='cross') .merge(df, how='left').fillna(0).convert_dtypes() ) Alternatively, using janitor's complete: import... | 3 | 2 |
77,401,175 | 2023-11-1 | https://stackoverflow.com/questions/77401175/how-to-make-flake8-ignore-syntax-within-strings | I'm suddenly getting flake8 errors for syntax within strings. For example, for the following line of code: tags.append(f'error_type:{error.get("name")}') I'm getting this error: E231 missing whitespace after ':'. I don't want to ignore all E231 errors, because I care about them when they don't refer to text within st... | This issue seems limited to Python 3.12+ and it was fixed by flake8 version 6.1.0. The errors stopped appearing when I upgrade to flake8 6.1.0. | 10 | 23 |
77,401,947 | 2023-11-1 | https://stackoverflow.com/questions/77401947/fill-null-values-with-the-closest-non-null-value-from-other-columns | I have the following polars dataframe import polars as pl data = { "product_id": ["1", "2", "3", "4", "5", "6", "7", "8", "9"], "col1": ["a", "a", "a", "a", "a", "a", "a", "a", "a",], "col2": ["b", None, "b", None, "b", None, "b", None, "b"], "col3": ["c", None, "c", None, None, None, None, None, None], "col4": [None, ... | It looks like "closest" means to favor the higher numbered columns ie 4,3,2,1. You can do that with just a coalesce df.with_columns( desired_column=pl.coalesce( 'col4', 'col3', 'col2', 'col1' ) ) shape: (9, 6) ┌────────────┬──────┬──────┬──────┬──────┬────────────────┐ │ product_id ┆ col1 ┆ col2 ┆ col3 ┆ col4 ┆ desired... | 2 | 4 |
77,399,830 | 2023-11-1 | https://stackoverflow.com/questions/77399830/python-script-is-unable-to-see-environment-variable-injected-by-docker | I have instructed Docker to inject an environment variable called "INJECT_THIS" using two different methodologies (env.list file via 'docker run', and Dockerfile). My Dockerfile's RUN command invokes a Python file (run.py), but the environment variable is not seen by the Python code's os.environ object: environ({'OLDPW... | When you do docker inspect <your image name> you will see, there's ENTRYPOINT specified. This entrypoint messes with environment variables. You can specify your ENTRYPOINT instead of CMD (note I removed the spaces in ENV): FROM linuxserver/blender WORKDIR /app ENV INJECT_THIS="inject this" COPY run.py ./ RUN apt-get up... | 3 | 2 |
77,390,826 | 2023-10-30 | https://stackoverflow.com/questions/77390826/sqlalchemy-error-invalidrequesterror-cant-operate-on-closed-transaction-insi | I'm encountering an issue while working with SQLAlchemy in a FastAPI project. I've set up a route that's supposed to add items to a database using a context manager and nested transactions. If a single item is failed to be added (due to constraints or any reason) it should not be included in the commit. However the rem... | Summary The error is caused by the rollbacks inside the except blocks. They roll back the outer transaction, rendering the outer context manager unusable. The inner transaction created by begin_nested() will roll back automatically if an exception occurs, so there is no need to roll back the outer transaction. Detail ... | 3 | 0 |
77,363,596 | 2023-10-26 | https://stackoverflow.com/questions/77363596/how-to-get-more-word-suggestions-from-hunspell-with-pyhunspell | I'm using hunspell with the pyhunspell wrapper. I'm calling: hunspell.suggest("Yokk") But this is returning only ["Yolk", "Yoke"]. I saw that "York" is in the dictionary but is not being returned. Is there a way to return more than 2 suggestions, either by increasing the distance threshold or the number of top suggest... | I have installed 2020 dictionaries from this link: http://wordlist.aspell.net/dicts/ the newest dictionaries available here: https://github.com/LibreOffice/dictionaries Then tested the code: import hunspell #0.5.5 hobj = hunspell.HunSpell('./en_US.dic', './en_US.aff') tt = hobj.suggest("Yokk") print(tt) And got the ou... | 4 | 2 |
77,364,550 | 2023-10-26 | https://stackoverflow.com/questions/77364550/attributeerror-module-pkgutil-has-no-attribute-impimporter-did-you-mean | Earlier I installed some packages like Matplotlib, NumPy, pip (version 23.3.1), wheel (version 0.41.2), etc., and did some programming with those. I used the command C:\Users\UserName>pip list to find the list of packages that I have installed, and I am using Python 3.12.0 (by employing code C:\Users\UserName>py -V). I... | Due to the removal of the long-deprecated pkgutil.ImpImporter class, the pip command may not work for Python 3.12. You just have to manually install pip for Python 3.12 python -m ensurepip --upgrade python -m pip install --upgrade setuptools python -m pip install <module> In your virtual environment: pip install --upg... | 206 | 290 |
77,385,142 | 2023-10-29 | https://stackoverflow.com/questions/77385142/using-a-pipe-symbol-in-typing-literal-string | I have a function that accepts certain literals for a specific argument: from typing import Literal def fn(x: Literal["foo", "bar", "foo|bar"]) -> None: reveal_type(x) The third contains a pipe symbol (|), "foo|bar". This is interpreted by mypy as an error, as the name foo is not defined. I guess this happens due to h... | This bug is now fixed. The change hasn't been released yet, however. | 5 | 2 |
77,391,156 | 2023-10-30 | https://stackoverflow.com/questions/77391156/custom-labels-in-vertex-ai-pipeline-pipelinejobschedule | I would like to know the steps involved in adding custom labels to a Vertex AI pipeline’s PipelineJobSchedule. Can anyone please provide me with the necessary guidance as it's not working when I am adding inside the Pipelinejob parameters? # https://cloud.google.com/vertex-ai/docs/pipelines/schedule-pipeline-run#create... | There was a bug in the Vertex AI platform SDK which has been discussed in the Github issue ticket below. It has been fixed in SDK versions 1.37.0 (released on December 5th, 2023). GitHub Issue ticket https://github.com/googleapis/python-aiplatform/issues/2929 | 3 | 1 |
77,388,920 | 2023-10-30 | https://stackoverflow.com/questions/77388920/error-could-not-build-wheels-for-aiohttp-which-is-required-to-install-pyprojec | Newbie here. I have been trying to installen the openai library into python, but I keep running into problems. I have already installed C++ libraries. It seems to have problems specific with aio http, and I get the error below. I a running a Windows 11 laptop without admin restrictions. Error "C:\Program Files (x86)\Mi... | Either use python 3.11 or pip install aiohttp==3.9.0b0 installs their current beta release that supports python 3.12.x then try openai installation Link to git :https://github.com/KillianLucas/open-interpreter/issues/581 | 9 | 10 |
77,362,308 | 2023-10-25 | https://stackoverflow.com/questions/77362308/whats-the-difference-between-pip3-install-e-and-python3-setup-py-develop | When installing a Python package locally in editable mode, both 'pip3 install -e .', and 'python3 setup.py develop', will both install the package locally in editable mode. I know that 'pip3 install -e .' is recommended over 'python3 setup.py develop', but I am unclear as to why and what the differences are between the... | At this point in time, trying to get an accurate description of the differences between python setup.py install and python -m pip install seems rather pointless. python setup.py develop and python setup.py install originate from a time before pip existed. The behavior of these commands has not been kept up to date with... | 2 | 4 |
77,371,281 | 2023-10-27 | https://stackoverflow.com/questions/77371281/why-does-unittests-mock-patch-start-re-run-the-function-in-which-the-patcher | Let's say we have two files: to_patch.py from unittest.mock import patch def patch_a_function(): print("Patching!") patcher = patch("to_be_patched.function") patcher.start() print("Done patching!") to_be_patched.py from to_patch import patch_a_function def function(): pass patch_a_function() function() And we run pyt... | Why isn't Done patching! ever printed? Can not reproduce. $ python -m to_be_patched Patching! Patching! Done patching! Done patching! Why is Patching! printed twice? Your module gets imported twice. If you add print(__name__) into the file to_be_patched.py it will be clear: from to_patch import patch_a_functio... | 2 | 2 |
77,358,061 | 2023-10-25 | https://stackoverflow.com/questions/77358061/how-does-ctrl-c-work-with-multiple-processes-in-python | I am trying to distribute work across multiple processes. Exceptions that occur in another process should be propagated back and handled in the main process. This seems to work for exceptions thrown in worker, but not for Ctrl-C. import time from concurrent.futures import ProcessPoolExecutor, Future, wait import traceb... | It wasn't clear to me whether you want your worker function to continue running until completion (normal or abnormal) ignoring any Ctrl-C events. Assuming that to be the case, the following code should work under both Linux and Windows. The idea is to use a "pool initializer", i.e. a function that will run in each pool... | 3 | 1 |
77,397,920 | 2023-10-31 | https://stackoverflow.com/questions/77397920/python-poetry-cant-publish-to-google-artifact-registry-repository-the-reque | I have a proprietary Python project that I manage using Poetry. I stored the code in the Google Artifact Registry in the past, but now I switched to a different dev environment (Arch Linux in a VM -> Windows + Ubuntu WSL) and I can't upload it the AR, while getting this error (this is on my new WSL machine): $ poetry p... | As @robert-g commented, the solution can be found in https://github.com/python-poetry/poetry/issues/7545 For posterity, this fixed my issue: poetry config http-basic.my-repo oauth2accesstoken $(gcloud auth print-access-token) | 3 | 7 |
77,371,521 | 2023-10-27 | https://stackoverflow.com/questions/77371521/making-function-single-threaded-and-running-in-background | I am trying to implement in-memory queue like Kafka using Python using concepts like re-entrant locks and threads. I am new to Python threading. I have a consumer which will subscribe to the topic and read a message from it. So far it's working fine but I have doubts related to threading. I am trying to make the consum... | When you create a consumer object you are creating a new thread as part of startup: class ConsumerImpl: ... def __init__(self, consumerName:str): ... self.threadInit() def threadInit(self): thread = Thread(target = self._consumerRunner) thread.start() ... This will execute _consumerRunner on a new thread. This method ... | 2 | 4 |
77,387,669 | 2023-10-30 | https://stackoverflow.com/questions/77387669/how-can-i-concat-strings-that-might-be-empty | Currently I am trying to concat three strings in my Ansible playbook. Two of them can be unset (None/null) and I need them to be separated by underscores. Here is an example: type_mode="A", level_mode=None, and what_to_run="C" combines to A_C. If both where None it would just be C, if all where set it would be A_B_C. M... | Make a list out of your strings: [type_mode, level_mode, what_to_run] Exclude the blank parts with the help of the select filter: [type_mode, level_mode, what_to_run] | select Join the remaining chunks [type_mode, level_mode, what_to_run] | select | join('_') Your set_fact task ends up being: - set_fact: name: ... | 2 | 4 |
77,397,374 | 2023-10-31 | https://stackoverflow.com/questions/77397374/using-index-better-than-sequential-scan-when-every-hundredth-row-is-needed-but | I have a table (under RDS Postgres v. 15.4 instance db.m7g.large): CREATE TABLE MyTable ( content_id integer, part integer, vector "char"[] ); There is a B-Tree index on content_id. My data consists of 100M rows. There are 1M (0 .. 10^6-1) different values of content_id. For each value of content_id there are 100 (0..... | plans 2 vs 3 The difference between plans 2 (literal IN list with bitmap) and 3 (generate_series with bitmap) is easy to explain. PostgreSQL doesn't know how to parallelize the function scan over generate_series, so it doesn't use parallelization in that case. This is indicated by the lack of a "Gather..." node in that... | 2 | 1 |
77,390,094 | 2023-10-30 | https://stackoverflow.com/questions/77390094/how-to-use-user-profile-with-seleniumbase | Code: from seleniumbase import Driver driver = Driver(uc=True) driver.get("https://example.com") driver.click("a") p_text = driver.find_element("p").text print(p_text) this code works fine but i want to add a user profile but when i try from seleniumbase import Driver ud = r"C:\Users\USER\AppData\Local\Google\Chrome\U... | Partially due to reasons outlined in https://stackoverflow.com/a/67960202/7058266, the best way to handle multiple profiles is to have a unique user-data-dir for each one. Also, since you're using SeleniumBase UC Mode, for reasons outlined in https://www.youtube.com/watch?v=5dMFI3e85ig at the 21-minute mark, don't mix ... | 5 | 3 |
77,398,359 | 2023-10-31 | https://stackoverflow.com/questions/77398359/iterate-through-dataframe-and-create-new-column-based-if-values-in-columns-are-n | df = pd.DataFrame({ 'subsegment': ['corp', np.nan, 'terr'], 'region': ['japan', np.nan, np.nan], 'subregion': [np.nan, 'se', 'ne'], 'segment': [np.nan,'ent','comm'] }) I am trying to iterate through the above dataframe and if the value is not NaN than adding the column header as the value or part of the value (dependi... | You can use a dot product: df['mode'] = (df.notna() @ (df.columns+'-')).str[:-1] Output: subsegment region subregion segment mode 0 corp japan NaN NaN subsegment-region 1 NaN NaN se ent subregion-segment 2 terr NaN ne comm subsegment-subregion-segment Alternatively, with a classical groupby.agg: s = df.notna().stack... | 3 | 7 |
77,392,627 | 2023-10-31 | https://stackoverflow.com/questions/77392627/how-to-bar-plot-the-top-n-categories-for-each-year | I am trying to plot a bar graph which highlights only the top 10 areas in Auckland district by the money spent on gambling. I have written the code to filter for the top 10 areas and also plot a bar plot in Seaborn. The issue is that the x-axis is crowded with labels of every area in Auckland district from the datafram... | seaborn is a high-level API for matplotlib, and pandas uses matplotlib as the default plotting backend. In this case, it's more direct to plot with pandas.DataFrame.plot, and avoid the extra import and dataframe reshaping. .pivot_table is used to reshape the dataframe and aggregate multiple values with 'mean'. The ... | 2 | 2 |
77,397,466 | 2023-10-31 | https://stackoverflow.com/questions/77397466/polars-python-select-based-on-dtype-pl-list | Hi I want to select those cols of a polars df that are of the dtype list. Selecting by dtypes works ususally fine with df.select(pl.col(pl.Utf8)). However for the type list this does not seem to work... MRE import polars as pl df = pl.DataFrame({"foo": [[c] for c in ["100CT pen", "pencils 250CT", "what 125CT soever", "... | You need to provide the type of the items in the List unlike primitive types (where print(df.select(pl.col(pl.Int64))) would work in the below example). import polars as pl df = pl.DataFrame({ "foo": [[c] for c in ["100CT pen", "pencils 250CT", "what 125CT soever", "this is a thing"]], "bar": [1, 2, 3, 4] } ) print(df.... | 2 | 3 |
77,385,587 | 2023-10-29 | https://stackoverflow.com/questions/77385587/persist-parentdocumentretriever-of-langchain | I am using ParentDocumentRetriever of langchain. Using mostly the code from their webpage I managed to create an instance of ParentDocumentRetriever using bge_large embeddings, NLTK text splitter and chromadb. I added documents to it, so that I c embedding_function = HuggingFaceEmbeddings(model_name='BAAI/bge-large-en-... | I had the same problem and found the solution here: https://github.com/langchain-ai/langchain/issues/9345 You need to use the create_kv_docstore() function like this: from langchain.storage._lc_store import create_kv_docstore fs = LocalFileStore("./store_location") store = create_kv_docstore(fs) parent_splitter = Recur... | 6 | 6 |
77,396,921 | 2023-10-31 | https://stackoverflow.com/questions/77396921/sum-multiple-columns-in-pandas-dataframe-without-losing-data-types | I have a pandas DataFrame that is typically grouped on a level (or several) of the MultiIndex, then summed. This produces a DataFrame where the rows correspond to the unique values in the grouping level(s), as expected. However, for my application, I am trying to allow for there to be no grouping while maintaining the ... | sum returns a Series, which is why you have a single dtype. You can use agg passing a list to force a DataFrame output: df.agg(['sum']) Output: x y sum 10 10.6 A simpler version of the dummy grouper would be: df.groupby([0]*len(df)).sum() Output: x y 0 10 10.6 | 3 | 3 |
77,394,812 | 2023-10-31 | https://stackoverflow.com/questions/77394812/awaiting-request-json-in-fastapi-hangs-forever | I added the exception handling as given here (https://github.com/tiangolo/fastapi/discussions/6678) to my code but I want to print the complete request body to see the complete content. However, when I await the request.json() it never terminates. request.json() returns a coroutine, so I need to wait for the coroutine ... | When awaiting request.json, you are trying to read the request body (not the response body, as you may have assumed) out from stream; however, this operation has already taken place in your API endpoint (behind the scenes, in your case). Hence, calling await request.json() is allowed only once in the API's request life... | 4 | 5 |
77,387,280 | 2023-10-30 | https://stackoverflow.com/questions/77387280/performance-issue-with-low-microservice-utilization-in-k8s-impact-to-developmen | When I designed microservice and made deployment to K8s, I saw that I had problem to get higher utilization for my microservices (max. utilization was only 0.1-0.3 CPU). Do you have best practices, how can we increase microservice CPU utilization? Let me describe the LAB environment: K8s with 5 nodes each node with 1... | Performance testing is a very complex topic, it requires a lot of precision when building the testing setup, and solid knowledge for all the building parts, since it's very easy to mess things up (I did that many times). Couple of ideas from my side: If you run a single-threaded app on a pod with more than 1 CPU confi... | 2 | 2 |
77,391,095 | 2023-10-30 | https://stackoverflow.com/questions/77391095/how-to-calculate-time-difference-from-previous-value-change-in-pyspark-dataframe | Suppose I have the following dataframe in pyspark: object time has_changed A 1 0 A 2 1 A 4 0 A 7 1 B 2 1 B 5 0 What I want is to add a new column that, for each row, keeps track of the time difference with respect to the last value change for the current object (or first element of the correspondi... | Step by step solution Create a window specification W = Window.partitionBy('object').orderBy('time') Mask the values in time column where has_changed is 0 masked = F.when(F.col('has_changed') == 1, F.col('time')) df = df.withColumn('masked', masked) # +------+----+-----------+------+ # |object|time|has_changed|masked|... | 2 | 2 |
77,392,718 | 2023-10-31 | https://stackoverflow.com/questions/77392718/is-there-a-way-to-expand-an-array-like-a-struct-in-pyspark-star-does-not-work | I have a data frame with the following nesting in Pyspark: >content: struct importantId: string >data: array >element: struct importantCol0: string importantCol1: string I need the following output: importantId importantCol0 importantCol1 10800005 0397AZ 0397AZ 10800006 0397BZ 0397BZ I tried the followin... | Let us use inline to explode array of structs to columns and rows result = df.select('*', F.inline('data')).drop('data') Example, df.show() +------------+--------------------+ |importantCol| data| +------------+--------------------+ | 1| [{1, 2}, {4, 3}]| | 2|[{10, 20}, {40, 30}]| +------------+--------------------+ r... | 3 | 3 |
77,392,792 | 2023-10-31 | https://stackoverflow.com/questions/77392792/is-there-a-way-to-interpolate-variables-into-a-python-string-without-using-the-p | Every example I have seen of Python string variable interpolation uses the print function. For example: num = 6 # str.format method print("number is {}".format(num)) # % placeholders print("number is %s"%(num)) # named .format method print("number is {num}".format(num=num)) Can you interpolate variables into strings w... | Ok...so, it's kind of easy. The old method: num = 6 mystr = 'number is %s' % num print(mystr) # number is 6 The newer .format method: num = 6 mystr = "number is {}".format(num) print(mystr) # number is 6 The .format method using named variable (useful for when sequence can't be depended upon): num = 6 mystr = "number... | 7 | 9 |
77,392,339 | 2023-10-30 | https://stackoverflow.com/questions/77392339/select-top-n-groups-in-pandas-dataframe | I have the following dataframe: Country Crop Harvest Year Area (ha) Afghanistan Maize 2019 94910 Afghanistan Maize 2020 140498 Afghanistan Maize 2021 92144 Afghanistan Winter Wheat 2019 2334000 Afghanistan Winter Wheat 2020 2668000 Afghanistan Winter Wheat 2021 1833357 Argentina Maize 2019 7232761 Argentina Maize 2020... | IIUC, you can do double .groupby: x = ( df.groupby("Crop") .apply(lambda x: x.groupby("Country")["Area (ha)"].mean()) .stack() .groupby(level=0, group_keys=False) .nlargest(2) ) print(x) Prints top 2 Crop/Countries by average area: Crop Country Maize China 4.198587e+07 India 9.485397e+06 Winter Wheat India 3.076193e+0... | 2 | 1 |
77,392,276 | 2023-10-30 | https://stackoverflow.com/questions/77392276/is-it-possible-to-make-django-urlpatterns-from-a-string | I have a list of strings that is used to define navigation pane in a Django layout template. I want to use the same list for view function names and use a loop to define urlpatterns in urls.py accordingly. Example: menu = ["register", "login", "logout"] urlpatterns = [path("", views.index, name="index"),] From the abo... | Yes, you can use: menu = ['register', 'login', 'logout'] urlpatterns = [ path('', views.index, name='index'), *[path(f'{name}/', getattr(views, name), name=name) for name in menu], ] | 2 | 2 |
77,391,553 | 2023-10-30 | https://stackoverflow.com/questions/77391553/extract-all-field-names-from-nested-dataclasses | I have a dataclass that contains within it another dataclass: @dataclass class A: var_1: str var_2: int @dataclass class B: var_3: float var_4: A I would like to create a list of all field names for attributes that aren't dataclasses, and if the attribute is a dataclass the to list the attributes of that class, so in ... | Use dataclasses.fields() to iterate over all the fields, making a list of their names. Use dataclasses.is_dataclass() to tell if a field is a nested dataclass. If so, recurse into it instead of adding its name to the list. from dataclasses import fields, is_dataclass def all_fields(c: type) -> list[str]: field_list = [... | 2 | 4 |
77,391,383 | 2023-10-30 | https://stackoverflow.com/questions/77391383/resamplew-weird-results | I have a pandas DataFrame containing daily dates, and within this DataFrame, some dates are missing. I aim to generate a new time series that includes only the last day of each week from that DataFrame. For instance, if there are only Wednesday and Thursday entries for a specific week, the resulting time series should ... | You can use the isocalendar() method to get the week of the year, and then group on that: df = pd.DataFrame({'date': date_rng, 'value': data}) df['week'] = df['date'].dt.isocalendar().week grouped = df.groupby('week').last().set_index('date') weekly_last = grouped['value'].copy() Then you get the expected result: >>> ... | 2 | 1 |
77,390,600 | 2023-10-30 | https://stackoverflow.com/questions/77390600/calling-same-function-by-different-objects-by-pressing-different-key-in-python | I have created two turtles say 'tur1' and 'tur2' in python using turtle module. I have created event listener on the screen. I have created a function 'move_fwd(turte_name)' which moves the turtle forward by 20 steps. I want that if key 'w' is pressed then this method shoud be called by 'tur1' and tur1 should move and ... | Use a lambda screen.onkey(lambda: move_fwd(tur1), "w") screen.onkey(lambda: move_fwd(tur2), "i") | 2 | 2 |
77,387,525 | 2023-10-30 | https://stackoverflow.com/questions/77387525/create-a-objective-function-to-minimize-the-number-of-maximum-task-assigned-and | I've a set of student and task which I wish to assign. How can I add an objective function so that I get a balance number of task assigned to each student? Subsequently, I will also add some constraints to restrict certain student(s) from receiving certain task hence I would like to balance out the task per student as ... | You can have a look at the balance_group example. It uses this trick to minimize the spread e = model.NewIntVar(0, 550, "epsilon") # Constrain the sum of values in one group around the average sum per group. for g in all_groups: model.Add( sum(item_in_group[(i, g)] * values[i] for i in all_items) <= average_sum_per_gr... | 2 | 2 |
77,387,556 | 2023-10-30 | https://stackoverflow.com/questions/77387556/equivalent-pandas-dataframe-in-javascript | Do you know what is the equivalent for javascript ? This is my code : def sort_df(datas): df_not_sorted = pd.read_json(StringIO(datas)) df_not_sorted["Date"] = df_not_sorted["Date"].apply(lambda dates: [datetime.fromisoformat(date.rstrip('Z')) for date in dates]) df_not_sorted["time"] = pd.to_datetime(df_not_sorted["ti... | You can use Danfo.js: Danfo.js is heavily inspired by the Pandas library and provides a similar interface and API. This means users familiar with the Pandas API can easily use Danfo.js. https://danfo.jsdata.org/ https://danfo.jsdata.org/getting-started | 4 | 2 |
77,386,620 | 2023-10-30 | https://stackoverflow.com/questions/77386620/is-it-possible-to-call-pyright-from-code-as-an-api | It seems that Pyright (the Python type checker made by Microsoft) can only be used as a command line tool or from VS Code. But is it possible to call pyright from code (as an API)? For example, mypy supports usage like: import sys from mypy import api result = api.run("your code") | like @Grismar said, this might be an xy problem... if not, here is a general solution: import subprocess command = ['pyright', 'path/to/your/file.py'] result = subprocess.run(command, capture_output=True, text=True) output = result.stdout print(output) | 2 | 3 |
77,384,806 | 2023-10-29 | https://stackoverflow.com/questions/77384806/pandas-conditionally-fill-a-column-using-values-from-another-dataframe | I have a dataframe containing costs for time periods: valid_from valid_to cost 2018-10-09 23:00:00 2019-09-30 23:00:00 28.6700 2019-09-30 23:00:00 2021-03-18 00:00:00 26.2700 2022-10-13 23:00:00 NaT 39.7339 If 'valid_to' is NaT it means the cost is still current. I want to add the correct cost to the ti... | The main idea is to get cost for rows where valid_from and valid_to overlap between the two dataframes - this is a form of inequality join which is effectively handled by conditional_join: # pip install pyjanitor import pandas as pd import janitor # fill df1's valid_to with a timestamp in the future df1.valid_to = df1.... | 3 | 1 |
77,385,134 | 2023-10-29 | https://stackoverflow.com/questions/77385134/tkinter-fullscreen-error-in-raspberry-pi-64-bits-os | I want to make a tkinter-based GUI in a RaspberryPi. I need it to be on a fullscreen mode. I have the following script: from tkinter import * win = Tk() win.geometry("650x250") label = Label(win, text="Hello World!", font=('Times New Roman bold', 20)) label.pack(padx=10, pady=10) # Utiliza wm_attributes para establecer... | As a workaround try to make the application fullscreen after some time, e.g.: Instead: win.wm_attributes('-fullscreen', 'true') try: win.after(1000, lambda: win.wm_attributes('-fullscreen', 'true')) | 2 | 3 |
77,362,703 | 2023-10-25 | https://stackoverflow.com/questions/77362703/how-to-plot-an-histogram-correctly-with-numpy-and-match-it-with-the-density-fun | TL;DR: How to plot the result of np.histogram(..., density=True) correctly with Numpy? Using density=True should help to match the histogram of the sample, and the density function of the underlying random variable, but it doesn't: import numpy as np import scipy.stats import matplotlib.pyplot as plt y = np.random.rand... | TL;DR: The default bar width of .bar() is too big (.hist() adjusts width internally). The number of bars is too high for the default figsize (that's why 100 bins is OK but 1000 is not). In Axes.hist, bar widths are computed by np.diff(bins) (source code). Since it allows a multi-dimensional array, there are a whole ... | 3 | 4 |
77,381,775 | 2023-10-29 | https://stackoverflow.com/questions/77381775/format-y-axis-as-trillions-of-u-s-dollars | Here's a Python program which does the following: Makes an API call to treasury.gov to retrieve data Stores the data in a Pandas dataframe Plots the data import requests import pandas as pd import matplotlib.pyplot as plt page_size = 10000 url = 'https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/acco... | I looked around for someone who did this in a nice looking way, and I found this graph on Wikipedia. I decided to do that. First, I converted the amount to a number. I found that your code for doing this conversion didn't work for me - it created a SettingWithCopy warning. rows = df[df['debt_held_public_amt'] != 'null'... | 2 | 1 |
77,379,001 | 2023-10-28 | https://stackoverflow.com/questions/77379001/efficient-computation-of-the-set-of-surjective-functions | A function f : X -> Y is surjective when every element of Y has at least one preimage in X. When X = {0,...,m-1} and Y = {0,...,n-1} are two finite sets, then f corresponds to an m-tuple of numbers < n, and it is surjective precisely when every number < n appears at least once. (When we require that every number appear... | Just optimized yours a little, mainly by using insert to build the tuple. About 5x faster than yours for m=9, n=7. def surjective_tuples(m: int, n: int) -> list[tuple]: """List of all m-tuples of numbers < n where every number < n appears at least once. Arguments: m: length of the tuple n: number of distinct values """... | 3 | 3 |
77,379,133 | 2023-10-28 | https://stackoverflow.com/questions/77379133/aggregate-string-column-close-in-time-in-pandas | I'm trying to group messages, which have been sent shortly after another. A parameter defines the maximum duration between messages for them to be considered part of a block. If a message is added to the block, the time window is extended for more messages to be considered part of the block. Example Input datetime... | Compare the current and previous datetime values to flag the rows where difference is greater than 1 min then apply cumulative sum on the flag to distinguish between different blocks of datetimes. Now, group the dataframe by these blocks and aggregate to get the result m = df['datetime'].diff() > pd.Timedelta(minutes=1... | 3 | 4 |
77,377,439 | 2023-10-27 | https://stackoverflow.com/questions/77377439/how-to-change-font-size-in-streamlit | I want to change the fontsize of the label above an input widget in my streamlit app. What I have so far: import streamlit as st label = "Enter text here" st.text_input(label) This renders the following: I want to make the label "Enter text here" bigger. I know there are various ways to change fontsize in st.write().... | Option 1: Components API So did a little digging and it turns out that streamlit has a components API which can be used to render an html string. So we can basically use a little javascript to change the font size of a specific label. Since labels are unique for each widget, we can simply search for the paragraph eleme... | 3 | 10 |
77,375,881 | 2023-10-27 | https://stackoverflow.com/questions/77375881/how-to-type-a-python-function-the-same-way-as-another-function | For writing a wrapper around an existing function, I want to that wrapper to have the same, or very similar, type. For example: import os def my_open(*args, **kwargs): return os.open(*args, **kwargs) Tye type signature for os.open() is complex and may change over time as its functionality and typings evolve, so I do n... | You could simply pass [the function you want to copy the signature of] into [a decorator factory] which produces a no-op decorator that affects the typing API of the decorated function. The following example can be checked on pyright-play.net (requires Python >= 3.12, as it uses syntax from PEP 695). from __future__ im... | 3 | 3 |
77,377,886 | 2023-10-28 | https://stackoverflow.com/questions/77377886/does-mypy-check-never-type-at-all | I was playing with Never type in mypy. If I have a function foo(x: int) I expected that when called with a value of type Never mypy would complain, but it silently typechecks the call: from typing import Never def foo(x: int): pass def bar(x: Never): foo(x) # ok, I exected a type error foo("foo") # err --- edit --- Ju... | This is normal. Never is a subtype of every other type. After all, Never is the type with no values. All values of Never type are values of every other type, because there are no values of Never type. | 2 | 3 |
77,376,677 | 2023-10-27 | https://stackoverflow.com/questions/77376677/why-does-datetime-module-behave-this-way-with-timezones | I am trying to work with time and timezones. I am in the US/Mountain time zone and my computer (Windows) is configured to that time zone. import datetime import zoneinfo utc = zoneinfo.ZoneInfo('UTC') mt = zoneinfo.ZoneInfo('US/Mountain') print(datetime.datetime.now()) print(datetime.datetime.now().astimezone(mt)) prin... | See the docs on astimezone: Return a datetime object with new tzinfo attribute tz, adjusting the date and time data so the result is the same UTC time as self, but in tz’s local time. If provided, tz must be an instance of a tzinfo subclass, and its utcoffset() and dst() methods must not return None. If self is naive,... | 2 | 1 |
77,376,535 | 2023-10-27 | https://stackoverflow.com/questions/77376535/how-to-sort-values-in-order-with-a-pandas-dataframe | I have a dataframe as follow: armed signs_of_mental_illness count gun False 628 gun True 155 knife False 142 vehicle False 104 knife True 84 metal pole True 1 metal rake True 1 I want to sort this dataframe as follow: armed signs_of_mental_illness count gun False 628 gun True 155 kni... | If you want to sort by the total per "armed", y first need to combine the counts with groupby.transform: import numpy as np order = np.lexsort([df['signs_of_mental_illness'], -df.groupby('armed')['count'].transform('sum')]) out = df.iloc[order] Alternative: out = (df.assign(total=df.groupby('armed')['count'].transform... | 2 | 2 |
77,375,755 | 2023-10-27 | https://stackoverflow.com/questions/77375755/how-can-i-dump-a-python-dataclass-to-yaml-without-tags | I have a nested dataclasses that I would like to convert and save to the yaml format using the PyYaml library. The resultant YAML output contains YAML tags which I would like to remove. I have the following Python code: from dataclasses import dataclass import yaml @dataclass class Database: host: str username: str pas... | When dumping instances of Python classes, PyYaml will serialize the contents and add a tag indicating the class in order to allow reading the yaml output back to the designated class. PyYaml does not tag native Python objects like lists and dicts, so by converting the dataclass instances to dictionaries with the asdict... | 5 | 4 |
77,375,606 | 2023-10-27 | https://stackoverflow.com/questions/77375606/separate-input-prompts-from-return-values-when-calling-python-script-inside-shel | I have a simple Python script that asks the user for an ID and returns a serial number: ... id = input("Enter ID (0-indexed):\n") ... print(serial_number) I'm using this .py script inside of a larger bash script via command substitution: serial_number=$(./get_serial_no.py) echo "$serial_number" The problem I'm facing... | I recommend against prompts if you are using a python script in a shell script. Use command-line options with a library such as argparse. It is so much easier, plus you get input validation as a bonus: import argparse parser.add_argument( '-s', '--serial_number', type = int, default = 12345, required = False, help = re... | 2 | 2 |
77,370,805 | 2023-10-26 | https://stackoverflow.com/questions/77370805/using-python-subprocess-to-open-powershell-causes-encoding-errors-in-stdout | I'm trying to run a Powershell script from python and print the output, but the output contains special characters "é". process = subprocess.Popen([r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe', 'echo é'], stdout=subprocess.PIPE) print(process.stdout.read().decode('cp1252')) returns "," process = subpro... | The powershell.exe, the Windows PowerShell CLI,[1] uses the active console window's code page to encode its stdout and stderr output, as reflected in the output from chcp, which by default is the legacy system locale's OEM code page, e.g. (expressed in Python terms) cp437. By contrast, the code page you used - cp1252 -... | 2 | 2 |
77,371,542 | 2023-10-27 | https://stackoverflow.com/questions/77371542/i-have-a-problem-with-python-in-vscode-typeerror-is-not-a-function | In VS Code, the latest Pylance extension (v2023.10.50) failed with this error: TypeError: _0x2f33cc[(_0x1efd68(...) + _0x1efd68(...))] is not a function (When I highlight on any line of code). I tried to delete some suspected libs but nothing happened. | The same error occurred when using Pylance v2023.10.50, and downgraded to v2023.10.40 and the problem was resolved. | 4 | 13 |
77,370,226 | 2023-10-26 | https://stackoverflow.com/questions/77370226/pyinstaller-generate-exe-file-outside-dist-folder | I'am using Pyinstaller package to build a python desktop app, however Pyinstaller seems to put the bundled exe file outside _internal folder is there a solution I can try ? Thanks in advance output by Pyinstaller _internal folder structure my goal is to package all the app in a folder (dist) that exe file must be insid... | From the update logs,on Pyinstaller's document:https://pyinstaller.org/en/stable/CHANGES.html#id2 it says: Restructure onedir mode builds so that everything except the executable (and if you’re using external PYZ archive mode) are hidden inside a sub-directory. This sub-directory’s name defaults to but may be configur... | 2 | 3 |
77,370,398 | 2023-10-26 | https://stackoverflow.com/questions/77370398/python-decimal-sum-returning-wrong-value | I'm using decimal module to avoid float rounding errors. In my case the values are money so I want two decimal places. To do that I do decimal.getcontext().prec = 2 but then I get some surprising results which make me think I'm missing something. In this code the first assertion works, but the second fails from decimal... | decimal does not implement fixed-point arithmetic directly. It implements base 10 floating-point arithmetic. The precision (prec) is the total number of significant digits retained and has nothing to do with the position of the radix point. Try displaying the computed value in your last example: >>> Decimal("3000") + D... | 2 | 4 |
77,370,358 | 2023-10-26 | https://stackoverflow.com/questions/77370358/python-check-if-value-in-tuple-fails-with-numpy-array | I've got a function that returns a tuple, and I need to check if a specific element is in the tuple. I don't know types of elements will be in the tuple, but I know that I want an exact match. For example, I want 1 in (1, [0, 6], 0) --> True 1 in ([1], 0, 6]) --> False This should be really straightforward, right? I j... | It breaks because if you in operator, Python under the hood is using the equality operator (==). Consider this: t = (2, np.array([0, 6]), 1) v = 1 print(v in t) Python checks each value in the tuple t for equality. For numpy array the operation 1 == np.array([0, 6]) is another boolean array [False False]. Python then ... | 5 | 2 |
77,368,894 | 2023-10-26 | https://stackoverflow.com/questions/77368894/python-packagenotfounderror-no-package-metadata-was-found-for-myproject | I have an existing python project and trying to debug in via Microsoft Visual Studio Code. Therefore I have the following launch.json: { "version": "0.2.0", "configurations": [ { "name": "Python: myproject", "type": "python", "request": "launch", "program": "E:\\<path>\\__main__.py", "cwd": "${workspaceFolder}", "env":... | After additional research it was just an only the following command, that helped: pip install -e . If someone has the same issue (the current project wasn't installed) | 2 | 7 |
77,367,745 | 2023-10-26 | https://stackoverflow.com/questions/77367745/numpy-and-linear-algebra-how-to-code-ax%ea%9e%8fy | I've some difficulty in matching what Numpy expects when performing the dot product and vector representation in linear algebra, in term of shapes. Let's say I've a matrix and two column vectors represented by Numpy arrays: import numpy as np A = np.array([[1,2], [3,1], [-5,2]]) x = np.array([[0], [2]]) y = np.array([[... | You can't compute a dot product between two (3, 1) arrays, a dot product A @ B is only valid if the shape of A and B are (n, k) and (k, m). It looks like you want: (A@x).T @ y Output: [[4]] Or as scalar: ((A@x).T @ y).item() Output: 4 NB. in the context of 2D arrays @ and dot are equivalent. Other operations that wo... | 3 | 4 |
77,366,058 | 2023-10-26 | https://stackoverflow.com/questions/77366058/sort-rows-in-sub-cluster-of-cluster-in-pandas-dataframe | I have a dataframe as below: Part Date Quantity A 2023-10-26 -1 A 2023-10-26 1 A 2023-11-03 1 A 2023-12-15 -1 B 2023-11-09 2 B 2023-11-14 -2 B 2023-11-14 2 B 2023-11-19 2 Each part is a cluster, and each date within a part is a sub-cluster. I want to order the Quantity values for each date for each part based on: posi... | Use key parameter in DataFrame.sort_values with specify column Quantity for False for positive values by compare bySeries.lt or Series.le: out = df.sort_values(['Part', 'Date', 'Quantity'], key=lambda x: x.le(0) if x.name=='Quantity' else x) print (out) Part Date Quantity 1 A 2023-10-26 1 0 A 2023-10-26 -1 2 A 2023-11-... | 3 | 4 |
77,362,216 | 2023-10-25 | https://stackoverflow.com/questions/77362216/add-startup-shutdown-handlers-to-fastapi-app-with-lifespan-api | Consider a FastAPI using the lifespan parameter like this: def lifespan(app): print('lifespan start') yield print('lifespan end') app = FastAPI(lifespan=lifespan) Now I want to register a sub app with its own lifecycle functions: app.mount(mount_path, sub_app) How can I register startup/shutdown handlers for the sub ... | I found a solution, but I'm not sure if I like it... It accesses the existing lifespan generator via app.router.lifespan_context and wraps it with additional startup/shutdown commands: from contextlib import asynccontextmanager ... main_app_lifespan = app.router.lifespan_context @asynccontextmanager async def lifespan_... | 8 | 7 |
77,363,773 | 2023-10-26 | https://stackoverflow.com/questions/77363773/append-string-to-list-directly-before-it-in-a-list-of-lists-and-strings | I have a list of lists and strings and would like to append the string elements into the list element directly before it. Below is a sample of the data. data = [['way','say','may','lay'], 'wake', ['hay','pay','yay'], 'lake', ['tay'], 'shake'] The desire output should be something like this: out = [['way','say','may','... | You could zip together the odd and even parts of data and use list addition of those parts to build your desired output: out = [odd + [even] for odd, even in zip(data[0::2], data[1::2])] Output: [ ['way', 'say', 'may', 'lay', 'wake'], ['hay', 'pay', 'yay', 'lake'], ['tay', 'shake'] ] | 3 | 2 |
77,363,316 | 2023-10-25 | https://stackoverflow.com/questions/77363316/how-to-resolve-issues-with-a-bar-plot-x-axis-being-overcrowded | Here's a Python program which does the following: Makes an API call to treasury.gov to retrieve data Stores the data in a Pandas dataframe Plots the data as a bar chart import requests import pandas as pd import matplotlib.pyplot as plt date = '1900-01-01' transaction_type = 'Withdrawals' transaction_catg = 'Interest... | The 'record_date' values are strings, not datetimes. df.record_date = pd.to_datetime(df.record_date) Typically, a line plot should be used for continuous timeseries data. Line Plot ax = df.plot(x='record_date', y='transaction_today_amt', figsize=(12, 7)) Scatter Plot ax = df.plot(kind='scatter', x='record_date',... | 3 | 1 |
77,361,304 | 2023-10-25 | https://stackoverflow.com/questions/77361304/fast-direct-pixel-access-in-python-go-or-julia | I wrote a small program that creates random noise and displays it full screen (5K resolution). I used pygame for it. However the refresh rate is horribly slow. Both the surfarray.blit_array and random generation take a lot of time. Any way to speed this up? I am also flexible to use julia or golang instead. or also psy... | Faster random number generation Generating random numbers is expensive. This is especially true when the random number generator (RNG) needs to be statistically accurate (i.e. random numbers needs to look very random even after some transformation), and when number are generated sequentially. Indeed, for cryptographic ... | 2 | 3 |
77,362,116 | 2023-10-25 | https://stackoverflow.com/questions/77362116/add-missing-index-dtype-string-to-value-counts-of-df-in-pandas | I can't seem to find this anywhere else, and I could be wording the question incorrectly, but I am getting the value counts for the 'Type' column in adf grouped by account ID and getting results like so: print(df_activities.groupby(['Account ID'])['Type'].value_counts().sort_index()) Account ID Type 0011N000017WOso Cal... | Instead of value_counts, use crosstab and stack: out = pd.crosstab(df['Account ID'], df['Type']).stack() For only specific types: types = ['Call', 'Email', 'LinkedIn', 'Meeting'] out = (pd.crosstab(df['Account ID'], df['Type']) .reindex(columns=types, fill_value=0).stack() ) Output: Account ID Type 0011N000017WOso Ca... | 2 | 2 |
77,357,723 | 2023-10-25 | https://stackoverflow.com/questions/77357723/how-can-i-create-xticks-with-varying-intervals | I am drawing a line chart using matplotlib as shown below. import matplotlib.pyplot as plt import pandas as pd import io temp = u""" tenor,yield 1M,5.381 3M,5.451 6M,5.505 1Y,5.393 5Y,4.255 10Y,4.109 """ data = pd.read_csv(io.StringIO(temp), sep=",") plt.plot(data['tenor'], data['yield']) Output: The tick intervals on... | In the column 'tenor', 'M' represents month and 'Y' represents year. Create a 'Month' column with 'Y' scaled by 12 Months. It's more concise to plot the data directly with pandas.DataFrame.plot, and use .set_xticks to change the xtick-labels. Tested in python 3.12.0, pandas 2.1.1, matplotlib 3.8.0 data = pd.read_csv(io... | 3 | 3 |
77,360,289 | 2023-10-25 | https://stackoverflow.com/questions/77360289/visual-studio-code-missing-select-linter | I just installed the latest version (1.83.1) of VSC on Ubuntu. I plan to develop in Python, and am just getting started using Linters. I have installed the VSC extensions for Python, including the Pylance extension. I also installed the pylint and flake8 extensions as I wanted to compare the two linters. All documentat... | The Python: Select Linter command was removed in the 2023.18.0 release / between that release and the 2023.16.0 release. You can see the command definition and the command palette menu item definition still there in the 2023.16.0 release's extension manifest (search "setLinter"), whereas it's gone in the 2023.18.0 exte... | 2 | 5 |
77,361,799 | 2023-10-25 | https://stackoverflow.com/questions/77361799/attributeerror-dataframe-object-has-no-attribute-group-by | I am trying to group by a polars dataframe following the document: https://pola-rs.github.io/polars/py-polars/html/reference/dataframe/api/polars.DataFrame.group_by.html#polars.DataFrame.group_by import polars as pl df = pl.DataFrame( { "a": ["a", "b", "a", "b", "c"], "b": [1, 2, 1, 3, 3], "c": [5, 4, 3, 2, 1], } ) df.... | On checking I found my polars version : pl.__version__ 0.17.3 https://pola-rs.github.io/polars/py-polars/html/reference/dataframe/api/polars.DataFrame.groupby.html I need to do: df.groupby("a").agg(pl.col("b").sum()) # there is no underscore in groupby #output shape: (3, 2) a b str i64 "a" 2 "c" 3 "b" 5 and the docum... | 5 | 6 |
77,360,947 | 2023-10-25 | https://stackoverflow.com/questions/77360947/how-to-make-dataframe-like-output-to-dictionary | I'm fetching list format depending on URL link and I want to extract terminal output to pandas Dataframe structure before doing so I must convert it to dictionary. How can I achieve that? Here's the code: import subprocess import pandas as pd url = 'https://www.youtube.com/watch?v=kjYW63CVbsE' command = subprocess.geto... | I would recommend against parsing the raw string and suggest using yt_dlp.YoutubeDL (or use --dump-json or --print "%()j" like the answer @AndrejKesely provided) as said in the yt-dlp doc: Your program should avoid parsing the normal stdout since they may change in future versions. Instead they should use options such... | 4 | 1 |
77,359,543 | 2023-10-25 | https://stackoverflow.com/questions/77359543/strip-strings-and-date-time-from-mixed-string-with-numbers | I have this kind of dataset: import pandas as pd import numpy as np x = np.array([ '355395.7037', '355369.6383', '355367.881', '355381.419', '357394.9D7a82te7o6fm4o9n4t3h7 print: 06/10/202', '357405.7897626596']) y = np.array([ '4521429.292', '4521430.0229', ' 4521430.1191', '4521430.1256', '3 13:36 4521735.552137422',... | The best would be to try avoiding this format in the first place, especially if numbers get mixed with your value. That said, you could try to get rid of letters with replace, and then to use a regex to str.extract the number: out = df.apply(lambda s: s.str.replace('[^\d .]+', '', regex=True) .str.extract(r'(\d{6,}(?:\... | 3 | 1 |
77,359,803 | 2023-10-25 | https://stackoverflow.com/questions/77359803/pandas-check-if-count-of-occurence-of-each-element-of-a-dataframe-column-is-equ | Giving two dataframes df1: col1 ----- 1 1 1 2 3 1 1 2 and df2: colA | colB ------------ 1 | 2 1 | 4 2 | 1 3 | 1 5 | 1 4 | 5 I want to return True if the count of the occurence of every element e in col1 in df1 is equal to the count of the occurence of e in both colA and colB in df2. In the example above for df1 and d... | You can use value_counts on col1 and the stacked version of df2, then compare the outputs: c1 = df1['col1'].value_counts(sort=False) c2 = df2.stack().value_counts(sort=False) # if more columns # c2 = df2[['colA', 'colB']].stack().value_counts() out = c1.eq(c2.reindex_like(c1)).all() numpy variant: # get values and cou... | 3 | 1 |
77,358,638 | 2023-10-25 | https://stackoverflow.com/questions/77358638/dynamic-numpy-conditions-based-on-values-from-array | I am trying to find out how I can use np.where in a dynamic way, where I select some predefined values, pass them to a function and let them create the condition. Ideally I want to create long conditions with several logical operators. In the code below I am stupidly trying to use a string: cond_arr[1]['cond'] as a log... | With pd.eval to evaluate a dynamic expression: def make_clause(df, col_d, cond_d, val_d): col, cond, val = col_d['ind'], cond_d['cond'], val_d['val'] df["signal"] = np.where(pd.eval(f'df.{col} {cond} {val}', target=df), 1, -1) selected_conds = [indicators[0], conds[0], values[0]] make_clause(df, *selected_conds) In c... | 2 | 2 |
77,356,307 | 2023-10-25 | https://stackoverflow.com/questions/77356307/boolean-mask-if-timestamp-from-a-df-is-with-two-time-points-from-second-df-pyt | I have two distinct data frames. Both contain timestamps and corresponding values. I'm aiming to subset or provide boolean indexing where the time from one df falls within two timepoints from a second df. df contains names and start/end times. I want to use this info for df2. So where the same name is present (John), I... | You can merge your dataframes as first approach. You need to reset_index to preserve the df2 index: idx = (df2.reset_index().merge(df, on='Name') .loc[lambda x:x['Time'].between(x['Start Time'], x['End Time']), 'index']) msk = df2.index.isin(idx) You have to re Output: >>> msk array([ True, True, True, True, True, Fal... | 2 | 2 |
77,353,981 | 2023-10-24 | https://stackoverflow.com/questions/77353981/layer-conv2d-11-expected-2-variables-but-received-0-variables-during-loading | I wanted to load a model using tf.keras.models.load_model('ACM1_9035P.keras') as I usually do but all of a sudden this time it wouldn't load. I got the error message seen in the title. This method has worked many times before but this time it didn't. What's the problem and how can I fix it? I can provide more informati... | I found the answer: The model was created and saved using TensorFlow version 2.13.0 I was trying to load it using TensorFlow version 2.14.0 Downgrading the version in Google Collab to 2.13.0 allowed me to load the model as I have done before. To see how you can change the TensorFlow version in Collab, check out this pa... | 4 | 5 |
77,333,833 | 2023-10-20 | https://stackoverflow.com/questions/77333833/how-can-i-update-a-toga-progress-bar-after-each-download | When the download button is pressed it is supposed to download a set of files from a specified url. After each download I update the progress bar accordingly, but the bar only updates after all the files have been downloaded. The UI is being blocked until all downloads are complete. I am using Beeware's Toga for the UI... | The main principles to remember in most UI frameworks are: Don't block the main thread for more than a small fraction of a second. Don't touch UI objects on any thread except the main one. Here's a solution that follows both of those rules. I haven't tested it, but it should be pretty close: def on_download(self, wi... | 2 | 2 |
77,324,915 | 2023-10-19 | https://stackoverflow.com/questions/77324915/nested-for-loops-to-do-a-check-of-the-elements-of-a-python-list | I need to insert within two new lists, objects that are not present in list 'PListaServiceID' but are present in list 'SListaServiceID', the same but in reverse. so I started by doing this PListaServiceName = [] PListaServiceID = [] SListaServiceName = [] SListaServiceID = [] CListaServiceID = [] C2ListaServiceID = [] ... | I found a difference, it depends on how you want the final data, in my case I wanted a list with all the repetitions within the list. either way works #Elements present in PListaServiceID but not in SListaServiceID #without repetition CListaServiceID = list(set(PListaServiceName) - set(SListaServiceName)) #with repetit... | 2 | 2 |
77,333,100 | 2023-10-20 | https://stackoverflow.com/questions/77333100/geoalchemy2-geometry-schema-for-pydantic-fastapi | I want to use PostGIS with FastAPI and therefore use geoalchemy2 with alembic to create the table in the DB. But I'm not able to declare the schema in pydantic v2 correctly. My Code looks as follows: # auto-generated from env.py from alembic import op import sqlalchemy as sa from geoalchemy2 import Geometry from sqlalc... | So I found the answer: # schemas.py from typing import List from pydantic import ConfigDict, BaseModel, Field from geoalchemy2.types import WKBElement from typing_extensions import Annotated class SolarParkBase(BaseModel): model_config = ConfigDict(from_attributes=True, arbitrary_types_allowed=True) name_of_model: str ... | 3 | 8 |
77,344,749 | 2023-10-23 | https://stackoverflow.com/questions/77344749/pythonvirtualenvoperator-gives-error-no-module-named-unusual-prefix-dag | I'm using airflow 2.5.3 with Kubernetes executor and Python 3.7. I've tried to make a simple DAG with only one PythonVirtualnvOperator and two context variables ({{ ts }} and {{ dag }}) passed into it. from datetime import timedelta from pathlib import Path import airflow from airflow import DAG from airflow.operators.... | This problem occurs if this function make_foo that is passed to an airflow operator as python_callable argument is defined in the same Python source with the DAG object. And the DAG has finally started working when I moved the make_foo function to another Python module. Here's my code now: dags/strange_pickling_error/... | 4 | 0 |
77,333,437 | 2023-10-20 | https://stackoverflow.com/questions/77333437/faster-way-to-pass-a-numpy-array-through-a-protobuf-message | I have a 921000 x 3 numpy array (921k 3D points, one point per row) that I am trying to pack into a protobuf message and I am running into performance issues. I have control over the protocol and can change it as needed. I am using Python 3.10 and numpy 1.26.1. I am using protocol buffers because I'm using gRPC. For th... | If your goal is just to send something over gRPC to another program that you control, then you don't actually have to convert everything into "native" protobuf messages; you can use a protobuf bytes field to store another serialization format, such as numpy tobytes() output, or Arrow. This will be much faster. | 2 | 4 |
77,353,466 | 2023-10-24 | https://stackoverflow.com/questions/77353466/decrypting-a-chacha20-poly1305-string-without-using-tag-mac | I am able to successfully encrypt and decrypt a string using Chacha20-Poly1305 in python without using the tag (or mac) as follows (using pycryptodome library): from Crypto.Cipher import ChaCha20_Poly1305 key = '20d821e770a6d3e4fc171fd3a437c7841d58463cb1bc7f7cce6b4225ae1dd900' #random generated key nonce = '18c02beda4f... | The issue is caused by different values for the initial counter regarding encryption/decryption in the libraries applied. Background: ChaCha20 is operated in counter mode to derive a key stream that is XORed with the plaintext. Thereby an (increment-by-one) counter counts through a sequence of input blocks for the ChaC... | 2 | 3 |
77,344,919 | 2023-10-23 | https://stackoverflow.com/questions/77344919/airflow-importing-dag-with-dependencies | I deployed airflow on kubernetes using the official helm chart. I'm using KubernetesExecutor and git-sync. I am using a seperate docker image for my webserver and my workers - each DAG gets its own docker image. I am running into DAG import errors at the airflow home page. E.g. if one of my DAGs is using pandas then I'... | It's great crafting an answer laid out by the OP's comments 😜 In the comments, @user430953 provided this link to Airflow's documentation, where it states: One of the important factors impacting DAG loading time, that might be overlooked by Python developers is that top-level imports might take surprisingly a lot of t... | 2 | 1 |
77,354,058 | 2023-10-24 | https://stackoverflow.com/questions/77354058/micromamba-and-dockerfile-error-bin-bash-activate-no-such-file-or-directory | Used to have a Dockerfile with conda and flask that worked locally but after installing pytorch had to switch to micromamba, the old CMD no longer works after switching to image mambaorg/micromamba:1-focal-cuda-11.7.1, this is how my Dockerfile looks like right now: FROM mambaorg/micromamba:1-focal-cuda-11.7.1 WORKDIR ... | Assuming these 2 files: environment.yml name: testenv channels: - conda-forge dependencies: - python >= 3.9 - flask app.py from flask import Flask # Create a Flask application app = Flask(__name__) # Define a route for the root URL @app.route("/") def hello_world(): return "Hello, World!" if __name__ == "__main__": # ... | 2 | 3 |
77,350,095 | 2023-10-24 | https://stackoverflow.com/questions/77350095/differences-between-matlab-and-scipy-numerical-integration-results-with-bessel-f | I'm looking to replicate the results of the following MATLAB code in SciPy. MATLAB Version: f = @(x, y) besselh(0, 2, x.^2 + y.^2); integral2(f, -0.1, 0.1, -0.1, 0.1) The MATLAB result is: ans = 0.0400 + 0.1390i SciPy Version: f = lambda x, y: scipy.special.hankel2(0, x**2 + y**2) scipy.integrate.dblquad(f, -0.1, 0.1... | I believe the issue is that the integral goes through the origin, which produces NaN for H0. This is because H0 = J0 - i*Y0, and Y0 asymptotes the y-axis. For this specific case, you can use the H0 definition above to split the integrals into the real and complex parts. When doing this, you can make sure you don't cros... | 4 | 3 |
77,347,140 | 2023-10-23 | https://stackoverflow.com/questions/77347140/how-to-create-a-single-figure-legend-for-geoaxes-subplots | I have looked at the many other questions on here to try and solve this but for whatever reason I cannot. Each solution seems to give me the same error, or returns nothing at all. I have a list of six dataframes I am looping through to create a figure of 6 maps. Each dataframe is formatted similar with the only differe... | These Axes are cartopy.mpl.geoaxes.GeoAxes axs[0].get_legend_handles_labels() results in UserWarning: Legend does not support handles for PatchCollection instances., and returns ([], []). Use Axes.get_legend() to get the Legend instance. .legend_handles is new in matplotlib 3.7.2 and returns the list of Artist obj... | 2 | 1 |
77,352,151 | 2023-10-24 | https://stackoverflow.com/questions/77352151/how-can-i-do-the-dot-product-of-a-window-and-a-constant-vector-in-polars | I am trying to do calculate a dot product between a window and a static array for all windows in my polars DataFrame and I am struggling to figure out the right way to do this. Anyone here have any hints for me? Here is a quick working example: import polars as pl import numpy as np dummy_data = { "id_": [1, 2, 3, 4, 5... | After receiving a few answers, and finding one of my own, I wanted to share some benchmarks. Here are 3 potential solutions to the problem (adjusted slightly to provide a more comprehensive look at the questions by adding a group column): Data: groups = [] for i in range(n): for j in range(m): groups.append(i) dummy_da... | 3 | 2 |
77,348,561 | 2023-10-23 | https://stackoverflow.com/questions/77348561/how-does-the-aws-cli-open-a-browser-and-wait-for-a-response-before-proceeding | I'm trying to build a golang cli tool for my company and as part of that build login and some other features into the tool. For the life of me I can't figure out how AWS is able to open a browser window and wait for a few button clicks before proceeding from the CLI. https://docs.aws.amazon.com/singlesignon/latest/OIDC... | One option that I just threw together that seems to be working is a loop that just checks every second for attempts <= 30 { fmt.Println(attempts) token, err := idc.CreateToken(context.TODO(), &createTokenInput) if err != nil { // if debug is enabled show error log.Debug(err.Error()) attempts++ // wait 1 second time.Sl... | 2 | 1 |
77,333,277 | 2023-10-20 | https://stackoverflow.com/questions/77333277/deprecationwarning-sippytypedict-is-deprecated-pyqt5 | I was writing the most simplest piece of code to run some small app. I got the next warning message: ~\PycharmProjects\LoggerTest\main.py:10: DeprecationWarning: sipPyTypeDict() is deprecated, the extension module should use sipPyTypeDictRef() instead class MainWindow(QMainWindow): My code: # Import libraries import s... | It is solved in python-3.12.0 After upgrading, the warning should be away. Ref: https://github.com/python/cpython/pull/105747 | 2 | 5 |
77,336,943 | 2023-10-21 | https://stackoverflow.com/questions/77336943/how-to-enforce-in-gekko-writing-a-sudoku-solver | I am writing a Sudoku solver in Gekko (mostly for fun, I'm aware there are better tools for this.) I would like to express the constraints the variables in each row, column, and square most be different from each other. Here is the code: import itertools from gekko import GEKKO SQUARES = [ ( (0, 0), (0, 1), (0, 2), (1,... | There is no != (not equal) constraint in gekko. You can set the sum of each row to be 1 where each value can be 0 or 1. If the value is equal to 1 then that corresponding value is filled in that cell. Here is an MILP version that is written in PuLP and solved with the MILP CBC solver (credit to TowardsDataScience) impo... | 2 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.