question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
78,719,078
2024-7-8
https://stackoverflow.com/questions/78719078/how-to-type-hint-a-pl-date
Suppose we create some dates: import polars as pl df = pl.DataFrame( [ pl.Series("start", ["2023-01-01"], dtype=pl.Date).str.to_date(), pl.Series("end", ["2024-01-01"], dtype=pl.Date).str.to_date(), ] ) Now I can create a date range from these: dates = pl.date_range(df[0, "start"], df[0, "end"], "1mo", eager=True) Bu...
Since datetime.date is compatible with the start and end parameters expected by pl.date_range() this should be sufficient: import polars as pl from datetime import date def my_date_range(start: date, end: date) -> pl.Series: return pl.date_range(start, end, "1mo", eager=True)
2
3
78,716,751
2024-7-7
https://stackoverflow.com/questions/78716751/removing-one-field-from-a-struct-in-polars
I want to remove one field from a struct. Currently, I have it set up like this, but is there a simpler way to achieve this? import polars as pl import polars.selectors as cs def remove_one_field(df: pl.DataFrame) -> pl.DataFrame: meta_data_columns = (df.select('meta_data') .unnest('meta_data') .select(cs.all() - cs.by...
You can use struct.field() which can accept either list of strings or multiple string arguments. You know your DataFrame' schema() so you can easily create list of fields you want fields = [c[0] for c in input_df.schema["meta_data"] if c[0] != "system_data"] input_df.with_columns( meta_data = pl.struct( pl.col.meta_dat...
5
5
78,713,279
2024-7-5
https://stackoverflow.com/questions/78713279/pyspark-retrieve-the-value-from-the-field-dynamically-specified-in-other-field
I'm working with PySpark and have a challenging scenario where I need to dynamically retrieve the value of a field specified in another field of the same DataFrame. I then need to compare this dynamically retrieved value with a fixed value. Here’s the context: I have a DataFrame df_exploded with the following schema: r...
You can create a udf to handle the dynamic comparison part as follows: from pyspark.sql import SparkSession from pyspark.sql import functions as F from pyspark.sql.types import StructType, StructField, StringType spark = SparkSession.builder.getOrCreate() data = [ ("1", "John", ("someField1", "equals", "100"), {"someFi...
2
1
78,716,778
2024-7-7
https://stackoverflow.com/questions/78716778/how-can-i-use-groupby-in-a-way-that-each-group-is-grouped-with-the-previous-over
My DataFrame: import pandas as pd df = pd.DataFrame( { 'a': list('xxxxxxxxxxyyyyyyyyy'), 'b': list('1111222333112233444') } ) Expected output is a list of groups: a b 0 x 1 1 x 1 2 x 1 3 x 1 4 x 2 5 x 2 6 x 2 a b 4 x 2 5 x 2 6 x 2 7 x 3 8 x 3 9 x 3 a b 10 y 1 11 y 1 12 y 2 13 y 2 a b 12 y 2 13 y 2 14 y 3 15 y 3 a b 1...
You can combine groupby, itertools.pairwise and concat: from itertools import pairwise out = [pd.concat([a[1], b[1]]) for a, b in pairwise(df.groupby(['a', 'b']))] Functional variant: from itertools import pairwise from operator import itemgetter out = list(map(pd.concat, pairwise(map(itemgetter(1), df.groupby(['a', '...
2
4
78,716,735
2024-7-7
https://stackoverflow.com/questions/78716735/scraping-table-from-web-page
I'm trying to scrape a table from a webpage using Selenium and BeautifulSoup but I'm not sure how to get to the actual data using BeautifulSoup. webpage: https://leetify.com/app/match-details/5c438e85-c31c-443a-8257-5872d89e548c/details-general I tried extracting table rows (tag <tr>) but when I call find_all, the arra...
why don't they show up with BeautifulSoup.find_all() ?? after taking a quick glance, it seems like it takes a long time for the page to load. The thing is, when you pass the driver.page_source to BeautifulSoup, not all the HTML/CSS is loaded yet. So, the solution would be to use an Explicit wait: Wait until page is l...
2
2
78,715,993
2024-7-6
https://stackoverflow.com/questions/78715993/how-do-i-add-legend-handles-in-matplotlib
I would like to add a legend to my Python plot, with a title and legend handles. My sincere apologies as a complete novice in Python, I got my code from a post. The code below works, but I want to add a legend. All the plots I have googled deal with line plots with several lines. import geopandas as gpd import matplotl...
You could map the risks to the labels and make a categorical plot : from matplotlib.colors import ListedColormap colors = {1: "green", 2: "yellow", 3: "orange", 4: "red"} # or a list labels = {1: "no risk", 2: "low risk", 3: "medium risk", 4: "high risk"} catego = map_df["risk"].astype(str).str.cat(map_df["risk"].map(l...
3
1
78,715,315
2024-7-6
https://stackoverflow.com/questions/78715315/filter-openstreetmap-edges-on-surface-type
I'm accessing OpenStreetMap data using osmnx, using: import osmnx as ox graph = ox.graph_from_place('Bennekom') nodes, edges = ox.graph_to_gdfs(graph) I know from openstreetmap.org/edit that all (?) street features have an attribute Surface, which can be Unpaved, Asphalt, Gravel, et cetera. However, that info is not i...
You need to include the surface key in the useful_tags_way : import osmnx as ox ox.settings.useful_tags_way = ["surface"] # << add this line graph = ox.graph_from_place("Bennekom") nodes, edges = ox.graph_to_gdfs(graph) NB: You might need to explode the surface column in order to get all matches when filtering. print(...
2
2
78,714,232
2024-7-6
https://stackoverflow.com/questions/78714232/how-to-convert-binary-to-string-uuid-without-udf-in-apache-spark-pyspark
I can't find a way to convert a binary to a string representation without using a UDF. Is there a way with native PySpark functions and not a UDF? from pyspark.sql import DataFrame, SparkSession import pyspark.sql.functions as F import uuid from pyspark.sql.types import Row, StringType spark_test_instance = (SparkSessi...
You can use hex for getting the id_str: from pyspark.sql import SparkSession import pyspark.sql.functions as F import uuid spark = SparkSession.builder.getOrCreate() data = [(uuid.uuid4().bytes,)] df = spark.createDataFrame(data, ["id"]) df = df.withColumn("id_str", F.lower(F.hex("id"))) df.show(truncate=False) # +----...
3
2
78,712,629
2024-7-5
https://stackoverflow.com/questions/78712629/gpt-langchain-experimental-agent-allow-dangerous-code
I'm creating a chatbot in VS Code where it will receive csv file through a prompt on Streamlit interface. However from the moment that file is loaded, it is showing a message with the following content: ValueError: This agent relies on access to a python repl tool which can execute arbitrary code. This can be dangerou...
The referenced security notice is in https://api.python.langchain.com/en/latest/agents/langchain_experimental.agents.agent_toolkits.pandas.base.create_pandas_dataframe_agent.html. Just do what the message tells you. Do a security analysis, create a sandbox environment for your thing to run in, and then add allow_danger...
2
2
78,709,252
2024-7-5
https://stackoverflow.com/questions/78709252/recursive-types-in-python-and-difficulties-inferring-the-type-of-typex
Trying to build recursive types to annotate a nested data structure, I hit the following. This code is correct according to mypy: IntType = int | list["IntType"] | tuple["IntType", ...] StrType = str | list["StrType"] | tuple["StrType", ...] def int2str(x: IntType) -> StrType: if isinstance(x, list): return list(int2st...
There's no type erasure for type(x). What should mypy say about the following? x: list[int] = [1] reveal_type(type(x)) If we ask, it says: Revealed type is "type[builtins.list[builtins.int]]" So, when you ask for type(x)(some_strtype_iterator), it rightfully complains that you try to construct a list[StrType] | tupl...
2
2
78,706,223
2024-7-4
https://stackoverflow.com/questions/78706223/how-to-efficiently-compute-running-geometric-mean-of-a-numpy-array
Rolling arithmetic mean can simply be computed with Numpy's 'convolve' function, but how could I efficiently create an array of running geometric means of some array a and a given window size? To give an example, for an array: [0.5 , 2.0, 4.0] and window size 2, (with window size decreasing at the edges) I want to quic...
import numpy as np from numpy.lib.stride_tricks import sliding_window_view from scipy.stats import gmean window = 2 a = [0.5, 2.0, 4.0] padded = np.pad(a, window - 1, mode="constant", constant_values=np.nan) windowed = sliding_window_view(padded, window) result = gmean(windowed, axis=1, nan_policy="omit") print(result)...
2
3
78,711,101
2024-7-5
https://stackoverflow.com/questions/78711101/change-mantissa-in-scientific-notation-from-0-1-instead-of-1-10
I want to format a number so that the mantissa is between 0 and 1 instead of 1 and 10 in scientific notation. For example; a=7.365 print("{:.6e}".format(a)) This will output 7.365000e+00, but I want it to be 0.736500e+01.
I suppose you could always try constructing your own preformatted string. (No idea if this works in Python 2.7, though). import math def fixit( x, n ): if x == 0.0: return f" {x:.{n}e}" s = ' ' if x >= 0 else '-' y = math.log10( abs(x) ) m = math.floor(y) + 1 z = 10 ** ( y - m ) return s + f"{z:.{n}f}e{m:+03d}" for x i...
2
1
78,710,552
2024-7-5
https://stackoverflow.com/questions/78710552/unexpected-generator-behaviour-when-not-assigned-to-a-variable
Could someone explain the difference between these two executions? Here is my generator function: def g(n): try: yield n print("first") except BaseException as e: print(f"exception {e}") raise e finally: print("second") When I execute: >>> a = next(g(2)) exception second Could someone explain why a = next(g(2)) raise...
In the first scenario, the generator is garbage collected after next(), triggering finally and raising an exception. In the second, the generator is kept by x, preventing this and allowing normal operation. Edit: GeneratorExit exception is thrown when a generator is closed, after that finally block will be exceuted. Al...
3
4
78,710,347
2024-7-5
https://stackoverflow.com/questions/78710347/pyspark-join-fields-in-json-to-a-dataframe
I am trying to pull out some fields from a JSONn string into a dataframe. I can achieve this by put each field in a dataframe then join all the dataframes like below. But is there some easier way to do this? Because this is just an simplified example and I have a lot more fields to extract in my project. from pyspark....
Update1: You don't even have to explicitly define the schema here and instead, you may simply use schema_of_json as follows: from pyspark.sql import SparkSession from pyspark.sql.functions import from_json, col, explode, schema_of_json, lit spark = SparkSession.builder.getOrCreate() s = '{"job_id":"123","settings":{"ta...
2
1
78,705,284
2024-7-4
https://stackoverflow.com/questions/78705284/using-variable-out-of-nested-function
class Solution: def isBalanced(self, root: Optional[TreeNode]) -> bool: balanced = [True] def node_height(root): if not root or not balanced[0]: return 0 left_height = node_height(root.left) right_height = node_height(root.right) if abs(left_height - right_height) > 1: balanced[0] = False return 0 return 1 + max(left_h...
Nested functions can access variables from their parent functions. However, in your first case, not only you are accessing the value of the balanced variable, but you are also attempting to modify it. Whenever you create a variable in a nested function with the same name as a variable in the parent function, the nested...
4
5
78,708,646
2024-7-4
https://stackoverflow.com/questions/78708646/how-to-translate-this-sql-line-to-work-on-flask-sqlalchemy
I need some help to translate a sql command to work on Flask. I am trying to filter the results of a query. This command below do what I need in mysql: select t.date, t.name from `capacitydata`.`allflash_dev` t inner join ( select name, max(date) as MaxDate from `capacitydata`.`allflash_dev` group by name) tm on t.name...
You can use this. Use statement with your flask sqlalchemy session / query. from sqlalchemy import func, select from sqlalchemy.orm import aliased allflash_dev = aliased(Block) tm = ( select(allflash_dev.name, func.max(allflash_dev.date).label("MaxDate")) .group_by(allflash_dev.name) .subquery() ) statement = select(Bl...
2
1
78,709,058
2024-7-4
https://stackoverflow.com/questions/78709058/subtracting-pandas-series-from-all-elements-of-another-pandas-series-with-a-comm
I have a pandas series.groupby objects, call it data. If I print out the elements, it looks like this: <pandas.core.groupby.generic.SeriesGroupBy object at ***> (1, 0 397.44 1 12.72 2 422.40 Name: value, dtype: float64) (2, 3 398.88 4 6.48 5 413.52 Name: value, dtype: float64) (3, 6 398.40 7 68.40 8 18.96 9 56.64 10 40...
Try: cumulative_sums = data.apply(lambda x: x.cumsum() - x.iat[0]) print(cumulative_sums) Prints: a b 1 0 0.00 1 12.72 2 435.12 2 3 0.00 4 6.48 5 420.00 3 6 0.00 7 68.40 8 87.36 9 144.00 10 550.56 Name: value, dtype: float64
2
1
78,708,937
2024-7-4
https://stackoverflow.com/questions/78708937/optimize-this-python-code-that-involves-matrix-inversion
I have this line of code that involves a matrix inversion: X = A @ B @ np.linalg.pinv(S) A is an n by n matrix, B is an n by m matrix, and S is an m by m matrix. m is smaller than n but usually not orders of magnitude smaller. Usually m is about half of n. S is a symmetrical positive definite matrix. How do I make thi...
So your problem is XS = AB = C. As you've stated, this can be rewritten as S'X' = B'A' = C'. C is of size m x n, but this batched problem can be solved using scipy.linalg.solve. In this case, I recommend the scipy alternative (rather than numpy) because you have stated that S is symmetric, so you can pass assume_a="sym...
2
2
78,706,643
2024-7-4
https://stackoverflow.com/questions/78706643/how-to-speed-up-the-interpolation-for-this-particular-example
I made a script that performs tri-linear interpolation on a set of points using pandas for data handling and Numba for computational efficiency. Currently, it requires $\mathcal{O}(1) \text{ s}$ if considering $10^{5}$ points. This is the code, assuming some test tabulated data: import numpy as np import pandas as pd f...
First of all, grid_x, grid_y and grid_z are small so a binary search is not the most efficient way to find a value. A basic linear search is faster for small arrays. Here is an implementation: @nb.njit('(float64[::1], float64)', inline='always') def searchsorted_opt(arr, val): i = 0 while i < arr.size and val > arr[i]:...
2
2
78,707,895
2024-7-4
https://stackoverflow.com/questions/78707895/type-of-iterator-is-any-in-zip
The following script: from collections.abc import Iterable, Iterator class A(Iterable): _list: list[int] def __init__(self, *args: int) -> None: self._list = list(args) def __iter__(self) -> Iterator[int]: return iter(self._list) a = A(1, 2, 3) for i in a: reveal_type(i) for s, j in zip("abc", a): reveal_type(j) yield...
Comparing for loop and zip object is not an apples-to-apples comparison. For loop How is for i in X checked? At least in current mypy source, for loop is checked by looking up __iter__ signature on the type of X and using its return type. So it doesn't look at your Iterable inheritance, it finds the nearest __iter__ in...
2
1
78,704,660
2024-7-4
https://stackoverflow.com/questions/78704660/how-to-format-the-dataframe-into-a-2d-table
I have following issue with formatting a pandas dataframe into a 2D format. My data is: +----+------+-----------+---------+ | | Jobs | Measure | Value | |----+------+-----------+---------| | 0 | Job1 | Temp | 43 | | 1 | Job1 | Humidity | 65 | | 2 | Job2 | Temp | 48 | | 3 | Job2 | TempS | 97.4 | | 4 | Job2 | Humidity | ...
You can use unstack() and join(): import pandas as pd from tabulate import tabulate data = { 'Jobs': ['Job1', 'Job1', 'Job2', 'Job2', 'Job2', 'Job3', 'Job1', 'Job1', 'Job3', 'Job1', 'Job1', 'Job2', 'Job2', 'Job2', 'Job3', 'Job1', 'Job1', 'Job3', 'Job2'], 'Measure': ['Temp', 'Humidity', 'Temp', 'TempS', 'Humidity', 'Hum...
3
1
78,699,964
2024-7-3
https://stackoverflow.com/questions/78699964/how-can-one-combine-iterables-keeping-only-the-first-element-with-each-index
Let's say I have a number of iterables: [[1, 2], [3, 4, 5, 6], [7, 8, 9], [10, 11, 12, 13, 14]] How can I get only each element that is the first to appear at its index in any of the iterables? In this case: [1, 2, 5, 6, 14] Visualized: [1, 2] [_, _, 5, 6] [_, _, _] [_, _, _, _, 14]
can it done in more functional style? Sure, but I wouldn't. Davis Herring's approach is already lovely. Here's a "more functional" way, but more obscure to my eyes: from itertools import zip_longest SKIP = object() def chain_suffixes(*iters): return (next(a for a in s if a is not SKIP) for s in zip_longest(*iters, fi...
3
3
78,701,979
2024-7-3
https://stackoverflow.com/questions/78701979/casting-rdd-to-a-different-type-from-float64-to-double
I have a code like below, which uses pyspark. test_truth_value = RDD. test_predictor_rdd = RDD. valuesAndPred = test_truth_value.zip(lasso_model.predict(test_predictor_rdd)).map(lambda x: ((x[0]), (x[1]))) metrics = RegressionMetrics(valuesAndPred) When i run the code, I get the following error pyspark.errors.exceptio...
First, as mentioned in Spark docs - here's the difference between float and double type: FloatType: Represents 4-byte single-precision floating point numbers. DoubleType: Represents 8-byte double-precision floating point numbers. Second, as you mentioned the error comes here: valuesAndPred = test_truth_value.zip(la...
2
1
78,701,305
2024-7-3
https://stackoverflow.com/questions/78701305/pandas-string-selection
I would like to extract rows containing a particular string - the string can be a part of a larger, space-separated string (which I would want to count in), or can be a part of another (continuous) string (which I would NOT want to count in). The string can be either at start, middle or end of the string value. Example...
You can use the str.contains method with the regex query \bHC\b >>> df[df['test'].str.contains(r'\bHC\b')] test 0 HC 2 HC RD 6 CEA HC \b: Word boundary
2
1
78,702,365
2024-7-3
https://stackoverflow.com/questions/78702365/how-to-quickly-find-the-minimum-element-to-the-right-for-every-element-of-a-nump
Let's say I have an array: a = [1,4,3,6,4] I want to get an array where for every element I have the smallest value in a to the right (inclusive). That is, for a, I would want to create an array: [1,3,3,4,4] Is there a quick, concise way to do this?
You question is actually ambiguous. Do you want to consider the following value or all following values? considering all following values compute a cumulated minimum on the reversed array with minimum.accumulate: a = np.array([1,4,3,6,4]) out = np.minimum.accumulate(a[::-1])[::-1] Output: array([1, 3, 3, 4, 4]) With ...
2
5
78,702,312
2024-7-3
https://stackoverflow.com/questions/78702312/python-pandas-market-calendars
Question on calendar derivation logic in the Python module https://pypi.org/project/pandas-market-calendars/. Does this module depend on any third party API's to get the calendars or the calendars are derived based on rules within the code?
There is no communication with a third party API, everything is hardcoded. You can easily see this in the source code. There is a calendars folder with definitions of each calendar (see for example the file for ASX). The project's documentation also mentions that: As of v2.0 this package provides a mirror of all the c...
2
1
78,702,014
2024-7-3
https://stackoverflow.com/questions/78702014/how-to-get-the-current-domain-name-in-django-template
How to get the current domain name in Django template? Similar to {{domain}} for auth_views. I tried {{ domain }}, {{ site }}, {{ site_name }} according to below documentation. It didnt work. <p class="text-right">&copy; Copyright {% now 'Y' %} {{ site_name }}</p> It can be either IP address 192.168.1.1:8000 or mydoma...
You can use {{ request.get_host }}
4
1
78,700,997
2024-7-3
https://stackoverflow.com/questions/78700997/how-to-generate-a-hierarchical-colourmap-in-matplotlib
I have a hierarchical dataset that I wish to visualise in this manner. I've been able to construct a heatmap for it. I want to generate a colormap in matplotlib such that Level 1 get categorical colours while Level 2 get different shades of the Level 1 colour. I was able to get Level 1 colours from a "tab20" palette b...
What about combining several gradients to form a multi-colored cmap, then rescaling your data? import matplotlib as mpl from matplotlib.colors import LinearSegmentedColormap df = pd.DataFrame({"Level 2": [1, 2, 1, 2, 3, 2, 3, 4, 0, 1, 5], "Level 1": [0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]}).T n = 5 # max value per level leve...
2
1
78,700,935
2024-7-3
https://stackoverflow.com/questions/78700935/advanced-logic-with-groupby-apply-and-transform-compare-row-value-with-previo
I have the following pandas dataframe: d= {'Time': [0,1,2,0,1,2,2,3,4], 'Price': ['Auction', 'Auction','800','900','By Negotiation','700','250','250','Make Offer'],'Item': ['Picasso', 'Picasso', 'Picasso', 'DaVinci', 'DaVinci', 'DaVinci', 'Dali', 'Dali', 'Dali']} df = pd.DataFrame(data=d) I would like to create a four...
You could use groupby.shift and numpy.select: # replace numbers by "Price" price = df['Price'].mask(pd.to_numeric(df['Price'], errors='coerce') .notna(), 'Price') # get previous price prev_price = price.groupby(df['Item']).shift() # identify first row per Item m1 = ~df['Item'].duplicated() # identify change in price m2...
2
1
78,700,714
2024-7-3
https://stackoverflow.com/questions/78700714/polars-groupby-mean-on-list
I want to make mean on groups of embeddings vectors. For examples: import polars as pl pl.DataFrame({ "id": [1,1 ,2,2], "values": [ [1,1,1], [3, 3, 3], [1,1,1], [2, 2, 2] ] }) shape: (4, 2) id values i64 list[i64] 1 [1, 1, 1] 1 [3, 3, 3] 2 [1, 1, 1] 2 [2, 2, 2] Expected result. import numpy as np pl.DataFrame({ "id":...
int_ranges() to create ordinality for lists. explode() to explode lists. group_by() twice, first to calculate mean() and then to combine results into lists. ( df .with_columns(i = pl.int_ranges(pl.col.values.list.len())) .explode('values', 'i') .group_by('id', 'i', maintain_order = True) .mean() .group_by('id', maint...
3
1
78,700,174
2024-7-3
https://stackoverflow.com/questions/78700174/attributeerror-module-pyperclip-has-no-attribute-waitforpaste
I installed pyperclip (a clipboard utility) on Windows VM and somehow some of the functions are not working. I am trying to use the waitForPaste() function as below: import pyperclip as pyc import os pyc.waitForPaste() However, this is producing the following error: AttributeError Traceback (most recent call last) Cel...
A CTRL+F for "waitForPaste" in the pyperclip source code suggests that the function no longer exists despite still being in the documentation; the only hits it gets are in the documentation. You have a few options if you still need this functionality: Find a workaround. This could be a similar function from another li...
2
0
78,699,625
2024-7-3
https://stackoverflow.com/questions/78699625/how-to-call-asyncio-create-task-within-asyncio-create-task
I have been attempting to run 10 different looping tasks simultaneously with asyncio. All 10 tasks call "asyncio.create_task()" within their loops. I can't use "asyncio.run()" on all of them because this functions blocks the thread its called on until the task is done. So I thought that I could simply circumvent this b...
You can create all the tasks and then asyncio.gather() them await asyncio.gather(*[task1(), task2()])
3
2
78,697,859
2024-7-2
https://stackoverflow.com/questions/78697859/how-to-solve-complex-equations-numerically-in-python
Originally, I had the following equation: 2mgv×sin(\alpha) = CdA×\rho(v^2 + v_{wind}^2 + 2vv_{wind}cos(\phi))^(3/2) which I could express as the following non-linear equation: (K × v)^(2/3) = v^2 + v_{wind} + 2vv_{wind}cos(\phi) To solve this, I need to use a numerical approach. I tried writing a code for this in Pyt...
The solution, using the secant method is the following: import numpy as np import matplotlib.pyplot as plt m = 60 g = 9.81 alpha = np.radians(2) # incline CdA = 0.321 rho = 1.225 v_wind = 4 phi = np.radians(60) # wind angle with the direction of motion mu = 0.005 cos_phi = np.cos(phi) sin_alpha = np.sin(alpha) lhs = m ...
3
0
78,669,908
2024-6-26
https://stackoverflow.com/questions/78669908/why-is-re-pattern-generic
import re x = re.compile(r"hello") In the above code, x is determined to have type re.Pattern[str]. But why is re.Pattern generic, and then specialized to string? What does a re.Pattern[int] represent?
re.Pattern was made generic because you can also compile a bytes pattern that will operate only on bytes objects: p = re.compile(b'fo+ba?r') p.search(b'foobar') # fine p.search('foobar') # TypeError: cannot use a bytes pattern on a string-like object At type-checking time, it is defined as generic over AnyStr: class P...
4
5
78,689,083
2024-6-30
https://stackoverflow.com/questions/78689083/combination-of-pso-and-gekko-error-intermediate-variable-with-no-equality
I want to optimize the best polynomial coefficients which describes a temperature profile in the interval [0, tf], where tf=100 min: p0 = 0.1 p1 = (t - 50)*(3**0.5/500) p2 = (t**2 - 100*t + 5000/3)*(3/(500000000**0.5)) T = coef0*p0 + coef1*p1 + coef2*p2 This temperature profile should maximize biodiesel concentration ...
Change how T is defined because it is an array of values. Also, optimization is not needed when Gekko is used for simulation. T = m.Param(coef0*p0 + coef1*p1 + coef2*p2,lb=298,ub=338) #m.Maximize(x4*final) m.options.IMODE = 4 For the Temperature profile T, Gekko expects m.Param() inputs when they are vectors. Here is ...
2
1
78,696,026
2024-7-2
https://stackoverflow.com/questions/78696026/jupyter-notebook-how-to-direct-the-output-to-a-specific-cell
Is there a way to specify the output cell where a function should print its output? In my specific case, I have some threads running, each with a logger. The logger output is printed on any running cell, interfering with that cell's intended output. Is there a way I can force the logger to print only on cell #1, for ex...
You could use the following approach: Redirect all log messages in the root logger (which you will get by calling getLogger()) to a QueueHandler to accumulate the log messages in a queue.Queue. In the intended output cell, start a QueueListener that wraps a StreamHandler. The QueueListener, as its name implies, will l...
5
6
78,694,739
2024-7-2
https://stackoverflow.com/questions/78694739/why-does-flask-seem-to-require-a-redirect-after-post
I have an array of forms I want rendered in a flask blueprint called fans. I am using sqlalchemy to SQLLite during dev to persist the data and flask-wtforms to render. The issue appears to be with DecimalRangeField - if I have two or more fans and change the slider on just one, the other slider appears to move to match...
FlaskForm will automatically use the values ​​from flask.request.form and flask.request.files. To work around this, you can pass None for the formdata attribute of the form. This way, the redirect that resets flask.request.form is no longer necessary. Your code would then look something like this. @bp.route('/', method...
2
2
78,689,530
2024-6-30
https://stackoverflow.com/questions/78689530/type-error-when-running-model-trained-in-roboflow-in-production-environment
I can make inference from my trained Roboflow model using Google Colab and the AWS cloud9 test environment. To do this, I used the following code: from roboflow import Roboflow rf = Roboflow(api_key="xxxxxxxxxxxxxxxxx") path = "/context/image.jpeg" project = rf.workspace().project("xxxxxx") model = project.version(x).m...
As @iurisilvio pointed out, try adding HOME environmental variable into your lambda configuration. The stack trace hints you where the error is, os.getenv("HOME") is None, and hence os.path.join(os.getenv("HOME"), ".config/roboflow/config.json") results in error. Below is from python3.8 >>> import os >>> os.path.join(N...
3
1
78,689,702
2024-6-30
https://stackoverflow.com/questions/78689702/different-embeddings-for-same-sentences-with-torch-transformer
Hey all and apologies in advance for what is probably a fairly basic question - I have a theory about what's causing the issue here, but would be great to confirm with people who know more about this than I do. I've been trying to implement this python code snippet in Google colab. The snippet is meant to work out simi...
You are correct the model layer weights for bert.pooler.dense.bias and bert.pooler.dense.weight are initialized randomly. You can initialize these layers always the same way for a reproducible output, but I doubt the inference code that you have copied from there readme is correct. As already mentioned by you the pooli...
3
1
78,689,321
2024-6-30
https://stackoverflow.com/questions/78689321/how-to-solve-sql-compilation-error-object-snowpark-temp-stage-flgviwvuc-alre
I have been using Snowflake to do ML works. I have built a Multiple linear regression. I am writing an output df as a table using session.write_pandas. I get this error 'SQL compilation error: Object 'SNOWPARK_TEMP_STAGE_XXXXX' already exists.' in snowflake streamlit app. This goes if I refresh the page. But why it oc...
Trying to patch away two types of errors when writing from pandas Dataframe() to tables in Snowflake. SNOWPARK_TEMP_FILE_FORMAT_XXXX already exists SNOWPARK_TEMP_STAGE_XXXX already exists There is also a race condition which ever may occur first, so we have to write try-except within a try-except to resolve this issu...
3
1
78,679,676
2024-6-27
https://stackoverflow.com/questions/78679676/how-to-remove-white-background-on-kivy-app-icon
Kivy app icon is not filling the entire space designed for It. I am not English fluent, but I will describe my problem as best as I can. I am using an icon with 480 x 320 of size and It works fine on the smartphone, but instead of occupying the entire space, the icon is being reduced to approximatelly 50% of the size. ...
There are in fact two ways to add icons for kivy apps. The quick one that you used which is simple but does not allow resize of the icon and an adaptative one which works as follows. You have to edit the following lines of the buildozer.spec file instead : # (str) Adaptive icon of the application (used if Android API l...
2
1
78,689,283
2024-6-30
https://stackoverflow.com/questions/78689283/exposing-11434-port-in-docker-container-to-access-ollama-local-model
I am trying to connect local Ollama 2 model, that uses port 11434 on my local machine, with my Docker container running Linux Ubuntu 22.04. I can confirm that Ollama model definitely works and is accessible through http://localhost:11434/. In my Docker container, I am also running GmailCTL service and was able to succe...
So remove the EXPOSE 11434 statement, what that does is let you connect to a service in the docker container using that port. 11434 is running on your host machine, not your docker container. To let the docker container see port 11434 on your host machine, you need use the host network driver, so it can see anything on...
4
0
78,683,593
2024-6-28
https://stackoverflow.com/questions/78683593/defining-dynamic-constraints-for-scipy-optimize-in-python
I wanted to abstract the following function that calculates minimum value of a objective function and values when we can get this minimal value for arbitrary number of g's. I started with simple case of two variables, which works fine import numpy as np from scipy.optimize import minimize def optimize(g_0, s, g_max, ef...
I see two mistakes. One is a mistake in the way you originally specified the two-variable constraint. The second is a mistake in the way the N-variable constraint is specified. I also see some opportunities for general improvements. Let's start with the mistake in the original specification: {'type': 'ineq', 'fun': la...
2
1
78,680,128
2024-6-27
https://stackoverflow.com/questions/78680128/redis-om-python-custom-primary-key
I've been trying to create a custom PK based on fields in the model. https://redis.io/learn/develop/python/redis-om "The default ID generation function creates ULIDs, though you can change the function that generates the primary key for models if you'd like to use a different kind of primary key." I would like to custo...
You can add Field(primary_key=True) to any of the attributes in your model. Here is the code provided in their example with the default pk: import datetime from typing import Optional from redis_om import HashModel class Customer(HashModel): first_name: str last_name: str email: str join_date: datetime.date age: int bi...
3
1
78,696,011
2024-7-2
https://stackoverflow.com/questions/78696011/how-can-i-set-all-form-fields-readonly-in-odoo-16-depending-on-a-field
In Odoo 16, I'm trying to make all fields from a form view readonly depending on the value of other field of the same form. First I've tried the following: <xpath expr="//field" position="attributes"> <attribute name="attrs">{'readonly': [('my_field', '=', True)]}</attribute> </xpath> With no result. I can't use <form...
Extending get_view actually is a good idea. There is a module in server-ux repo of the OCA where something similar is done: when something is saved in a one2many field, every field in the form view will be set to readonly. To do this, the readonly modifier is rewritten for each field. The module: base_tier_validation T...
2
2
78,699,450
2024-7-2
https://stackoverflow.com/questions/78699450/what-is-the-fastest-way-to-calculate-a-daily-balance-with-compound-interest-in-p
I have a DataFrame (DF) with deposits and withdrawals aggregated by day, and I want to know what is the fastest way to calculate the balance for each day. Because it must be able to scale. Answers in both Pandas and Spark are welcome! Here is an example of how the input DF looks like: Input date deposit withdrawal ...
For this type of computations I'd use numba, e.g.: from numba import njit @njit def calculate(deposits, withdrawals, out_daily_return, out_balance): prev_balance = 0 for i, (deposit, withdrawal) in enumerate(zip(deposits, withdrawals)): movements = prev_balance + deposit - withdrawal interest = 0.1 if movements > 0 els...
3
4
78,699,293
2024-7-2
https://stackoverflow.com/questions/78699293/efficiently-reparsing-string-series-in-a-dataframe-into-a-struct-recasting-th
Consider the following toy example: import polars as pl xs = pl.DataFrame( [ pl.Series( "date", ["2024 Jan", "2024 Feb", "2024 Jan", "2024 Jan"], dtype=pl.String, ) ] ) ys = ( xs.with_columns( pl.col("date").str.split(" ").list.to_struct(fields=["year", "month"]), ) .with_columns( pl.col("date").struct.with_fields(pl.f...
.str.splitn() should be more efficient as it avoids the List creation + .list.to_struct() .struct.field() can also be used to "unnest" the fields directly. xs.select( pl.col.date.str.splitn(" ", 2) .struct.rename_fields(["year", "month"]) .struct.with_fields(pl.field("year").cast(pl.Int16)) .struct.field("year", "month...
3
1
78,698,840
2024-7-2
https://stackoverflow.com/questions/78698840/get-the-dpi-for-a-pyplot-figure
At least in Spyder, the PyPlot plots can be low resolution, e.g., from: import numpy as np import matplotlib.pyplot as plt # import seaborn as sns rng = np.random.default_rng(1) scat = plt.scatter( *rng.integers( 10, size=(2,10) ) ) My web surfing has brought me to a suggested solution: Increase the dots-per-inch. plt...
There doesn't seem to be a scat.dpi, scat.getdpi, or scat.get_dpi. This makes sense, because scatter returns a PathCollection. The relevant property and method are Figure.dpi or Figure.get_dpi. Highly suggest you use the object-oriented interface: fig, ax = plt.subplots() ax.scatter(*rng.integers(10, size=(2,10))) pr...
2
1
78,698,110
2024-7-2
https://stackoverflow.com/questions/78698110/is-s-rfind-in-python-implemented-using-iterations-in-backward-direction
Does rfind iterates over a string from end to start? I read the docs https://docs.python.org/3.12/library/stdtypes.html#str.rfind and see str.rfind(sub[, start[, end]]) Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end ...
The sources are easier to navigate if you're familiar with some history of Python. Specifically, the type str was historically called unicode in CPython and is still called unicode in the C sources. So, for string methods: headers are found in Include/unicodeobject.h implementation can be found in Objects/unicodeobjec...
4
6
78,697,829
2024-7-2
https://stackoverflow.com/questions/78697829/folium-plugins-featuregroupsubgroup-how-to-remove-the-name-of-the-tiles-from-th
I'm building a map with Folium. I used plugins.FeatureGroupSubGroup in order to create four subgroup so that one can filter the markers. As you can see in the picture below, at the top of the white box there is the name of the tiles I'm using (Cartodb dark_matter). Is there any chance to have the box without that writi...
One option would be to add the TileLayer manually and turn-off its control : import folium m = folium.Map(location=[0, 0], zoom_start=6, tiles=None) t = folium.TileLayer(tiles="cartodbdark_matter", control=False).add_to(m) # irrelevant / just for reproducibility from folium.plugins import FeatureGroupSubGroup, Marker...
2
2
78,696,575
2024-7-2
https://stackoverflow.com/questions/78696575/error-failed-to-build-installable-wheels-for-some-pyproject-toml-based-projects
I am trying to install Pyrebase to my NewLoginApp Project using PyCharm IDE and Python. I checked and upgraded the version of the software and I selected the project as my interpreter, but I still get this error: ERROR: ERROR: Failed to build installable wheels for some pyproject.toml based projects (pycryptodome) Bel...
I think you should install Pyrebase4 pip install Pyrebase4 or pip3 install Pyrebase4 https://pypi.org/project/Pyrebase4/ A simple python wrapper for the Firebase API with current deps This is a more recent one with last released on Apr 30, 2024 The old one was : pip install Pyrebase it was last released on Jan ...
7
4
78,692,458
2024-7-1
https://stackoverflow.com/questions/78692458/extract-the-closest-two-numbers-that-multiply-to-create-a-given-number
I made a CPU based raytracer in PyGame which uses a tile per thread to render each section of the screen. Currently I divide the screen vertically between lines, this doesn't give me the best distribution: I want to divide threads in even boxes covering both the X and Y directions. For example: If my resolution is x = ...
If I understand you correctly, you are looking for the following: Given a number x > 0, find the pair of factors (z, h) where the absolute difference of (z, h) is the at a minimum. x is the number of available threads and (z, h) will then be the number of tilings you will have (vertically, horizontally). If the number ...
2
1
78,695,836
2024-7-2
https://stackoverflow.com/questions/78695836/in-a-gradio-tab-gui-a-button-calls-the-other-tab
I have the following script import gradio as gr # Define the function for the first tab def greet(text): return f"Hello {text}" # Define the function for the second tab def farewell(text): return f"Goodbye {text}" # Create the interface for the first tab with gr.Blocks() as greet_interface: input_text = gr.Textbox(labe...
Yes, tabbed gradio was buggy. It was fixed in version 4.36.1 See the changelog: Fixes TabbedInterface bug where only first interface events get triggered. This explains the differences you see between both versions (4.32.2 < 4.36.1 < 4.37.2)
2
2
78,694,862
2024-7-2
https://stackoverflow.com/questions/78694862/problems-with-recursive-functions
I have recently challenged myself to write the Depth First Search algorithm for maze generation and am on the home stretch of completing it but I have been battling a specific error for most of the final half of the project. I use binary for notating the connections between two neighboring nodes on the tree (learn netw...
There are several issues: With a depth-first traversal you shouldn't recur deeper when backtracking. Backtracking involves getting out of recursion. That also means you don't need an explicit stack like you have priorPoses, ...etc. The callstack serves for that purpose. For the reason in the previous point, you would...
3
4
78,695,350
2024-7-2
https://stackoverflow.com/questions/78695350/pyparsing-back-to-basics
In attempting to put together a very simple example to illustrate an issue I'm having with pyparsing, I have found that I can't get my simple example to work - this example is barely more complex than Hello, World! Here is my example code: import pyparsing as pp import textwrap as tw text = ( """ A) Red B) Green C) Blu...
My dude! You forgot to wrap raw string into a list! I tested for 30 mins and felt something was odd, then found this in document: run_tests(tests: Union[str, List[str]], ...) -> ... Execute the parse expression on a series of test strings, showing each test, the parsed results or where the parse failed. Quick and easy...
2
2
78,678,526
2024-6-27
https://stackoverflow.com/questions/78678526/iterate-over-intflag-enumeration-using-iter-differs-in-python-3-8-and-3-12-4
I have the following working in python 3.8.1 @unique class Encoder(IntFlag): # H1 sensor signal H1 = 0x00 # H2 sensor signal H2 = 0x01 # H3 sensor signal H3 = 0x02 Then I am trying to catch with an assert if the value is not within the enum, i.e. from enum import unique, IntFlag signal = Encoder.H1 assert signal in it...
enum.Flag implements __contains__. For membership checks, drop the iter call and just use: signal in Encoder This will work in both 3.8.1 and 3.12.4. Note: The change in iteration behavior for flags happened in Python 3.11 and is mentioned in the changelog here. Also, you should probably be using IntEnum rather than I...
2
3
78,690,568
2024-7-1
https://stackoverflow.com/questions/78690568/openpyxl-delete-rows-doesnt-completely-remove-rows-if-row-height-is-set
Any suggestions? If I ever the row height in openpyxl, delete_rows will appear to remove the rows, but when I save and open in Excel, the rows are empty but not all row information is removed. The scroll bar still scrolls to where the last row was prior to deleting. So "ghosts" of the empty rows remain. Sample code: fr...
Yes, the delete clears the cells however as the row dimensions have been adjusted (by changing the height) they now exist in the Sheet profile. The row delete function does not remove that from the Sheet. The result being that the workbook retains the rows to 100 defined in the Sheet with those above row 35 having no c...
2
1
78,695,314
2024-7-2
https://stackoverflow.com/questions/78695314/weird-behavior-when-updating-the-values-using-iloc-in-pandas-dataframe
While copying a pandas dataframe, ideally, we should use .copy(), which is a deep copy by default. We could also achieve the same using new_df = pd.Dataframe(old_df), which is also intuitive (and common style across most programming languages since in principle, we are calling a copy constructor). In both cases, they h...
This is the expected behavior of DataFrame, it is also happening when you're passing a numpy array as input: a = np.array([[1,2],[3,4]]) df = pd.DataFrame(a) a[0][0] = 9 print(df) 0 1 0 99 2 1 3 4 It is actually well described in the DataFrame documentation: copy: bool or None, default None Copy data from inputs. For...
2
1
78,689,947
2024-6-30
https://stackoverflow.com/questions/78689947/how-to-restructure-instance-segmentation-predictions-into-a-custom-dictionary-fo
I'm performing instance segmentation using a model trained in RoboFlow, for the prediction result I'm getting: [InstanceSegmentationInferenceResponse(visualization=None, frame_id=None, time=None, image=InferenceResponseImage(width=720, height=1280), predictions=[ InstanceSegmentationPrediction(x=352.0, y=569.0, width=4...
I'm assuming you're getting this as a response from the inference call on Roboflow and you want to use a more JSON-esque approach to things, I used (assuming you set your response to 'model_response'): json_data_string = model_response.model_dump_json() results = json.loads(json_data_string) Some real good documentati...
4
2
78,692,255
2024-7-1
https://stackoverflow.com/questions/78692255/merge-dataframe-based-on-substring-column-labeld-while-keep-the-original-columns
I have a dataframe having columns with the a label pattern (name/startDateTime/endDateTime) import pandas as pd pd.DataFrame({ "[RATE] BOJ presser/2024-03-19T07:30:00Z/2024-03-19T10:30:00Z": [1], "[RATE] BOJ/2024-01-23T04:00:00Z/2024-01-23T07:00:00Z": [2], "[RATE] BOJ/2024-03-19T04:00:00Z/2024-03-19T07:00:00Z": [3], "[...
There are a couple of ways to do this, since you are operating along the columns you can do this in either a pure pandas or more typical Python approach. The whole idea is that you need to find the unique groups in your columns and perform aggregation within those groups. Pandas groupby(…) Pandas (version <= 2.1.0) sup...
2
2
78,689,833
2024-6-30
https://stackoverflow.com/questions/78689833/texttestrunner-doesnt-recognize-modules-when-executing-tests-in-a-different-pro
i am currently working on a project, where i need to run tests inside a different file structure like this: /my_project ├── __init__.py ├── ...my python code /given_proj ├── __init__.py ├── /package │ ├── __init__.py │ └── main.py └── /tests └── test_main.py Current approach From inside my project i want to execute th...
A possible solution is to add the following instructions in your file test_main.py: import unittest import sys # <-- add this import sys.path.insert(1, '..') # <-- add this instruction print(sys.path) # <--- TO CHECK THE CONTENT OF sys.path #from package.main import my_function # <--- comment your import from given_pro...
3
2
78,679,818
2024-6-27
https://stackoverflow.com/questions/78679818/terminology-for-ordinal-index-versus-dataframe-index
I've set up a dataframe: df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Aritra'], 'Age': [25, 30, 35], 'Location': ['Seattle', 'New York', 'Kona']}, index=([10, 20, 30])) I ask the user to put in which row of the data they want to see. They input a 0, indicating the first row. However, df.loc[0] does not refer to the fi...
If you look at the documentation you've linked, pandas uses the term index label to describe what you call a dataframe index. It's more clearly explained in this documentation on indexing, where the term position is used to refer to what you call an ordinal index. (Note that some popular answers on Stack Overflow use t...
2
2
78,693,052
2024-7-1
https://stackoverflow.com/questions/78693052/how-to-efficiently-calculate-the-share-of-an-aggregated-column
I have the following DataFrame and want to calulate the "share". import pandas as pd d = {"col1":["A", "A", "A", "B", "B", "B"], "col2":["start_amount", "mid_amount", "end_amount", "start_amount", "mid_amount", "end_amount"], "amount":[0, 2, 8, 1, 2, 3]} df_test = pd.DataFrame(d) df_test["share"] = 0 for i in range(le...
This is equivalent to selecting the rows with "end_amount", then performing a map per "col1" to then divide "amount": s = df_test.loc[df_test['col2'].eq('end_amount')].set_index('col1')['amount'] df_test['share'] = df_test['amount']/df_test['col1'].map(s) Output: col1 col2 amount share 0 A start_amount 0 0.000000 1 A...
4
2
78,688,703
2024-6-30
https://stackoverflow.com/questions/78688703/altair-barchart-is-blank-matplotlib-equivalent-shows-correct-visualization
I have been using altair for a time and this is the first time that I have experienced this issue, I have this simple code: import pandas as pd import altair as alt # extract data into a nested list data = { "Name of District": ["Kollam", "Beed", "Kalahandi", "West Medinipur", "Birbhum", "Howrah"], "No. of Cases": [19,...
Altair requires that special characters be escaped in the column names. See documentation here. This code should produce the plot you're looking for. chart = alt.Chart(df).mark_bar( ).encode( x='Name of District', y='No\. of Cases', tooltip=['Name of District', 'No\. of Cases'] ).properties( title='Bar Chart of No. of ...
3
2
78,692,959
2024-7-1
https://stackoverflow.com/questions/78692959/polars-truncates-decimals
I'm trying to truncate floating point numbers in my DataFrame to a desired number of decimal places. I've found that this can be done using Pandas and NumPy here, but I've also seen that it might be possible with polars.Config.set_float_precision. Below is my current approach, but I think I might be taking extra steps....
You can use the Polars - Numpy integration like this: df = df.with_columns(truncated_grade=np.trunc(pl.col("grade") * 10) / 10) Output: ┌─────────┬──────────┬─────────────────┐ │ name ┆ grade ┆ truncated_grade │ │ --- ┆ --- ┆ --- │ │ str ┆ f64 ┆ f64 │ ╞═════════╪══════════╪═════════════════╡ │ Alice ┆ 90.23456 ┆ 90.2 ...
3
6
78,690,388
2024-7-1
https://stackoverflow.com/questions/78690388/python3-8-cannot-import-name-windowed-complete
Ubuntu 20.04 Python 3.8 Got error ImportError: cannot import name 'windowed_complete' from 'more_itertools' However more_itertools is clearly installed. Is it possible, that Python 3.9 required to run windowed_complete ? Or how this error should be resolved ? Traceback (most recent call last): File "diarize.py", line...
pip install more-itertools==10.3.0 (latest version) solved it
2
1
78,688,251
2024-6-30
https://stackoverflow.com/questions/78688251/making-sale-line-id-field-invisible
I'm working on customizing Odoo and have encountered an issue with the sale_line_id field. I'm inheriting the project.task model in my custom module (wsl_available_drivers). In view, I need to make the sale_line_id field invisible. <record id="view_task_form2" model="ir.ui.view"> <field name="name">Project.task.view.fo...
The sale_project module adds two sale_line_id fields and the visibility of the field depends on the group to which the user belongs, the second field has an additional invisible attribute The XPath expression will match the first node it finds. If you need to hide the two fields, add another XPath to target the second ...
3
1
78,692,139
2024-7-1
https://stackoverflow.com/questions/78692139/sum-multiple-rows-from-multiple-columns-in-a-dataframe-for-a-group
For each group in a groupby, I want to sum certain rows from several columns and output them in a new column, is_m_days. Each Group (a Group has CT/RT and has a Quantity from 1 or 2 or 3 or more rows, randomly mixed up) in 'ATEXT' For the Sum, each group has a Row before and after. DataFrame: data = {'ATEXT': ['', 'C...
Your approach is good, you could simplify it to use a single groupby (with extra boolean masks): m1 = df['ATEXT'].eq('') m2 = m1 & m1.shift(fill_value=True) m3 = m1!=m2 group = m2.cumsum() df.loc[m3, 'is_m_days'] = (pd .DataFrame({'A': df['BEGUZ_UE'].mask(m2), 'B': df['add'].sub(df['subtract']).where(m2)}) .groupby(gro...
3
2
78,676,400
2024-6-27
https://stackoverflow.com/questions/78676400/customizing-pygtk-file-chooser-dialog
I am creating a Gtk file chooser dialog as follows (see below for full example): dialog = Gtk.FileChooserDialog( title="Select a File", action=Gtk.FileChooserAction.OPEN) I would also like to add a checkbox and dropdown combobox as extra widgets. Adding one extra widget works fine: cb = Gtk.CheckButton("Only media fil...
It appears that solution #2 was the right way to go. However, I did not use the show_all method to actually show the widgets, which was the problem. With the following fragment the file chooser dialog with extra widgets works: cb = Gtk.CheckButton("Only media files") db = Gtk.ComboBoxText() db.append_text("Option 1") d...
2
1
78,690,267
2024-7-1
https://stackoverflow.com/questions/78690267/how-to-add-a-column-with-json-representation-of-rows-in-polars-dataframe
I want to use polars to take a csv input and get for each row another column (e.g called json_per_row) where the entry per row is the json representation of the entire row. I also want to select only a subset of the columns to be included alongside the json_per_row column. Ideally I don’t want to hardcode the number / ...
you can use read_csv() to read your csv data, but here I'll just use Series data you provided. .struct() to combine all the columns into one struct column. struct.json_encode() to convert to json. ( pl.DataFrame([s1,s2,s3]) .select( pl.col.time, json_per_row = pl.struct(pl.all()).struct.json_encode() ) ) ┌──────┬────...
3
2
78,689,910
2024-6-30
https://stackoverflow.com/questions/78689910/why-is-numpy-converting-an-object-int-type-to-an-object-float-type
This could be a bug, or could be something I don't understand about when numpy decides to convert the types of the objects in an "object" array. X = np.array([5888275684537373439, 1945629710750298993],dtype=object) + [1158941147679947299,0] Y = np.array([5888275684537373439, 1945629710750298993],dtype=object) + [115894...
In [323]: X = np.array([5888275684537373439, 1945629710750298993],dtype=object) Case 1 - not too large integer in second argument: In [324]: X+[1158941147679947299,0] Out[324]: array([7047216832217320738, 1945629710750298993], dtype=object) Same thing if we explicity make an object array: In [325]: X+np.array([115894...
2
1
78,682,941
2024-6-28
https://stackoverflow.com/questions/78682941/updating-callback-parameters-for-sending-post-requests-to-a-site
It is simple enough to send a GET request to the url https://apps.fpb.org.za/erms/fpbquerytitle.aspx?filmtitle=&Submit1=Search to get the 1st page of search results of the wesbite. However, I cannot figure out how to request subsequent pages, which involve sending a POST request to the same url but with a lot form data...
The only variable part of __CALLBACKPARAM that matters is: PAGERONCLICK{}, 2{};12 and PN{}. __VIEWSTATE, __CALLBACKID and vwfpbquerytitle$CallbackState don't actually need to be changed. credit to @xoxouser for figuring out that 777 was the length of str(array), it was the only part that seemed random, but in the end i...
2
2
78,689,213
2024-6-30
https://stackoverflow.com/questions/78689213/polars-cumulative-count-over-sequential-dates
Here's some sample data import polars as pl df = pl.DataFrame( { "date": [ "2024-08-01", "2024-08-02", "2024-08-03", "2024-08-04", "2024-08-04", "2024-08-05", "2024-08-06", "2024-08-08", "2024-08-09", ], "type": ["A", "A", "A", "A", "B", "B", "B", "A", "A"], } ).with_columns(pl.col("date").str.to_date()) And my desire...
What about first creating a secondary grouper based on the duration ≥ 1day? from datetime import timedelta (df.with_columns(group=pl.col("date").diff().gt(timedelta(days=1)) .fill_null(True).cum_sum().over("type")) .with_columns(days_in_a_row=pl.cum_count("date").over(["type", "group"])) ) Output: ┌────────────┬──────...
3
3
78,689,352
2024-6-30
https://stackoverflow.com/questions/78689352/why-doesnt-randrangestart-100-raise-an-error
In the docs for randrange(), it states: Keyword arguments should not be used because they can be interpreted in unexpected ways. For example randrange(start=100) is interpreted as randrange(0, 100, 1). If the signature is random.randrange(start, stop[, step]), why doesn't randrange(start=100) raise an error, since st...
This is because the code for randrange must also support the alternative signature: random.randrange(stop) The implementation performs a check to see whether the call uses this signature or the other one: random.randrange(start, stop[, step]) It does so with this code: istart = _index(start) if stop is None: if ista...
2
3
78,688,751
2024-6-30
https://stackoverflow.com/questions/78688751/how-to-explicitly-list-allowed-keyword-arguments-in-python-for-ide-support
I'm using argparse.ArgumentParser in python and giving users the option to add their own functions to my script. For that, I'm giving them a function that generates data that gets used in argparse's add_argument() function. I noticed that add_argument's signature is add_argument(self, *args, **kwargs) but when looking ...
VSCode's language server is pulling from the stub file in the typeshed, where the current definition is: def add_argument( self, *name_or_flags: str, action: _ActionStr | type[Action] = ..., nargs: int | _NArgsStr | _SUPPRESS_T | None = None, const: Any = ..., default: Any = ..., type: _ActionType = ..., choices: Itera...
3
2
78,684,997
2024-6-29
https://stackoverflow.com/questions/78684997/efficiently-storing-data-that-is-partially-columnar-into-a-duckdb-database-in-a
I have some partially columnar data like this: "hello", "2024 JAN", "2024 FEB" "a", 0, 1 If it were purely columnar, it would look like: "hello", "year", "month", "value" "a", 2024, "JAN", 0 "a", 2024, "FEB", 1 Suppose the data is in the form of a numpy array, like this: import numpy as np data = np.array([["hello", ...
Note: I added another row ("b",1,0) to make the data a bit more substantive so that it's easier to see what's happening. Essentially what you have is a "pivoted" dataset: D SELECT * FROM 'pivoted-data.csv'; ┌─────────┬──────────┬──────────┐ │ hello │ 2024 JAN │ 2024 FEB │ │ varchar │ int64 │ int64 │ ├─────────┼────────...
2
1
78,687,512
2024-6-30
https://stackoverflow.com/questions/78687512/move-buttons-to-east-with-grid-method
So a little stylistic thing I want to do is move some buttons to the east side of the window while having them all on the same row. Sounds easy enough and the grid method has a sticky parameter that should make this easy to do, right? No. This is the basic code from tkinter import * window = Tk() window.geometry("200x2...
Give column 0 some weigth. It will force column 1 and 2 to right. from tkinter import * window = Tk() window.geometry("200x200") window.columnconfigure(0, weight=3) btn1 = Button(window, text="btn1") btn1.grid(row=0, column=1) btn2 = Button(window, text="btn2") btn2.grid(row=0, column=2) window.mainloop() Another way ...
2
2
78,684,832
2024-6-29
https://stackoverflow.com/questions/78684832/issue-installing-matplotlib-on-python-32-bit
I'm trying to install Matplotlib on a 32-bit version of Python. When I run pip install matplotlib, I get the following error when it tries to "Prepare metadata." WARNING: Failed to activate VS environment: Could not find C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe ..\meson.build:1:0: ERROR: Un...
I had this same issue and here's how I solved it. Originally, I wanted to use Numpy, Scipy, Matplotlib, PyQt, and pyinstaller on a 32-bit version of Python. I've found out these libraries need to have "wheels" (I don't know what that actually is) that are compatible with 32-bit Python. That means that on pypi.org under...
2
3
78,686,295
2024-6-29
https://stackoverflow.com/questions/78686295/import-python-libraries-in-jinja2-templates
I have this template: % template.tmpl file: % set result = fractions.Fraction(a*d + b*c, b*d) %} The solution of ${{a}}/{{b}} + {{c}}/{{d}}$ is ${{a * d + b*c}}/{{b*d}} = {{result.numerator}}/{{result.denominator}}$ which I invoke by from jinja2 import Template import fractions with open("c.jinja") as f: t = Template(...
It can be done in two ways. Calculate the result in Python code and then pass it as a parameter to the template. You can pass the fractions module as a parameter to the template. Folder structure: . ├── c.jinja └── template_example.py Option 1: Pass result to the template: template_example.py: from jinja2 import Tem...
2
3
78,686,253
2024-6-29
https://stackoverflow.com/questions/78686253/encountering-valueerror-upon-joining-two-pandas-dataframes-on-a-datetime-index-c
I have two tables which I need to join on a date column. I want to preserve all the dates in both tables, with the empty rows in each table just being filled with NaNs in the final combined array. I think an outer join is what I'm looking for. So I've written this code (with data_1 and data_2 acting as mockups of my ac...
You need to use merge, not join (that will use the index): # ensure datetime df1['Date'] = pd.to_datetime(df1['Date'], format='%B-%Y') df2['Date'] = pd.to_datetime(df2['Date'], dayfirst=True) # use merge merged = df1.merge(df2, how='outer', on=['Date']) For join to work: merged_df = df1.set_index('Date').join(df2.set_...
3
1
78,685,143
2024-6-29
https://stackoverflow.com/questions/78685143/how-to-show-one-figure-in-loop-in-python
I want to show a figure that is calculated in a loop, let say with 5 iterations. This is the code that I wrote import numpy as np import matplotlib.pyplot as plt x = np.linspace(0,1,100) y = np.linspace(0,1,100) xx,yy = np.meshgrid(x,y) for n in range(5): a = np.sin(xx-2*n) plt.imshow(a,interpolation='bilinear') plt.sh...
You can simulate an animation by using a display/clear_output from ipython (used by Colab): import time import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output, display x = np.linspace(0, 1, 100) y = np.linspace(0, 1, 100) xx, yy = np.meshgrid(x, y) # you could initialize a subplots ...
2
1
78,682,716
2024-6-28
https://stackoverflow.com/questions/78682716/spark-getitem-shortcut
I am doing the following in spark sql: spark.sql(""" SELECT data.data.location.geometry.coordinates[0] FROM df""") This works fine, however I do not want to use raw SQL, I use dataframe API like so: df.select("data.data.location.geometry.coordinates[0]") Unfortunately this does not work: AnalysisException: [DATATYPE_...
TL;DR; use selectExpr() df.selectExpr('data.data.location.geometry.coordinates[0]') Looks like indexing inside an array using [] is considered an expression, where as data.data.location... is considered a column name. DataFrame.select() takes column name as arguments, so doesn't understand [0], what you want is DataFr...
2
1
78,683,884
2024-6-28
https://stackoverflow.com/questions/78683884/is-there-any-benefit-of-using-a-dictionary-comprehension-if-an-equivalent-dictz
Recently I have been working with dictionaries and I was to told to make dictionaries out of two lists like this: zipped = {key: value for key, value in zip(drinks, caffeine)} Later I forgot how to do that and found a different way that seems simpler to me: zipped = dict(zip(drinks, caffeine)) Is there something wors...
Dictionary/List comprehensions are great flexible tools. You were taught this way so that the solution was more flexible and aligns with current coding practices. It's a "skill issue" as they say. There's nothing wrong with either. Always read company coding guidelines where possible.
2
1
78,681,694
2024-6-28
https://stackoverflow.com/questions/78681694/how-to-detect-edges-in-image-using-python
I'm having problems trying to detect edges in images corresponding to holes in a glass sample. Images look like this: images Single sample: Each image contains part of a hole that was cut into a glass sample. Inspecting the images with my eyes, I can clearly see two regions, the glass and the hole. Sadly, all methods ...
It looks to me that the variance/uniformity is significantly different in the two regions of the image, so maybe consider calculating the variance/standard-deviation within each 25x25 pixel block and normalising the result. I am doing it with ImageMagick here, because I am quicker with that, but you can do the same wit...
2
4
78,684,010
2024-6-28
https://stackoverflow.com/questions/78684010/cartesian-product-of-dict-of-lists-in-python
I would like to have a Python function cartesian_product which takes a dictionary of lists as input and returns as output a list containing as elements all possible dictionary which can be formed by taking from each list one element. Here would be an example: Calling cartesian_product({1: ['a', 'b'], 2: ['c', 'd'], 3: ...
This should do the trick: import itertools def cartesian_product(d): return [dict(zip(d, p)) for p in itertools.product(*d.values())] Demo: >>> d = {1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f']} >>> from pprint import pp >>> pp(cartesian_product(d)) [{1: 'a', 2: 'c', 3: 'e'}, {1: 'a', 2: 'c', 3: 'f'}, {1: 'a', 2: 'd', ...
2
1
78,683,848
2024-6-28
https://stackoverflow.com/questions/78683848/attribute-error-none-type-object-in-linked-list
I tried to create a simple single-linked list as the following: class node: def __init__(self, data=None): self.data = data self.next = None class linkedlist: def __init__(self): self.head = node() def append(self, data): curr = self.head new_node = node(data) while curr.next != None: curr = curr.next curr.next = new_n...
In this implementation, each node point to the next node of the list, and the last one points to None, signifying that's the end of the list. The loop in look tries to iterate over the nodes until it gets to the indexth item and then prints it, but the loop is not terminated there. In fact, it will continue indefinitel...
2
4
78,677,255
2024-6-27
https://stackoverflow.com/questions/78677255/optimal-multiplication-of-two-3d-arrays-having-a-variable-dimension
I would like to multiply tensors R = {R_1, R_2, ..., R_M} and X = {X_1, X_2, ..., X_M} where R_i and X_i are 3×3 and 3×N_i matrices, respectively. How can I make maximum use of NumPy functionalities during the formation of the R_i × X_i arrays? My MWE is the following: import numpy as np np.random.seed(0) M = 5 R = [np...
I know I am neither @mozway nor @hpaulj (this is referring to @chrslg's comment), but indeed there seems to be a feasible solution with einsum: np.einsum("ijk,ki->ji", np.repeat(R, [x.shape[1] for x in X], axis=0), np.hstack(X)) Here is the full code with which I tested: import numpy as np from timeit import Timer np....
4
4
78,680,411
2024-6-28
https://stackoverflow.com/questions/78680411/how-to-predict-the-resulting-type-after-indexing-a-pandas-dataframe
I have a Pandas DataFrame, as defined here: df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Aritra'], 'Age': [25, 30, 35], 'Location': ['Seattle', 'New York', 'Kona']}, index=([10, 20, 30])) However, when I index into this DataFrame, I can't accurately predict what type of object is going to result from the indexing: # (...
You got the general idea. To make it simple, what matter is not the number of items but the type of indexer. You can index as 0D (with a scalar), let's just consider the index for now: df.iloc[0] df.loc[0] or 1D (with a slice or iterable): df.loc[[0]] df.loc[1:2] df.loc[:0] Then the rule is simple, consider both axes...
2
1
78,676,602
2024-6-27
https://stackoverflow.com/questions/78676602/how-can-i-determine-whether-a-word-document-has-a-password
I am trying to read word documents using Python. However, I am stuck in places where the document is password protected, as I do not have the password for the file(s). How can I detect if the file has password, so can I ignore such files from opening? Currently, the below code opens a dialog/prompt window in MS-Word to...
Well I figured out the answer myself. Passed a wrong password as a parameter and it raised an exception saying Invalid/Incorrect password which I can handle it in a try except block. Little strange but works well. word = win32.gencache.EnsureDispatch('Word.Application') word.Visible = False try: doc = word.Documents.Op...
2
2
78,680,015
2024-6-27
https://stackoverflow.com/questions/78680015/behavior-of-object-new-python-dunder-what-is-happening-under-the-hood
I'm experimenting with metaprogramming in Python (CPython 3.10.13) and noticed some weird behavior with object.__new__ (well, weird to me, at least). Take a look at the following experiment (not practical code, just an experiment) and the comments. Note that object.__new__ seems to change it's behavior based on the fir...
Python's object.__init__ and object.__new__ base methods suppress errors about excess arguments in the common situation where exactly one of them has been overridden, and the other has not. The non-overriden method will ignore the extra arguments, since they usually get passed in automatically (rather than by an explic...
4
6
78,679,962
2024-6-27
https://stackoverflow.com/questions/78679962/gitlab-ci-artefacts
I am doing my first CI project and I have recently got confused about artefacts... Say I have config with next jobs: cleanup_build: tags: - block_autotest stage: cleanup script: - Powershell $env:P7_TESTING_INSTALLATION_PATH\client\p7batch.exe --log-level=error --run $env:JOBS_FOLDER_PATH\clear.py install_block: tags: ...
By default, every job starts with a 'clean' workspace. If one job modifies the workspace, it is not persisted into any other job. To pass files between jobs, you must explicitly declare artifacts to be passed between each job. Also note that the aritfact path is relative to the workspace root. stages: - one - two my_jo...
2
2
78,679,802
2024-6-27
https://stackoverflow.com/questions/78679802/how-to-make-a-functools-reduce-implementation-that-looks-similarly-as-reduce
Here is an R example of using Reduce x <- c(1, 2, 2, 4, 10, 5, 5, 7) Reduce(\(a, b) if (tail(a, 1) != b) c(a, b) else a, x) # equivalent to `rle(x)$values` The code above is to sort out the extract unique values in terms of run length, which can be easily obtained by rle(x)$values. I know in Python there is itertools...
you could use a list as the initial: from functools import reduce x = [1,2,2,4,10,5,5,7] reduce(lambda a, b: a + [b] if a[-1]!= b else a, x, [x[0]]) [1, 2, 4, 10, 5, 7] Note that you could use groupby from itertools: from itertools import groupby [i for i,j in groupby(x)] [1, 2, 4, 10, 5, 7]
3
5
78,679,079
2024-6-27
https://stackoverflow.com/questions/78679079/finding-count-of-unique-sequence-made-up-of-values-spanned-over-several-columns
A contains columns x, y1, y2, y3 & y4. I am interested in studying the {y1,y2,y3,y4} sequence w.r.t x. To find unique {y1,y2,y3,y4} sequence occurring for each x, I do the following: B = pd.DataFrame() for x_temp in A['x'].unique(): B = pd.concat([B, A[A['x'] == x_temp][['x','y1','y2','y3','y4']]]) B = B.drop_duplicate...
Assuming you want to count the values and then get the sum across the different xs, you could use: cols = ['x','y1','y2','y3','y4'] out = (A[cols].value_counts(dropna=False, sort=False) .reset_index(name='count') .sort_values(by=cols, na_position='last') .assign(count=lambda x: x.groupby(cols[1:], dropna=False) ['count...
3
1
78,676,973
2024-6-27
https://stackoverflow.com/questions/78676973/how-can-i-preserve-the-previous-value-to-find-the-row-that-is-greater-than-it
This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'start': [3, 11, 9, 19, 22], 'end': [10, 17, 10, 25, 30] } ) And expected output is creating column x: start end x 0 3 10 10 1 11 17 17 2 9 10 NaN 3 19 25 25 4 22 30 NaN Logic: I explain it row by row. For row 0, x is df.end.iloc[0]. Now this value of x ...
updated answer If the previous end should be propagated, then the logic cannot be vectorized. However, it is possible to be much faster than iterrows using numba: from numba import jit @jit(nopython=True) def f(start, end): prev_e = -np.inf out = [] for s, e in zip(start, end): if s>prev_e: out.append(e) prev_e = e els...
4
3
78,678,138
2024-6-27
https://stackoverflow.com/questions/78678138/how-to-apply-hierarchical-numbering-to-indented-titles
I have a table of content in the form of indention to track the hierarchy like: - title1 -- title1-1 -- title1-2 --- title1-2-1 --- title1-2-2 - title2 -- title2-1 -- title2-2 - title3 - title4 I want to translate them with a numbering format like: 1 title1 1.1 title1-1 1.2 title1-2 1.2.1 title1-2-1 1.2.2 title1-2-2 2...
You could use the replacer callback of re.sub to implement the logic. In that callback use a stack (that is maintained across multiple replacements) to track the chapter numbers of upper "levels". Code: import re def add_numbers(s): stack = [0] def replacer(s): indent = len(s.group(0)) - 1 del stack[indent+1:] if inden...
3
5
78,676,407
2024-6-27
https://stackoverflow.com/questions/78676407/polars-pandas-equivalent-of-selecting-column-names-from-a-list
I have two DataFrames in polars, one that describes the meta data, and one of the actual data (LazyFrames are used as the actual data is larger): import polars as pl df = pl.LazyFrame( { "ID": ["CX1", "CX2", "CX3"], "Sample1": [1, 1, 1], "Sample2": [2, 2, 2], "Sample3": [4, 4, 4], } ) df_meta = pl.LazyFrame( { "sample"...
Just to build upon https://stackoverflow.com/a/78676922/ - I find require_all=False rather cryptic. It is also possible to set intersect with the cs.all() selector: >>> meta_ids = df_meta.filter(pl.col("qc") == "pass")["sample"] >>> cs.all() & cs.by_name(meta_ids) (cs.all() & cs.by_name('Sample1', 'Sample2', 'Sample4')...
2
2
78,676,983
2024-6-27
https://stackoverflow.com/questions/78676983/get-rows-from-related-table-orm-object-via-array-agg
I want to get the product table data array using the array_agg function. In Postgers, this works great, but in SQLalchemy this can only be done with data types such as integer, strings, and so on. How do I implement this in SQLalchemy? Code in postgresql: select DISTINCT seller.title, array_agg(product), COUNT(product...
The GitHub discussion that @snakecharmerb cites above includes the comment relationship does exactly what you are looking for in an object oriented way. # https://stackoverflow.com/q/78676983/2144390 # fmt: off from sqlalchemy import Column, ForeignKey, Integer, String, Table, create_engine, select from sqlalchemy.or...
2
1
78,676,841
2024-6-27
https://stackoverflow.com/questions/78676841/dealing-with-columns-with-datatype-object
I read in a stored numpy array with dtype object in polars. I want to change column dtype from object to float in the polars dataframe. Minimal example: # generate sample data data = {"1": ["1.0", "2.0", "3.0", "4.0"], "2": [10, 20, 30, 40]} df = pl.DataFrame(data, schema={'1':pl.Object, '2':pl.Object}) # what I want t...
Usually, by the time an object dtype made it into your dataframe, it is already too late to perform any native polars operation on it. Still, you can apply pl.Expr.map_elements to map a user-defined function over elements. df.with_columns( pl.col("1").map_elements(lambda x: x, return_dtype=pl.String), pl.col("2").map_e...
2
3
78,676,685
2024-6-27
https://stackoverflow.com/questions/78676685/why-does-x-1-not-reverse-a-grouped-pandas-dataframe-column-in-python-3-12-3
I have a large pandas DataFrame (160k records, 60 columns of mostly text) but for this example, I have the following DataFrame: df1 = pd.DataFrame([{"GROUP": "A", "COL2": "1", "COL3": "P"}, {"GROUP": "A", "COL2": "2", "COL3": "Q"}, {"GROUP": "A", "COL2": "3", "COL3": "R"}, {"GROUP": "B", "COL2": "4", "COL3": "S"}, {"GR...
Because the output of transform is aligned back to the original index when it is a Series, which in your case reverts it back to its original order. To avoid this you must convert to array/list (with values/array/to_numpy): df1['REVERSED_COL'] = (df1.groupby("GROUP")["COL2"] .transform(lambda x: x[::-1].array) ) Outpu...
3
1
78,676,037
2024-6-27
https://stackoverflow.com/questions/78676037/turn-a-list-of-tuples-into-pandas-dataframe-with-single-column
I have a list of tuples like: tuple_lst = [('foo', 'bar'), ('bar', 'foo'), ('ping', 'pong'), ('pong', 'ping')] And I want to create a Dataframe with one column containing each tuple pair, like: | one col | | -------- | | ('foo', 'bar') | | ('bar', 'foo') | | ('ping', 'pong') | | ('pong', 'ping') | I tried: df = pd.Da...
Use a dictionary, this will ensure the DataFrame constructor doesn't try to interpret the data as 2D: pd.DataFrame({'one col': tuple_lst}) You could also have used a Series and converted to_frame: pd.Series(tuple_lst).to_frame(name='one col') Or, closer to your original approach, which could be useful if you have con...
3
2