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,675,968
2024-6-27
https://stackoverflow.com/questions/78675968/pandas-compact-rows-when-data-is-missing
I have a list of dicts where each dict can have different keys. I want to create a dataframe with one row where each key is a column and the row is its value: import pandas as pd data = [{"A":1}, {"B":2}, {"C":3}] df = pd.DataFrame(data) print(df.to_string(index=False)) # A B C # 1.0 NaN NaN # NaN 2.0 NaN # NaN NaN 3.0...
One option would be to stack: df.stack().droplevel(0).to_frame().T Or using a dummy groupby: import numpy as np df.groupby(np.repeat(0, len(df))).first() Output: A B C 0 1.0 2.0 3.0
3
2
78,674,348
2024-6-26
https://stackoverflow.com/questions/78674348/how-to-merge-2-pandas-dataframes-based-on-criteria
I’m having some issues joining 2 dataframes using pandas.merge(), based on certain conditions. I would appreciate some advice In the example below, I wish to join the 2 dataframes on customerId. However, I’m interested in only the EARLIEST record in loans_df which matches the condition: Customers.EndDate < Loans.Date ...
It looks like a merge_asof after pre-filtering Loans_df to only keep the values above 100: # prerequisite: ensure correct datetime # Customer_df['End date'] = pd.to_datetime(Customer_df['End date'], format='%Y%m%d') # Loans_df['Date'] = pd.to_datetime(Loans_df['Date'], format='%Y%m%d') out = pd.merge_asof(Customer_df.s...
2
3
78,672,815
2024-6-26
https://stackoverflow.com/questions/78672815/combine-multiple-conditions-for-finding-elements-in-nested-tuple
Python novice here. I have the following nested tuple containing values, sides and context: my_tuple = [(121, 131, 174, 188, 228, 242, 282), ('Left', 'Right', 'Right', 'Left', 'Left', 'Right', 'Right'), ('Foot Strike', 'Foot Off', 'Foot Strike', 'Foot Off', 'Foot Strike', 'Foot Off', 'Foot Strike')] I would like to ex...
out = (el[0] for el in zip(*my_tuple) if el[1]=='Right' and el[2]=='Foot Strike') Explanation: First, we use zip to obtain iterable of (value, side, context) tuples. Then we can go through that iterable, filter on our condition and return first element of each tuple. Output: print(list(out)) [174, 282]
2
4
78,671,071
2024-6-26
https://stackoverflow.com/questions/78671071/numpy-array-slicing-with-a-comma
There are multiple questions on StackOverflow, asking how the comma syntax works, but most of them refer to m[:,n] which refers to the nth column. Similarly, m[n,:] refers to the nth row. I find this method of slicing used in the labs of Machine Learning Specialization by Andrew Ng. But does this slicing have any advan...
For an array with 2 or more dimensions, m[n] and m[n, :] are identical. The first can be considered shorthand for the second. For an array with 1 dimension, m[n] will return element n, and m[n, :] will result in an error. I personally would choose m[n, :] in some cases to make the code more human-readable: for example,...
3
4
78,671,711
2024-6-26
https://stackoverflow.com/questions/78671711/how-can-i-filter-groups-by-comparing-the-first-value-of-each-group-and-the-last
My DataFrame: import pandas as pd df = pd.DataFrame( { 'group': ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'e', 'e', 'e'], 'num': [1, 2, 3, 1, 12, 12, 13, 2, 4, 2, 5, 6, 10, 20, 30] } ) Expected output is getting three groups from above df group num 0 a 1 1 a 2 2 a 3 group num 6 c 13 7 c 2 8 c 4 gro...
IIUC, you can aggregate as first/last per group, mask the unwanted values and map back to the group. Finally shift one row up: tmp = df.groupby('group')['num'].agg(['first', 'last']) s = tmp['last'].where(tmp['last'].shift(fill_value=0).le(tmp['first'])).ffill().cummax() df['desired_cummax'] = df['group'].map(s.shift()...
2
3
78,653,631
2024-6-21
https://stackoverflow.com/questions/78653631/polars-selectors-alias-with-when-then-otherwise
Say I have this: import polars as pl import polars.selectors as cs df = pl.select( j = pl.int_range(10, 99).sample(10, with_replacement=True), k = pl.int_range(10, 99).sample(10, with_replacement=True), l = pl.int_range(10, 99).sample(10, with_replacement=True), ) shape: (10, 3) ┌─────┬─────┬─────┐ │ j ┆ k ┆ l │ │ ---...
You can use .name.keep() df.select( pl.when(cs.numeric() < 50) .then(1) .otherwise(2) .name.keep() ) shape: (10, 3) ┌─────┬─────┬─────┐ │ j ┆ k ┆ l │ │ --- ┆ --- ┆ --- │ │ i32 ┆ i32 ┆ i32 │ ╞═════╪═════╪═════╡ │ 1 ┆ 1 ┆ 2 │ │ 2 ┆ 1 ┆ 1 │ │ 1 ┆ 2 ┆ 1 │ │ 2 ┆ 2 ┆ 1 │ │ 2 ┆ 1 ┆ 2 │ │ 2 ┆ 2 ┆ 2 │ │ 2 ┆ 2 ┆ 1 │ │ 2 ┆ 2 ┆ 2...
2
5
78,668,351
2024-6-25
https://stackoverflow.com/questions/78668351/changing-taipy-selector-lov-at-runtime
I am trying to change the List of Values of a Taipy selector at runtime, but I keep failing. My lov is defined as the keys of a dictionary in my application, called shapes. I define my selector like this: tgb.selector(value="{sel_shape}", lov=list(shapes.keys()), dropdown=True, label="Shapes") At startup, the default ...
Try this syntax: tgb.selector(value="{sel_shape}", lov="{list(shapes.keys())}", dropdown=True, label="Shapes") Here is a full example: from taipy.gui import Gui import taipy.gui.builder as tgb shapes = {"Mail":["example@example", "example2@example"], "Person":["John Doe", "Jane Doe"]} selected_shape = None def add_sha...
2
1
78,650,222
2024-6-21
https://stackoverflow.com/questions/78650222/valueerror-numpy-dtype-size-changed-may-indicate-binary-incompatibility-expec
MRE pip install pandas==2.1.1 numpy==2.0.0 Python 3.10 on Google Colab Output Collecting pandas==2.1.1 Downloading pandas-2.1.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (12.3 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 12.3/12.3 MB 44.7 MB/s eta 0:00:00 Collecting numpy==2.0.0 Using cached numpy-2.0...
I found a solution for now: I need to downgrade numpy to version 1.26.4 pip install numpy==1.26.4 or pip install "numpy<2" Restart session after downgrading numpy Was able to successfully import pandas. Related git : https://github.com/numpy/numpy/issues/26710
20
48
78,646,329
2024-6-20
https://stackoverflow.com/questions/78646329/provide-multiple-languages-via-odoo-rpc-call
I would like to write multiple languages to a ir.ui.view Object's arch_db field. However, if I provide a dict/json value with languages as keys and HTML as values ({"de_DE"=><german-html>, "en_US"=><american-html>}), validation will fail. If I write html with a de_DE context first, and then with en_US context, the latt...
Found solution: One has to use xml_translate to extract translatable terms from arch_db[context lang] and then use it multiple times to extract translations from all arch_db[other lang]. (I built a Flask JSON API to interact with Odoo code not reachable via RPC from Go.) Next, one can create view via RPC (with same con...
3
0
78,640,035
2024-6-19
https://stackoverflow.com/questions/78640035/are-none-and-typenone-really-equivalent-for-type-analysis
According to the PEP 484's "Using None" part: When used in a type hint, the expression None is considered equivalent to type(None). However, I encountered a case where both don't seem equivalent : from typing import Callable, NamedTuple, Type, Union # I define a set of available return types: ReturnType = Union[ int,...
As showed in the post, the PEP 484 stated something ambiguous: When used in a type hint, the expression None is considered equivalent to type(None). But I found out about the PEP 483 that uses a much clearer wording in its Pragmatics: Where a type is expected, None can be substituted for type(None); e.g. Union[t1, N...
4
0
78,640,132
2024-6-19
https://stackoverflow.com/questions/78640132/how-to-make-scipy-newton-krylov-use-a-different-derivative-approximation-method
After reading the documentation seems like it uses forward difference as its approximation method, but I can't see any direct way to make it use other method or a custom one. Using the tools in the documentation I tried this to make it use a custom method and did this implementation to test if the results were the same...
I misunderstood, the 'inner_M' parameter does not do what I thought it did, but I found a solution by creating a custom scipy Jacobian class following the same implementation scipy does. import numpy as np import scipy.sparse.linalg from scipy.linalg import norm import scipy.optimize._nonlin from scipy.optimize._nonlin...
4
0
78,650,025
2024-6-21
https://stackoverflow.com/questions/78650025/partial-chained-callbacks-using-plotly-dash
I'm trying to filter data using multiple dropdown bars within a plotly dashboard. There are 5 dropdown options in total. I want the first 3 to operate indepently, while the last two should be chained, both ways, to the first 3. Specifically, the features that I'm aiming to implement are: A default of all values should...
That can be accomplished with plotly dash. The trick is to use or operators between the first three filters to make them additive and and operators between the last two to make them subtractive. The first three options need to be resolved as one block before involving the last two options. Example query structure: (opt...
2
2
78,669,632
2024-6-25
https://stackoverflow.com/questions/78669632/one-liner-split-and-map-within-list-comprehension
I have this bit for parsing some output from stdout: out_lines = res.stdout.split("\n") out_lines = [e.split() for e in out_lines] out_vals = [{"date":e[0], "time":e[1], "size":e[2], "name":e[3]} for e in out_lines if e] Is there an idiomatic way to merge the second and third lines here so that the splitting and mappi...
@trincot's answer works but can avoid a post-processing filter by mapping the lines to str.split so that the filtering can be done with the if clause of the comprehension instead: out_vals = [ dict(zip(("date", "time", "size", "name"), e)) for e in map(str.split, res.stdout.split("\n")) if e ]
3
2
78,652,843
2024-6-21
https://stackoverflow.com/questions/78652843/why-does-csv-reader-with-textiowrapper-include-new-line-characters
I have two functions, one downloads individual csv files and the other downloads a zip with multiple csv files. The download_and_process_csv function works correctly with response.iter_lines() which seems to delete new line characters. 'Chicken, water, cornmeal, salt, dextrose, sugar, sodium phosphate, sodium erythorb...
I've played around with a mock server which serves this CSV file: "foo bar" The CSV has a single field, "foo\nbar", in a single row. I call a newline in the data an embedded newline. When I use the iter_content method on the Response object: print("Getting CSV") resp = requests.get("http://localhost:8999/csv") x = res...
2
2
78,669,613
2024-6-25
https://stackoverflow.com/questions/78669613/how-to-check-if-some-number-can-be-retrieved-as-the-result-of-the-summation-or-d
I have an arbitrary list of positive integers and some number X. I want to check if it is possible to retrieve X using basic operations such as summation and difference. Any number from the list can be used only once. There might be duplicates. We can use any amount of numbers from the list to get X, i.e. we can use ju...
For each number in the list, you have to make a decision whether: you add the number you subtract the number you drop the number Here is a solution with breadth-first search of the decision tree: def isRepresentable(input_list, num): reachable = { 0 } for n in input_list: reachable = { y for x in reachable for y in [...
2
3
78,667,408
2024-6-25
https://stackoverflow.com/questions/78667408/how-to-get-as-fast-as-possible-a-specific-sequence-of-numbers-all-numbers-twice
Knowing a final number (for example 5), I would like to create an array containing the following sequence: [0,1,1,2,2,3,3,4,4,5] Meaning that the list should contain all numbers repeated twice, except for the first and last. Here is the code I use to achieve this : import numpy as np # final number last = 35 # first s...
What about using arange on 2*N, add 1 and take the floor division by 2? N = 5 out = (np.arange(2*N)+1)//2 # or variant suggested by @TlsChris # out = (np.arange(2*N)+1)>>1 Alternatively, with repeat and excluding the first/last: out = np.repeat(np.arange(N+1), 2)[1:-1] Or with broadcasting: out = (np.arange(N)[:, Non...
3
5
78,668,507
2024-6-25
https://stackoverflow.com/questions/78668507/python-regex-split-string-with-multiple-delimeters
I know this question has been answered but my use case is slightly different. I am trying to setup a regex pattern to split a few strings into a list. Input Strings: 1. "ABC-QWERT01" 2. "ABC-QWERT01DV" 3. "ABCQWER01" Criteria of the string ABC - QWERT 01 DV 1 2 3 4 5 The string will always start with three chars The ...
You can use a pattern similar to : (?i)([A-Z]{3})(-?)([A-Z]*)([0-9]{2})([A-Z]*) Code: import re def _parts(s): p = r'(?i)([A-Z]{3})(-?)([A-Z]*)([0-9]{2})([A-Z]*)' return re.findall(p, s) print(_parts('ABC-QWERT01DV')) print(_parts('ABCQWER01')) print(_parts('ABC-QWERT01')) Prints [('ABC', '-', 'QWERT', '01', 'DV')] [...
3
4
78,666,883
2024-6-25
https://stackoverflow.com/questions/78666883/pip-install-quickfix-failed-in-windows
I'm trying to install the quikcfix library on my windows machine. The python version is 3.12.2. However I get the below error. python setup.py bdist_wheel did not run successfully exit code: 1 [7 lines of output] Testing for std::tr1::shared_ptr... ...not found Testing for std::shared_ptr... ...not found Testing for st...
Download the quickfix from here: https://github.com/kazcfz/QuickFIX-prebuilt-wheel What I see from the link, the latest version of python which supports quickfix is 3.9 It will not work for python 3.12
5
3
78,666,961
2024-6-25
https://stackoverflow.com/questions/78666961/meta-feature-analysis-split-data-for-computation-on-available-memory
I am working with the meta-feature extractor package: pymfe for complexity analysis. On a small dataset, this is not a problem, for example. pip install -U pymfe from sklearn.datasets import make_classification from sklearn.datasets import load_iris from pymfe.mfe import MFE data = load_iris() X= data.data y = data.tar...
Managed to find a workaround. # helper functions def split_dataset(X, y, n_splits): # data splits split_X = np.array_split(X, n_splits) split_y = np.array_split(y, n_splits) return split_X, split_y def compute_meta_features(X, y): # meta-features for a partition extractor = MFE(features=["t1"], groups=["complexity"], s...
2
0
78,664,686
2024-6-24
https://stackoverflow.com/questions/78664686/itertools-islice-iterate-over-input-even-when-stop-is-smaller-than-start
For a custom container wrapping an iterator, I intended to delegate some of my logic to itertools.islice. One consideration was to avoid unnecessary iterations over the wrapped iterator. When calling itertools.islice(iterable, start, stop, step) with stop<=start, the result is an empty generator, as expected. But even ...
Consuming elements from the underlying iterator is part of the islice contract, and cannot be optimized out. There's even a recipe in the recipes section of the official itertools docs that relies on empty islices consuming elements: def consume(iterator, n=None): "Advance the iterator n-steps ahead. If n is None, cons...
3
4
78,641,844
2024-6-19
https://stackoverflow.com/questions/78641844/thread-safeness-and-slow-pyplot-hist
The hist function of matplotlib.pyplot runs very slow which seemingly has to do with the structure I have chosen. I built a front panel in Tkinter which starts a control loop for a camera. To keep the control loop responsive I created an ImageProcessor class which collects, processes and plots the images in cv2. The Im...
The solution is straightforward and has nothing to do with plt.hist. Simply add the line time.sleep(0.01) in your main loop. The reason is that threading is not the same as multiprocessing. All threads share the same process (CPU), meaning only one thread can run at a time. In your case, the main thread (the while ctl_...
3
1
78,665,686
2024-6-25
https://stackoverflow.com/questions/78665686/calculate-distance-to-the-nearest-object
I need to make a map of distances to the nearest object. I have a solution where i am looping over every point of a map, and every object, calculating the distance to all of them, and then leaving only minimum distance. The problem here is that if I am woking with real data, the map can easily contain 10s of millions o...
KDTree is what you are looking for, there is an implementation of it in scipy.spatial. import numpy as np import matplotlib.pyplot as plt from scipy import spatial Given your trial points: x_value = np.arange(0, 10000, 50) y_value = np.arange(0, 5000, 50) X, Y = np.meshgrid(x_value, y_value) points = np.stack([X.ravel...
2
4
78,665,006
2024-6-25
https://stackoverflow.com/questions/78665006/time-library-returns-incorrect-execution-time-for-decorator-functions-in-flask
Say I have the following python files in my src directory for my Flask application (Flask-smortest to be specific): src/ ham.py eggs.py endpoint.py ham.py has 1 decorator function, while eggs.py has 3 decorator functions #ham.py script from functools import wraps import time def ham1(func): @wraps(func) def wrapper(*a...
If you're trying to measure total time then what you did on egg is correct, but wrong for ham. But if time measuring is only intended for decorator-specific operations excluding decoration target's execution time - you must not put target function execution between time measurements. So either: # assuming return value ...
2
1
78,664,366
2024-6-24
https://stackoverflow.com/questions/78664366/how-to-add-a-foreignkey-field-to-be-saved-in-modelform-django
While creating my website, I face the following problem: a user can add an article, and so the article model has a ForeignKey field - author. I created a form for adding it, inheriting from ModelForm, since I think it is more logical that way (as it interacts directly with db). The problem is that I cannot add this fie...
There are other ways. Such as adding a hidden field to your form and set its value as the request.user.id. Although, I must say that your initial thought related to the save() method is the correct one. However, not overriding it but using an optional keyword provided by the method itself. Also, do not forget to set fo...
2
1
78,653,824
2024-6-21
https://stackoverflow.com/questions/78653824/efficiently-marking-holidays-in-a-data-column
I'm trying to add a column that indicates whether a date is a holiday or not. I found some code online, but I believe there's a more efficient way to do it, possibly using a polar method instead of map elements and lambda. Example code: import polars as pl import holidays # Initialize the holidays for Chile cl_holidays...
After doing some research, I found that I need to pass the years into my 'holidays.CL' constructor import polars as pl import holidays # Initialize the holidays for Chile cl_holidays = holidays.CL() # Sample data data = { "Date": ["2024-06-20 00:00:00", "2024-06-21 00:00:00", "2024-06-22 00:00:00", "2024-06-23 00:00:00...
5
1
78,663,783
2024-6-24
https://stackoverflow.com/questions/78663783/polars-datime-range-with-multiple-values-per-date
I'm trying to assign multiple entries from a list per date to my dateframe, so for each day, I would have all the values from the list. I tried passing the list as an argument; however, I'm having problems with the length of the dataframe. Conceptual code: from datetime import datetime import polars as pl Value_list = ...
Are you looking for a cross-join? from datetime import datetime import polars as pl dates = pl.datetime_range( start=datetime(2023, 1, 1), end=datetime(2023, 12, 10), interval="1d", eager=True, closed="both", ).to_frame('date') values = pl.Series('producto', ['xd', 'xd1']).to_frame() print(dates.join(values, how='cross...
2
4
78,653,708
2024-6-21
https://stackoverflow.com/questions/78653708/parallelizing-numpy-sort
I need to sort uint64 arrays of length 1e8-1e9, which is one of the performance bottlenecks in my current project. I have just recently updated numpy v2.0 version, in which the sorting algorithm is significantly optimized. Testing it on my hardware, its about 5x faster than numpy v1.26 version. But currently numpy's so...
This answer show why a pure-Python, Numba or Cython implementation certainly cannot be used to write a (reasonably-simple) efficient implementation (this summaries the comments). It provides a C++ version which can be called from CPython. The provided version is fast independently of the Numpy version used (so Numpy 2....
7
5
78,658,850
2024-6-23
https://stackoverflow.com/questions/78658850/difference-between-time-vs-time-vs-timeit-timeit-in-jupyter-notebook
Help me in finding out the exact difference between time and timeit magic commands in jupyter notebook. %time a="stack overflow" time.sleep(2) print(a) It shows only some micro seconds, But I added sleep time as 2 seconds
Magics that are prefixed with double percentage signs (%%) are considered cell magics. This differs from line magics which are prefixed with a single percentage sign (%). It follows that, time is used to time the execution of code either at a line level (%) or cell level (%%). timeit is similar but runs the code multi...
2
3
78,658,424
2024-6-23
https://stackoverflow.com/questions/78658424/matplotlib-set-ticks-and-labels-at-regular-intervals-but-starting-at-specific-d
I am trying to set the following dates (year only): lab = [1969, 1973, 1977, 1981, 1985, 1989, 1993, 1997, 2001, 2005, 2009, 2013, 2017, 2021, 2025] I tried with dates.YearLocator(base=4), but didn't find a way to set the starting year. I get the labels starting in 1968 instead of 1969. I also tried with ticker.FixedFo...
You can directly set the x-ticks you want with a list of datetimes: lab = [1969, 1973, 1977, 1981, 1985, 1989, 1993, 1997, 2001, 2005, 2009, 2013, 2017, 2021, 2025] lab_dates = [datetime.date(year, 1, 1) for year in lab] ax.xaxis.set_ticks(lab_dates) that overrides the formatting so that the labels show up like "1973-...
2
1
78,641,150
2024-6-19
https://stackoverflow.com/questions/78641150/a-module-that-was-compiled-using-numpy-1-x-cannot-be-run-in-numpy-2-0-0
I installed numpy 2.0.0 pip install numpy==2.0.0 import numpy as np np.__version__ #2.0.0 then I installed: pip install opencv-python Requirement already satisfied: opencv-python in /usr/local/lib/python3.10/dist-packages (4.8.0.76) Requirement already satisfied: numpy>=1.21.2 in /usr/local/lib/python3.10/dist-packag...
There are two solutions for this error: 1. downgrade your numpy to 1.26.4 pip install numpy==1.26.4 or pip install "numpy<2.0" Make sure to restart your kernel after downgrading numpy Another option is: 2. install the latest version of the module which is failing* I had an old version of opencv-python 4.8.0.76 I wa...
19
46
78,658,024
2024-6-23
https://stackoverflow.com/questions/78658024/add-the-row-counts-as-a-list-to-column-using-groupby
I am working on an application that needs to provide the count of certain entries in a dataframe. Am I missing something that is not rendering the required outcome? Input: | Release | Mapping | Coding | |-----------|---------|--------| | release_a | A1 | C2 | | release_c | A1 | C2 | | release_a | A1 | C2 | | release_a ...
Here's an approach with collections.Counter: from collections import Counter out = (df.groupby('Release')['Mapping'] .agg(lambda x: ", ".join(f"{k} - {v}" for k, v in Counter(x).items())) .reset_index() ) Output: Release Mapping 0 release_a A1 - 3, C - 2 1 release_b B - 1 2 release_c A1 - 3, B - 2 Or via Series.valu...
2
4
78,657,980
2024-6-23
https://stackoverflow.com/questions/78657980/save-data-to-a-new-tab-in-the-xlsx-file
My program generates a data_list using a while loop (the code for generating the data_list is not important, and I have attached the main code below). At the end of the loop, after the data_list is generated, I want to write this data_list to the test.xlsx file. However, for each new data_list to be saved in a new tab ...
Instead of saving each sheet use with to create the ExcelWriter with pd.ExcelWriter('test.xlsx') as writer: while finish < 11: data = datas[start:finish] data_list = [] df = pd.DataFrame(data_list) df.to_excel(writer, sheet_name=f'{finish}', index=False) finish += 1 start += 1
4
1
78,657,336
2024-6-22
https://stackoverflow.com/questions/78657336/convex-function-in-cvxpy-does-not-appear-to-be-producing-the-optimal-solution-fo
I am working on optimizing a battery system(1 MWh) that, in conjunction with solar power(200 kW nameplate capacity), aims to reduce electricity costs for a commercial building. For those unfamiliar with commercial electricity pricing, here's a brief overview: charges typically include energy charges (based on total ene...
A couple caveats: I didn't look at the load following stuff, but you should compute the costs for that and compare with the optimization I think the way you are constructing the cost vector with all of the numpy/diagonals/ones/zeros/etc. is pretty confusing, but that is just an aside. I plotted the costs (alpha) and i...
2
1
78,657,011
2024-6-22
https://stackoverflow.com/questions/78657011/how-to-work-with-a-type-from-a-rust-made-library-in-python
I am making a Rust based library for Python which implements different cryptographic protocols, and I'm having trouble working with EphemeralSecret, as I keep getting the error log: "no method named to_bytes found for struct EphemeralSecret in the current scope method not found in EphemeralSecret" This is being used t...
EphemeralSecret does not have a to_bytes method as Ephemeral Secrets cannot be serialized to Vec as mentioned in the docs. This type is identical to the StaticSecret type, except that the EphemeralSecret::diffie_hellman method consumes and then wipes the secret key, and there are no serialization methods defined To c...
2
4
78,652,436
2024-6-21
https://stackoverflow.com/questions/78652436/pandas-extract-sequence-where-prev-value-current-value
Need to extract sequence of negative values where earlier negative value is smaller than current value and next value is smaller than current value import pandas as pd # Create the DataFrame with the given values data = { 'Value': [0.3, 0.2, 0.1, -0.1, -0.2, -0.3, -0.4, -0.35, -0.25, 0.1, -0.15, -0.25, -0.13, -0.1, 1] ...
You can build masks to identify the negative values and consecutive decreasing values and use groupby to split: # is the value negative? m1 = df['Value'].lt(0) # is the value decreasing? m2 = df['Value'].diff().le(0) m = m1&m2 # aggregate out = df[m].groupby((~m).cumsum())['Value'].agg(list).tolist() Output: [[-0.1, -...
3
1
78,646,747
2024-6-20
https://stackoverflow.com/questions/78646747/wrong-shape-at-fully-connected-layer-mat1-and-mat2-shapes-cannot-be-multiplied
I have the following model. It is training well. The shapes of my splits are: X_train (98, 1, 40, 844) X_val (21, 1, 40, 844) X_test (21, 1, 40, 844) However, I am getting the following error at x = F.relu(self.fc1(x)) in forward. When I attempt to interpret the model on the validation set. # Create a DataLoader for ...
I was able to pass the data to the fastai.Learner to train the model and get results from plot_confusion_matrix. My conclusion that fastai is not designed to work with custom Datasets and DataLoaders and expecting you to use their API for loading the data. I think that in your case it might be worth to switch to Tabula...
2
1
78,655,628
2024-6-22
https://stackoverflow.com/questions/78655628/inverse-fourier-transform-x-axis-scaling
I'm implementing a discrete inverse Fourier transform in Python to approximate the inverse Fourier transform of a Gaussian function. The input function is sqrt(pi) * e^(-w^2/4) so the output must be e^(-x^2). While the shape of the resulting function looks correct, the x-axis scaling seems to be off (There might be ju...
It looks like you're using frequency in the x-axis when you expect angular frequency. You should modify your x_range computation like this: x_range = 2 * np.pi * np.fft.ifftshift(np.fft.fftfreq(n, d=delta_omega)) With this change, the resulting plot looks like this:
3
3
78,655,732
2024-6-22
https://stackoverflow.com/questions/78655732/how-to-efficiently-compare-2-dataframe-and-produce-a-column-value-based-on-condi
data1 = { 'alias_cd': ['12345', '12345', '12345'], 'country_cd': ['AU', 'AU', 'AU2'], 'pos_name': ['st1', 'Jh', 'Jh'], 'ts_allocated': [100, 100, 100], 'tr_id': ['None', 'None', 'None'], 'ty_name': ['E2E', 'E2E', 'E2E'] } data2 = { 'alias_cd': ['12345', '12345'], 'country_cd': ['AU', 'AU3'], 'pos_name': ['st1', 'st2'],...
IIUC, you can first perform a left-merge with indicator on df2 to identify the U/D status, then concat. df1 always gets an I: # columns used as primary key cols = ['alias_cd', 'country_cd'] out = pd.concat( [df2.assign(etl_flag=df2.merge(df1[cols].drop_duplicates(), on=cols, how='left', indicator=True) ['_merge'].map({...
2
2
78,653,471
2024-6-21
https://stackoverflow.com/questions/78653471/how-can-i-form-groups-by-a-mask-and-n-rows-after-that-mask
My DataFrame is: import pandas as pd df = pd.DataFrame( { 'a': [False, True, False, True, False, True, False, True, True, False, False], } ) Expected output is forming groups like this: a 1 True 2 False 3 True a 5 True 6 False 7 True a 8 True 9 False 10 False The logic is: Basically I want to form groups where df.a ...
Since you problem is inherently iterative, you must loop. The most straightforward option IMO is to use a simple python loop: def split(df, N=2): i = 0 a = df['a'].to_numpy() while i < len(df): if a[i]: yield df.iloc[i:i+N+1] i+=N i+=1 out = list(split(df)) Output: [ a 1 True 2 False 3 True, a 5 True 6 False 7 True, a...
3
1
78,654,841
2024-6-22
https://stackoverflow.com/questions/78654841/scipy-integrate-quad-gives-incorrect-value
I was trying defining a trajectory using velocity and curvature by time; i.e. v(t) and k(t). To get x and y position at time t, I used scipy.integrate.quad but it gives a wrong value. Below is what I've tried. import numpy as np from scipy.integrate import quad # Define v(t) and k(t) def v(t): return 10.0 def k(t): ret...
You can use solve_ivp(), which is designed for solving initial value problems for ODEs: import numpy as np from scipy.integrate import solve_ivp def system(t, y, v, k): x, y_pos, theta = y dxdt = v(t) * np.cos(theta) dydt = v(t) * np.sin(theta) dthetadt = v(t) * k(t) return [dxdt, dydt, dthetadt] def v(t): return 10.0 ...
2
1
78,654,580
2024-6-21
https://stackoverflow.com/questions/78654580/how-to-perform-single-synchronous-and-multiple-asynchronous-requests-in-python
I'm working on a Python script where I need to make an initial request to obtain an ID. Once I have the ID, I need to make several additional requests to get data related to that ID. I understand that these subsequent requests can be made asynchronously to improve performance. However, I'm not sure how to implement thi...
Similar but using a task group (python >= 3.11) import httpx import asyncio async def main(): async with httpx.AsyncClient() as client: response = await client.get('https://api.example.com/get_id') id = response.json()['id'] async with asyncio.TaskGroup() as tg: task1 = tg.create_task(client.get(f'https://api.example.c...
4
3
78,654,017
2024-6-21
https://stackoverflow.com/questions/78654017/how-to-type-hint-dictionaries-that-may-have-different-custom-keys-and-or-values
In the previous versions of our app, people would just pass some arguments with plain strings to certain functions, as we did not have specific type hinting or data types for some of them. Something like: # Hidden function signature: def dummy(var: str): pass # Users: dummy("cat") But now we want to implement custom d...
The core issue is this: Of course doing something like: input_data2: DataTypes = { "dog": "dog", } would solve it, but I can't ask the users to always do that when they create their datatypes. If you don't want your users to provide annotations, then they will have to pass the data directly to the function (dummy({"...
2
2
78,642,079
2024-6-19
https://stackoverflow.com/questions/78642079/how-to-properly-calculate-psd-plot-power-spectrum-density-plot-for-images-in-o
I'm trying to remove periodic noise from an image using PSDP, I had some success, but I'm not sure if what I'm doing is 100% correct. This is basically a kind of follow up to this video lecture which discusses this very subject on 1d signals. What I have done so far: Initially I tried flattening the whole image, and t...
Here are some things you can do to improve your results: The hard transition from 1 to 0 in your frequency-domain kernel (ind in the 2nd block of code, it is implicit in the 3rd) means that you’ll get lots of ringing artifacts back in the spatial domain. This is 99% of the strange stuff in your output. To see this rin...
2
3
78,650,040
2024-6-21
https://stackoverflow.com/questions/78650040/optimization-challenge-due-to-l1-cache-with-numba
I've been working on optimizing the calculation of differences between elements in NumPy arrays. I have been using Numba for performance improvements, but I get a 100-microsecond jump when the array size surpasses 1 MB. I assume this is due to my CPU's Ryzen 7950X 1 MB L1 cache size. Here is an example code: @jit(nopyt...
TL;DR: The performance issue is not caused by your CPU cache. It comes from the behaviour of the allocator on your target platform which is certainly Windows. Analysis I assume this is due to my CPU's Ryzen 7950X 1 MB L1 cache size. First of all, the AMD Ryzen 7950X CPU is a Zen4 CPU. This architecture have L1D cach...
5
4
78,645,142
2024-6-20
https://stackoverflow.com/questions/78645142/attention-weights-on-top-of-image
h = 16 fig, ax = plt.subplots(ncols=3, nrows=1, figsize=(15, 5)) for i, q_id in enumerate(sorted_indices[0]): logit = itm_logit[:, q_id, :] prob = torch.nn.functional.softmax(logit, dim=1) name = f'{prob[0, 1]:.3f}_query_id_{q_id}' # Attention map attention_map = avg_cross_att[0, q_id, :-1].view(h, h).detach().cpu().nu...
The root cause of this is the different resolution of the image and the attention map. This way, the second imshow call reduced the displayed area to a tiny corner of the original image, with an overlay of the 16x16 attention map. To fix this, the attention map needs to be upscaled (e.g. via np.repeat) to the image res...
2
1
78,649,817
2024-6-20
https://stackoverflow.com/questions/78649817/pandas-groupby-expanding-mean-does-not-accept-missing-values
I've been looking to retrieve group-based expanding means from the following dataset: df = pd.DataFrame({'id':[1,1,1,2,2,2],'y':[1,2,3,1,2,3]}) and df.groupby('id').expanding().mean().values returns the correct: array([[1. ], [1.5], [2. ], [1. ], [1.5], [2. ]]) However, in my specific case I have to deal with some mi...
You can convert column 'y' with pd.to_numeric, which will coerce pd.NaN into nan. The latter can be interpreted correctly by the following operations: df2["y"] = pd.to_numeric(df2["y"]) df2 = df2.groupby("id").expanding().mean().values [[1. ] [1. ] [2. ] [1. ] [1.5] [2. ]]
2
3
78,648,876
2024-6-20
https://stackoverflow.com/questions/78648876/nested-condition-on-simple-data
I have a dataframe having 3 columns, two boolean type and one column as string. from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField, BooleanType, StringType # Create a Spark session spark = SparkSession.builder \ .appName("Condition Test") \ .getOrCreate() # Sample data data = [ (...
The condition is invalid because it doesn't consider operator precedence and hence the wrong result. Operator & has a higher precedence than !=. Here's the updated condition with parentheses: condition = ( (~col("is_flag")) | ((col("is_flag")) & (trim(col("country")) != 'CA') & (nvl(col("rule"),lit(False)) != True)) ) ...
2
3
78,649,010
2024-6-20
https://stackoverflow.com/questions/78649010/how-to-pass-optimization-options-such-as-read-only-true-to-pandas-read-excel
I want to use pandas.read_excel to read an Excel file with the option engine="openpyxl". However, I also want to pass additional optimization options to openpyxl such as: read_only=True data_only=True keep_links=False How do I do this?
These are already implemented by default. From version 2.2: def load_workbook( self, filepath_or_buffer: FilePath | ReadBuffer[bytes], engine_kwargs ) -> Workbook: from openpyxl import load_workbook default_kwargs = {"read_only": True, "data_only": True, "keep_links": False} return load_workbook( filepath_or_buffer, **...
2
6
78,645,965
2024-6-20
https://stackoverflow.com/questions/78645965/why-is-the-bat-board-not-moving-up-or-down-in-the-pong-game-when-the-screen-lis
Using the turtle module to make a pong game. For this part, when I press the up/down keys the board doesn't respond to the onkey listen function. I created the board/bat (or bat specs function from turtle called bat_specs_p2() ) and set the positions of the board/bat (x and y) on the screen. All is fine at this point....
You have two correctness problems: If you use tracer(0) to disable turtle's control of the rendering loop, you need to call screen.update() whenever you want to perform a redraw of the canvas. You're changing variables, but those variables aren't associated with any turtle object, so they're meaningless as far as turt...
2
2
78,646,217
2024-6-20
https://stackoverflow.com/questions/78646217/tkinter-updating-window-while-calculating-otherthings
I am triying to write sudoku solver. This is really complicated code for me. I want to update board while python calculating other things. However, code could not do that. Should I try threading or is there easy way to do that? CURRENT SITUATION: end of the calculation. I am inserting values. Then, I click solve. I am ...
Add a window.update() in your set_text function. This should update the tkinter window and show you the labels in real-time.
4
4
78,645,930
2024-6-20
https://stackoverflow.com/questions/78645930/how-can-i-find-the-first-row-after-a-number-of-duplicated-rows
My DataFrame is: import pandas as pd df = pd.DataFrame( { 'x': ['a', 'a', 'a','b', 'b','c', 'c', 'c',], 'y': list(range(8)) } ) And this is the expected output. I want to create column z: x y z 0 a 0 NaN 1 a 1 NaN 2 a 2 NaN 3 b 3 3 4 b 4 NaN 5 c 5 NaN 6 c 6 NaN 7 c 7 NaN The logic is: I want to find the first row af...
One option, using a custom mask: # flag rows after the first group m = df['x'].ne(df['x'].iat[0]).cummax() # pick the first one out = df[m & ~m.shift(fill_value=False)] If your first value is always a and you want to find the first non-a you could also use: m2 = df['x'].eq('a') out = df[m2.shift(fill_value=False) & ~m...
3
2
78,645,653
2024-6-20
https://stackoverflow.com/questions/78645653/typing-with-typevar-converts-a-type-to-an-object
I am trying to implement a generator that will return a pair of a sequence element and a boolean value indicating whether the element is the last one. from collections.abc import Generator, Iterable from itertools import chain, tee from typing import TypeVar _T1 = TypeVar('_T1') _MISSING = object() def pairwise(iterabl...
This is because you created a chain iterator like so: chain(sequence, [_MISSING]), and the type inference has to infer the most generic type from these arguments, but _MISSING is object, so it has to be an iterator of object. Note, you can implement the function you want with the signature you want straightforwardly (a...
2
3
78,645,378
2024-6-20
https://stackoverflow.com/questions/78645378/how-to-write-type-hint-for-decorated-implemented-by-a-class
Here's a classical example of a decorator implemented by a class: class Decorator: def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): self.func(*args, **kwargs) How to make __call__ have the same signature and type hints as func has? I've tried the following code: from typing import Callab...
You want to explicitly replace the function with a callable with a specific signature, instead of replacing the function with an instance of a callable class that works the same but does not share the signature. This shows the difference: from typing import Callable, TypeVar, ParamSpec, Generic PT = ParamSpec('PT') RT ...
2
2
78,645,337
2024-6-20
https://stackoverflow.com/questions/78645337/python-failed-to-initialize-a-2d-array-as-class-attributes
I am implementing a transition tables as a class attribute with, class Phase: num_states = 15 transition_table = [[False for _ in range(num_states)] for _ in range(num_states)] but it failed with NameError: name 'num_states' is not defined. However, 1d array works as expected, class Phase: num_states = 15 transition_t...
It looks like num_states is out of scope from the class definition. You can workaround this by passing the class variable into a lambda and run the list comprehension inside the lambda class Phase: num_states = 15 transition_table = (lambda x=num_states: [[False for _ in range(x)] for _ in range(x)])()
2
2
78,645,106
2024-6-20
https://stackoverflow.com/questions/78645106/get-distance-from-a-point-to-the-nearest-box
I have a 3D space where positions are stored as tuples, eg: (2, 0.5, -4). If I want to know the distance between two points I just do dist = (abs(x1 -x2), abs(y1 - y2), abs(z1 - z2)) and if I want a radius distf = (dist[0] + dist[1] + dist[2]) / 3. Now I have boxes each defined by two min / max positions (eg: (-4 8 -16...
You can use (dx ** 2 + dy ** 2 + dz ** 2) ** 0.5 for calculating the distance: def _dist(A, B, C): dx = max(B[0] - A[0], 0, A[0] - C[0]) dy = max(B[1] - A[1], 0, A[1] - C[1]) dz = max(B[2] - A[2], 0, A[2] - C[2]) return (dx ** 2 + dy ** 2 + dz ** 2) ** 0.5 def _dist_b(A, B, C): dx = max(B[0] - A[0], 0, A[0] - C[0]) dy ...
2
1
78,645,037
2024-6-20
https://stackoverflow.com/questions/78645037/how-do-i-perform-pandas-cumsum-while-skipping-rows-that-are-duplicated-in-anothe
I am trying to use the pandas.cumsum() function, but in a way that ignores rows with a value in the ID column that is duplicated and specifically only adds the last value to the cumulative sum, ignoring all earlier values. Example code below (I couldn't share the real code, which is for work). import pandas as pd, nump...
Try: df["out"] = ( df.groupby("id")["value"].transform("diff").fillna(df["value"]).cumsum().astype(int) ) print(df) Prints: id value cumsum_of_value desired_output out 0 a 12 12 12 12 1 b 14 26 26 26 2 c 3 29 29 29 3 a 13 42 30 30 4 b 16 58 32 32 5 e 7 65 39 39 6 f 4 69 43 43 7 a 6 75 36 36 8 b 10 85 30 30 9 k 18 103...
11
8
78,642,891
2024-6-19
https://stackoverflow.com/questions/78642891/create-array-by-combining-neighbouring-pairs-of-items
I have the following array of four elements: arr = [{"location": 10, "value": 50}, {"location": 21, "value": 70}, {"location": 33, "value": 20}, {"location": 48, "value": 0}] I would like to create a new array of three elements combining adjacent items: [ {index 0, 1}, {index 1, 2}, {index 2, 3} ] The function to run ...
You can use zip(arr, arr[1:]): def get_combine_neighbors(A): _comb = lambda x, y: (y["location"] - x["location"]) * x["value"] return [_comb(x, y) for x, y in zip(A, A[1:])] A = [{"location": 10, "value": 50}, {"location": 21, "value": 70}, {"location": 33, "value": 20}, {"location": 48, "value": 0}] print(get_combine_...
2
3
78,641,381
2024-6-19
https://stackoverflow.com/questions/78641381/display-pdf-without-pymupdf
Is there a way to display a PDF (only a single page, if that matters) in Python, without using the PyMuPDF library? I want to export my project via PyInstaller and including PyMuPDF increases the file size from ~40 to ~105 MB. Since I only want to display my pdf and don't need any of the advanced functionalities of PyM...
I got it to work with the pypdfium2 package, which only adds ~3MB to the exported .exe instead of the ~60MB from mupdf. import pypdfium2 as pdfium image_buffer = io.BytesIO() doc2 = pdfium.PdfDocument(input=pdf_buffer, autoclose=True) doc2[0].render().to_pil().save(image_buffer, format='PNG') image_bytes = image_buffer...
4
2
78,642,298
2024-6-19
https://stackoverflow.com/questions/78642298/check-following-element-in-list-in-pandas-dataframe
I have created the following pandas dataframe import pandas as pd import numpy as np ds = { 'col1' : [ ['U', 'U', 'U', 'U', 'U', 1, 0, 0, 0, 'U','U', None], [6, 5, 4, 3, 2], [0, 0, 0, 'U', 'U'], [0, 1, 'U', 'U', 'U'], [0, 'U', 'U', 'U', None] ] } df = pd.DataFrame(data=ds) The dataframe looks like this: print(df) col1...
If you only want to test if there is at least one case in which a non-None follow a U, use itertools.pairwise and any: from itertools import pairwise def count_after_U(lst): return int(any(a=='U' and b not in {'U', None} for a, b in pairwise(lst))) df['iCount'] = list(map(count_after_U, df['col1'])) Output: col1 iCou...
4
2
78,640,519
2024-6-19
https://stackoverflow.com/questions/78640519/remove-items-from-list-starting-with-a-list-of-prefixes
I have a list of strings and a list of prefixes. I want to remove all elements from the list of strings that start with a prefix from the list of prefixes. I used a for loop, but why doesn't it seem to work? list_of_strings = ['test-1: foo', 'test-2: bar', 'test-3: cat'] list_of_prefixes = ['test1', 'test-2'] final_lis...
Your approach doesn't work because you potentially perform an append for each element in list_of_prefixes, but if the string does start with one of the prefixes, it's guaranteed to not start with one of the others, so they all get added. With list comprehensions, generator expressions, and any, this is very straightfor...
5
2
78,640,057
2024-6-19
https://stackoverflow.com/questions/78640057/matplotlib-colormap-not-showing-in-legend
I was working on this introduction to geospatial data analysis with Python. I've replicated each line of code in my own Jupyter notebook and have obtained the same results except for the last graph. The code for the graph is: fig, ax = plt.subplots(1, figsize=(20,20)) base = country[country['NAME'].isin(['Alaska','Hawa...
They must be doing some classification by quantiles that wasn't covered in their tutorial : fig, ax = plt.subplots(1, figsize=(20, 20)) base = ( country[country["NAME"].isin(["Alaska", "Hawaii"]) == False].plot( ax=ax, color="#3B3C6E" ) ) florence.plot( ax=base, column="Wind", marker="<", markersize=10, cmap="cool", sc...
2
1
78,639,491
2024-6-18
https://stackoverflow.com/questions/78639491/how-to-shutdown-resources-using-dependency-injector
I'm using dependency_injector to manage DI. I don't understand how to release my resources using this library. I found shutdown_resources method but have no idea how to use it properly. Example: class Resource: """Resource example.""" def __init__(self): """.""" # Initialize session def close(self): """Release resource...
It took some time but I found out. An initialization generator should be used for these purposes instead of a default constructor: from dependency_injector import containers, providers class Resource: """Resource example.""" def __init__(self): """.""" # Initialize session def close(self): """Release resources.""" # Cl...
2
1
78,635,838
2024-6-18
https://stackoverflow.com/questions/78635838/bundling-python-app-compiled-with-cython-with-pyinstaller
Problem I have an application which is bundled with pyinstaller. Now a new feature request is, that parts are compiled with cyphon to c libraries. After the compilation inside the activated virtual environment (poetry) the app runs as expected. BUT, when I bundle it with pyinstaller the executable afterwards can't find...
Problem The main problem pyinstaller faces is that it can't follow imports of files/modules compiled by cython. Therefore, it can only resolve and package files & libraries named in main.py, but not in main_window.py. To make it work, we need to specify all imports that are hidden from pyinstaller. I have found two sui...
5
1
78,638,290
2024-6-18
https://stackoverflow.com/questions/78638290/client-error-404-not-found-for-url-http-localhost11434-api-chat-while-usi
I am following this tutorial, https://youtu.be/JLmI0GJuGlY?si=eeffNvHjaRHVV6r7&t=1915, and trying to build a simple LLM agent. I am on WSL2, Windows 11, and I am coding in VSC. I use Ollama to download and store my LLMs. My python is 3.9. My script my_main3.py is very simple: from llama_index.llms.ollama import Ollama ...
Someone posted further down in the comments on the video. I had this same issue. @HodBuri 1 month ago Error 404 not found - local host - api - chat [FIX] If anyone else gets an error like that when trying to run the llamacode agent, just run the llamacode llm in terminal to download it, as it did not download it automa...
4
2
78,636,327
2024-6-18
https://stackoverflow.com/questions/78636327/pyinstaller-in-virtual-environment-still-yields-very-large-exe-file
I have a Python code of 78 lines using the following packages: import pandas as pd import base64 from bs4 import BeautifulSoup import os import win32com.client as win32 import pathlib I ran the following commands: venv\Scripts\activate python -m pip install pandas python -m pip install pybase64 python -m pip install b...
It doesn't look like you've installed pyinstaller within your virtual environment. I suspect it's attempting to use your global pyinstaller, which may be attempting to wrap any other packages you've installed globally. Try this: venv\Scripts\activate python -m pip install pyinstaller # install other dependencies as nee...
2
2
78,639,613
2024-6-18
https://stackoverflow.com/questions/78639613/from-a-list-containing-letters-and-numbers-how-do-i-create-a-list-of-the-positi
I have a list created from a list(input()), that contains letter and numbers, like ['F', 'G', 'H', '1', '5', 'H'] I don't know the contents of the list before hand. How would I create a new list that shows the positions of strings that fit a predefined parameter so that I could receive an output like number_list = [3, ...
You can use a simple for loop with isdigit(): def _collect(L): nums, alphas = [], [] for i, val in enumerate(L): if val.isdigit(): nums.append(i) else: alphas.append(i) return nums, alphas print(_collect(['F', 'G', 'H', '1', '5', 'H'])) Prints ([3, 4], [0, 1, 2, 5])
3
1
78,639,769
2024-6-18
https://stackoverflow.com/questions/78639769/how-to-scrape-data-from-arbitrary-number-of-row-listings-using-python-selenium
So I'm trying to create a bot that identifies nft loan listings on blur that meet certain criteria such as the loans total value being 80% or less than its floor price or APY being greater than 100%. I've figured out the basics of loading up chrome using selenium and navigating to the correct section of the website to ...
I would recommend searching "how to locate elements with Selenium" and doing some reading. But maybe this get you started... Your XPATH to select the "ALL LOANS" button is /html/body/div/div/main/div/div[3]/div/div[2]/div[1]/div[1]/nav/button[2]--it's clear you got this by clicking "Copy XPATH" in developer console. Th...
2
1
78,634,235
2024-6-17
https://stackoverflow.com/questions/78634235/numpy-dtype-size-changed-may-indicate-binary-incompatibility-expected-96-from
I want to call my Python module from the Matlab. I received the error: Error using numpy_ops>init thinc.backends.numpy_ops Python Error: ValueError: numpy.dtype size changed, may indicate binary incompatibility. Expected 96 from C header, got 88 from PyObject. The Python script is as follows import spacy def text_re...
The reason is that pandas defines its numpy dependency freely as "anything newer than certain version of numpy". The problem occured, when numpy==2.0.0 has been released on June 16th 2024, because it is no longer compatible with your pandas version. The solution is to pin down the numpy version to any before the 2.0.0....
138
212
78,633,798
2024-6-17
https://stackoverflow.com/questions/78633798/is-there-a-way-to-mock-strip-for-unit-testing-in-python-2-7s-unittest-module
I am using Python 2.7 for a coding project. I'd love to switch to Python 3, but unfortunately I'm writing scripts for a program that only has a python package in 2.7 and even if it had one in 3 our codebase would be impractical to switch over, so it's not possible. My code involves checking if a path it is given in str...
Use side_effect for os.path.exists; not mock strip() I suggest you to use the attribute side_effect (see here for documentation) of Mock object patchexist instead return_value. In this way you can return False at first called of os.path.exists() and True at second called (after strip()). Furthermore: It is not necessa...
2
2
78,639,645
2024-6-18
https://stackoverflow.com/questions/78639645/python-powershell-combo-make-pwsh-load-even-faster
My main programming is done within Python, and want to invoke custom Powershell cmdlets I wrote. Added my .psm1 file to the $PSModulePath, and my cmdlets are always loaded. And I -NoProfile, and -NoLogo to invoke pwsh cmd a little bit faster. Something like cmd = ['pwsh', '-NoLogo', '-NoProfile', '-Command', cmdToRun] ...
Python cannot host PowerShell in-process, so you cannot avoid the costly creation of a PowerShell child process, via pwsh, the PowerShell (Core) 7 CLI (the same applies analogously to powershell.exe, the Windows PowerShell CLI). -NoProfile would only make a difference if large / slowly executing $PROFILE file(s) were p...
4
4
78,639,630
2024-6-18
https://stackoverflow.com/questions/78639630/scalable-approach-instead-of-apply-in-python
I use apply to loop the rows and get the column names of feat1, feat2 or feat3 if they are equal to 1 and scored is equal to 0. The column names are then inserted into a new feature called reason. This solution doesn't scale to larger dataset. I'm looking for faster approach. How can I do that? df = pd.DataFrame({'ID':...
Another possible solution, around 8x faster than @Andrej Kesely's, according to rough estimates: feat_columns = df.filter(regex=r"^feat").columns reasons = df.mask(df["scored"] != 0, 0)[feat_columns].to_numpy() df["reason"] = np.array( [", ".join(feat_columns[row == 1]) if np.any(row == 1) else None for row in reasons]...
3
3
78,634,781
2024-6-17
https://stackoverflow.com/questions/78634781/how-to-find-which-labeled-rows-from-a-table-are-at-or-above-certain-points-from
I'm new to Python and am struggling to understand how to code this specific situation. I have included an Excel screenshot to better describe the tables and graphs I am working with. From Table 1, column headings 10-13 serve as the x-values. Row # Label provides which row between 1-6 is being affected. Table 2 provides...
When working with tables in Python, I suggest that you use pandas. It is typically imported like this import pandas as pd. Let us consider the following example tables: data1= {'11': [0.2, 0.3, 0.1, 2, 0.6, 1.2], '12': [0.3, 0.33, 0.18, 2.5, 1, 1.4]} data2= {'Point': ["A","B"], 'X': [11,12], 'Y': [0.18, 1.24]} table1 =...
2
2
78,637,658
2024-6-18
https://stackoverflow.com/questions/78637658/accessing-attributes-of-a-python-descriptor
Not sure if this is feasible or not. The implementation/example below is dummy, FYI. I have a Python class, Person. Each person has a public first name and a public last name attribute with corresponding private attributes - I'm using a descriptor pattern to manage access to the underlying private attributes. I am usin...
Currently you don't differentiate when the descriptor is accessed through the instance or through the class itself. property does this for example. It gives you the descriptor object when you access it through the class. You can do the same: def __get__(self, instance, owner): if instance is None: return self self._ac...
3
3
78,633,756
2024-6-17
https://stackoverflow.com/questions/78633756/how-to-resize-an-image-in-gradio
I'm looking for an approach to resize an image as a header in Gradio generated UI to be smaller. According to a closed issue on their Github, I followed the following manner: import gradio as gr with gr.Blocks() as app: gr.Image("logo.png", label="Top Image").style(width=600, height=400) app.launch(server_name="0.0.0.0...
Documentation for Image shows that you can use Image(..., width=..., height=...) I test it and it works but it can't be smaller than width=160. And it needs to change also min_width= to smaller value because it has default value 160 If you don't need label and download button then you can uses Image(..., show_label=F...
2
3
78,637,169
2024-6-18
https://stackoverflow.com/questions/78637169/both-increment-and-decrement-in-while-loop-in-matrix-in-python
I created a 15 x 15 matrix in a pandas dataframe type. I want to make changes in some cells, following this logic: The diagonal of the matrix is set to 0 In each row, if 0 appears in any position, the values in the next/ previous 5 columns should be updated to 1. (df.iloc[i][j] = 0 --> df.iloc[i][j+5] = 1 or df.iloc[i...
I would use numpy here and build a mask with roll: # distance to 0 N = 5 # replace diagonal with 0 np.fill_diagonal(a.values, 0) # build mask m = (a==0).to_numpy() # apply mask iteratively for i in range(1, a.shape[1]//N): a[np.roll(m, i*N, axis=1)] = 1 Variant using pandas' shift: N = 5 np.fill_diagonal(a.values, 0) ...
2
2
78,636,238
2024-6-18
https://stackoverflow.com/questions/78636238/wrap-around-2d-coordinates-of-numpy-array
I have a (5, 5) 2D Numpy array: map_height = 5 map_width = 5 # Define a 2D np array- a = np.arange(map_height * map_width).reshape(map_height, map_width) # a ''' array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) ''' I can wrap this array around on both of its...
First of all, you can simplify your calculation of the 2D coordinates as follows: a_2d_coords = np.moveaxis(np.mgrid[:map_height, :map_width], 0, -1) Let's check if this still produces the same result: import numpy as np # For the check, use different height and width values to detect swaps map_height, map_width = 3, ...
2
2
78,636,936
2024-6-18
https://stackoverflow.com/questions/78636936/avoiding-merge-in-pandas
I have a data frame that looks like this : I want to group the data frame by #PROD and #CURRENCY and replace TP with the contents of the Offshore data in the Loc column Without creating two data frames and joining them. The final output will look something like: I was able to create the output by splitting the data f...
I think a merge is the most straightforward and efficient way to do this: df['TP'] = df[cols].merge(df[df['Loc'].eq('Offshore')], how='left')['TP'].values No need to sort, no need to worry about which values are initially present. Alternatively: cols = ['#PROD', '#CURRENCY'] s = (df[cols].reset_index().merge(df[df['Lo...
2
1
78,637,002
2024-6-18
https://stackoverflow.com/questions/78637002/child-classs-attribute-did-not-override-which-was-defined-in-parent-class
I have a parent and two child classes defined like this import pygame class Person(): def __init__(self): self.image = pygame.image.load('person.png').convert_alpha() self.image = pygame.transform.scale(self.image, (int(self.image.get_width() * 0.5), int(self.image.get_height() * 0.5))) print('size: ', self.image.get_s...
It's a matter of the order how everything is executed: In the subclasses, you call the super-constructor (super().__init__()), which still will load the picture person.png and output the size. Only afterwards the code in the constructors of the subclasses will be executed. So after the construction, the image property ...
2
4
78,636,490
2024-6-18
https://stackoverflow.com/questions/78636490/counting-items-in-an-array-and-making-counts-into-columns
I am working in databricks where I have a dataframe as follows: dummy_df names items Ash [c1,c2,c2,c3] Bob [c1,c2] May [] Amy [c2,c3,c3] Where names column contains strings for values and items is a column of arrays. I would like to count how many times each item appears for each name and make each count into a column...
Explode the column items and then use crosstab to get the number of items for each name. exploded_df = dummy_df.explode('items') crosstab_df = (pd.crosstab(exploded_df['names'], exploded_df['items'], dropna=False) .drop(columns=np.nan) .add_prefix('Count_') .reset_index() ) new_df = df.merge(crosstab_df, on='names') O...
2
4
78,626,515
2024-6-15
https://stackoverflow.com/questions/78626515/what-exactly-is-slowing-np-sum-down
It is known that np.sum(arr) is quite a lot slower than arr.sum(). For example: import numpy as np np.random.seed(7) A = np.random.random(1000) %timeit np.sum(A) 2.94 µs ± 13.8 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) %timeit A.sum() 1.8 µs ± 40.8 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 l...
When I run np.sum(a) in debug mode on my PC, it steps into the following code. https://github.com/numpy/numpy/blob/v1.26.5/numpy/core/fromnumeric.py#L2178 The following is the part of the code where it is relevant. import numpy as np import types def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs): passk...
6
10
78,633,947
2024-6-17
https://stackoverflow.com/questions/78633947/filter-dataframe-events-not-in-time-windows-dataframe
I have a DataFrame of events (Event Name - Time) and a DataFrame of time windows (Start Time - End Time). I want to get a DataFrame containing only the events not in any of the time windows. I am looking for a "pythonic" way to filter the DataFrame. Example: Events DataFrame: Event Name Event Time Event1 02/01/2...
You can build an IntervalIndex then create a boolean mask with reindex: # build IntervalIndex idx = pd.IntervalIndex.from_arrays(df_time['Start Time'], df_time['End Time']) # build boolean mask m = (pd.Series(False, index=idx) .reindex(df_events['Event Time'],fill_value=True) .to_numpy() ) # select non-matching rows ou...
2
3
78,630,047
2024-6-16
https://stackoverflow.com/questions/78630047/how-to-stop-numpy-floats-being-displayed-as-np-float64
I have a large library with many doctests. All doctests pass on my computer. When I push changes to GitHub, GitHub Actions runs the same tests in Python 3.8, 3.9, 3.10 and 3.11. All tests run correctly on on Python 3.8; however, on Python 3.9, 3.10 and 3.11, I get many errors of the following type: Expected: [13.0, 12....
This is due to a change in how scalars are printed in numpy 2: numpy 1.x.x: >>> repr(np.array([1.0])[0]) '1.0' numpy 2.x.x: >>> repr(np.array([1.0])[0]) 'np.float64(1.0)' You should restrict the version of numpy to be 1.x.x in your requirements file to make sure you don't end up installing numpy 2.x.x: numpy ~> 1.26 ...
4
5
78,632,725
2024-6-17
https://stackoverflow.com/questions/78632725/python-django-access-fields-from-inherited-model
Hi I have a question related to model inheritance and accessing the fields in a Django template. My Model: class Security(models.Model): name = models.CharField(max_length=100, blank=False) class Stock(Security): wkn = models.CharField(max_length=15) isin = models.CharField(max_length=25) class Asset(models.Model): sec...
Django does not support polymorphism out of the box: even if you use inheritance and you retrieve an item from the database that is a Stock, if you query through Security, you retrieve it as a Security object, so without the specific Stock fields. Inheritance and polymorphism are often a pain in relational databases, a...
2
1
78,632,001
2024-6-17
https://stackoverflow.com/questions/78632001/need-to-provide-addition-steps-to-pydantic-model-initialisation-method
I am trying to add custom steps to the Pydantic model __init__ method. Pseudo Sample Code : class Model(BaseModel): a: int b: Optional[List[int]] = None c: Optional[int] = None def __init__(self, *args, **kwargs): super.__init__(*args, **kwargs) self.method() def method(self): assert self.a is not None, "Value for a is...
Pydantic v2 answer: If you want to both validate and add logic to your property during initialization, you can use model_validator: from pydantic import BaseModel from pydantic import model_validator class Model(BaseModel): a: int b: Optional[List[int]] = None c: Optional[int] = None @model_validator(mode='after') def ...
2
3
78,628,027
2024-6-16
https://stackoverflow.com/questions/78628027/broken-pipe-passing-python-output-to-c-input-due-to-size
I'm trying to transform an image into a matrix of it's rbg values in c++, i really like the simplicity of PIL on handling different images extensions, so i currently have two codes from PIL import Image img=Image.open("oi.png") pixel=img.load() width,height=img.size print(height) print(width) def rgb(r, g, b): return (...
"Broken pipe" means that a program tried to write to a pipe that no longer had any programs reading from it. This means that your C++ program is exiting before it should. For a 1000x1000 image, assuming you're running this on x86_64 Linux, img is 8MB. I suspect that's too big for the stack, which is causing your C++ pr...
2
1
78,628,103
2024-6-16
https://stackoverflow.com/questions/78628103/assign-each-list-element-to-a-row-of-pandas-dataframe-sequentially-and-equally
I have a pandas dataframe with 25 rows, and also a list with 5 elements. How do I: - assign 1st element of the list to first row of the dataframe - 2nd element of the list to second row - ... - 1st element to 6th row of dataframe etc Eg: Need to assign a doctor to each patient sequentially df: | Name | Gender | | ----...
Approach To avoid Python for loop we can use itertools functions cycle and islice as follows: cycle to make an iterator that will indefinitely loop through a list islice to create an iterator that returns selected elements from the iterable list to instantiate the iterator elements Code import pandas as pd from itert...
3
4
78,628,078
2024-6-16
https://stackoverflow.com/questions/78628078/why-does-this-error-when-converting-a-python-list-of-lists-to-a-numpy-array-only
I have a somewhat peculiar structure of python list of lists that I need to convert to a numpy array, so far I have managed to simply get by using np.array(myarray, dtype = object), however a seemingly insignificant change to the structure of myarray has caused me to get an error. I have managed to reduce my issue down...
np.array tries, as first priority, to make a n-d numeric array - one where all elements are numeric, and the shape is consistent in all dimensions. i.e. no 'ragged' array. In [36]: alist = [np.array([[1,2,3,4],[5,6,7,8]]), np.array([[9,10],[11,12]]), np.array([[13,14],[15,16],[17,18]])] In [38]: [a.shape for a in alist...
4
3
78,626,866
2024-6-15
https://stackoverflow.com/questions/78626866/keep-button-visible-after-click-to-change-graph
When I click on the buttons to change the graph they become invisible, but are still usable. How do you keep them always displayed on the window? I know it's plt.clf() that clears the content, but how to place buttons that will always stay under the graph? import matplotlib.pyplot as plt from matplotlib.widgets import ...
You have to use ax. instead of plt.. First you have to use it to create plot ax.scatter(...) Next you have to use it to remove plot ax.clear() # PEP8: use space after `,` around `=`, etc. import matplotlib.pyplot as plt from matplotlib.widgets import Button def plot1(event): ax.clear() ax.scatter(liste_x, liste_graphe_...
2
1
78,628,020
2024-6-16
https://stackoverflow.com/questions/78628020/how-can-i-rewrite-this-so-that-it-does-not-repeat
I'm looking for suggestions on how I could rewrite this so that the code isn't repeating. It's suppose to separate the float(digits) from the string(alphabetical characters) within a dictionary's value, and subtract or add a user's numerical input to the float. Afterwards, it rejoins the digits and the letters, convert...
The best practice for this would be wrapping up the code within a function. Infact whenever you find some part of code is repeating multiple times, you are supposed to put it into a function. Here's how to do it: def update_inventory(key, option, quantity): quantity_value = float(re.findall(r"[0-9]+(?:\.[0-9]*)?", inve...
2
0
78,627,912
2024-6-15
https://stackoverflow.com/questions/78627912/python-dataframe-info-output-doesnt-reflect-dropped-rows
I have a dataset with 2111 rows in it. When I drop the 27 duplicate rows the DataFrame.info output still shows the rows numbered from 0 to 2110, but reports 2085 rows. Is there a refresh command associated with DataFrame metadata I need to call? Original unpreprocessed DataFrame.info output: !!!!!!!!!!!!!!!!!! Size an...
The rows are being dropped correctly. However please note that the index won't automatically reset after dropping the duplicates. You need to reset the index to get your desired output: df.reset_index(drop=True, inplace=True)
2
1
78,626,707
2024-6-15
https://stackoverflow.com/questions/78626707/leetcode-417-bfs-time-limit-exceeded
I am working on Leetcode 417 Pacific Atlantic Water Flow: There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of ...
There are two issues in your bfs function that negatively affect performance: pop(0) is not efficient on a list. Instead use a deque You mark a node as visited, after having taken it from the queue, but that means you can have several copies of the same cell in the queue, increasing the number of iterations the BFS lo...
2
2
78,620,310
2024-6-13
https://stackoverflow.com/questions/78620310/calculate-windowed-event-chains
Given a Polars DataFrame data = pl.DataFrame({"user_id": [1, 1, 1, 1, 1, 2, 2, 2, 2], "event": [False, True, True, False, True, True, True, False, False] I wish to calculate a column event_chain which counts the streak of times where a user has an event, where in any of the previous 4 rows they also had an event. Ever...
updated version I looked at @jqurious answer and I think you can make it even more concise .sum_horizontal() to precalculate counter while checking previous N rows. We only need sum for previous rows, for next rows we just need to know if they exist, so max is enough. Also note that we use window of size 5 (including ...
2
2
78,624,158
2024-6-14
https://stackoverflow.com/questions/78624158/arma-model-function-for-future-unseen-data-with-start-and-end-dates
I have a dataframe like this lstvals = [30.81,27.16,82.15,31.00,9.13,11.77,25.58,7.57,7.98,7.98] lstdates = ['2021-01-01', '2021-01-05', '2021-01-09', '2021-01-13', '2021-01-17', '2021-01-21', '2021-01-25', '2021-01-29', '2021-02-02', '2021-02-06'] data = { "Dates": lstdates, "Market Value": lstvals } df = pd.DataFrame...
Issues: Specify the frequency for the dates index: df = pd.DataFrame(data) df['Dates'] = pd.to_datetime(df['Dates']) df.set_index('Dates', inplace=True) df = df.asfreq('4D') forecast is strictly for out-of-sample forecasts, and has no start or end parameters. (Note that its steps parameter can be passed a string or ...
2
1
78,623,142
2024-6-14
https://stackoverflow.com/questions/78623142/python-numexpr-evaluating-complex-numbers-in-scientific-notation-yields-valuee
I am using the Python numexpr module to evaluate user inputs (numeric or formula). Numbers can be complex, and this works as long as I'm avoiding scientific notation: >>> import numexpr as ne >>> ne.evaluate("1000000000000j") array(0.+1.e+12j) >>> ne.evaluate("0.+1.e+12j") ValueError: Expression 0.+1.e+12j has forbidde...
The errors you see with numexpr when trying to evaluate the expression "0.+1.e+12j" are due to the fact that numexpr parses complex numbers differently than standard Python. It does not accept "0.+1.e+12j" as valid because it prefers expressions where operations between numerical and logical units are explicitly define...
2
1
78,617,024
2024-6-13
https://stackoverflow.com/questions/78617024/get-swagger-ui-html-causing-unwanted-server-options-to-display-in-fastapi-applic
I need to change the styling and add extra HTML to the default generated docs in my FastAPI application, so I use get_swagger_ui_html to achieve this. This causes the operation level options for 'Servers' to appear when clicking the 'Try it out' section button - I do not want this visible for users. I am using FastAPI ...
It's most likely this Swagger UI bug that affects OpenAPI 3.1 documents. The bug seems to have been introduced in Swagger UI v. 5.9.2. FastAPI 0.111 uses Swagger UI v. 5.9.0 by default, whereas your 2nd example fetches v. 5.17.14 as of this writing, hence the difference. (By the way, the next update of FastAPI will swi...
2
1
78,621,820
2024-6-14
https://stackoverflow.com/questions/78621820/efficiently-look-up-a-column-value-in-a-column-containing-lists-with-pandas
Assuming the following pandas data frame: data lookup_val 0 [1.3, 4.5, 6.4, 7.3, 8.9, 10.3] 5 1 [2.5, 4.7, 6.4, 6.6, 8.5, 9.3, 17.4] 3 2 [3.3, 4.2, 5.1, 7.8, 9.2, 11.5] 6 I need to look up the value within the list of each 'data' column at the position of the value in the 'lookup_val' column. Expected output would be...
There is no efficient vectorial way to perform this. You need to loop. The easiest is most likely to use a list comprehension and zip: df['output'] = [l[i-1] for l, i in zip(df['data'], df['lookup_val'])] Since your lookup values use a one-based indexing, you must subtract 1. Output: data lookup_val output 0 [1.3, 4....
5
7
78,618,055
2024-6-13
https://stackoverflow.com/questions/78618055/derive-approximate-rotation-transform-matrix-numpy-on-a-unit-sphere-given-a
While I am aware of vaguely similar questions, I seem to be stuck on this. Buckminster Fuller introduced a spherical mapping of the world onto an icosahedron - it's known as the Dymaxion Map A common way of identifying the cartesian coordinates of an icosahedron is by using the coordinates, where 𝜑 is the golden ratio...
Note: the permutation matrix i2d supplied in the original post is not correct and does not give a correct mapping of points (so NO method would be able to compute the rotation matrix from it). An alternative i2d array was found by searching permutations and is included in the code below. Note that, due to the symmetrie...
3
1
78,620,337
2024-6-13
https://stackoverflow.com/questions/78620337/issues-with-double-gaussian-fit-using-curve-fit-in-python
I used find_peaks to locate the peaks and estimated the initial parameters for the double Gaussian fit. I expected the curve_fit function to accurately fit the double Gaussian to my data, aligning the peaks and widths correctly. However, the resulting fit does not match the data well, and the Gaussian peaks are misalig...
When data are not exactly Gaussian (peaks have bigger tailing, even in a small extent), it is a common approach to fit a Voigt or a Pseudo-Voigt (which is easier to compute) profile instead of Gaussian. import numpy as np import matplotlib.pyplot as plt from scipy import optimize, stats We define the Pseudo Voigt peak...
2
2
78,620,797
2024-6-14
https://stackoverflow.com/questions/78620797/defaultdict-ignores-its-default-factory-argument-when-assigned-explicitly
I ran into this problem when working with defaultdict. Here's a program that demonstrates it: from collections import defaultdict d1 = defaultdict(default_factory=dict) d2 = defaultdict(dict) print("d1's default_factory:", d1.default_factory) print("d2's default_factory:", d2.default_factory) try: d1['key'].update({'a'...
default_factory is a positional-only argument. It cannot be passed by keyword. d1 = defaultdict(default_factory=dict) creates a defaultdict with no default factory and a key 'default_factory' with value dict. It's as if you did d1 = defaultdict() d1['default_factory'] = dict
2
4
78,620,709
2024-6-14
https://stackoverflow.com/questions/78620709/sorting-months-inside-a-multi-index-groupby-object
Its the sample input. i wanted to group according to the Year column,and wanted to use value counts on month column, then to sort the 'month' column according to the month order. Year month 2000 Oct 2002 Jan 2002 Mar 2000 Oct 2002 Mar 2000 Jan I did this: df.groupby(['Year'])['month'].value_counts()...
You can use groupby() and sort_values(by=['Year', 'month']): import pandas as pd def _sort_month(df): month_order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] df['month'] = pd.Categorical(df['month'], categories=month_order, ordered=True) GB = df.groupby(['Year'])['month'].valu...
4
2