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,709,741
2023-3-11
https://stackoverflow.com/questions/75709741/pydantic-nested-setting-objects-load-env-variables-from-file
Using pydantic setting management, how can I load env variables on nested setting objects on a main settings class? In the code below, the sub_field env variable field doesn't get loaded. field_one and field_two load fine. How can I load an environment file so the values are propagated down to the nested sub_settings o...
There are some examples of nested loading of pydantic env variables in the docs. Option 1 If you're willing to adjust your variable names, one strategy is to use env_nested_delimiter to denote nested fields. This appears to be the way that pydantic expects nested settings to be loaded, so it should be preferred when po...
6
8
75,707,605
2023-3-11
https://stackoverflow.com/questions/75707605/cant-get-telegram-bot-to-send-messages-to-user-and-run-polling-loop-at-the-same
I m trying to build a telegram bot usin the telegram.ext.Application class of python-telegram-bot and I need the bot to send periodic messages to a specific user while also running its polling loop to receive incoming messages from other users. I ve done a lot-lot-lot of searching and tried various combinations but I c...
python-telegram-bot comes with the JobQueue, a built-in scheduling interface that allows you to run repeating tasks seamlessly within the framework. You might also be interested in this wiki section, which covers the general use case of running some asyncio logic in parallel to the bot. Disclaimer: I'm currently the m...
3
4
75,704,418
2023-3-11
https://stackoverflow.com/questions/75704418/parallelization-of-un-bzipping-millions-of-files
I have millions of compressed .bz2 files which I need to uncompressed. Can uncompression be parallelized ? I have access to the server with many cpu cores for the purpose. I worked with the following code which is correct but it is extremely slow. import os, glob, bz2 files = glob.glob("/data01/*.bz2") for fi in files:...
Multithreading would ideal for this because it's primarily IO-bound. from concurrent.futures import ThreadPoolExecutor import glob import bz2 import shutil def process(filename): with bz2.BZ2File(filename) as fr, open(filename[:-4], "wb") as fw: shutil.copyfileobj(fr, fw) def main(): with ThreadPoolExecutor() as tpe: t...
3
2
75,671,038
2023-3-8
https://stackoverflow.com/questions/75671038/pytest-manually-add-test-to-discovered-tests
# tests/test_assert.py @pytest.mark.mymark def custom_assert(): assert True How do I force pytest to discover this test? In general, how do I dynamically add any test to pytest's list of discovered tests, even if they don't fit in the naming convention?
pytest is fairly customisable, but you'll have to look at its extensive API. Luckily, the code base is statically typed, so you can navigate from functions and classes to other functions and classes fairly easily. To start off, it pays to understand how pytest discovers tests. Recall the configurable discovery naming c...
4
4
75,698,393
2023-3-10
https://stackoverflow.com/questions/75698393/create-a-raster-from-points-gpd-geodataframe-object-in-python-3-6
I want to create a raster file (.tif) from a points file using a geopandas.geodataframe.GeoDataFrame object. My dataframe has two columns: [geometry] and [Value]. The goal is to make a 10m resolution raster in [geometry] point with the [Value] value. My dataset is: geometry | Value 0 | POINT (520595.000 5720335.000) | ...
Assign x and y columns, convert to xarray, then export to tiff using rioxarray: # do this before sending to xarray # to ensure extension is loaded import rioxarray # assuming your GeoDataFrame is called `gdf` gdf["x"] = gdf.x gdf["y"] = gdf.y da = ( gdf.set_index(["y", "x"]) .Value .to_xarray() ) da.rio.to_raster("myfi...
4
6
75,702,760
2023-3-11
https://stackoverflow.com/questions/75702760/how-to-call-an-imported-module-knowing-its-name-as-a-string
I am writing an application that should test the solution of many students. I have structure like this app/ students/ A/ lab1/ solution.py lab2 solution.py B/ lab1/ solution.py C/ test.py I want to import the solution file in the testing module and run the main method. I know there is __import__ function that returns ...
Your most immediate problem is that you aren't returning anything from test so, result will always be None. The second and most important problem you have is that you don't really have any modules. You actually have a bunch of random folders with arbitrary python scripts in them. This means __import__ is going to be qu...
5
3
75,701,643
2023-3-10
https://stackoverflow.com/questions/75701643/remove-an-element-from-a-set-and-return-the-set
I need to iterate over a copy of a set that doesn't contain a certain element. Until now I'm doing this: for element in myset: if element != myelement: ... But I want something like this, in one line: for element in myset.copy().remove(myelement): ... Obviously this doesn't work because the remove method returns None...
Use the set difference operator. for element in myset - {myelement}: ... This creates a new set containing the elements of myset that aren't in {myelement} (namely, myelement itself).
6
12
75,699,024
2023-3-10
https://stackoverflow.com/questions/75699024/finding-the-centroid-of-a-polygon-in-python
I want to calculate the centroid of a figure formed by the points: (0,0), (70,0), (70,25), (45, 45), (45, 180), (95, 188), (95, 200), (-25, 200), (-25,188), (25,180), (25,45), (0, 25), (0,0). I know that the correct result for the centroid of this polygon is x = 35 and y = 100.4615 (source), but the code below does not...
Fixed: def centroid(vertices): x, y = 0, 0 n = len(vertices) signed_area = 0 for i in range(len(vertices)): x0, y0 = vertices[i] x1, y1 = vertices[(i + 1) % n] # shoelace formula area = (x0 * y1) - (x1 * y0) signed_area += area x += (x0 + x1) * area y += (y0 + y1) * area signed_area *= 0.5 x /= 6 * signed_area y /= 6 *...
6
5
75,696,056
2023-3-10
https://stackoverflow.com/questions/75696056/pythons-inspect-getsource-throws-error-if-used-in-a-decorator
I have the following function def foo(): for _ in range(1): print("hello") Now I want to add another print statement to print "Loop iterated" after every loop iteration. For this I define a new function that transforms foo into an ast tree, inserts the corresponding print node and then compiles the ast tree into an ex...
After some experimenting, I found out my initial hypothesis is incorrect: inspect.getsource is smart enough to retrieve the source code even if the function name is not yet set in the module globals. (surprisingly). What happens is that the source code is retrieved along with the decorator calls as well, and when the f...
3
2
75,690,784
2023-3-9
https://stackoverflow.com/questions/75690784/polars-for-python-how-to-get-rid-of-ensure-you-pass-a-path-to-the-file-instead
The statement I'm reading data sets using Polars.read_csv() method via a Python file handler: with gzip.open(os.path.join(getParameters()['rdir'], dataset)) as compressed_file: df = pl.read_csv(compressed_file, sep = '\t', ignore_errors=True) A performance warning keeps popping up: Polars found a filename. Ensure...
I had a similar issue with opening from a ZipFile object. The solution was to add a .read() method to the filename. Maybe the same would work in your case? with gzip.open(os.path.join(getParameters()['rdir'], dataset)) as compressed_file: df = pl.read_csv(compressed_file.read(), sep = '\t', ignore_errors=True)
13
6
75,690,334
2023-3-9
https://stackoverflow.com/questions/75690334/replace-two-adjacent-duplicate-characters-in-string-with-the-next-character-in-a
I want to write a function, that will find the first occurrence of two adjacent characters that are the same, replace them with a single character that is next in the alphabet and go over the string until there are no duplicates left. In case of "zz" it should go in a circular fashion back to "a". The string can only i...
As a trivial optimisation: instead of the hard reset i = 1, you can use a softer reset i = i-1. Indeed, if there was no duplicate between 1 and i before the transformation, then there still won't be any duplicate between 1 and i-1 after the transformation. def solve(s): i = 1 while i < len(s): if s[i] == s[i-1]: l = s[...
4
2
75,677,991
2023-3-8
https://stackoverflow.com/questions/75677991/polars-datetime-5-minutes-floor
I have polars dataframe with timestamp folumn of type datetime[ns] which value is 2023-03-08 11:13:07.831 I want to use polars efficiency to round timestamp to 5 minutes floor. Right now I do: import arrow def timestamp_5minutes_floor(ts: int) -> int: return int(arrow.get(ts).timestamp() // 300000 * 300000) df.with_col...
You could try to use .dt.truncate: With the sample dataframe df = pl.DataFrame({ "ts": ["2023-03-08 11:01:07.831", "2023-03-08 18:09:01.007"] }).select(pl.col("ts").str.strptime(pl.Datetime, "%Y-%m-%d %H:%M:%S%.3f")) ┌─────────────────────────┐ │ ts │ │ --- │ │ datetime[ms] │ ╞═════════════════════════╡ │ 2023-03-08 1...
3
8
75,676,642
2023-3-8
https://stackoverflow.com/questions/75676642/how-to-perform-conditional-join-more-efficiently-in-polars
I have a reasonably large dataframe on hand. Joining it with itself takes some time. But I want to join them with some conditions, which could make the resulting dataframe much smaller. My question is how can I take advantage of such conditions to make the conditional join faster to plain full join? Code below for illu...
With lazy and streaming=True, it is faster: In [5]: start = time.perf_counter() ...: df.lazy().join(df.lazy(), on=["id", "id2"], how="left").filter( ...: (pl.col("day") < pl.col("day_right")) & (pl.col("day_right") - pl.col("day") <= 30) ...: ).collect() ...: time.perf_counter() - start Out[5]: 11.083821532000002 In [6...
5
5
75,680,658
2023-3-9
https://stackoverflow.com/questions/75680658/where-to-put-a-small-utility-function-that-i-would-like-to-use-across-multiple-p
Right now I have one function that would be useful in a number of distinct packages that I work on. The function is only a handful of lines. But I would like to be able to use this code in a number of packages/projects that I work on and are deployed, I would like this code to be version controlled etc. There isn't, fo...
The entire packaging system is designed to solve exactly this problem - sharing code between different applications. So yes, the ideally you'd want to create a package out of this and add it as a dependency to all the other packages that use this code. There are a few upsides to this option: Package management is clea...
3
3
75,677,363
2023-3-8
https://stackoverflow.com/questions/75677363/does-pip-provide-a-toml-parser-for-python-3-9
I want to parse TOML files in python 3.9, and I am wondering if I can do so without installing another package. Since pip knows how to work with pyproject.toml files, and I already have pip installed, does pip provide a parser that I can import and use in my own code?
For 3.9, pip vendors tomli: from pip._vendor import tomli For consenting adults, importing the vendored module should work as usual. However, this is an implementation detail of pip, and it could change without a deprecation period at any moment in a future release of pip. Therefore, for anything apart from a quick ha...
10
9
75,649,038
2023-3-6
https://stackoverflow.com/questions/75649038/training-difference-between-lightgbm-api-and-sklearn-api
I'm trying to train a LGBClassifier for multiclass task. I tried first working directly with LightGBM API and set the model and training as follows: LightGBM API train_data = lgb.Dataset(X_train, (y_train-1)) test_data = lgb.Dataset(X_test, (y_test-1)) params = {} params['learning_rate'] = 0.3 params['boosting_type'] =...
It was my mistake. I thought the output in both APIs would be the same but it doesn't seem like that. I just removed the np.argmax() line when predicting with Sklearn API. It seems this API already predict directly the class. Don't remove the question in case someone else is dealing with similar issues.
3
0
75,628,413
2023-3-3
https://stackoverflow.com/questions/75628413/cast-column-of-type-list-to-str-in-polars
Currently, using the polars' cast() method on columns of type list[] is not supported. It throws: ComputeError: Cannot cast list type Before I do as usual (use rows(), or convert to pandas, or work with apply()). Is there any trick or best practice to convert polars list[] to strings? Here a quick snippet for you to r...
You can use the datatype pl.List(pl.String) df.with_columns(pl.col("foo").cast(pl.List(pl.String))) shape: (1, 2) ┌─────────────────┬─────────────┐ │ foo | bar │ │ --- | --- │ │ list[str] | str │ ╞═════════════════╪═════════════╡ │ ["1", "2", "3"] | Hello World │ └─────────────────┴─────────────┘ To create an actual ...
3
6
75,654,140
2023-3-6
https://stackoverflow.com/questions/75654140/trouble-with-conversion-of-duration-time-strings
I have some duration type data (lap times) as pl.String that fails to convert using strptime, whereas regular datetimes work as expected. Minutes (before :) and Seconds (before .) are always padded to two digits, Milliseconds are always 3 digits. Lap times are always < 2 min. df = pl.DataFrame({ "lap_time": ["01:14.007...
General case In case you have duration that may exceed 24 hours, you can extract data (minutes, seconds and so on) from string using regex pattern. For example: df = pl.DataFrame({ "time": ["+01:14.007", "100:20.000", "-05:00.000"] }) df.with_columns( pl.col("time").str.extract_all(r"([+-]?\d+)") # / # you will get arr...
4
3
75,601,543
2023-3-1
https://stackoverflow.com/questions/75601543/access-newly-created-column-in-with-columns-when-using-polars
I am new to Polars and I am not sure whether I am using .with_columns() correctly. Here's a situation I encounter frequently: There's a dataframe and in .with_columns(), I apply some operation to a column. For example, I convert some dates from str to date type and then want to compute the duration between start and en...
The second .with_columns() is needed. From the GitHub Issues I don't want this extra complexity in polars. If you want to use an updated column, you need two with_columns. This makes it much more readable, simple, and explainable. In the given example, passing multiple names to col() could simplify it slightly. (df.w...
7
13
75,633,075
2023-3-4
https://stackoverflow.com/questions/75633075/why-do-image-size-differ-when-vertical-vs-horizontal
Tried to create a random image with PIL as per the example: import numpy from PIL import image a = numpy.random.rand(48,84) img = Image.fromarray(a.astype('uint8')).convert('1') print(len(img.tobytes())) This particular code will output 528. Wen we flip the numbers of the numpy array: a = numpy.random.rand(84,48) The...
When you call tobytes() on the boolean array*, the data is likely encoded per row. In your second example, there are 48 booleans in each row of img. So each row can be represented with 6 bytes (48 bits). 6 bytes * 84 rows = 504 bytes in img. However, in your first example, there are 84 pixels per row, which is not divi...
4
5
75,626,974
2023-3-3
https://stackoverflow.com/questions/75626974/is-it-possible-to-load-huggingface-model-which-does-not-have-config-json-file
I am trying to load this semantic segmentation model from HF using the following code: from transformers import pipeline model = pipeline("image-segmentation", model="Carve/u2net-universal", device="cpu") But I get the following error: OSError: tamnvcc/isnet-general-use does not appear to have a file named config.json...
TL;DR You will need to make a lot of assumption if you don't have the config.json and the model card doesn't have any documentation After some guessing, possibly it's this: from u2net import U2NET import torch model = U2NET() model.load_state_dict(torch.load('full_weights.pth', map_location=torch.device('cpu'))) In L...
8
5
75,617,865
2023-3-2
https://stackoverflow.com/questions/75617865/openai-chat-completions-api-error-invalidrequesterror-unrecognized-request-ar
I am currently trying to use OpenAI's most recent model: gpt-3.5-turbo. I am following a very basic tutorial. I am working from a Google Collab notebook. I have to make a request for each prompt in a list of prompts, which for sake of simplicity looks like this: prompts = ['What are your functionalities?', 'what is the...
Problem You used the wrong method to get a completion. When using the OpenAI SDK, whether you use Python or Node.js, you need to use the right method. Which method is the right one? It depends on the OpenAI model you want to use. Solution The tables below will help you figure out which method is the right one for a giv...
38
55
75,666,486
2023-3-7
https://stackoverflow.com/questions/75666486/the-explicit-passing-of-coroutine-objects-to-asyncio-wait-is-deprecated
From this github link: https://github.com/pyxll/pyxll-examples/blob/master/bitmex/bitmex.py When I run this code, I get the message saying the explicit passing of coroutine objects to asyncio.wait() is deprecated. I've pinpointed this to line 71: await asyncio.wait(tasks), but can't figure out how to resolve the issue....
Don't pass the tasks list to asyncio.wait(). The documentation for asyncio.wait states "Run Future and Task instances in the aws iterable concurrently and block until the condition specified by return_when.". The type returned by an async def ...(...)-like defined function is a coroutine(type(async_function)==types.cor...
9
3
75,598,463
2023-3-1
https://stackoverflow.com/questions/75598463/pytest-ordering-of-test-suites
I've a set of test files (.py files) for different UI tests. I want to run these test files using pytest in a specific order. I used the below command python -m pytest -vv -s --capture=tee-sys --html=report.html --self-contained-html ./Tests/test_transTypes.py ./Tests/test_agentBank.py ./Tests/test_bankacct.py The pyt...
To specify the order in which tests are run in pytest, you can use the pytest-order plugin. This plugin allows you to customize the order in which your tests are run by providing the order marker, which has attributes that define when your tests should run in relation to each other. You can use absolute attributes (e.g...
4
4
75,648,132
2023-3-6
https://stackoverflow.com/questions/75648132/openai-gpt-3-api-why-do-i-get-only-partial-completion-why-is-the-completion-cu
I tried the following code but got only partial results like [{"light_id": 0, "color I was expecting the full JSON as suggested on this page: https://medium.com/@richardhayes777/using-chatgpt-to-control-hue-lights-37729959d94f import json import os import time from json import JSONDecodeError from typing import List i...
In general GPT-3 API (i.e., Completions API) If you get partial completion (i.e., if the completion is cut off), it's because the max_tokens parameter is set too low or you didn't set it at all (in this case, it defaults to 16). You need to set it higher, but the token count of your prompt and completion together canno...
4
8
75,651,880
2023-3-6
https://stackoverflow.com/questions/75651880/python-abstract-instance-property-alternative
If I have for example: class Parent(object): @property @abc.abstractmethod def asdf(self) -> str: """ Must be implemented by child """ @dataclass class Children(Parent): asdf = "1234" def some_method(self): self.asdf = "5678" I get an error from mypy saying I am shadowing class attribute in some_method. This is unders...
You might be misunderstanding the purpose of the @property decorator. Generally it's used for a function that is supposed to be accessed / "feel like" a constant to outside code. Python does not do strict type-checking of variables without significant effort. (It does constrain the types of values at runtime, so a vari...
3
3
75,611,661
2023-3-2
https://stackoverflow.com/questions/75611661/is-there-any-logical-reason-not-to-reuse-a-deleted-slot-immediately-in-hash-tabl
I have seen several implementations of dynamic tables with open addressing using linear probing that does not use deleted slots before resizing. Here is one example: https://gist.github.com/EntilZha/5397c02dc6be389c85d8 Is there any logical reason not to reuse a deleted slot immediately? I know why it makes sense not t...
No, there’s no reason not to fill tombstone slots as soon as you find them. In fact, a recent paper by Bender et al shows that in the absence of tombstones, primary clustering (where long runs of elements arise because collisions start linking together smaller runs of elements) can largely be eliminated in linear probi...
3
1
75,663,384
2023-3-7
https://stackoverflow.com/questions/75663384/how-to-log-python-code-memory-consumption
Question Hi, I am runnin' a Docker container with a Python application inside. The code performs some computing tasks and I would like to monitor it's memory consumption using logs (so I can see how different parts of the calculations perform). I do not need any charts or continous monitoring - I am okay with the inacc...
Fargate is using cgroup for memory limiting. As mentioned here and here, the CPU/memory values provided by /proc refer to the host, not the container. As a result, userspace tools such as top and free report misleading values. You can try with something like: with open('/sys/fs/cgroup/memory/memory.stat', 'r') as f: fo...
4
1
75,614,728
2023-3-2
https://stackoverflow.com/questions/75614728/cuda-12-tf-nightly-2-12-could-not-find-cuda-drivers-on-your-machine-gpu-will
tf-nightly version = 2.12.0-dev2023203 Python version = 3.10.6 CUDA drivers version = 525.85.12 CUDA version = 12.0 Cudnn version = 8.5.0 I am using Linux (x86_64, Ubuntu 22.04) I am coding in Visual Studio Code on a venv virtual environment I am trying to run some models on the GPU (NVIDIA GeForce RTX 3050) using te...
I think that, as of March 2023, the only tensorflow distribution for cuda 12 is the docker package from NVIDIA. A tf package for cuda 12 should show the following info >>> tf.sysconfig.get_build_info() OrderedDict([('cpu_compiler', '/usr/bin/x86_64-linux-gnu-gcc-11'), ('cuda_compute_capabilities', ['compute_86']), ('cu...
58
34
75,660,251
2023-3-7
https://stackoverflow.com/questions/75660251/textual-ui-is-not-updating-after-change-the-value
I am trying to build a simple TUI based app using Python's textual package. I have one left panel where I want to display list of items and on right panel I wan to show details of the selected item from left panel. So I want add items in the left panel using keybinding provided by textual lib but when I add new item to...
It should work if you call the .append method of the ListView instance. To achieve this you can give it its own id: yield = ListView( *self.items, initial_index=None, id = "my_list_LV" ) and then use # ... def action_add_item(self): self.query_one("#my_list_LV").append(ListItem(Label(str(uuid.uuid4()), classes="reque...
3
2
75,666,408
2023-3-7
https://stackoverflow.com/questions/75666408/how-can-i-collect-the-results-of-a-repeated-calculation-in-a-list-dictionary-et
There are a great many existing Q&A on Stack Overflow on this general theme, but they are all either poor quality (typically, implied from a beginner's debugging problem) or miss the mark in some other way (generally by being insufficiently general). There are at least two extremely common ways to get the naive code wr...
General approaches There are three ordinary ways to approach the problem: by explicitly using a loop (normally a for loop, but while loops are also possible); by using a list comprehension (or dict comprehension, set comprehension, or generator expression as appropriate to the specific need in context); or by using the...
9
12
75,666,062
2023-3-7
https://stackoverflow.com/questions/75666062/discrete-date-values-for-x-axis-in-seaborn-objects-plot
I am trying to prepare a bar plot using seaborn.objects with time series data where the x-axis ticks and labels are only on the dates that really appear in the data. import pandas as pd import seaborn.objects as so df1 = pd.DataFrame({'date': pd.to_datetime(['2022-01-01', '2022-02-01']), 'val': [10,20,]}) so.Plot(df1, ...
You can convert your date column as string: (so.Plot(df1.assign(date=df1['date'].dt.strftime('%b %Y')), x='date', y='val') .add(so.Bar()).show()) # Or, as suggested by @mwaskom: so.Plot(x=df1['date'].dt.strftime('%b %Y'), y=df1['val']).add(so.Bar()).show() Output:
3
2
75,660,016
2023-3-7
https://stackoverflow.com/questions/75660016/multiply-scipy-sparse-matrix-with-a-3d-numpy-array
I have the following matrices a = sp.random(150, 150) x = np.random.normal(0, 1, size=(150, 20)) and I would basically like to implement the following formula I can calculate the inner difference like this diff = (x[:, None, :] - x[None, :, :]) ** 2 diff.shape # -> (150, 150, 20) a.shape # -> (150, 150) I would basi...
import numpy as np import scipy.sparse from numpy.random import default_rng rand = default_rng(seed=0) # \sigma_k = \sum_i^N \sum_j^N A_{i,j} (x_{i,k} - x_{j,k})^2 # Dense method N = 100 x = rand.integers(0, 10, (N, 2)) A = np.clip(rand.integers(0, 100, (N, N)) - 80, a_min=0, a_max=None) diff = (x[:, None, :] - x[None,...
5
2
75,668,272
2023-3-7
https://stackoverflow.com/questions/75668272/how-to-assign-numeric-labels-to-all-elements-in-a-list-series-array-based-on-num
I have two lists that contains two series of numbers, such as: A = [1.0, 2.9, 3.4, 4.2, 5.5....100.3] B = [1.1, 1.2, 1.3, 2.5, 3.0, 3.1, 5.2] I would like to create another list of labels based on whether the elements in list B falls in an (any) interval from list A. Something like this: C = [group_1, group_1, group_1...
So, assuming A is sorted, you can use binary search, which already comes with the python standard library in the (rather clunky) module bisect: >>> A = [1.0, 2.9, 3.4, 4.2, 5.5] >>> B = [1.1, 1.2, 1.3, 2.5, 3.0, 3.1, 5.2] >>> [bisect.bisect_left(A, b) for b in B] [1, 1, 1, 1, 2, 2, 4] This takes O(N * logN) time. Note...
3
5
75,667,225
2023-3-7
https://stackoverflow.com/questions/75667225/how-to-get-latest-version-of-not-installed-package-using-pip
I want to know, for a package which is not installed in my virtual environment, what is the latest version available. For example, if I had to install requests library, I would want to know the version before installation. I considered pip search but that was deprecated in Python 3.11. Is there any other way to get the...
You can use the currently-experimental pip index: C:\>pip index versions requests WARNING: pip index is currently an experimental command. It may be removed/changed in a future release without prior warning. requests (2.28.2) Available versions: 2.28.2, 2.28.1, 2.28.0, 2.27.1, 2.27.0, 2.26.0, 2.25.1, 2.25.0, 2.24.0, 2....
4
4
75,664,524
2023-3-7
https://stackoverflow.com/questions/75664524/pandas-multiindex-updating-with-derived-values
I am tryng to update a MultiIndex frame with derived data. My multiframe is a time series where 'Vehicle_ID' and 'Frame_ID' are the levels of index and I iterate through each Vehicle_ID in order and compute exponential weighted avgs to clean the data and try to merge the additional columns to the original MultiIndex da...
You can create an empty dataframe outside the loop to store the results, and then concatenate the results from each iteration to this empty dataframe. v_ids = trajec.index.get_level_values('Vehicle_ID').unique().values results = pd.DataFrame() # empty dataframe to store results for id in v_ids: ewm_x = trajec.loc[(id,)...
3
1
75,664,404
2023-3-7
https://stackoverflow.com/questions/75664404/how-to-extract-hex-color-codes-from-a-colormap
From the below branca colormap import branca color_map = branca.colormap.linear.PuRd_09.scale(0, 250) colormap = color_map.to_step(index=[0, 10, 20, 50, 70, 90, 120, 200]) How can I extract hex colours for all the steps(index) from the above Branca colormap?
You can use matplotlib.colors.to_hex on colormap.colors: from matplotlib.colors import to_hex out = [to_hex(c) for c in colormap.colors] # or out = list(map(to_hex, colormap.colors)) Output: ['#f7f4f9', '#f0ebf4', '#e3d9eb', '#d0aad2', '#d084bf', '#e44199', '#67001f']
3
2
75,663,632
2023-3-7
https://stackoverflow.com/questions/75663632/airflow-exceptions-airflowexception-branch-task-ids-must-contain-only-valid-t
I have a dag which contains 1 custom task, 1 @task.branch task decorator and 1 taskgroup, inside the taskgroup I have multiple tasks that need to be triggered sequentially depending on the outcome of the @task.branch. PROCESS_BATCH_data_FILE = "batch_upload" SINGLE_data_FILE_FIRST_OPERATOR = "validate_data_schema_task"...
When referring to a task nested in a task group you need to specify their task _id as "group_id.task_id". This should work: @task.branch(task_id = 'check_payload_type') def is_batch(**context): # data = context["dag_run"].conf["execution_context"].get("data") if isinstance(data, dict): subdag = "group1.validate_data_s...
4
7
75,663,011
2023-3-7
https://stackoverflow.com/questions/75663011/how-to-include-both-ends-of-a-pandas-date-range
From a pair of dates, I would like to create a list of dates at monthly frequency, including the months of both dates indicated. import pandas as pd import datetime # Option 1 pd.date_range(datetime(2022, 1, 13),datetime(2022, 4, 5), freq='M', inclusive='both') # Option 2 pd.date_range("2022-01-13", "2022-04-05", freq=...
using MonthEnd and Day offsets This is because 2022-04-05 is before your month end (2022-04-30). You can use: pd.date_range("2022-01-13", pd.Timestamp("2022-04-05")+pd.offsets.MonthEnd(), freq='M', inclusive='both') A more robust variant to also handle the case in which the input date is already the month end: pd.date...
3
3
75,600,994
2023-3-1
https://stackoverflow.com/questions/75600994/i-am-getting-access-blocked-error-while-trying-to-get-athentication-code-which-i
here is what is tried I changed the status of O Auth Consent screen from testing to publish and the app scope is external then i created the O Auth client Id token and then i tried this code but this is giving error when i try to authenticate to the app. from google.oauth2.credentials import Credentials from google_aut...
you cant use urn:ietf:wg:oauth:2.0:oob, this was discontinued. You would have better luck following the official QuickStart This sample will use creds = flow.run_local_server(port=0) to open the consent screen for you rather then asking you to click a link which will probably return a 404 error because you don't have a...
4
1
75,616,542
2023-3-2
https://stackoverflow.com/questions/75616542/how-to-set-whisper-decodingoptions-language
I'm trying to run whisper and I want to set the DecodingOptions.language with France (instead of using it's language detection). I have tried to write: options = whisper.DecodingOptions() options.language = "fr" but I'm getting error: FrozenInstanceError: cannot assign to field 'language' How can I set the language i...
You can change the language in the DecodingOptions in Whisper with the following command (as, for example, shown here): options = whisper.DecodingOptions(language="en")
5
8
75,657,917
2023-3-7
https://stackoverflow.com/questions/75657917/how-to-define-a-script-in-the-venv-bin-dir-with-pyproject-toml-in-hatch-or-any
Im unsure about the new doc on packaging with hatch and wonder if someone worked out how to define a script in a pip installable package. So in short I need to be able to direct python -m build to make a package with open_foo_bar.py as in the example, install into the (virtual env)/bin dir. my package looks like this (...
In theory the Python spec defines how entrypoints and scripts are supposed to be handled. Hatch has chosen to do it a bit differently, and I'm not sure if this is even considered best-practice. This approach combines Forced Inclusion with Metadata Entrypoints/CLI. Here's how you might achieve your desired outcome: Add...
3
2
75,653,850
2023-3-6
https://stackoverflow.com/questions/75653850/python-mypy-type-checking-not-working-as-expected
I'm new to python, and am a huge fan of static type checkers. I have some code that handles file uploads with the Bottle framework. See below. def transcribe_upload(upload: FileUpload) -> Alternative: audio:AudioSource = upload_source(upload) ... def upload_source(upload:FileUpload) -> AudioSource: ... I made a really...
bottle is not a statically-typed library (it offers no type annotations in bottle.py). Its organisation as a single bottle.py (instead of a package) also prevents you from making a py.typed yourself, which would otherwise allow mypy to pick up at least the class attributes, function/method signatures, and global variab...
4
5
75,656,976
2023-3-7
https://stackoverflow.com/questions/75656976/whats-the-difference-between-pip-install-bs4-and-pip-install-beautifulsoup4
When I search about the installation of the BeautifulSoup lib, sometimes I see pip install bs4, and sometimes pip install BeautifulSoup4. What's the difference between these 2 methods of installation?
bs4 is technically a different package; however, it is a dummy package designed to install the correct package: beautifulsoup4. https://pypi.org/project/bs4/ TLDR: You can use either the short name or long name
3
4
75,652,936
2023-3-6
https://stackoverflow.com/questions/75652936/how-to-unit-test-that-a-flask-apps-routes-are-protected-by-authlibs-resourcepr
I've got a Flask app with some routes protected by authlib's ResourceProtector. I want to test that a route I've set up is indeed protected by a authlib.integrations.flask_oauth2.ResourceProtector but I don't want to go to the trouble of creating a valid jwt token or anything like that. I want to avoid feeling like I'm...
The Flask docs subtly refer to Application Factories as having a use case involving testing: So why would you want to do this? Testing. You can have instances of the application with different settings to test every case. ... We can use an application factory to keep code out of the top-level which makes life hard ...
3
3
75,647,682
2023-3-6
https://stackoverflow.com/questions/75647682/how-can-i-resolve-flake8-unused-import-error-for-pytest-fixture-imported-from
I wrote pytest fixture in fixtures.py file and using it in my main_test.py . But I am getting this error in flake8: F401 'utils_test.backup_path' imported but unused for this code: @pytest.fixture def backup_path(): ... from fixtures import backup_path def test_filename(backup_path): ... How can I resolve this?
generally you should not do this making fixtures available via import side-effects is an unintentional implementation detail of how fixtures work and may break in the future of pytest if you want to continue doing so, you can use # noqa: F403 on the import, telling flake8 to ignore the unused imports (though the linter...
11
12
75,649,804
2023-3-6
https://stackoverflow.com/questions/75649804/create-dictionary-of-each-row-in-polars-dataframe
Lets assume we have below given dataframe. Now for each row I need to create dictionary and pass it to UDF for some logic processing.Is there a way to achieve this using either polars or pyspark dataframe ?
With Polars, you can use: # Dict of lists >>> df.transpose().to_dict(as_series=False) {'column_0': [1.0, 100.0, 1000.0], 'column_1': [2.0, 200.0, None]} # List of dicts >>> df.to_dicts() [{'Account number': 1, 'V1': 100, 'V2': 1000.0}, {'Account number': 2, 'V1': 200, 'V2': None}] Input dataframe: >>> df shape: (2, 3)...
4
6
75,646,975
2023-3-6
https://stackoverflow.com/questions/75646975/pandas-1-5-3-index-get-indexer-not-working-like-index-get-loc
I recently updated Pandas to the latest version, 1.5.3. I was using a version pre 1.4 previously. With the newest update I am getting a bunch of depreciation notices on index.get_loc and I am to use index.get_indexer. I updated my code to get_indexer, but now I am receiving a bunch of errors. My code uses timestamps as...
Here, the get_indexer() method expects an iterable object such as a list or an array of timestamps, not a single timestamp as an argument. To use the get_indexer() method with a single timestamp, you need to put the timestamp in a list or an array like below. idx_get_indexer = df.index.get_indexer([searchDate], method=...
4
5
75,627,734
2023-3-3
https://stackoverflow.com/questions/75627734/python-sparse-matrix-c-with-elements-c-ij-sum-j-mina-ij-b-ji-from-sparse-ma
I have two sparse matrices A and B where A and B have the same number of columns (but potentially different numbers of rows). I'm trying to get a sparse matrix C with elements c_ij = sum_j min(a_ij,b_ji), where a_ij and b_ij are elements of A and B, respectively. Can this be done efficiently, and ideally sparsely? Even...
In normal dense arrays this would be done more easily with a three-dimensional array, but those are unavailable in sparse form. Instead, import numpy as np from scipy.sparse import csr_array, coo_array # If you're able to start in COO format instead of CSR format, it will make the code below simpler A = csr_array([ [1,...
3
1
75,645,306
2023-3-5
https://stackoverflow.com/questions/75645306/plot-radial-heatmap-in-python
I have problems when plotting a radial heatmap in Python. I would like to plot values from pandas dataframe that has column angle, distance and count. Values for angle are from -180 to 180. The distance are values from 0 to 20 and count tells the value count of that pair (angle, distance). Example of one dataframe whit...
You can use np.histogram2d to calculate the counts for each bin. It has a parameter weight= where you can put the given counts per entry. The heatmap can be directly plotted via ax.pcolormesh on a polar subplot. The angles need to be converted to radians to match the polar plot. Optionally you can use ax.set_theta_zero...
3
5
75,645,700
2023-3-5
https://stackoverflow.com/questions/75645700/how-do-i-query-a-dynamodb-and-get-all-rows-where-col3-exists-not-0-null-bot
This is my DynamoDB table via serverless framework, added a secondary column index for "aaa_id": Devices: Type: AWS::DynamoDB::Table Properties: TableName: Devices BillingMode: PAY_PER_REQUEST AttributeDefinitions: - AttributeName: serial AttributeType: S - AttributeName: aaa_id AttributeType: N KeySchema: - Attribute...
You're over complicating things. Firstly, a number type cannot be null, as DynamoDB is schemaless you simply omit any value. Secondly, indexes can be sparse. As you're not interested in items which are 0 then simply don't set a value for that, which in turn will mean the item won't exist in the index. Then you simply S...
3
2
75,645,297
2023-3-5
https://stackoverflow.com/questions/75645297/django-gettext-lazy-not-working-in-string-interpolation-concatenation-inside
I have a dictionary of items with multiple properties. from django.utils.translation import ( gettext_lazy as _, ) {"item1": { "labels": [ _("label1"), "this is" + _("translatethis") + " label2", ] These items are then serialized in DRF. The problem is that _("label1") is being translated but "this is" + _("translatet...
The main problem is that _('translatethis') is not a string, but something that promises, when necessary, to be a string. When you however concatenate it with a string, it is time to keep its promise, and it thus presents a string, and it no longer can thus, when needed, check the active language. An option might be to...
3
3
75,644,077
2023-3-5
https://stackoverflow.com/questions/75644077/pytorch-runtimeerror-zero-dimensional-tensor-at-position-0-cannot-be-concate
I have two tensors: # losses_q tensor(0.0870, device='cuda:0', grad_fn=<SumBackward0>) # this_loss_q tensor([0.0874], device='cuda:0', grad_fn=<AddBackward0>) When I am trying to concat them, PyTorch raises an error: losses_q = torch.cat((losses_q, this_loss_q), dim=0) RuntimeError: zero-dimensional tensor (at positio...
losses_q is zero dimensional so can't be concatenated with anything. You can reshape it into a one dimensional tensor before concatenation. losses_q = torch.cat((losses_q.reshape(1), this_loss_q), dim=0)
6
8
75,641,884
2023-3-5
https://stackoverflow.com/questions/75641884/caching-behavior-in-jax
I have a function f that takes in a boolean static argument flag and performs some computation based on it's value. Below is a rough outline of this function. @partial(jax.jit, static_argnames=['flag']) def f(x, flag): # Preprocessing if flag: ... else: ... # Postprocessing Each time f is called with a different value...
If I understand your question correctly, then JAX by default behaves the way you would like it to behave. Each JIT-compiled function has an LRU cache of compilations based on the shape and dtype of dynamic arguments and the hash of static arguments. You can inspect the size of this cache using the _cache_size method of...
3
3
75,642,045
2023-3-5
https://stackoverflow.com/questions/75642045/separate-this-string-using-these-separator-elements-but-without-removing-them-fr
import re input_string = "Sus cosas deben ser llevadas allí, ella tomo a sí, Lucy la hermana menor, esta muy entusiasmada. por verte hoy por la tarde\n sdsdsd" #result_list = re.split(r"(?:.\s*\n|.|\n|;|,\s*[A-Z])", input_string) result_list = re.split(r"(?=[.,;]|(?<=\s)[A-Z])", input_string) print(result_list) Separa...
Condense your delimiter list pattern to the following "([.;\n]|,(?=\s*[A-Z]))" and use itertools.zip_longest to combine resulting substrings with followed delimiters: import re from itertools import zip_longest input_string = "Sus cosas deben ser llevadas allí, ella tomo a sí, Lucy la hermana menor, esta muy entusiasma...
3
2
75,639,679
2023-3-5
https://stackoverflow.com/questions/75639679/type-hint-for-a-cast-like-function-that-raises-if-casting-is-not-possible
I am having a function safe_cast which casts a value to a given type, but raises if the value fails to comply with the type at runtime: from typing import TypeVar T = TypeVar('T') def safe_cast(t: type[T], value: Any) -> T: if isinstance(value, t): return cast(T, value) raise TypeError() This works nicely with primiti...
typing.cast is likely to be special-cased in a type-checking implementation, because while this works in mypy, import typing as t if t.TYPE_CHECKING: reveal_type(t.cast(str | int, "string")) # mypy: Revealed type is "Union[builtins.str, builtins.int]" the type annotations for typing.cast don't actually do anything mea...
4
4
75,640,162
2023-3-5
https://stackoverflow.com/questions/75640162/django-showing-error-constraints-refers-to-the-joined-field
I have two models Product and Cart. Product model has maximum_order_quantity. While updating quantity in cart, I'll have to check whether quantity is greater than maximum_order_quantityat database level. For that am comparing quantity with maximum_order_quantity in Cart Model But it throws an error when I try to migrat...
You cannot reference fields on related models in database-level constraints like CheckConstraint. The error message you received is indicating that you cannot reference the maximum_order_quantity field of the Products model in the constraints attribute of the CartItems model. The reason for this is that the maximum_ord...
11
14
75,621,245
2023-3-2
https://stackoverflow.com/questions/75621245/how-to-solve-an-overdetermined-non-linear-set-of-equations-numerically-in-python
I am trying to solve a system of 4 exponential equations with two variables. However If I use fsolve python will only allow me two use as many equations as I have variables. But as I have infinitely many pairs of solutions (if only two equations are used) and I need to find the pair of variables that fits not only two ...
To add an arbitrary number of equations, I don't think you can use fsolve at all. Just run a least-squares minimisation, and make sure that you vectorise properly instead of rote repetition. The following does run and generate a result, though I have not assessed its accuracy. import numpy as np from scipy.optimize imp...
3
2
75,637,278
2023-3-4
https://stackoverflow.com/questions/75637278/why-do-small-changes-have-dramatic-effects-on-the-runtime-of-my-numba-parallel-f
I'm trying to understand why my parallelized numba function is acting the way it does. In particular, why it is so sensitive to how arrays are being used. I have the following function: @njit(parallel=True) def f(n): g = lambda i,j: zeros(3) + sqrt(i*j) x = zeros((n,3)) for i in prange(n): for j in range(n): tmp = g(i,...
TL;DR: allocations and inlining are certainly the source of the performance gap between the different version. Operating on Numpy array is generally a bit more expensive than view in Numba. In this case, the problem appear to be that Numba perform an allocation when using x[i] while it does not with x[i,:]. The thing i...
3
4
75,634,466
2023-3-4
https://stackoverflow.com/questions/75634466/include-or-exclude-license-files-from-package-data-with-pyproject-toml-and-set
TL;DR How does one reliably include files from LICENSES/ (REUSE-style) in source archive and wheels for a Python package with a src/ layout? How does one exclude specific files? Details I have a project structure that looks like . ├── pyproject.toml ├── LICENSES │ ├── MAIN.txt │ ├── SECUNDARY.txt ├── MANIFEST.in ├── ra...
It turns out that I was mistaken about the location of license-files (I first saw it in the "metadata" section on the doc); it must actually be in [tool.setuptools]. The other data include issue was maybe a cache issue, it seems to work in the following pyproject.toml: [build-system] requires = ["setuptools>=61.0"] bui...
5
5
75,632,978
2023-3-4
https://stackoverflow.com/questions/75632978/correct-way-to-use-venv-and-pip-in-pypy
I've been using cpython forever, but I'm new to pypy. In cpython, this is how I use virtual environments and pip. python3 -m venv venv source venv/bin/activate python3 -m pip install <package> I recently started using pypy for a project, and noticed that the following works. pypy3 -m venv venv source venv/bin/activate...
Are there any differences between cpython venv/pip and pypy venv/pip? Yes, PyPy make some changes in the venv Python code, so they may have some differences. Example for 3.7: CPython stdilb: https://github.com/python/cpython/blob/v3.7.13/Lib/venv/__init__.py PyPy stdlib: https://github.com/mozillazg/pypy/blob/releas...
6
3
75,602,771
2023-3-1
https://stackoverflow.com/questions/75602771/attributeerror-readonlyworksheet-object-has-no-attribute-defined-names
I am trying to open an xlsx file with Pandas and i recieve this error: Output exceeds the size limit. Open the full output data in a text editor --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[20], line 1 ----> 1 df = pd.read_excel("C:...
Restart Kernel. Had the same problem, downgraded openpyxl version to the 3.1.0, still wasn't working. Did a restart and runned it again. Worked!
3
1
75,627,989
2023-3-3
https://stackoverflow.com/questions/75627989/git-filter-repo-loses-the-remotes
I previously got this rewrite of history commit messages to work: #!/bin/bash # Create a temporary file to store the commit messages temp_file=$(mktemp) main_head_hash=$(git rev-parse main) suffix="⚠️ rebased since!" # Use git log to retrieve the commit messages and store them in the temporary file git log --pretty=for...
Removing the remote is by design. Quote from the author: filter-repo defaults to rewriting the whole repository and as such it creates history incompatible with the original. There are lots of things that can go wrong with pushing a rewritten history back up to the original location, something that other tools did not...
3
4
75,629,940
2023-3-3
https://stackoverflow.com/questions/75629940/how-to-replace-particular-characters-of-a-string-with-the-elements-of-a-list-in
There is a string: input_str = 'The substring of "python" from index @ to index @ inclusive is "tho"' and a list of indices: idx_list = [2, 4] I want to replace the character @ in str_input with each element of the idx_list to have the following output: output_str = 'The substring of "python" from index 2 to index 4 in...
One concise approach uses re.sub with a callback function: input_str = 'The substring of "python" from index @ to index @ inclusive is "tho"' idx_list = [2, 4] output_str = re.sub(r'\bindex @', lambda m: str(idx_list.pop(0)), input_str) print(output_str) # The substring of "python" from 2 to 4 inclusive is "tho" The i...
3
1
75,628,106
2023-3-3
https://stackoverflow.com/questions/75628106/python-creating-plot-based-on-observation-dates-not-as-a-time-series
I have the following dataset df id medication_date 1 2000-01-01 1 2000-01-04 1 2000-01-06 2 2000-04-01 2 2000-04-02 2 2000-04-03 I would like to first reshape the data set into days after the first observation per patient: id day1 day2 day3 day4 1 yes no no yes 2 yes yes yes no in order to ultimately create a plot wi...
Transform the sparse Series ('yes' medication) to dense Series by adding missing days ('no' medication) then reset the Series index (2000-01-01 -> 0, 2000-04-01 -> 0). Finally, reshape your dataframe. def f(sr): # Create missing dates dti = pd.date_range(sr.min(), sr.max(), freq='D') # Fill the Series with 'yes' or 'no...
3
2
75,627,029
2023-3-3
https://stackoverflow.com/questions/75627029/how-to-organise-dataframe-columns
I am trying to organise DataFrame columns based on the specific rules, but I don't know the way. For example, I have a DataFrame related to chemistry as shown below. Each row shows the number of chemical bonds in a chemical compound. OH HO CaO OCa OO NaMg MgNa 0 2 3 2 0 1 1 1 1 0 2 3 4 5 2 0 2 1 2 3 0 0 0 0 In chemis...
You can use str.findall to extract individual element and use frozenset and sort individual elements to reorganize the pairs. Using frozenset is not a good solution because for OO, the second will be lost. Now you can group by this sets and apply sum: # Modified from https://www.johndcook.com/blog/2016/02/04/regular-ex...
6
6
75,617,527
2023-3-2
https://stackoverflow.com/questions/75617527/why-do-similar-signal-slot-connections-behave-differently-after-pyqt5-to-pyside6
I'm porting a pyqt5 GUI to pyside6 and I'm running into an issue I don't understand. I have two QSpinboxes that control two GUI parameters: One spinbox controls the weight of a splitter, the other controls the row height in a QtableView. This is the code in pyqt5: spinbox1.valueChanged.connect(my_splitter.setHandleWidt...
It looks like PySide (or, to be precise, Shiboken, the wrapper that allows Python access to Qt objects) is not able to directly connect to slots of objects directly created by Qt. That seems a PySide bug: PyQt does not show that behavior, meaning that it's completely possible to achieve it. A similar behavior sometimes...
4
6
75,618,364
2023-3-2
https://stackoverflow.com/questions/75618364/why-does-true-2-in-python
I am completely perplexed. We came across a bug, which we easily fixed, but we are perplexed as to why the value the bug was generating created the output it did. Specifically: Why does ~True equal -2 in python? ~True >> -2 Shouldn't the bitwise operator ~ only return binary? (Python v3.8)
True is a specialization of int. In python, integers are signed and unbounded. If one were to invert a fixed-size integer like the 16 bit 0x0001, you'd get 0xfffe which is -2 signed. But python needs a different definition of that operation because it is not size bounded. In Unary arithmetic and bitwise operations pyth...
3
6
75,616,052
2023-3-2
https://stackoverflow.com/questions/75616052/sort-list-based-on-dictionary-values-even-with-missing-keys
I am trying to sort a list based on dictionary values. The only problem is that if a list contains something that doesn't exist in the dictionary it wont sort it. here is what I have d = { "hello0" : 0, "hello1" : 1, "hello2" : 2, "hello3" : 3 } l1 = ["hello1","hello3","hello0","hello2"] #list 1 l2 = ["hello4","hello1"...
max_value_dict = max(d.values()) sorted_l2 = sorted(l2,key=lambda x : d.get(x, max_value_dict + 1)) Whenever x is not a key in d, the value associated to x by d.get in the sort is strictly greater than every value in d. Thus x is placed at the end.
3
4
75,605,184
2023-3-1
https://stackoverflow.com/questions/75605184/left-align-the-titles-of-each-plotly-subplot
I have a facet wraped group of plotly express barplots , each with a title. How can I left align each subplot's title with the left of its plot window? import lorem import plotly.express as px import numpy as np import random items = np.repeat([lorem.sentence() for i in range(10)], 5) response = list(range(1,6)) * 10 ...
There's a few major challenges here: annotations are not aware of their column in the facet plot (which makes determining the x value difficult) the order in which annotations are created are from left to right, bottom to top (therefore, the annotations at the bottom of the plot are created first) if the number of sub...
3
6
75,601,631
2023-3-1
https://stackoverflow.com/questions/75601631/nested-loop-over-all-row-pairs-in-a-pandas-dataframe
I have a dataframe in the following format with ~80K rows. df = pd.DataFrame({'Year': [1900, 1902, 1903], 'Name': ['Tom', 'Dick', 'Harry']}) Year Name 0 1900 Tom 1 1902 Dick 2 1903 Harry I need to call a function with each combination of the name column as parameters. Currently I am doing this with the following code ...
Another solution to keep track of index/years would be to use a cross join: import pandas as pd df = pd.DataFrame({'Year': [1900, 1902, 1903], 'Name': ['Tom', 'Dick', 'Harry']}) df = df.reset_index() print(df.join(df, how='cross', lsuffix='_1', rsuffix='_2')) Output: index_1 Year_1 Name_1 index_2 Year_2 Name_2 0 0 19...
3
3
75,530,375
2023-2-22
https://stackoverflow.com/questions/75530375/polars-vs-pandas-size-and-speed-difference
I have a parquet file (~1.5 GB) which I want to process with polars. The resulting dataframe has 250k rows and 10 columns. One column has large chunks of texts in it. I have just started using polars, because I heard many good things about it. One of which is that it is significantly faster than pandas. Here is my issu...
Edit 30 January 2025: The answer below isn't true anymore and Polars switched to a faster implementation of the string type. As mentioned: a column "content" stores large texts (1 to 20 pages of text) which I need to preprocess and the store differently I guess. This is where polars must do much more work than pandas...
7
9
75,554,856
2023-2-24
https://stackoverflow.com/questions/75554856/how-do-you-fill-missing-dates-in-a-polars-dataframe-python
I do not seem to find an equivalent for Polars library. But basically, what I want to do is fill missing dates between two dates for a big dataframe. It has to be Polars because of the size of the data (> 100 mill). Below is the code I use for Pandas, but how can I do the same thing for Polars? import janitor import pa...
It sounds like you're looking for .upsample() Note that you can use the group_by parameter to perform the operation on a per-group basis. import polars as pl from datetime import datetime df = pl.DataFrame({ "date": [datetime(2023, 1, 2), datetime(2023, 1, 5)], "value": [1, 2] }) shape: (2, 2) ┌─────────────────────┬─...
4
4
75,588,250
2023-2-28
https://stackoverflow.com/questions/75588250/what-are-the-downsides-to-relying-purely-on-pyproject-toml
Say you have a Python program that you can successfully package using only pyproject.toml. What are the downsides? Why use setup.py or setup.cfg in this case?
There is no downside in not having a setup.py. It is just that in some particular cases some elements of the packaging can not be expressed in a descriptive manner (which means without code) in setup.cfg or pyproject.toml. This can range from some custom dynamic package metadata to the handling of packaging for custom ...
5
6
75,595,957
2023-2-28
https://stackoverflow.com/questions/75595957/how-to-flatten-split-a-tuple-of-arrays-and-calculate-column-means-in-polars-data
I have a dataframe as follows: df = pl.DataFrame( {"a": [([1, 2, 3], [2, 3, 4], [6, 7, 8]), ([1, 2, 3], [3, 4, 5], [5, 7, 9])]} ) Basically, each cell of a is a tuple of three arrays of the same length. I want to fully split them to separate columns (one scalar resides in one column) like the shape below: shape: (2, 9...
Piggybacking on some of the concepts in the other answers... We can see how much nesting there is by checking the inner datatype of the pl.List datatype for the column. This can be the condition for a loop. Here's an example with one further nesting of lists than the initial question: df = pl.DataFrame({"a": [([[1, 2],...
4
1
75,569,521
2023-2-26
https://stackoverflow.com/questions/75569521/why-does-math-cosmath-pi-2-not-return-zero
I came across some weird behavior by math.cos() (Python 3.11.0): >>> import math >>> math.cos(math.pi) # expected to get -1 -1.0 >>> math.cos(math.pi/2) # expected to get 0 6.123233995736766e-17 I suspect that floating point math might play a role in this, but I'm not sure how. And if it did, I'd assume Python just ch...
Any error in math.pi vs. π (there always is some) makes very little difference in one case math.cos(math.pi) and is quite significant in math.cos(math.pi/2). The curve is flat When math.cos(x) is very near 1.0, the curve is very flat: the slope is "close" to zero. About 47 million floating point x values near π have a...
5
8
75,568,011
2023-2-25
https://stackoverflow.com/questions/75568011/filter-polars-dataframe-based-on-when-rows-whose-specific-columns-contain-pairs
In this example, on columns ["foo", "ham"], I want rows 1 and 4 to be removed since they match a pair in the list df = pl.DataFrame( { "foo": [1, 1, 2, 2, 3, 3, 4], "bar": [6, 7, 8, 9, 10, 11, 12], "ham": ["a", "b", "c", "d", "e", "f", "b"] } ) pairs = [(1,"b"),(3,"e"),(4,"g")] The following worked for me but I think ...
It looks like an ANTI JOIN schema = ["foo", "ham"] (df.with_row_index() # just to show what "row numbers" were "removed" .join( pl.DataFrame(pairs, orient="row", schema=schema), on = schema, how = "anti" ) ) shape: (5, 4) ┌───────┬─────┬─────┬─────┐ │ index ┆ foo ┆ bar ┆ ham │ │ --- ┆ --- ┆ --- ┆ --- │ │ u32 ┆ i64 ┆ i...
4
7
75,550,124
2023-2-23
https://stackoverflow.com/questions/75550124/python-polars-how-to-add-a-progress-bar-to-map-elements-map-groups
Is it possible to add a progress bar to a Polars apply loop with a custom function? For example, how would I add a progress bar to the following toy example: df = pl.DataFrame( { "team": ["A", "A", "A", "B", "B", "C"], "conference": ["East", "East", "East", "West", "West", "East"], "points": [11, 8, 10, 6, 6, 5], "rebo...
I like the progress bars from Rich (which also comes bundled with pip) There's probably a neater way to package this up, but something like: from pip._vendor.rich.progress import ( Progress, SpinnerColumn, TimeElapsedColumn ) def polars_bar(total, title="Processing", transient=True): bar = Progress( SpinnerColumn(), *P...
5
7
75,534,590
2023-2-22
https://stackoverflow.com/questions/75534590/how-to-smooth-adjacent-polygons-in-python
I'm looking for a way to smooth polygons such that adjacent/touching polygons remain touching. Individual polygons can be smoothed easily, e.g., with PAEK or Bezier interpolation (https://pro.arcgis.com/en/pro-app/latest/tool-reference/cartography/smooth-polygon.htm), which naturally changes their boundary edge. But ho...
You can do this with the topojson library. Sample script: import matplotlib.pyplot as plt import geopandas as gpd from shapely import geometry import topojson x_min, x_max, y_min, y_max = 0, 20, 0, 20 ## Create original (coarse) polygons: staircase_points = [[(ii, ii), (ii, ii + 1)] for ii in range(x_max)] staircase_po...
4
1
75,583,626
2023-2-27
https://stackoverflow.com/questions/75583626/a-comprehensive-way-to-perform-step-by-step-debugging-of-python-code
I was wondering is there is a good and comprehensive way to debug python code step by step so that I can have a better idea of all the variables involved, their dimensions and values? What can be done to do step-by-step debugging?
JupyterLab is the current generation of Jupyter interface and has a debugger mode that allows you to step through code. See this post here and a related one here. Documentation is here. You can try it out without installing anything on your own system by clicking here to launch a temporary Jupyter session running on a ...
6
5
75,575,346
2023-2-26
https://stackoverflow.com/questions/75575346/how-can-i-configure-my-tools-to-ignore-or-prevent-updates-to-the-execution-count
I'm using the Jupyter extension (v2022.9.1303220346) in Visual Studio Code (v1.73.1). To reproduce this issue, make any modification to the notebook and check it into git. You'll observe that you get an extra difference for execution_count. For example (display from Git Gui): - "execution_count": 7, + "execution_count"...
Can Jupyter or VS Code be configured to stop updating this value or (better) ignore it altogether? I'm not sure about VS Code, and I think the answer for VS Code config options might be no after reading some discussions in GitHub feature-request issue tickets for Jupyter notebooks, where the fact that they are featur...
7
4
75,539,007
2023-2-22
https://stackoverflow.com/questions/75539007/custom-validation-for-fastapis-query-parameter-using-pydatinc-causes-internal-s
My GET endpoint receives a query parameter that needs to meet the following criteria: be an int between 0 and 10 be even number 1. is straight forward using Query(gt=0, lt=10). However, it is not quiet clear to me how to extend Query to do extra custom validation such as 2.. The documentation ultimately leads to pyda...
Option 1 Raise HTTPException directly instead of ValueError, as demonstrated in Option 1 of this answer. Example: from fastapi import FastAPI, Depends, Query, HTTPException from pydantic import BaseModel, validator app = FastAPI() class CommonParams(BaseModel): n: int = Query(default=..., gt=0, lt=10) @validator('n') d...
6
4
75,548,444
2023-2-23
https://stackoverflow.com/questions/75548444/polars-dataframe-drop-nans
I need to drop rows that have a nan value in any column. As for null values with drop_nulls() df.drop_nulls() but for nans. I have found that the method drop_nans exist for Series but not for DataFrames df['A'].drop_nans() Pandas code that I'm using: df = pd.DataFrame( { 'A': [0, 0, 0, 1,None, 1], 'B': [1, 2, 2, 1,1,...
Another definition is: to keep rows where all values are not NaN For that, we can use: .is_not_nan() to test for "not nan" pl.col(pl.Float32, pl.Float64) to select only float columns .all_horizontal() to compute a row-wise True/False comparison DataFrame.filter to keep only the "True" rows df = pl.from_repr(""" ┌────...
7
6
75,559,239
2023-2-24
https://stackoverflow.com/questions/75559239/how-do-i-write-a-polars-dataframe-to-an-external-database
I have a Polars dataframe that I want to write to an external database (SQLite). How can I do it? In Pandas you have to_sql() but I couldn't find any equivalent in Polars.
You can use the DataFrame.write_database method.
4
3
75,563,256
2023-2-25
https://stackoverflow.com/questions/75563256/after-the-mambaforge-install-completes-how-do-i-get-to-be-able-to-run-mamba-com
I downloaded the mambaforge install file for Windows, ran it, and it successfully completed. Mamba has a quickstart guide with CLI commands here: https://mamba.readthedocs.io/en/latest/user_guide/mamba.html But I can't figure out WHERE to enter the commands (e.g. mamba create -n envname). Is there supposed to be a Star...
I was expecting it to create a "mambaforge" start menu shortcut. As far as I can tell no start menu shortcuts were created. The start menu shortcut is called "miniforge prompt" and behaves as you expect from Anaconda prompt. Mambaforge is based on miniforge, and the prompt stems from that.
11
7
75,529,492
2023-2-22
https://stackoverflow.com/questions/75529492/importerror-cannot-import-name-ordereddict-from-typing
C:\Users\jpala\.conda\envs\tf\python.exe C:\Users\jpala\Documents\ML\train.py Traceback (most recent call last): File "C:\Users\jpala\Documents\ML\train.py", line 5, in <module> import tensorflow as tf File "C:\Users\jpala\.conda\envs\tf\lib\site-packages\tensorflow\__init__.py", line 37, in <module> from tensorflow.py...
According to [Python.docs]: class typing.OrderedDict(collections.OrderedDict, MutableMapping[KT, VT]) (emphasis is mine): New in version 3.7.2. Example: (base) [cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q075529492]> sopr.bat ### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ### [p...
4
4
75,552,364
2023-2-24
https://stackoverflow.com/questions/75552364/callback-to-subset-geometry-data-dash-plotly
I'm hoping to include a dropdown bar with a callback function that allows the user to display specific points within smaller areas. Initially, I want to use all point geometry data as a default. I'm then aiming to include a dropdown bar and callback function that returns smaller subsets from this main df. This is accom...
I think the main task is converting update_dataset into a callback function that takes the dropdown selection as an input, and outputs both the newly updated scatter mapbox and bar chart. In order to do this, you need to provide an id argument in dcc.Graph for both of those figures. Then inside the callback, you can re...
6
2
75,596,471
2023-2-28
https://stackoverflow.com/questions/75596471/error-while-working-with-instapy-modulenotfounderror-no-module-named-clarifa
from instapy import InstaPy session = InstaPy(username='name', password='password') session.login() (I use VSC) my code breaks at the first line with error: from clarifai.rest import ClarifaiApp, Workflow ModuleNotFoundError: No module named 'clarifai.rest' I tried reinstalling instapy, that specific module, but nothi...
The solution is here I tested Franchen Bao's comment and it worked for me. I had this error after the emoji error. Looks like this project is a little unstable and can only handle certain versions of each package, like Franchen Bao said. pip uninstall clarifai pip install clarifai==2.6.2
4
7
75,533,746
2023-2-22
https://stackoverflow.com/questions/75533746/custom-component-in-streamlit-is-having-trouble-loading
I'm testing out a custom authentication component for my Streamlit app. However, when using the component in production, it fails to render for some reason. I've managed to get i to work in dev mode by forking the code and adding it to my Streamlit project - but I still can't make it run in production. Upon digging a ...
I am the author of said custom Streamlit Component, and I have made a small sample project that utilizes the component. I just ran the project in Docker, and it works for me. I have yet to discover what can cause the troubles on Windows. Essentially, the sample project is just a barebone Streamlit dashboard consisting ...
5
1
75,582,039
2023-2-27
https://stackoverflow.com/questions/75582039/how-to-optimize-a-function-involving-max
I am having problems minimizing a simple if slightly idiosyncratic function. I have scipy.optimize.minimize but I can't get consistent results. Here is the full code: from math import log, exp, sqrt from bisect import bisect_left from scipy.optimize import minimize from scipy.optimize import Bounds import numpy as np d...
The problem here is that you are exploring immense non convex search space by trying to optimize 20 variables at the same time, so usual optimization methods such as gradient descent related etc. will potentially be trapped in a local minima. In your case, as you are starting from a random coordinates each time, you en...
4
6
75,590,142
2023-2-28
https://stackoverflow.com/questions/75590142/decorators-to-configure-sentry-error-and-trace-rates
I am using Sentry and sentry_sdk to monitor errors and traces in my Python application. I want to configure the error and trace rates for different routes in my FastAPI API. To do this, I want to write two decorators called sentry_error_rate and sentry_trace_rate that will allow me to set the sample rates for errors an...
I finally managed to do it using a registry mechanism. Each route with a decorator are registred in a dictionary with their trace/error rate. I then used a trace_sampler/before_send function as indicated here: Setting a sampling function Filtering error events Here's my sentry_wrapper.py: import asyncio import random...
3
2
75,590,032
2023-2-28
https://stackoverflow.com/questions/75590032/how-do-i-create-a-model-instance-using-raw-sql-in-async-sqlalchemy
I have asyncio sqlalchemy code: import asyncio from sqlalchemy.orm import sessionmaker, declarative_base from sqlalchemy import text, Column, Integer, String from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession async_engine = create_async_engine(f'mysql+aiomysql://root:example@127.0.0.1:3306/spy-bot') A...
You would do it in the same way, albeit using 2.0-style syntax as the legacy Query class is not supported in asyncio: result = await session.scalars(select(User).from_statement(text_object)) The docs at Getting ORM Results from Textual Statements apply. The complete function might look like this: import sqlalchemy as ...
3
5
75,596,780
2023-2-28
https://stackoverflow.com/questions/75596780/error-when-trying-to-display-colorbar-using-matplotlib-library-python-3-9
I'm currently learning to use the librosa library and when trying to display a colorbar on an associated spectrogram, I get an inexplicable error. I'm not that familiar with matplotlib I've searched everywhere for a solution and I can't help but feel I'm missing something here. The following code: n_fft = 2048 #number ...
It seems the problem was to do with the most recent version of matplotlib. I managed to fix the problem by downgrading matplotlib 3.7.0 to matplotlib 3.6.0 using pip install matplotlib==3.6.0 I got the desired colorbar after doing this. Thank you for trying to help!
3
3
75,598,282
2023-2-28
https://stackoverflow.com/questions/75598282/why-is-matplotlib-cutting-off-my-very-specific-axis-label
Here's the bottom line: I need to make publication-quality plots with Greek letters and subscripts in axis labels. Yet, in some rather specific cases, the label gets cut off near the tick labels. For example, I really need a label of $\alpha_-$ for some plots, but the bottom of the $\alpha$ gets cut off. Interestingly,...
If there is a "bigger" subscript, it seems to work better import matplotlib.pyplot as plt plt.rc("axes", labelsize=22) plt.plot([0,1],[0,1]) plt.ylabel(r"$\alpha_{x}$") plt.show() It's when the subscript is "-" that we get problems If you become desperate, here is a hack that makes the whole alpha visible plt.ylabel...
4
2
75,587,445
2023-2-28
https://stackoverflow.com/questions/75587445/no-module-named-sqlalchemy-databases
While trying to install the requirements to use magic sql, I encounter this error, No module named 'sqlalchemy.databases', with this code: import pandas as pd from sqlalchemy.engine import create_engine # Presto engine = create_engine('presto://localhost:8080/system/runtime') #Read Presto Data query into a DataFrame df...
ipython-sql 0.5.0 depends on sqlalchemy 2 which deprecated the sqlalchemy.databases package in favor of the sqlalchemy.dialects package (details). My solution was to pin both of these libraries to the following versions: %pip install ipython-sql==0.4.1 %pip install sqlalchemy==1.4.46
3
3
75,594,651
2023-2-28
https://stackoverflow.com/questions/75594651/cant-create-exe-with-pyinstaller-when-openais-whisper-is-imported
I am trying to create a small program that works with OpenAI's Whisper. I then build the Python script to the .exe file using PyInstaller (auto-py-to-exe). When I run the .exe file, I get the following error: Traceback (most recent call last): File "transformers\utils\versions.py", line 108, in require_version File "im...
My problem was solved by adding --recursive-copy-metadata "openai-whisper" to the PyInstaller command.
4
2
75,591,496
2023-2-28
https://stackoverflow.com/questions/75591496/why-autopep8-dont-format-on-save
Autopep8 don't working at all. Here's my setting: { "editor.defaultFormatter": "ms-python.autopep8", "editor.formatOnSave": true, "editor.formatOnPaste": true, "editor.formatOnType": true, "autopep8.showNotifications": "always", "indentRainbow.colorOnWhiteSpaceOnly": true, "[python]": { "editor.formatOnType": true }, "...
Add "python.formatting.provider": "autopep8", to your settings.json. Read document for more information.
3
2
75,597,598
2023-2-28
https://stackoverflow.com/questions/75597598/how-to-efficiently-remove-duplicates-from-list-of-lists-nested-containing-dict
I have a list of lists, where each list contains a dictionary and integer. Sometimes duplicate lists occur, and I wish to remove these from the parent list directly. Currently, I am creating a new list and iterating over the old list to ensure only unique values are appended, but I feel this is bad practice. Can this b...
If you can use pandas: import pandas as pd df = pd.DataFrame(TRIAL, columns=['d', 'i']) out = df.groupby(df['d'].apply(dict.values).apply(tuple)).last().values.tolist() print(out) [[{'http': '130.61.100.135:80', 'https': '130.61.100.135:80'}, 1], [{'http': '157.245.27.9:3128', 'https': '157.245.27.9:3128'}, 0], [{'http...
3
5
75,567,769
2023-2-25
https://stackoverflow.com/questions/75567769/vscode-does-not-recognize-my-flask-dependency-installed-with-poetry
I am learning how to use VSCode for Python development by building a simple Flask app. I use Poetry for dependency management. I have a simple app.py where I'm importing flask and defining a basic route like so: from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello, Flask!" In the VSC...
Re-starting VSCode did the trick. I wasn't seeing the Poetry interpreter when I looked for it via cmd+shift+p and Python: Select Interpreter prior to re-starting, and now I do. Selecting the Poetry interpreter it fixes the issue!
4
2
75,593,816
2023-2-28
https://stackoverflow.com/questions/75593816/simplify-expressions-given-by-sympy-sympify
sp.simplify doesn't seem to work when your expression is given by sp.sympify. How can I change that? import sympy as sp r = sp.Symbol('r', real = True) f_str = 'sqrt(1/r**4)' f1 = sp.sympify( f_str ) f2 = sp.sqrt(1/r**4) for f in f1,f2: sp.pprint(sp.simplify(f)) which outputs ____ ╱ 1 ╱ ── # f1 ╱ 4 ╲╱ r 1 ── # f2 2 r...
The r in f1 isn't the same as the r symbol you defined: >>> f1.free_symbols == f2.free_symbols False In particular, this means that the assumption that r is real doesn't carry through, which is necessary for the simplification you want. You can remedy this postmortem by substituting the r in f1 with your r symbol: >>>...
3
6