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 |
|---|---|---|---|---|---|---|
75,205,191 | 2023-1-23 | https://stackoverflow.com/questions/75205191/python-thread-calling-wont-finish-when-closing-tkinter-application | I am making a timer using tkinter in python. The widget simply has a single button. This button doubles as the element displaying the time remaining. The timer has a thread that simply updates what time is shown on the button. The thread simply uses a while loop that should stop when an event is set. When the window is... | Ok, so, first I would like to introduce the .after method, which can be used in conjunction with your widget, not requiring the use of threads Notice that the update_time function is called once and calls itself again, making the loop not interfere with tkinter's mainloop in general. This will close along with the prog... | 6 | 3 |
75,218,781 | 2023-1-24 | https://stackoverflow.com/questions/75218781/how-to-read-udp-data-from-a-given-port-with-python-in-windows | On Windows 10 I want to read data from UDP port 9001. I have created the following script which does not give any output (python 3.10.9): import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(("", 9001)) while True: data, addr = sock.recv(1024) print(f"received message: {data.decode()} from {a... | As far as I can see, your posted Python code should have given you an error when run if it was receiving any data, so that suggests that the data was not getting to the process at all. I'd recommend checking your Windows Firewall settings for that port, and any other host-based firewalls you might be running. But also,... | 6 | 4 |
75,161,099 | 2023-1-18 | https://stackoverflow.com/questions/75161099/using-great-expectations-with-index-of-pandas-data-frame | If I have a a data frame df = pd.DataFrame({'A': [1.1, 2.2, 3.3], 'B': [4.4, 5.5, 6.6]}) I can use Great Expectations to check the name and dtypes of the columns like so: import great_expectations as ge df_asset = ge.from_pandas(df) # List of expectations df_asset.expect_column_to_exist('A') df_asset.expect_column_to_... | One quick hack is to use .reset_index to convert the index into a regular column: import great_expectations as ge df_asset = ge.from_pandas(df.reset_index()) # List of expectations df_asset.expect_column_to_exist('A') df_asset.expect_column_to_exist('B') df_asset.expect_column_values_to_be_of_type('A', 'float') df_asse... | 4 | 2 |
75,223,195 | 2023-1-24 | https://stackoverflow.com/questions/75223195/getting-attributeerror-module-shapely-geos-has-no-attribute-lgeos | I am trying to do this exercise from momepy (https://github.com/pysal/momepy/blob/main/docs/user_guide/getting_started.ipynb), but on the third codeblock f, ax = plt.subplots(figsize=(10, 10)) buildings.plot(ax=ax) ax.set_axis_off() plt.show() I got the following error AttributeError Traceback (most recent call last) ... | In the new version(2.0.0 released on 12 December 2022) of shapely there is no attribute 'lgeos'. Link to document: https://pypi.org/project/Shapely/#history You can check version by: shapely.__version__ If you want to use lgeos in your code you can downgrade your version to 1.8.5 %pip install shapely==1.8.5 I was abl... | 4 | 4 |
75,174,062 | 2023-1-19 | https://stackoverflow.com/questions/75174062/how-to-implement-a-fast-type-inference-procedure-for-ski-combinators-in-python | How to implement a fast simple type inference procedure for SKI combinators in Python? I am interested in 2 functions: typable: returns true if a given SKI term has a type (I suppose it should work faster than searching for a concrete type). principle_type: returns principle type if it exists and False otherwise. ... | Simple, maybe not the fastest (but reasonably fast if the types are small). from dataclasses import dataclass class OccursError(Exception): pass parent = {} Var = int def new_var() -> Var: t1 = Var(len(parent)) parent[t1] = t1 return t1 @dataclass class Fun: dom: "Var | Fun" cod: "Var | Fun" def S() -> Fun: t1 = new_va... | 3 | 2 |
75,224,154 | 2023-1-24 | https://stackoverflow.com/questions/75224154/python-backoff-decorator-library-for-retrying-with-exception-treatment | I need the function do_it retrying up to 10 times if any exception is raised, with an interval of 0.5 to 1.5 seconds between retries. I am trying to do it with backoff decorator and the following code: import backoff x = 0 @backoff.on_exception(max_tries=10) def do_it(): global x x = x + 1 print(f'x: {x}') try: z = dow... | but if the function fail after the 10 retries, how to instruct my code on how to move forward First, a caveat: the usage of the backoff decorator you show in your question is invalid; you must provide the wait_gen and exception parameters. If you're using the backoff.on_exception method, then you want your function t... | 5 | 14 |
75,222,897 | 2023-1-24 | https://stackoverflow.com/questions/75222897/sort-dataframe-based-on-minimum-value-of-two-columns | Let's assume I have the following dataframe: import pandas as pd d = {'col1': [1, 2,3,4], 'col2': [4, 2, 1, 3], 'col3': [1,0,1,1], 'outcome': [1,0,1,0]} df = pd.DataFrame(data=d) I want this dataframe sorted by col1 and col2 on the minimum value. The order of the indexes should be 2, 0, 1, 3. I tried this with df.sort... | Using numpy.lexsort: order = np.lexsort(np.sort(df[['col1', 'col2']])[:, ::-1].T) out = df.iloc[order] Output: col1 col2 col3 outcome 2 3 1 1 1 0 1 4 1 1 1 2 2 0 0 3 4 3 1 0 Note that you can easily handle any number of columns: df.iloc[np.lexsort(np.sort(df[['col1', 'col2', 'col3']])[:, ::-1].T)] col1 col2 col3 out... | 3 | 4 |
75,216,528 | 2023-1-23 | https://stackoverflow.com/questions/75216528/blinding-a-message-with-pycrypto-in-python-3 | In Python 2, there were two methods called blind/unblind. Their docs recommend that you should now use pkcs1_15, however they only show how to sign/verify a message. Their sample code looks like this: from Crypto.Signature import pkcs1_15 from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA # Generate a new ... | Firstly: PyCrypto is no longer maintained, and one should use its mostly-API-compatible successor, PyCryptodome, instead. If one is willing to learn a new API, they even advocate to switch to the Cryptography library instead. According to their documentation, they fully dropped support for manually blinding and unblind... | 4 | 1 |
75,219,023 | 2023-1-24 | https://stackoverflow.com/questions/75219023/how-to-convert-date-as-monday-1st-tomonday-1-in-python | I have tried a lot. Banning words doesn't help, removing certain characters doesn't help. The datetime module doesn't have a directive for this. It has things like %d which will give you today's day, for example 24. I have a date in the format of 'Tuesday 24th January' but I need it to be 'Tuesday 24 January'. Is there... | You can use a regex: import re d = 'Tuesday 24th January' d = re.sub(r'(\d+)(st|nd|rd|th)', r'\1', d) # \1 to restore the captured day print(d) # Output Tuesday 24 January For Saturday 21st January: d = 'Saturday 21st January' d = re.sub(r'(\d+)(st|nd|rd|th)', r'\1', d) print(d) # Output Saturday 21 January | 3 | 2 |
75,211,952 | 2023-1-23 | https://stackoverflow.com/questions/75211952/test-fails-in-foundry-when-using-asterisk-for-unpacking-when-creating-a-data | I want to create a DataFrame in a fixture using the following code: @pytest.fixture def my_fun(spark_session): return spark_session.createDataFrame( [ (*['test', 'testy']) ], T.StructType([ T.StructField('mytest', T.StringType()), T.StructField('mytest2', T.StringType() ]) ) def test_something(my_fun): return However,... | They are not the same. The round brackets in your example are not a tuple, they are just round brackets around a list. To make it a tuple you need to add a comma test = (*['test1', 'test2'],) # ('test1', 'test2') | 3 | 2 |
75,217,710 | 2023-1-24 | https://stackoverflow.com/questions/75217710/pandas-adding-a-row-to-each-group-if-missing-values-from-a-list | I hope you're doing okay. I've been trying to think how to solve the next problem, but I can't find a way to do it. Can you guys give me a hand, please? I have a dataframe with 4 columns, I want to add the remaining rows per group to have 3 Calendar Weeks, I want the new rows to keep the same value of ID of the group a... | (df.set_index(["ID", "Calendar Week"]) .reindex(pd.MultiIndex.from_product([df["ID"].unique(), ["1", "2", "3"]], names=["ID", "Calendar Week"])) .reset_index()[df.columns]) you can move ID & Calendar Week to index part then reindex with the every possibility of ID versus Calendar Week generated with a product then mo... | 4 | 2 |
75,211,183 | 2023-1-23 | https://stackoverflow.com/questions/75211183/what-does-pydantic-orm-mode-exactly-do | According to the docs, Pydantic "ORM mode" (enabled with orm_mode = True in Config) is needed to enable the from_orm method in order to create a model instance by reading attributes from another class instance. If ORM mode is not enabled, the from_orm method raises an exception. My questions are: Are there any other e... | Fortunately, at least the first question can be answered fairly easily. As of version 1.10.4, there are only two places (aside from the plugins), where orm_mode comes into play. BaseModel.from_orm This is basically an alternative constructor. It forgoes the regular __init__ method in favor of a marginally different se... | 14 | 9 |
75,207,298 | 2023-1-23 | https://stackoverflow.com/questions/75207298/drawing-an-arc-tangent-to-two-lines-segments-in-python | I'm trying to draw an arc of n number of steps between two points so that I can bevel a 2D shape. This image illustrates what I'm looking to create (the blue arc) and how I'm trying to go about it: move by the radius away from the target point (red) get the normals of those lines get the intersections of the normals t... | You could try making a Bezier curve, like in this example. A basic implementation might be: import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt Path = mpath.Path fig, ax = plt.subplots() # roughly equivalent of your purple, red and green points points = [(3, 6.146), (4,... | 4 | 1 |
75,214,934 | 2023-1-23 | https://stackoverflow.com/questions/75214934/python3-10-bdist-wheel-did-not-run-successfully-when-install-cffi | i installed Ubuntu 22.04 (fresh installation) an create an virtualenv with Python 3.10. The installed packages are as follows: libpython3.10:amd64 libpython3.10-dbg:amd64 libpython3.10-dev:amd64 libpython3.10-minimal:amd64 libpython3.10-stdlib:amd64 python3.10 python3.10-dbg python3.10-dev python3.10-minimal python3.10... | Most probably cffi==1.14.0 is not compatible with Python 3.10. Try the latest version: pip install cffi==1.15.1 | 4 | 4 |
75,209,249 | 2023-1-23 | https://stackoverflow.com/questions/75209249/overriding-a-method-mypy-throws-an-incompatible-with-super-type-error-when-ch | For the following code: class Person: number: int def __init__(self) -> None: self.number = 0 def __add__(self, other: 'Person') -> 'Person': self.number = self.number + other.number return self class Dan(Person): def __init__(self) -> None: super().__init__() def __add__(self, other: 'Dan') -> 'Dan': self.number = sel... | Why it violates the LSP The LSP states that method return types are covariant, whereas method parameter types are contravariant in the subtype. You shall not strengthen the preconditions, i.e. you shall not require Dan -- a strict subtype of Person -- for other in the Dan.__add__ method, if you annotated other with Per... | 3 | 4 |
75,211,830 | 2023-1-23 | https://stackoverflow.com/questions/75211830/how-to-install-python-modules-where-pipy-org-is-is-not-accessible-from-iran | so the problem is that pypi.org hase been filtered by iranian government(yes , i know it's ridiculous!). i tried to install some python modules from Github downloaded files: pip install moduleName but every module has it's own dependencies and try to connect to pipy.org to reach them. then there will be an error during... | I live in a country that also blocks services, mostly streaming platforms. In theory, the way behind this is the same whether to watch Netflix or download python and its dependencies. That is you'll probably need to use a VPN. As said by d-dutchveiws, there's tons of videos and resources on how to set up a VPN. If you ... | 7 | 0 |
75,200,316 | 2023-1-22 | https://stackoverflow.com/questions/75200316/modulenotfounderror-no-module-named-nbformat | I would like to run python in a Quarto document. I followed the docs about installing and using python in Quarto, but the error stays. Here is some reproducible code: --- title: "matplotlib demo" format: html: code-fold: true jupyter: python3 --- For a demonstration of a line plot on a polar axis, see @fig-polar. ```{p... | This error usually occurs when jupyter is not installed in the environment that is being used and from the output of quarto checks, its seems that Quarto is referring to the r-reticulate environment and possibly jupyter is not installed in that environment. If thats the case, you simply need to install jupyter in the r... | 3 | 3 |
75,167,317 | 2023-1-19 | https://stackoverflow.com/questions/75167317/make-pydantic-basemodel-fields-optional-including-sub-models-for-patch | As already asked in similar questions, I want to support PATCH operations for a FastApi application where the caller can specify as many or as few fields as they like, of a Pydantic BaseModel with sub-models, so that efficient PATCH operations can be performed, without the caller having to supply an entire valid model ... | When I first posed this question I thought that the only problem was how to turn all fields Optional in a nested BaseModel, but actually that was not difficult to fix. The real problem with partial updates when implementing a PATCH call is that the Pydantic BaseModel.copy method doesn't attempt to support nested models... | 4 | 5 |
75,204,560 | 2023-1-22 | https://stackoverflow.com/questions/75204560/consuming-taskgroup-response | In Python3.11 it's suggested to use TaskGroup for spawning Tasks rather than using gather. Given Gather will also return the result of a co-routine, what's the best approach with TaskGroup. Currently I have async with TaskGroup() as tg: r1 = tg.create_task(foo()) r2 = tg.create_task(bar()) res = [r1.result(), r2.result... | The task groups were implemented more as a cleaner way to handle task lifetimes and exception handling, enabled greatly by the new exceptions group rework. I think its a popular misconception right now, but the TaskGroup is not a drop in replacement for all of the gather use-cases. For cases where you do not care about... | 13 | 19 |
75,194,858 | 2023-1-21 | https://stackoverflow.com/questions/75194858/best-way-to-feed-data-into-multiprocess | I have some ambiguity in me. I'm novice. I have reads that Multiprocessing are making local copies of Global Variable on each Process. However, this only applies on Windows, since it creates new instance of Python. Meanwhile, in Linux, Child Process are forked into Parent. Now, I have Global Variable that contains stat... | Update Based on your updated code/description where the dictionary has no keys added or deleted but integer values of existing keys might be changed by a process and the change reflected to other processes using the dictionary, then there are two approaches: Use a managed dictionary (e.g. multiprocessing.Manager().dic... | 3 | 2 |
75,161,513 | 2023-1-18 | https://stackoverflow.com/questions/75161513/cant-pause-python-process-using-debug | I have a python script which starts multiple sub processes using these lines : for elm in elements: t = multiprocessing.Process(target=sub_process,args=[elm]) threads.append(t) t.start() for t in threads: t.join() Sometimes, for some reason the thread halts and the script never finishes. I'm trying to use VSCode debug... | First, those are subprocesses, not threads. It's important to understand the difference, although it doesn't answer your question. Second, a pause (manual break) in the Python debugger will break in Python code. It won't break in the machine code below that executes the Python, or in the machine code below that perform... | 3 | 13 |
75,202,407 | 2023-1-22 | https://stackoverflow.com/questions/75202407/creating-a-date-range-in-python-polars-with-the-last-days-of-the-months | How do I create a date range in Polars (Python API) with only the last days of the months? This is the code I have: pl.date_range(datetime(2022,5,5), datetime(2022,8,10), "1mo", name="dtrange") The result is: '2022-05-05', '2022-06-05', '2022-07-05', '2022-08-05' I would like to get: '2022-05-31', '2022-06-30', '2022-... | I think you'd need to create the range of days and filter: (pl.date_range(datetime(2022,5,5), datetime(2022,8,10), "1d", name="dtrange") .to_frame() .filter( pl.col("dtrange").dt.month() < (pl.col("dtrange") + pl.duration(days=1)).dt.month() ) ) shape: (3, 1) ┌─────────────────────┐ │ dtrange │ │ --- │ │ datetime[μs] ... | 3 | 3 |
75,202,610 | 2023-1-22 | https://stackoverflow.com/questions/75202610/typeerror-type-object-is-not-subscriptable-python | Whenever I try to type-hint a list of strings, such as tricks: list[str] = [] , I get TypeError: 'type' object is not subscriptable. I follow a course where they use the same code, but it works for them. So I guess the problem is one of these differences between my an the courses environments. I use: vs code anaconda... | You're on an old Python version. list[str] is only valid starting in Python 3.9. Before that, you need to use typing.List: from typing import List tricks: List[str] = [] If you're taking a course that uses features introduced in Python 3.9, you should probably get a Python version that's at least 3.9, though. | 31 | 61 |
75,165,351 | 2023-1-18 | https://stackoverflow.com/questions/75165351/how-can-i-return-progress-hook-for-yt-dlp-using-fastapi-to-end-user | Relevant portion of my code looks something like this: @directory_router.get("/youtube-dl/{relative_path:path}", tags=["directory"]) def youtube_dl(relative_path, url, name=""): """ Download """ relative_path, _ = set_path(relative_path) logger.info(f"{DATA_PATH}{relative_path}") if name: name = f"{DATA_PATH}{relative_... | You could use a Queue object to communicate between the threads. So when you call youtube_dl pass in a Queue that you can add messages inside yt_dlp_hook (you'll need to use partial functions to construct it). You'll be best off using asyncio to run the download at the same time as updating the user something like: imp... | 7 | 3 |
75,195,622 | 2023-1-21 | https://stackoverflow.com/questions/75195622/download-video-with-yt-dlp-using-format-id | How can I download a specific format without using options like "best video", using the format ID... example: 139, see the picture ❯ yt-dlp --list-formats https://www.youtube.com/watch?v=BaW_jenozKc [youtube] Extracting URL: https://www.youtube.com/watch?v=BaW_jenozKc [youtube] BaW_jenozKc: Downloading webpage [youtube... | yt-dlp -f <format_id> <url> | 20 | 21 |
75,198,911 | 2023-1-22 | https://stackoverflow.com/questions/75198911/usage-of-nested-protocol-member-of-protocol-is-also-a-protocol | Consider a Python protocol attribute which is also annotated with a protocol. I found in that case, both mypy and Pyright report an error even when my custom datatype follows the nested protocol. For example in the code below Outer follows the HasHasA protocol in that it has hasa: HasA because Inner follows HasA protoc... | There's an issue on GitHub which is almost exactly the same as your example. I think the motivating case on the mypy docs explains quite well why this is illegal. Bringing a structural analogy to your example, let's fill in an implementation for func and tweak Inner slightly: def func(b: HasHasA) -> None: b.hasa.a += 1... | 7 | 6 |
75,198,932 | 2023-1-22 | https://stackoverflow.com/questions/75198932/how-to-call-an-async-function-from-the-main-thread-without-waiting-for-the-funct | I'm trying to call an async function containing an await function from the main thread without halting computation in the main thread. I've looked into similar questions employing a variety of solutions two of which I have demonstrated below, however, none of which seem to work with my current setup involving aioconsol... | As pointed out to me by @flakes there were a couple of problems with my approach: asyncio.run is a blocking function so wrapping my async function calls in it was preventing any following code from running. The main content needs to be wrapped in an asynchronous function to give the indented async function time to run... | 3 | 3 |
75,198,303 | 2023-1-22 | https://stackoverflow.com/questions/75198303/splitting-based-on-condtions | Say I have df as follows: MyCol Red Motor Green Taxi Light blue small Taxi Light blue big Taxi I would like to split the color and the vehicle into two columns. I used this command to split the last word. But sometimes, there is a 'big' or 'small' associated with the car name. How can do the splitting with conditions?... | I think the best approach is to use extract with a regex pattern df['MyCol'].str.extract('^(.*?)\s((?:small|big)?\s?\w+)$') 0 1 0 Red Motor 1 Green Taxi 2 Light blue small Taxi 3 Light blue big Taxi Regex details: ^: Matches start of the string (.*?): first capturing group .*?: matches any character zero or more ... | 3 | 2 |
75,164,313 | 2023-1-18 | https://stackoverflow.com/questions/75164313/selenium-in-google-colab-stopped-working-showing-an-error-as-service-chromedrive | Few hour ago my setup in google colab for selenium worked fine. Now it stopped working all of a sudden. This is a sample: !pip install selenium !apt-get update !apt install chromium-chromedriver from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_op... | This error message... WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 1 ...implies that the chromedriver service unexpectedly exited. This is because of the of an issue induced as the colab system was updated from v18.04 to ubuntu v20.04 LTS recently. The main reason is, with Ub... | 5 | 4 |
75,196,568 | 2023-1-21 | https://stackoverflow.com/questions/75196568/how-do-i-get-page-level-data-of-a-parquet-file-with-pyarrow | Given a ParquetFile object (docs) I am able to retrieve data at row group / column chunk level either with read_row_group or with the metadata attribute: from pyarrow import fs from pyarrow.parquet import ParquetFile s3 = fs.S3FileSystem(region='us-east-2') path = 'voltrondata-labs-datasets/nyc-taxi/year=2009/month=1/p... | You cannot access that information in pyarrow today. Pyarrow has initally been focused on converting parquet files to the Arrow representation. There is no equivalent to pages in Arrow. The info should be available in parquet-cpp (which, confusingly, is a project that also lives in the Arrow GitHub repo) if you're able... | 3 | 3 |
75,196,143 | 2023-1-21 | https://stackoverflow.com/questions/75196143/seaborn-error-with-kde-plot-the-following-variable-cannot-be-assigned-with-wide | I have a pandas dataframe df with two columns (type and IR) as this one: type IR 0 a 0.1 1 b 0.3 2 b 0.2 3 c 0.8 4 c 0.5 ... I want to plot three distributions (one for each type) with the values of the IR so, I write: sns.displot(df, kind="kde", hue='type', rug=True) but I get this error: The following variable can... | Use: df = pd.DataFrame({'type': {0: 'a', 1: 'b', 2: 'b', 3: 'c', 4: 'c'}, 'IR': {0: 0.1, 1: 0.3, 2: 0.2, 3: 0.8, 4: 0.5}}) print (df) type IR 0 a 0.1 1 b 0.3 2 b 0.2 3 c 0.8 4 c 0.5 sns.displot(df.reset_index(drop=True), x='IR', kind="kde", hue='type', rug=True) | 3 | 3 |
75,176,669 | 2023-1-19 | https://stackoverflow.com/questions/75176669/emulating-matlab-mesh-plot-in-matplotlib-yielding-shadow-effects | I have this meshplot that looks very clean in matlab for a 3d surface (Ignore the red border line): And I am trying to emulate the same image in matplotlib. However, I get this weird shadow effect where the top of the surface is pure black and only the bottom is white: I have the code for both plots here *my surface ... | My guess is that you don't know the keyword argument shade=..., that by default is True but it seems that you prefer no shading. Here it is the (very simple) code that produces the graph above. import numpy as np import matplotlib.pyplot as plt x = y = np.linspace(0, 10, 51) x, y = np.meshgrid(x, y) z = np.sin(y/7*x) ... | 3 | 2 |
75,194,696 | 2023-1-21 | https://stackoverflow.com/questions/75194696/pandas-groupby-agg-with-condition | I have a pandas data frame similar to this: name sales profit profit_flag Joe 200 100 True Joe 300 150 False Mark 200 100 True Mark 300 150 True Judy 300 150 False The actual data frame has 100 columns. The idea is: I want to group by name, and aggregate all the columns. However, certain columns dep... | You can mask the values prior to aggregation: (df.assign(profit=lambda d: d['profit'].where(d['profit_flag'])) .groupby('name', as_index=False)[['sales', 'profit']].sum(min_count=1) ) Output: name sales profit 0 Joe 500 100.0 1 Judy 300 NaN 2 Mark 500 250.0 | 3 | 4 |
75,192,148 | 2023-1-21 | https://stackoverflow.com/questions/75192148/fastapi-and-postgresql-in-docker-compose-file-connection-error | This question has been asked already for example Docker: Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? but I still can't figure out how to properly connect the application to the database. Files: Dockerfile FROM python:3.10-slim WORKDIR /app COPY . . RUN pip install --up... | You should update your config to reference the service name of postgres and the port the database runs on inside the container DATABASE_URL = "postgresql://postgres:password@postgres:5432/fastapi_database" When your app was running locally on your machine with the database running in the container then localhost:5433 ... | 3 | 4 |
75,175,322 | 2023-1-19 | https://stackoverflow.com/questions/75175322/sum-elements-before-and-replace-element-with-sum | I have the numpy array arr = np.array([[0, 0, 2, 5, 0, 0, 1, 8, 0, 3, 0], [1, 2, 0, 0, 0, 0, 5, 7, 0, 0, 0], [8, 5, 3, 9, 0, 1, 0, 0, 0, 0, 1]]) I need the result array like this: [[0, 0, 0, 0, 7, 0, 0, 0, 9, 0, 3] [0, 0, 3, 0, 0, 0, 0, 0, 12, 0, 0] [0, 0, 0, 0, 25, 0, 1, 0, 0, 0, 0]] What's happened? We go along the... | First, we want to find the locations where the array has a zero next to a non-zero. rr, cc = np.where((arr[:, 1:] == 0) & (arr[:, :-1] != 0)) Now, we can use np.add.reduceat to add elements. Unfortunately, reduceat needs a list of 1-d indices, so we're going to have to play with shapes a little. Calculating the equiva... | 3 | 4 |
75,185,990 | 2023-1-20 | https://stackoverflow.com/questions/75185990/filtering-a-dataframe-with-uuids-returns-an-empty-result | I have this data frame: df: id hint 29c45630-7d41-11e9-8ea2-9f2bfe5760ab None 61afc910-3918-11ea-b078-93fcef773138 Yes and I want to find the first row that has this id = 29c45630-7d41-11e9-8ea2-9f2bfe5760ab when I run this code: df[df['id'] == '29c45630-7d41-11e9-8ea2-9f2bfe5760ab'] return empty!!! and t... | You code didn't work because you have UUIDs, not strings, you first need to convert to string: df[df['id'].astype(str).eq('29c45630-7d41-11e9-8ea2-9f2bfe5760ab')] Output: id hint 0 29c45630-7d41-11e9-8ea2-9f2bfe5760ab None | 3 | 2 |
75,186,036 | 2023-1-20 | https://stackoverflow.com/questions/75186036/why-does-the-last-line-in-a-cell-generate-output-but-preceding-lines-do-not | Given this Jupyter notebook cell: x = [1,2,3,4,5] y = {1,2,3,4,5} x y When the cell executes, it generates this output: {1, 2, 3, 4, 5} The last line in the cell generates output, the line above it has no effect. This works for any data type, as far as I can tell. Here's a snip of the same code as above: | You can change this behaviour with: from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" The reason why only the last line is printed is that the default value of ast_node_interactivity is: last_expr. You can read more about that here: https://ipython.readthedocs.i... | 6 | 9 |
75,182,198 | 2023-1-20 | https://stackoverflow.com/questions/75182198/how-to-pass-additional-arguments-to-a-function-when-using-threadpoolexecutor | I would like to read several png images by utilizing the ThreadPoolExecutor and cv2.imread. Problem is that I don't know where to place cv2.IMREAD_UNCHANGED tag/argument to preserve alpha channel (transparency). The following code works but alpha channel is lost. Where should I place the cv2.IMREAD_UNCHANGED argument? ... | Use a lambda that accepts one argument img and pass the argument to the imread function along with the cv2.IMREAD_UNCHANGED. import cv2 import concurrent.futures images=["pic1.png", "pic2.png", "pic3.png"] images_list=[] with concurrent.futures.ThreadPoolExecutor() as executor: images_list=list(executor.map(lambda img... | 3 | 2 |
75,178,360 | 2023-1-19 | https://stackoverflow.com/questions/75178360/what-is-the-difference-between-np-min-and-min | I have trying to learn Python on datacamp. When I run statistical codes with agg - like min, max - I realized that it is the same result with using np with these codes. But I can not use mean and median methods without np. So, is there any difference between np.min and min , np.max and max? why don't median and mean ... | min is the builtin python function and numpy.min is another min function that is in the numpy package. They act similarly but different. Given a single list, they will act the same: print(np.min([1, 2, 3, 4, 5])) print(min([1, 2, 3, 4, 5])) 1 1 However, given multiple arguments, numpy.min will throw an error as the fi... | 3 | 4 |
75,176,951 | 2023-1-19 | https://stackoverflow.com/questions/75176951/python-add-weights-associated-with-values-of-a-column | I am working with an ex termly large datfarem. Here is a sample: import pandas as pd import numpy as np df = pd.DataFrame({ 'ID': ['A', 'A', 'A', 'X', 'X', 'Y'], }) ID 0 A 1 A 2 A 3 X 4 X 5 Y Now, given the frequency of each value in column '''ID''', I want to calculate a weight using the function below and add a colu... | If you rely on duck-typing a little bit more, you can rewrite your function to return the same input type as outputted. This will save you of needing to explicitly reaching back into the .index prior to calling .map import pandas as pd df = pd.DataFrame({'ID': ['A', 'A', 'A', 'X', 'X', 'Y'}) def get_weights_inverse_num... | 6 | 7 |
75,155,648 | 2023-1-18 | https://stackoverflow.com/questions/75155648/find-total-combinations-of-length-3-such-that-sum-is-divisible-by-a-given-number | So, I have been trying to find optimum solution for the question, but I can not find a solution which is less than o(n3). The problem statemnt is :- find total number of triplet in an array such that sum of a[i],a[j],a[k] is divisible by a given number d and i<j<k. I have tried a multiple solutions but the solutions al... | Let A be an array of numbers of length N: A = [1,2,3,4,5,6,7,8] Let D be the divider D = 4 It is possible to reduce complexity O(N^2) with an extra dictionary that saves you iterating through the array for each pair (a[i],a[j]). The helper dictionary will be built before iterating through the pairs (i,j) with the cou... | 4 | 6 |
75,159,821 | 2023-1-18 | https://stackoverflow.com/questions/75159821/installing-python-3-11-1-on-a-docker-container | I want to use debian:bullseye as a base image and then install a specific Python version - i.e. 3.11.1. At the moment I am just learning docker and linux. From what I understand I can either: Download and compile sources Install binaries (using apt-get) Use a Python base image I have come across countless questions o... | In case you want to install Python 3.11 in debian bullseye you have to compile it from source following the next steps (inside the Dockerfile): sudo apt update sudo apt install software-properties-common wget wget https://www.python.org/ftp/python/3.11.1/Python-3.11.1.tar.xz sudo tar -xf Python-3.11.1.tar.xz cd Python-... | 8 | 8 |
75,170,069 | 2023-1-19 | https://stackoverflow.com/questions/75170069/strip-colum-values-if-startswith-a-specific-string-pandas | I have a pandas dataframe(sample). id name 1 Mr-Mrs-Jon Snow 2 Mr-Mrs-Jane Smith 3 Mr-Mrs-Darth Vader I'm looking to strip the "Mr-Mrs-" from the dataframe. i.e the output should be: id name 1 Jon Snow 2 Jane Smith 3 Darth Vader I tried using df['name'] = df['name'].str.lstrip("Mr-Mrs-") But while doing so, some of t... | Don't strip, replace using a start of string anchor (^): df['name'] = df['name'].str.replace(r"^Mr-Mrs-", "", regex=True) Or removeprefix: df['name'] = df['name'].str.removeprefix("Mr-Mrs-") Output: id name 1 Jon Snow 2 Jane Smith 3 Darth Vader | 3 | 4 |
75,169,285 | 2023-1-19 | https://stackoverflow.com/questions/75169285/how-to-change-numbers-in-a-list-to-make-it-monotonically-decreasing | I have got a list: first = [100, 110, 60] How to make that: if the next number is greater than the previous one, then it is necessary to reduce this number like preceding number. For example, the answer should be: ans = [100, 100, 60] The second example: arr = [60,50,60] ans = [60, 50, 50] The third example: arr = [... | This will modify the list in situ: def fix_list(_list): for i, v in enumerate(_list[1:], 1): _list[i] = min(v, _list[i-1]) return _list print(fix_list([100, 110, 60])) print(fix_list([60, 50, 60])) print(fix_list([20, 100, 150])) Output: [100, 100, 60] [60, 50, 50] [20, 20, 20] | 5 | 3 |
75,167,963 | 2023-1-19 | https://stackoverflow.com/questions/75167963/polars-slower-than-numpy | I was thinking about using polars in place of numpy in a parsing problem where I turn a structured text file into a character table and operate on different columns. However, it seems that polars is about 5 times slower than numpy in most operations I'm performing. I was wondering why that's the case and whether I'm do... | Polars does extra work in filtering string data that is not worth it in this case. Polars uses arrow large-utf8 buffers for their string data. This makes filtering more expensive than filtering python strings/chars (e.g. pointers or u8 bytes). Sometimes it is worth it, sometimes not. If you have homogeneous data, numpy... | 7 | 6 |
75,164,872 | 2023-1-18 | https://stackoverflow.com/questions/75164872/bar-polar-with-areas-proportional-to-values | Based on this question I have the plot below. The issue is plotly misaligns the proportion between plot area and data value. I mean, higher values (e.g. going from 0.5 to 0.6) lead to a large increase in area (big dark green block) whereas from 0 to 0.1 is not noticiable (even if the actual data increment is the same 0... | You can construct a new column called r_outer_diff that stores radius differences (as you go from the inner most to outer most sector for each direction) to ensure the area of each sector is equal. The values for this column can be calculated inside the loop we are using to construct df_test_sectors using the following... | 4 | 2 |
75,165,745 | 2023-1-18 | https://stackoverflow.com/questions/75165745/cannot-determine-if-type-of-field-in-a-pydantic-model-is-of-type-list | I am trying to automatically convert a Pydantic model to a DB schema. To do that, I am recursively looping through a Pydantic model's fields to determine the type of field. As an example, I have this simple model: from typing import List from pydantic import BaseModel class TestModel(BaseModel): tags: List[str] I am r... | Pydantic has the concept of the shape of a field. These shapes are encoded as integers and available as constants in the fields module. The more-or-less standard types have been accommodated there already. If a field was annotated with list[T], then the shape attribute of the field will be SHAPE_LIST and the type_ will... | 4 | 5 |
75,164,370 | 2023-1-18 | https://stackoverflow.com/questions/75164370/python-polars-how-to-convert-a-list-of-dictionaries-to-polars-dataframe-without | I have a list of dictionaries like this: [{"id": 1, "name": "Joe", "lastname": "Bloggs"}, {"id": 2, "name": "Bob", "lastname": "Wilson"}] And I would like to transform it to a polars dataframe. I've tried going via pandas but if possible, I'd like to avoid using pandas. Any thoughts? | Just pass it to pl.DataFrame In [2]: pl.DataFrame([{"id": 1, "name": "Joe", "lastname": "Bloggs"}, {"id": 2, "name": "Bob", "lastname": "Wilson"}]) Out[2]: shape: (2, 3) ┌─────┬──────┬──────────┐ │ id ┆ name ┆ lastname │ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str │ ╞═════╪══════╪══════════╡ │ 1 ┆ Joe ┆ Bloggs │ │ 2 ┆ Bob ┆ ... | 7 | 10 |
75,160,024 | 2023-1-18 | https://stackoverflow.com/questions/75160024/matplotlib-step-function-how-to-extend-the-first-and-last-steps | I am using a step and fill_between functions in Matplotlib and want the steps to be centred on the x points. Code import matplotlib.pyplot as plt import numpy as np xpoints=np.array([1,2,3,4]) ypoints=np.array([4,6,5,2]) ypoints_std=np.array([0.5,0.3,0.4,0.2]) plt.step(xpoints,ypoints,where='mid') plt.fill_between(xpoi... | Using a bar plot at a height The error bands could be shown via a bar plot with a bottom at ypoints - ypoints_std and a height of 2*ypoints_std. import matplotlib.pyplot as plt import numpy as np xpoints = np.array([1, 2, 3, 4]) ypoints = np.array([4, 6, 5, 2]) ypoints_std = np.array([0.5, 0.3, 0.4, 0.2]) plt.bar(xpoin... | 4 | 2 |
75,161,173 | 2023-1-18 | https://stackoverflow.com/questions/75161173/nested-dictionary-creation-python | I have a dictionary setup like this: company = {'Honda': {} ,'Toyota':{} ,'Ford':{} } I have a list containing data like this: years = ['Year 1', 'Year 2', 'Year 3'] Finally, I also have a list of lists containing data like this: sales = [[55,9,90],[44,22,67],[83,13,91]] I am trying to achieve a final result that lo... | You can use a dict comprehension with zip. res = {k : dict(zip(years, sale)) for k, sale in zip(company, sales)} | 3 | 5 |
75,158,767 | 2023-1-18 | https://stackoverflow.com/questions/75158767/mypy-doesnt-allow-a-generic-attribute-to-be-marked-as-final | I'm trying to create a class which has an attribute that should be a constant. This attribute could have different types depending on were the class is used in the codebase. Moreover, the type of this attribute is used in various type hints throughout the class¹, so I decided to convert the class to a Generic, like so:... | Your code is correct per PEP591, mypy applies the rules in a wrong order, annotate in __init__ to solve the issue. Here are the links to the docs and PEP591. mypy should've checked the presence of initializer and then decide whether the initializer is missing, but it doesn't in fact and thinks that you define a final c... | 3 | 3 |
75,100,102 | 2023-1-12 | https://stackoverflow.com/questions/75100102/get-app-version-from-pyproject-toml-inside-python-code | I am not very familiar with python, I only done automation with so I am a new with packages and everything. I am creating an API with Flask, Gunicorn and Poetry. I noticed that there is a version number inside the pyproject.toml and I would like to create a route /version which returns the version of my app. My app str... | You should not use __package__, which is the name of the "import package" (or maybe import module, depending on where this line of code is located), because this is not what is expected here. importlib.metadata.version() expects the name of the "distribution package" (the thing that you pip-install), which is the one y... | 12 | 24 |
75,091,265 | 2023-1-12 | https://stackoverflow.com/questions/75091265/python-setuptools-scm-get-version-from-git-tags | I am using project.toml file to package my module, I want to extract the version from git tag using setuptools_scm module. When I run python setup.p y --version command it gives this output 0.0.1.post1.dev0. How will I get only 0.0.1 value and omit the .post.dev0 value? Here is project.toml file settings: [build-system... | setuptools_scm out-of-the-box generates development and post-release versions. To generate a release version like 0.0.1, you can pass a callable into use_scm_version: # content of setup.py def my_version(): from setuptools_scm.version import SEMVER_MINOR, guess_next_simple_semver, release_branch_semver_version def my_r... | 8 | 4 |
75,133,458 | 2023-1-16 | https://stackoverflow.com/questions/75133458/polars-str-starts-with-with-values-from-another-column | I have a polars DataFrame for example: >>> df = pl.DataFrame({'A': ['a', 'b', 'c', 'd'], 'B': ['app', 'nop', 'cap', 'tab']}) >>> df shape: (4, 2) ┌─────┬─────┐ │ A ┆ B │ │ --- ┆ --- │ │ str ┆ str │ ╞═════╪═════╡ │ a ┆ app │ │ b ┆ nop │ │ c ┆ cap │ │ d ┆ tab │ └─────┴─────┘ I'm trying to get a third column C which is T... | Expression support was added for .str.starts_with() in pull/6355 as part of the Polars 0.15.17 release. df.with_columns(pl.col("B").str.starts_with(pl.col("A")).alias("C")) shape: (4, 3) ┌─────┬─────┬───────┐ │ A | B | C │ │ --- | --- | --- │ │ str | str | bool │ ╞═════╪═════╪═══════╡ │ a | app | true │ │ b | nop | fa... | 3 | 5 |
75,150,535 | 2023-1-17 | https://stackoverflow.com/questions/75150535/polars-create-column-with-string-formatting | I have a polars dataframe: df = pl.DataFrame({'schema_name': ['test_schema', 'test_schema_2'], 'table_name': ['test_table', 'test_table_2'], 'column_name': ['test_column, test_column_2','test_column']}) schema_name table_name column_name test_schema test_table test_column, test_column_2 test_schema_2 test_tab... | Another option is to use polars.format to create your string. For example: date_field_value_max_query = ( '''select {} as schema_name, {} as table_name, greatest({}) from {}.{} group by 1, 2 ''' ) ( df .with_columns( pl.format(date_field_value_max_query, 'schema_name', 'table_name', 'column_name', 'schema_name', 'table... | 3 | 5 |
75,108,379 | 2023-1-13 | https://stackoverflow.com/questions/75108379/python-poetry-adding-dependency-to-a-group | I am using Poetry of version 1.3.2 (currently the last version), and added group to .toml file as below: [tool.poetry.group.dev.dependencies]. And following official documentation tried to add library to this group using command: poetry add pytest --group dev. But always getting error that says: The "--group" option do... | Just type: poetry add --group dev 'package_name' That should work | 10 | 18 |
75,150,942 | 2023-1-17 | https://stackoverflow.com/questions/75150942/how-to-get-a-session-from-async-session-generator-fastapi-sqlalchemy | I see in many places an approach for getting SqlAlchemy session just like this one below: async def get_session() -> AsyncSession: async with async_session() as session: yield session It used together with Depends: @app.post("/endpoint") async def vieww(session: AsyncSession = Depends(get_session)): session.execute(so... | get_session is an asynchronous generator function. It returns an asynchronous iterator. You can't await those. You can await their __anext__ method though. from asyncio import run from collections.abc import AsyncIterator async def get_generator() -> AsyncIterator[int]: yield 1 async def main() -> None: generator = get... | 5 | 7 |
75,146,691 | 2023-1-17 | https://stackoverflow.com/questions/75146691/way-to-specify-viewpoint-distance-in-3d-plots | I am working on an animation of a 3D plot using mpl_toolkits.mplot3d (Matplotlib 3.6.3) and need to set the view distance. It seems that earlier versions of Matplotlib allowed the elevation, azimuth, and distance of the viewpoint "camera" to be set for 3D plots using methods like this: ax.elev = 45 ax.azim = 10 ax.dist... | According to the documentation, you now need to use the zoom argument of set_box_aspect: ax.set_box_aspect(None, zoom=2) Where the first argument is the aspect ratio. Use None to use the default values. | 3 | 3 |
75,145,424 | 2023-1-17 | https://stackoverflow.com/questions/75145424/fastapi-starlette-how-to-handle-exceptions-inside-background-tasks | I developed some API endpoints using FastAPI. These endpoints are allowed to run BackgroundTasks. Unfortunately, I do not know how to handle unpredictable issues from theses tasks. An example of my API is shown below: # main.py from fastapi import FastAPI import uvicorn app = FastAPI() def test_func(a, b): raise ... @a... | Can you help me to handle any type of exception from such a background task? Background tasks, as the name suggests, are tasks that are going to run in the background after returning a response. Hence, you can't raise an Exception and expect the client to receive some kind of response. If you are just looking to catc... | 3 | 7 |
75,114,841 | 2023-1-13 | https://stackoverflow.com/questions/75114841/debugger-warning-from-ipython-frozen-modules | I created a new environment using conda and wanted to add it to jupyter-lab. I got a warning about frozen modules? (shown below) $ ipython kernel install --user --name=testi2 0.00s - Debugger warning: It seems that frozen modules are being used, which may 0.00s - make the debugger miss breakpoints. Please pass -Xfrozen... | This is just a warning that the debugger cannot debug frozen modules. In Python 3.11, the core modules essential for Python startup are “frozen”. ... This reduces the steps in module execution process ... Interpreter startup is now 10-15% faster in Python 3.11. This has a big impact for short-running programs using Py... | 25 | 28 |
75,102,134 | 2023-1-12 | https://stackoverflow.com/questions/75102134/mat1-and-mat2-must-have-the-same-dtype | I'm trying to build a neural network to predict per-capita-income for counties in US based on the education level of their citizens. X and y have the same dtype (I have checked this) but I'm getting an error. Here is my data: county_FIPS state county per_capita_personal_income_2019 \ 0 51013 VA Arlington, VA 97629 per... | The reason for this is because the parameters dtype of nn.Linear doesn't match your input's dtype; the default dtype for nn.Linear is torch.float32 which is in your case different from your input data - float64. The solution to this question solves your problem and explains why @Anonymous answer works. In short, add se... | 7 | 9 |
75,111,217 | 2023-1-13 | https://stackoverflow.com/questions/75111217/how-do-i-run-dbt-models-from-a-python-script-or-program | I have a DBT project, and a python script will be grabbing data from the postgresql to produce output. However, part of the python script will need to make the DBT run. I haven't found the library that will let me cause a DBT run from an external script, but I'm pretty sure it exists. How do I do this? ETA: The correct... | Update: v1.5 has arrived! With v1.5 of dbt, we get a stable and officially supported Python API for invoking dbt operations; this API has functional parity with the CLI. From the docs: from dbt.cli.main import dbtRunner, dbtRunnerResult # initialize dbt = dbtRunner() # create CLI args as a list of strings cli_args = ["... | 10 | 16 |
75,114,334 | 2023-1-13 | https://stackoverflow.com/questions/75114334/flask-limiter-error-typeerror-limiter-init-got-multiple-values-for-argum | I am attempting to use Flask's rate limiting library to rate limit an API based on the seconds. So I have used this exact same format to limit requests to an API on an Apache Server. However I am now using an NGINX. I do not thinks this makes a difference but when I run this code: import api app = Flask(__name__, insta... | Your Limiter class instantiation is incorrect. Below is the correct one- limiter = Limiter(get_remote_address, app=app, default_limits=["200 per day", "50 per hour"]) | 3 | 7 |
75,099,182 | 2023-1-12 | https://stackoverflow.com/questions/75099182/stable-diffusion-error-couldnt-install-torch-no-matching-distribution-found | I am trying to install locally Stable Diffusion. I follow the presented steps but when I get to the last one "run webui-use file" it opens the terminal and it's saying "Press any key to continue...". If I do so the terminal instantly closes. I went to the SB folder, right-clicked open in the terminal and used ./webui-u... | I had a similar error. What solved the issue was, I installed the 32 bit version of python. I uninstalled and installed the x86-64 bit version. And everything installed just fine. I have version 3.8 installed as i have found out it is the most stable version. I downloaded the 64 bit installer from here python 3.8 | 4 | 0 |
75,121,807 | 2023-1-14 | https://stackoverflow.com/questions/75121807/what-are-keypoints-in-yolov7-pose | I am trying to understad the keypoint output of the yolov7, but I didn't find enough information about that. I have the following output: array([ 0, 0, 430.44, 476.19, 243.75, 840, 0.94348, 402.75, 128.5, 0.99902, 417.5, 114.25, 0.99658, 385.5, 115, 0.99609, 437.75, 125.5, 0.89209, 366.75, 128, 0.66406, 471, 229.62, 0.... | I assume you have passed your output through output_to_keypoint function in utils.plots. Based on the comment left by the authors of that function, the first 7 values should be (in order): batch_id class_id x coordinate of the center of the bounding box y coordinate of the center of the bounding box w - width of the b... | 5 | 3 |
75,093,503 | 2023-1-12 | https://stackoverflow.com/questions/75093503/are-python-3-11-objects-as-light-as-slots | After Mark Shannon's optimisation of Python objects, is a plain object different from an object with slots? I understand that after this optimisation in a normal use case, objects have no dictionary. Have the new Python objects made the use of slots totally unnecessary? | No, __slots__ still produces more compact objects. With __slots__ for attributes, an object's memory layout only needs one pointer per slot. With the new lazy __dict__ creation, an object needs to store a PyDictValues object and a pointer to that PyDictValues object. The PyDictValues object contains room for a number o... | 15 | 13 |
75,114,624 | 2023-1-13 | https://stackoverflow.com/questions/75114624/multiline-ruleorder-in-snakemake | I have 3 rules and their names are somewhat long. When using ruleorder, the line goes over my desired 80 character limit. Is it possible break up the ruleorder into multiple lines in such a way that the behaviour is exactly the same as if I wrote it all in one line? Example: ruleorder: long_rule_1 > long_rule_2 > long_... | After looking at ways to do this, I believe the best way is pretty simple: ruleorder: long_rule_1 > long_rule_2 > long_rule_3 The other answers are good too, but this is the one that I'm using | 5 | 1 |
75,118,904 | 2023-1-14 | https://stackoverflow.com/questions/75118904/why-does-the-python-tutorial-say-it-is-an-error-that-other-scripts-in-the-curren | The Python Tutorial chapter 6 (Modules) says: The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless t... | After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an e... | 3 | 2 |
75,141,237 | 2023-1-17 | https://stackoverflow.com/questions/75141237/general-function-to-turn-string-into-kwargs | I'm trying to find a way to pass a string (coming from outside the python world!) that can be interpreted as **kwargs once it gets to the Python side. I have been trying to use this pyparsing example, but the string thats being passed in this example is too specific, and I've never heard of pyparsing until now. I'm try... | One option could be to use the ast module to parse some wrapping of the string that turns it into a valid Python expression. Then you can even use ast.literal_eval if you’re okay with everything it can produce: >>> import ast >>> kwargs = "a = [1,2], b= False, c =('abc', 'efg'),d=1" >>> expr = ast.parse(f"dict({kwargs}... | 4 | 11 |
75,135,530 | 2023-1-16 | https://stackoverflow.com/questions/75135530/error-exporting-styled-dataframes-to-image-syntaxerror-not-a-png-file-using | I've been using dataframe_image for a while and have had great results so far. Last week, out of a sudden, all my code containing the method dfi.export() stopped working with this error as an output raise SyntaxError("not a PNG file") File <string> SyntaxError: not a PNG file I can export the images passing the argume... | dataframe_image has a dependency on Chrome, and a recent Chrome update (possibly v109 on 2013-01-10) broke dataframe_image. v0.1.5 was released on 2023-01-14 to fix this. pip install --upgrade dataframe_image pip show dataframe_image The version should now be v0.1.5 or later, which should resolve the problem. Some us... | 4 | 3 |
75,107,763 | 2023-1-13 | https://stackoverflow.com/questions/75107763/why-binary-mode-when-reading-writing-toml-in-python | When reading a toml file in normal read ("r") mode, I get an error import tomli with open("path_to_file/conf.toml", "r") as f: # have to use "rb" ! toml_dict = tomli.load(f) TypeError: File must be opened in binary mode, e.g. use open('foo.toml', 'rb') Same happens when writing a toml file. Why? tomli github readme ... | To wrap this up, the problem/behavior described in the question is actually a specific case of a more general problem: how to enforce a specific decoding when reading a text file with Python's open built-in. Or rephrased: ensure the file has a specific encoding. tomli requires the user to handle the file IO, so the use... | 3 | 5 |
75,150,625 | 2023-1-17 | https://stackoverflow.com/questions/75150625/pandas-dataframe-check-list-in-column-an-set-value-in-different-column | I need your help for the following task: I have the following dataframe: test = {'Col1':[2,5], 'Col2':[5,7], 'Col_List':[['One','Two','Three','Four','Five'], ['Two', 'Four']], 'One':[0,0], 'Two':[0,0], 'Three':[0,0], 'Four':[0,0], 'Five':[0,0],} df=pd.DataFrame.from_dict(test) df which looks like: Col1 Col2 Col_Li... | exploded = df.explode("Col_List") df.update(pd.get_dummies(exploded["Col_List"]) .mul(exploded["Col1"], axis="rows") .groupby(level=0).sum()) explode lists' elements to their own rows get 1-hot representation of "One", "Two" etc. multiply it with the (exploded) "Col1" values 1/0 values will act as a selector then ... | 5 | 3 |
75,149,969 | 2023-1-17 | https://stackoverflow.com/questions/75149969/duplicate-row-in-pandas-dataframe-based-on-condition-then-update-a-new-column-b | I have a dataframe that looks like : df = pd.DataFrame({'qty': [10,7,2,1], 'status 1': [5,2,2,0], 'status 2': [3,2,0,1], 'status 3': [2,3,0,0] }) Each row has a qty of items. These items have one status (1,2 or 3). So qty = sum of values of status 1,2,3. I would like to : Duplicate each row by the "qty" column Then... | Here is a possible solution: import numpy as np import pandas as pd E = pd.DataFrame(np.eye(df.shape[1] - 1, dtype=int)) result = pd.DataFrame( df['qty'].reindex(df.index.repeat(df['qty'])).reset_index(drop=True), ) result[df.columns[1:]] = pd.concat( [E.reindex(E.index.repeat(df.iloc[i, 1:])) for i in range(len(df))],... | 4 | 3 |
75,148,272 | 2023-1-17 | https://stackoverflow.com/questions/75148272/how-to-convert-pandas-dataframe-to-nested-dictionary | I have a pandas DataFrame like this: id unit step phase start_or_end_of_phase op_name occurence 1 A 50l LOAD start P12load5 2 2 A 50l LOAD end P12load5 2 3 A 50l STIR start P12s5 4 4 A 50l STIR end P13s5 3 5 A 50l COLLECT start F7_col1 1 6 A 50l COLLECT end H325_col1 1 7 A 1000l SET_TEMP start xyz 2... | You have to reshape your dataframe before export as dictionary: nested_cols = ['step', 'phase', 'start_or_end_of_phase'] value_cols = ['op_name', 'occurence'] # Reshape your dataframe df1 = df.set_index(nested_cols)[value_cols].stack() # Export nested dict d = {} # items(): # t -> flatten index to convert to nested dic... | 3 | 4 |
75,127,785 | 2023-1-15 | https://stackoverflow.com/questions/75127785/mypy-seems-to-think-that-args-kwargs-could-match-to-any-funtion-signature | How does mypy apply the Liskov substitution principle to *args, **kwargs parameters? I thought the following code should fail a mypy check since some calls to f allowed by the Base class are not allowed by C, but it actually passed. Are there any reasons for this? from abc import ABC, abstractmethod from typing import ... | Unlike Daniil said in currently accepted answer, the reason is exactly (*args: Any, **kwargs: Any) signature part. Please check the corresponding discussion on mypy issue tracker: I actually like this idea, I have seen this confusion several times, and although it is a bit unsafe, most of the time when people write (*... | 7 | 5 |
75,144,059 | 2023-1-17 | https://stackoverflow.com/questions/75144059/python-playwright-start-maximized-window | I have a problem starting Playwright in Python maximized. I found some articles for other languages but doesn't work in Python, also nothing is written about maximizing window in Python in the official documentation. I tried browser = p.chromium.launch(headless=False, args=["--start-maximized"]) And it starts maximized... | I just found the answer: I need to set also the following and it works: browser.new_context(no_viewport=True) | 6 | 4 |
75,142,154 | 2023-1-17 | https://stackoverflow.com/questions/75142154/refrehing-the-django-model-after-save-and-5-second-sleep-get-me-old-state-what | I was able to save the data to a Django model without any errors, but data not reflected in db. But after a sleep time I was able to save the data again with same method. What might be causing this ? I suspect use of the Google API, but was able to print the data before performing the save operation. def update_channel... | This can happen if another process has already fetched the same client object and saved the object after your save operation. In this case, the data in the second process still be the old one and overwrites your change when it saves. | 3 | 3 |
75,141,732 | 2023-1-17 | https://stackoverflow.com/questions/75141732/regex-only-replace-if-wrapped-in-certain-function | I am looking to create a python function that will take a long SQL script that I have to create a table and place the session variables into the script so it can be used as a view within Snowflake. For example, SET TABLE_NAME = MY_TABLE_NAME; CREATE OR REPLACE VIEW MY_VIEW AS ( SELECT * FROM IDENTIFIER($TABLE_NAME) ) ... | There are two patterns you're looking for here: one enclosed in the identifier function, and the other with just a preceding $ character, so you can use an alternation pattern to search for both of them, capture the variable names of each, if any, and replace the match with what's captured. Find (with the case-insensit... | 4 | 0 |
75,113,742 | 2023-1-13 | https://stackoverflow.com/questions/75113742/improving-performance-for-a-nested-for-loop-iterating-over-dates | I am looking to learn how to improve the performance of code over a large dataframe (10 million rows) and my solution loops over multiple dates (2023-01-10, 2023-01-20, 2023-01-30) for different combinations of category_a and category_b. The working approach is shown below, which iterates over the dates for different p... | Efficient algorithm First of all, the complexity of the algorithm can be improved. Indeed, (df['category_a'] == category_a) & (df['category_b'] == category_b) travels the whole dataframe and this is done for each item in unique_pairs. The running time is O(U R) where U = len(unique_pairs) and R = len(df). An efficient ... | 14 | 7 |
75,138,693 | 2023-1-16 | https://stackoverflow.com/questions/75138693/pandas-isin-function-in-polars | Once in a while I get to the point where I need to run the following line: DF['is_flagged'] = DF['id'].isin(DF2[DF2['flag']==1]['id']) Lately I started using polars, and I wonder how to convert it easily to polars. For example: df1 = pl.DataFrame({ 'Animal_id': [1, 2, 3, 4, 5, 6, 7], 'age': [4, 6, 3, 8, 3, 8, 9] }) df... | So to be honest I am not quite sure from your question, your pandas snippet and your example what your desired solution is, but here are my three takes. import polars as pl df1 = pl.DataFrame( {"Animal_id": [1, 2, 3, 4, 5, 6, 7], "age": [4, 6, 3, 8, 3, 8, 9]} ).lazy() df2 = pl.DataFrame( { "Animal_id": [1, 2, 3, 4, 5, ... | 5 | 3 |
75,136,603 | 2023-1-16 | https://stackoverflow.com/questions/75136603/how-to-import-numpy-using-layer-in-lambda-aws | I am trying to add the numpy package to my lambda function, but I can't import it. I have followed several tutorials, but they all have the same problem. On my last attempt, I executed the following step by step: I created a lambda function in AWS and tested it Installed the numpy package on my local machine and zippe... | There are at least two ways to add NumPy to your AWS Lambda as layer: Add an AWS (Managed) Layer: From your Lambda console, choose AWS Layers and AWSSDKPandas-Python39 (Choose a layer accordingly for your Python version). Since Pandas is built on top of NumPy, you should be able to use NumPy once you add this Pandas l... | 4 | 4 |
75,135,206 | 2023-1-16 | https://stackoverflow.com/questions/75135206/printing-all-member-names-of-a-enum-class | class MyValues(enum.Enum): value1 = 1 value2 = 2 value3 = 1 print(MyValues._member_names_) Output would be a list with only the first two members [value1,value2] I would also like to have value3 in that list, i tried with aenum with NoAlias setting but did not work. Is there any way to get all members even if they hav... | _member_names_ is not part of the Enum documented public API. You should not use it. __members__ is what you're looking for. It's a mapping from member names to members, including all aliases. You can use list(MyValues.__members__) if you just want a list of the names. | 3 | 5 |
75,116,947 | 2023-1-14 | https://stackoverflow.com/questions/75116947/how-to-send-messages-to-telegram-using-python | I have a python script in which logs messages to the console. But I also want those messages to be sent to the telegram using my bot. Any hint and suggestion will be helpful. Thanks in advance. I haven't tried anything yet, just got thought if that possible or not and if it is then how? | Make A Telegram Bot Using BotFather for Telegram Search for BotFather in your Telegram client by opening it. A pre-installed Telegram bot that assists users in making original Telegram bots To create a new bot, enter /newbot. Name and username your bot. Copy the token for your new Telegram bot. Please take note that a... | 9 | 30 |
75,125,071 | 2023-1-15 | https://stackoverflow.com/questions/75125071/extend-list-with-another-list-in-specific-index | In python we can add lists to each other with the extend() method but it adds the second list at the end of the first list. lst1 = [1, 4, 5] lst2 = [2, 3] lst1.extend(lst2) Output: [1, 4, 5, 2, 3] How would I add the second list to be apart of the 1st element? Such that the result is this; [1, 2, 3, 4, 5 ] I've tried... | For those who don't like reading comments: lst1 = [1, 4, 5] lst2 = [2, 3] lst1[1:1] = lst2 print(lst1) Output: [1, 2, 3, 4, 5] | 9 | 13 |
75,118,159 | 2023-1-14 | https://stackoverflow.com/questions/75118159/generate-specific-toeplitz-covariance-matrix | I want to generate a statistical sample from a multidimensional normal distribution. For this I need to generate one specific kind of covariance matrix: 1 0.99 0.98 0.97 ... 0.99 1 0.99 0.98 ... 0.98 0.99 1 0.99 ... 0.97 0.98 0.99 1 ... ... ... ... ... Is there a way to generate this kind of matrix for multiple dimens... | You can use the scipy.linalg.toeplitz function, as it is made for exactly this kind of matrix: >>> import numpy as np >>> from scipy import linalg >>> linalg.toeplitz(np.arange(1,0,-0.1), np.arange(1,0,-0.1)) array([[1. , 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1], [0.9, 1. , 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2], ... | 3 | 3 |
75,116,574 | 2023-1-14 | https://stackoverflow.com/questions/75116574/interpolation-using-asfreqd-in-multiindex | The following code generates two DataFrames: frame1=pd.DataFrame({'dates':['2023-01-01','2023-01-07','2023-01-09'],'values':[0,18,28]}) frame1['dates']=pd.to_datetime(frame1['dates']) frame1=frame1.set_index('dates') frame2=pd.DataFrame({'dates':['2023-01-08','2023-01-12'],'values':[8,12]}) frame2['dates']=pd.to_dateti... | You have to drop the first level index (the group key) before use asfreq like your initial dataframes: >>> concat.groupby('frame').apply(lambda g: g.loc[g.name].asfreq('D').interpolate()) values frame dates f1 2023-01-01 0.0 2023-01-02 3.0 2023-01-03 6.0 2023-01-04 9.0 2023-01-05 12.0 2023-01-06 15.0 2023-01-07 18.0 20... | 4 | 5 |
75,115,582 | 2023-1-14 | https://stackoverflow.com/questions/75115582/how-to-load-toml-file-in-python | How to load toml file into a python file that my code python file: import toml toml.get("first").name toml file : [first] name = "Mark Wasfy" age = 22 [second] name = "John Wasfy" age = 25 | it can be used without open as a file import toml data = toml.load("./config.toml") print(data["first"]["name"]) | 7 | 10 |
75,115,515 | 2023-1-14 | https://stackoverflow.com/questions/75115515/does-anything-supercede-pep-8 | Trying to go from a script kiddie to a semi-respectable software engineer and need to learn how to write clean, digestible code. The book I'm reading pointed me towards PEP 8 - I know this is the foundational styling guide for Python. What I can't seem to figure out is if all the guidelines are still valid today in 202... | At the top, below the authors, you can see it says Status: Active As the tooltip explains, that means PEP 8 is Currently valid informational guidance, or an in-use process If the PEP is ever replaced it will say "Status: Superseded". At the bottom of the page it says: Last modified: 2022-05-11 17:45:05 GMT You ca... | 6 | 4 |
75,103,151 | 2023-1-12 | https://stackoverflow.com/questions/75103151/using-pyfirmata-with-a-simulator-like-simulide | I'm trying to learn PyFirmata, but don't want to get all of the hardware I need to do so. Instead I want to use a simulator, right now I'm using SimulIDE. In order to use PyFirmata, a board has to be connected to a COM port. Is there a way to get around this and use SimulIDE, or another simulator, instead? Here is the ... | According to this page, it's possible to connect your simulated Arduino to a real or virtual serial port (look for the "Connecting to Serial Port" section). You haven't specified what OS you're using; I'll show an example of doing that with Linux. Create a virtual serial port on your host We can use socat to create a v... | 4 | 3 |
75,103,127 | 2023-1-12 | https://stackoverflow.com/questions/75103127/getting-notimplementederror-could-not-run-torchvisionnms-with-arguments-fr | The full error: NotImplementedError: Could not run 'torchvision::nms' with arguments from the 'CUDA' backend. This could be because the operator doesn't exist for this backend, or was omitted during the selective/custom build process (if using custom build). If you are a Facebook employee using PyTorch on mobile, pleas... | This error occurs when you have Torch and Torchaudio for CUDA but not Torchvision for CUDA installed. Uninstall Torch and Torchvision, I used pip: pip uninstall torch torchvision Then go here to install the proper versions of both using the nice interface. I got the following command: pip install torch torchvision tor... | 14 | 33 |
75,112,136 | 2023-1-13 | https://stackoverflow.com/questions/75112136/python-unable-to-install-guesslang | I'm trying to install guesslang with pip but it seems that the last version (which was released on August 2021) depends on an obsolete version of Tensorflow (2.5.0). The problem is that I can't find this version anywhere. So, how can I install it? Or is there any other python library that does language detection? Howev... | tensorflow 2.5.0 released wheels for Python 3.6-3.9. Downgrade to Python 3.9 to install guesslang with tensorflow 2.5.0. | 4 | 3 |
75,111,518 | 2023-1-13 | https://stackoverflow.com/questions/75111518/analyze-if-the-value-of-a-column-is-less-than-another-and-this-another-is-less-t | Currently I do it this way: import pandas as pd dt = pd.DataFrame({ '1st':[1,0,1,0,1], '2nd':[2,1,2,1,2], '3rd':[3,0,3,2,3], '4th':[4,3,4,3,4], '5th':[5,0,5,4,5], 'minute_traded':[6,5,6,5,6] }) dt = dt[ (dt['1st'] < dt['2nd']) & (dt['2nd'] < dt['3rd']) & (dt['3rd'] < dt['4th']) & (dt['4th'] < dt['5th']) & (dt['5th'] < ... | Using shift to perform the comparison and all to aggregate as single boolean for boolean indexing: out = dt[dt.shift(axis=1).lt(dt).iloc[:, 1:].all(axis=1)] Output: 1st 2nd 3rd 4th 5th minute_traded 0 1 2 3 4 5 6 2 1 2 3 4 5 6 3 0 1 2 3 4 5 4 1 2 3 4 5 6 | 3 | 2 |
75,111,569 | 2023-1-13 | https://stackoverflow.com/questions/75111569/streamlit-on-aws-serverless-options | My goal is to deploy a Streamlit application to an AWS Serverless architecture. Streamlit does not appear to function properly without a Docker container, so the architecture would need to support containers. From various tutorials, EC2 is the most popular deployment option for Streamlit, which I have no interest in pu... | AWS Lambda: AWS Lambda can run containers, but those containers have to implement the Lambda runtime API. Lambda can't run any generic container. Lambda has a maximum run time (for processing a single request) of 15 minutes. Behind API gateway that maximum time is reduced to 60 seconds. Lambda isn't running 24/7. Your... | 3 | 4 |
75,110,547 | 2023-1-13 | https://stackoverflow.com/questions/75110547/tensorflows-random-truncated-normal-returns-different-results-with-the-same-see | The following lines are supposed to get the same result: import tensorflow as tf print(tf.random.truncated_normal(shape=[2],seed=1234)) print(tf.random.truncated_normal(shape=[2],seed=1234)) But I got: tf.Tensor([-0.12297685 -0.76935077], shape=(2,), dtype=tf.float32) tf.Tensor([0.37034193 1.3367208 ], shape=(2,), dty... | This seems to be intentional, see the docs here. Specifically the "Examples" section. What you need is stateless_truncated_normal: print(tf.random.stateless_truncated_normal(shape=[2],seed=[1234, 1])) print(tf.random.stateless_truncated_normal(shape=[2],seed=[1234, 1])) Gives me tf.Tensor([1.0721238 0.10303579], shape... | 3 | 2 |
75,103,449 | 2023-1-12 | https://stackoverflow.com/questions/75103449/dict-of-dataframes | Let's say I initialize a df and then I assign it to a dict 3 times, each one with a specific key. import pandas as pd df = pd.DataFrame({'A': [2, 2], 'B': [2, 2]}) dict = {} for i in range(3): dict_strat['Df {0}'.format(i)] = df Alright, what I'm not understanding is that when I try to change value of one element in t... | The DataFrames are all shallow copies, meaning that mutating one of them will mutate the others in the dictionary. To resolve this issue, make deep copies using .copy(). You also should be using f-strings rather than .format(): for i in range(3): dict_strat[f'Df {i}'] = df.copy() | 3 | 2 |
75,101,952 | 2023-1-12 | https://stackoverflow.com/questions/75101952/minimizing-a-function-using-pytorch-optimizer-return-values-are-all-the-same | I'm trying to minimize a function in order to better understand the optimizer process. As an example I used the Eggholder-Function (https://www.sfu.ca/~ssurjano/egg.html) which is 2d. My goal is to get the values of my parameters (x and y) after every optimizer iteration so that i can visualize it afterwards. Using Pyt... | Because they all refer to the same object. You can check it by: id(list_of_params[0]), id(list_of_params[1]) You can clone the params to avoid that: import torch def eggholder_function(x): return -(x[1] + 47) * torch.sin(torch.sqrt(torch.abs(x[1] + x[0]/2 + 47))) - x[0]*torch.sin(torch.sqrt(torch.abs(x[0]-(x[1]+47))))... | 3 | 3 |
75,085,009 | 2023-1-11 | https://stackoverflow.com/questions/75085009/how-to-type-hint-a-function-added-to-class-by-class-decorator-in-python | I have a class decorator, which adds a few functions and fields to decorated class. @mydecorator @dataclass class A: a: str = "" Added (via setattr()) is a .save() function and a set of info for dataclass fields as a separate dict. I'd like VScode and mypy to properly recognize that, so that when I use: a=A() a.save()... | TL;DR What you are trying to do is not possible with the current type system. 1. Intersection types If the attributes and methods you are adding to the class via your decorator are static (in the sense that they are not just known at runtime), then what you are describing is effectively the extension of any given clas... | 13 | 19 |
75,100,393 | 2023-1-12 | https://stackoverflow.com/questions/75100393/how-to-find-every-combination-of-numbers-that-sum-to-a-specific-x-given-a-large | I have a large array of integers (~3k items), and I want to find the indices of every combination of numbers where the sum of said numbers is equal to X. How to do this without the program taking years to execute? I can find the first combination possible with the following Python code: def find_numbers_that_sum_to(sou... | Unfortunately, this problem is NP-hard, meaning that there's no currently known polynomial time algorithm for this. If you want to benchmark your current code against other implementations, this SO question contains a bunch. Those implementations may be faster, but their runtimes will still be exponential. | 3 | 4 |
75,080,993 | 2023-1-11 | https://stackoverflow.com/questions/75080993/dbuserrorresponse-while-running-poetry-install | I tried to upgrade my poetry from 1.1.x version to 1.3 but as an official manual (https://python-poetry.org/docs/) recommends I removed the old version manually. Unfortunately I probably deleted wrong files because after installing 1.3 version I was still receiving errors that seemed sth was in conflict with old poetry... | Finally I was able to find the answer here. There are several ways to do that: Running export PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring in shell will work for following poetry commands until you close (exit) your shell session Add environment variable for each! poetry command, for example PYTHON_KEYRING_BA... | 11 | 25 |
75,077,369 | 2023-1-11 | https://stackoverflow.com/questions/75077369/how-to-import-module-using-path-related-to-working-directory-in-a-python-project | I'm using poetry to manage my python project, here's the project: my_project/ ├── pyproject.toml ├── module.py └── scripts/ └── main.py And I want to know how to import function from module.py into my_scripts/main.py correctly. My pyproject.toml: [tool.poetry] name = "my_project" version = "0.1.0" description = "" aut... | What made it work for me is to create a folder in your root with the same name of the package in the pyproject.toml file. If you don't do this, poetry will not find your project and will not install it in editable mode. You also need to let Python know that a folder is a package or sub-package by placing an __init__.py... | 4 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.