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,620,611
2024-6-14
https://stackoverflow.com/questions/78620611/join-merge-multiple-pandas-dataframes-with-blending-of-values-on-one-column
I have two pandas dataframes width unique column names except: year student_id student_name I would like to merge on these 3 columns (year, student_id, student_name), however sometimes the student_name is misspelled (or has a different spelling). Essentially I would like to merge on year & column, while preserving th...
To get the most common name, concatenate all the student ids and names, group on 'student_id' and aggregate with mode. Do an outer merge of left and right dataframes excluding column 'student_name'. To streamline this, you can create a function that takes a list of dataframes, and returns the resulting dataframe. As...
2
1
78,617,536
2024-6-13
https://stackoverflow.com/questions/78617536/a-reliable-way-to-check-if-a-method-has-been-wrapped-with-a-decorator-from-withi
In python 3.7 or higher. I have the following class: def dec(method): @functools.wraps(method) def wrapper(*args, **kwargs): print("wrapped") return method(*args, **kwargs) return wrapper class A: @dec() def f1(self): print(is_wrapped()) def f2(self): print(is_wrapped()) I want A().f1() to print True and A().f2() to p...
I have revisited this question since my last comment, and here's a probably better way: instead of looking for a local variable with same __code__ as frame's code, let's look for something that has __wrapped__ satisfying that condition. Why is this better? Since you say that functools.wraps is a requirement for decorat...
4
2
78,619,953
2024-6-13
https://stackoverflow.com/questions/78619953/why-is-format-throwing-valueerror-unknown-format-code-f-for-object-of-type
I am using Python 2.7. (Switching to Python 3 for this particular code is not an option, please don't suggest it.) I am writing unit tests for some code. Here is the relevant piece of code: class SingleLineGrooveTable: VEFMT = '.3f' @classmethod def formatve(cls, value, error=None): er = 0 if error is not None: er = er...
On Python 2, object.__format__ effectively delegates to format(str(self), format_spec). You can see the implementation here. Since list inherits object.__format__, your first format call is effectively calling format(str([3.1423]), '.3f'). That's why you get the error message you do. This would still produce an error o...
3
2
78,619,364
2024-6-13
https://stackoverflow.com/questions/78619364/python-nbtlib-cant-append-a-compound-to-a-list
I am trying to add a Compound to a List to make a Compound List: import nbtlib from nbtlib.tag import * CpdList = List(Compound()) Cpd = Compound() Cpd['name'] = String("Name") Cpd['test'] = Byte(0) CpdList.append(Cpd) This returns the following error: >>> nbtlib.tag.IncompatibleItemType: Compound({'name': String('Nam...
You just need to properly use nbtlib.tag.List with the Compound type and properly make a call: import nbtlib from nbtlib.tag import Compound, List, String, Byte CpdList = List[Compound]() Cpd = Compound() Cpd['name'] = String("Name") Cpd['test'] = Byte(0) CpdList.append(Cpd) print(CpdList) Note: Note that the nbtlib...
2
2
78,619,084
2024-6-13
https://stackoverflow.com/questions/78619084/unable-to-convert-the-column-data-and-store-it-in-one-new-column-in-dataframe-pa
I have a dataframe like below. A B C 0 3 329430734 998 1 3 329430742 258 2 3 329430776 126 3 3 329430778 998 4 3 329430784 33 5 3 329430851 21 6 3 329430897 998 7 3 329430917 998 8 3 329430943 998 9 3 329430945 998 and I am trying to transform the data in below way to store it in a new column. df["x"]= np.where((df['...
You can use np.maximum: df["x"] = np.where(df["C"].isin([998, 999]), np.maximum(0, df["A"] - 1), df["C"]) A B C x 0 3 329430734 998 2 1 3 329430742 258 258 2 3 329430776 126 126 3 3 329430778 998 2 4 3 329430784 33 33 5 3 329430851 21 21 6 3 329430897 998 2 7 3 329430917 998 2 8 3 329430943 998 2 9 3 329430945 998 2
2
4
78,617,576
2024-6-13
https://stackoverflow.com/questions/78617576/in-confluence-how-to-replicate-manual-search-with-api-search
I am following the Confluence API search documentation to implement text search with CQL (confluence query language) in the company Confluence pages. Here is my code for a search query: import requests from requests.auth import HTTPBasicAuth import urllib.parse # Replace with your Confluence credentials and base URL ba...
I used the Network tab of developer console to see what exactly Confluence's "Simple" search is doing. Turns out it constructs a cql as follows: siteSearch ~ "SEARCH TEXT HERE" AND type in ("space","user","com.atlassian.confluence.extra.team-calendars:calendar-content-type","attachment","page","com.atlassian.confluence...
2
2
78,618,381
2024-6-13
https://stackoverflow.com/questions/78618381/why-numpy-data-type-kind-returns-void-when-it-was-created-as-float64
I have this code: >>> d = np.dtype([("pos", np.float64, 3)]) >>> d[0].kind 'V' Why does it return 'V' instead of 'f'? In the full code, I need to know if the field corresponds to an integer, float, string...
d[0].kind does not return 'f' because it is not a floating-point dtype: it is a structured dtype with a floating point base. There are several other attributes of structured dtypes that you might be able to inspect depending on your particular goal. For example: >>> d[0].base dtype('float64') >>> d[0].subdtype[0].kind ...
4
5
78,618,287
2024-6-13
https://stackoverflow.com/questions/78618287/image-not-found-in-my-django-project-only-in-one-of-the-2-pages
i'm trying to display an home image at top of the page but it doesn't work. I have the same image in an other page and it works. also if i hold mouse on image source link on the ide it says me that the path is correct. . : Here is the line code (path in the images): <p><img src="../media/images/home.png" width="30px" ...
Relative paths are probably the culprit: if you visit a page that has more slashes, then the .. thus points to a different directory. Use absolute paths, so: /media/… instead of ../media/….
2
3
78,617,300
2024-6-13
https://stackoverflow.com/questions/78617300/what-is-the-most-efficient-way-to-fillna-multiple-columns-with-values-from-other
This is my DataFrame: import pandas as pd import numpy as np df = pd.DataFrame( { 'x': [1, np.nan, 3, np.nan, 5], 'y': [np.nan, 7, 8, 9, np.nan], 'x_a': [1, 2, 3, 4, 5], 'y_a': [6, 7, 8, 9, 10] } ) Expected output is fill_na columns x and y: x y x_a y_a 0 1.0 6.0 1 6 1 2.0 7.0 2 7 2 3.0 8.0 3 8 3 4.0 9.0 4 9 4 5.0 10...
What about using an Index to select all columns at once and set_axis to realign the DataFrame: cols = pd.Index(['x', 'y']) df[cols] = df[cols].fillna(df[cols+'_a'].set_axis(cols, axis=1)) NB. this is assuming all columns in cols and all '_a' columns exist. If you're not sure you could be safe and use intersection and ...
11
10
78,614,904
2024-6-12
https://stackoverflow.com/questions/78614904/plotting-a-baseball-field-animation
I have a dataframe that includes position data from all 9 players on a baseball field including the hitter throughout a given play as well as the ball trajectory. I need some help with figuring out possibly why my animation is not working. The code below plots an instance of the plot, but it doesn't show a continuous a...
There are few problems in code: Using field.draw() inside update() it tries to create many plots which slows down all program. But in matplotlib you can create it only once - outside update() It creates two plots - one with fields, and second with plot and data. And even example on homepage sportypy (in section Adding ...
2
4
78,615,700
2024-6-13
https://stackoverflow.com/questions/78615700/aggregate-columns-that-fall-within-range
I have two dataframes called df and ranges: data = { 'group': ['A', 'B', 'A', 'C', 'B'], 'start': [10, 20, 15, 30, 25], 'end': [50, 40, 60, 70, 45], 'val1': [5, 10, 11, 12, 6], 'val2': [5, 2, 1, 1, 0], } df = pd.DataFrame(data) data = { 'group': ['A', 'B', 'C'], 'start': [0, 5, 25], 'end': [50, 7, 35], } ranges = pd.Da...
IIUC, I would pre-filter the dataframe with map and boolean indexing, then perform a classical groupby.agg. This should keep the masks and intermediate (filtered) DataFrame minimal for memory efficiency, and minimize the size of the input for groupby. # columns to aggregate cols = ['val1', 'val2'] # ensure data is nume...
4
4
78,614,773
2024-6-12
https://stackoverflow.com/questions/78614773/with-polars-how-to-concatenate-list-of-string-expression-column-to-string
Here's a naive solution of what I want to do using map_elements. How can I do this with only Polars functions? import polars as pl # Create a DataFrame with a column containing lists of strings df = pl.DataFrame({ "list_of_strings": [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]] }) # Define a function to concatena...
As already mentioned in the comments, there is pl.Expr.list.join in polars' native expression API to join all string items in a sublist with a separator between them. df.with_columns( pl.col("list_of_strings").list.join("") ) shape: (3, 1) ┌─────────────────┐ │ list_of_strings │ │ --- │ │ str │ ╞═════════════════╡ │ a...
2
2
78,613,926
2024-6-12
https://stackoverflow.com/questions/78613926/how-can-i-merge-two-dataframes-based-on-last-date-of-each-group
These are my DataFrames: import pandas as pd df1 = pd.DataFrame( { 'close': [100, 150, 200, 55, 69, 221, 2210, 111, 120, 140, 150, 170], 'date': [ '2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05', '2024-01-06', '2024-01-07', '2024-01-08', '2024-01-09', '2024-01-10', '2024-01-11', '2024-01-12', ] } )...
You could add the missing dates with groupby.apply, then map the unknown dates: # ensure datetime df1['date'] = pd.to_datetime(df1['date']) df2[['date', 'extend']] = df2[['date', 'extend']].apply(pd.to_datetime) # fill missing dates # map missing one with values of df1 out = (df2.set_index('date').groupby('group') .app...
4
3
78,613,142
2024-6-12
https://stackoverflow.com/questions/78613142/polars-convert-duration-to-integer-number-of-hours-minutes-seconds
I want to convert a duration to integer number of hour (or minute or seconds). I though the .dt namespace would work the same as for the datetimes, but I get an error instead. This example from datetime import datetime import polars as pl pl.__version__ dx = pl.DataFrame({'dt1': datetime(2024, 1, 12, 13, 45)}) dx.selec...
After the subtraction, you don't have a date anymore but a timedelta, you should use dt.total_seconds: dx.select((pl.col('dt1') - pl.col('dt1').dt.date()).dt.total_seconds()) Output: ┌───────┐ │ dt1 │ │ --- │ │ i64 │ ╞═══════╡ │ 49500 │ └───────┘ Or, as total_hours / fractional hours: dx.select((pl.col('dt1') - pl.co...
2
3
78,612,486
2024-6-12
https://stackoverflow.com/questions/78612486/rolling-aggregation-in-polars-and-also-get-the-original-column-back-without-join
Using polars .rolling and .agg, how do I get the original column back, without having to join back with the original column, or without having to use .over? Example: import polars as pl dates = [ "2020-01-01 13:45:48", "2020-01-01 16:42:13", "2020-01-01 16:45:09", "2020-01-02 18:12:48", "2020-01-03 19:45:32", "2020-01-...
There are dedicated rolling_*_by expressions which can be used with .over() df.with_columns( pl.col("a").rolling_sum_by("dt", "2d").over("cat").name.prefix("sum_"), pl.col("a").rolling_min_by("dt", "2d").over("cat").name.prefix("min_"), pl.col("a").rolling_max_by("dt", "2d").over("cat").name.prefix("max_") ) shape: (1...
4
4
78,605,727
2024-6-11
https://stackoverflow.com/questions/78605727/exception-stack-trace-not-clickable-in-pycharm
PyCharm suddenly changed the way it shows the stack trace on the run tab and does not let me click on the exception (or anywhere else) and go to the specific point of the error file anymore. How can I fix this? Running on OSX Sonoma, PyCharm 2022.2.3 (Community Edition)
The short answer: Eliminate all (direct or indirect) imports of the pretty_errors package. The medium answer If you use the torchmetrics package in your project, which tries to use pretty_errors, one of the following should work: (1) just uninstall the pretty_errors package from your Python environment, (2) update torc...
6
4
78,590,453
2024-6-7
https://stackoverflow.com/questions/78590453/type-hinting-a-hypothesis-composite-strategy
I am using the hypothesis library and I would like to annotate my code with type hints. The docs are mentioning the hypothesis.strategies.SearchStrategy as the type for all search strategies. Take this example: @composite def int_strategy(draw: DrawFn) -> hypothesis.strategies.SearchStrategy[int]: ... # some computatio...
Functions decorated with @composite should be type hinted as normal: @composite def int_strategy(draw: DrawFn) -> int: ... @composite will then automatically transform this to something like: # As if it doesn't have the `draw` parameter and that it returns a `SearchStrategy` def int_strategy() -> SearchStrategy[int]: ...
5
6
78,591,577
2024-6-7
https://stackoverflow.com/questions/78591577/mypy-error-source-file-found-twice-under-different-module-names-when-using-edi
mypy throws an error when I have an editable installation (pip install -e .) of my library. It works fine with the non-editable installation (pip install .). I was able to reproduce it with a toy example, so here are the files: . ├── src │ └── my_ns │ └── mylib │ ├── __init__.py │ ├── main.py │ ├── py.typed │ └── secon...
Add the following to your mypy.ini: mypy_path = src (Credit goes to Mario Ishac, who got this from a GitHub issue comment.)
3
4
78,607,542
2024-6-11
https://stackoverflow.com/questions/78607542/simulation-of-a-spring-loaded-pendulum-on-a-spinning-disk
I want to write a simulation in Python similar to the one described in Simulation of a Pendulum hanging on a spinning Disk. But I want the system to be spring loaded. So instead of the mass hanging from a thread, I want the mass to hang from a spring, that rotates. I have tried putting the ODE together but it takes for...
Once you remove the constraint of a fixed-length pendulum it is probably easier to solve this in Cartesian coordinates using Newton's 2nd Law (F=ma), rather than via the Lagrangian equations of motion. Consider a spring of natural length L and stiffness k, one end attached to a point on the edge of a disk of radius R ...
2
2
78,609,131
2024-6-11
https://stackoverflow.com/questions/78609131/vs-code-not-jumping-to-the-top-stack-frame
I'm trying to debug some Django library code with the default VS Code Python and Django debugging settings (and "justMyCode" = False). I've set a breakpoint in one of the library functions: I call this from some user code, eg. formset.save(). When I debug and hit the breakpoint, VS Code jumps to this user code instead...
I see the same thing. Looks like a recent bug in VSCode. I rolled back to VSCode version 1.89 and it worked as expected. This was fixed in version 1.90.1 (list of addressed issues).
2
2
78,605,948
2024-6-11
https://stackoverflow.com/questions/78605948/django-simple-history-how-display-related-fields-in-the-admin-panel
I use django-simple-history.I keep the historical table of the product and the price, the price is associated with the product and an inlane is added to the admin panelю I want to display in the admin panel in the product history records of the stories of related models (price). How can I do this? And that the fields c...
I found a solution, it's a bit of a kludge. Since we will not display the app price separately in the admin panel (it only participates in the inline of the product), we can change the history_view() function from django-simple-history. I will add an image model to the example to show how to use this approach with both...
3
0
78,607,642
2024-6-11
https://stackoverflow.com/questions/78607642/how-to-remove-motion-blur-from-a-given-image-in-frequency-domain-deconvolution
I have read that if we have the PSF of a given image, using deconvolution we can reverse the distortion and get the original image. I tried to do the same thing, however, I'm getting an image that looks like complete noise: def add_motion_blur(img, size=31, angle=11): kernel = np.zeros((size,size), dtype=np.float32) # ...
side note: Thanks to @Cris Luengo, the issues were identified and corrected. Here is a summary of all of the points addressed in the comment section which lead to the final solution: Long Answer: There are several issues at play here, which are as follows: The Wiener deconvolution algorithm is implemented incorrectly,...
3
2
78,603,670
2024-6-10
https://stackoverflow.com/questions/78603670/how-to-extract-n-elements-every-m-elements-from-an-array
Suppose I have a numpy array [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], How do I take 4 elements every 8 elements). Here is the expected result: a -> [1,2,3,4, 9,10,11,12] b -> [5,6,7,8, 13,14,15,16] My array has hundreds of elements. I went through the numpy array documentation but I never succeeded to perform this co...
For a generic and pure numpy approach, you could argsort then split: N = 4 # number of consecutive elements M = 2 # number of output arrays idx = np.argsort(np.arange(len(arr))%(N*M)//N, kind='stable') # array([ 0, 1, 2, 3, 8, 9, 10, 11, 4, 5, 6, 7, 12, 13, 14, 15]) a, b = np.split(arr[idx], M) As a one liner: out = n...
6
6
78,607,102
2024-6-11
https://stackoverflow.com/questions/78607102/how-to-load-a-quantized-fine-tuned-llama-3-8b-model-in-vllm-for-faster-inference
I am working on deploying a quantized fine-tuned LLaMA 3-8B model and I aim to use vLLM to achieve faster inference. I am currently using the following Python code to load the model: import torch import transformers from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig import bitsandbytes as ...
Unfortunately vLLM does not support bitsandbytes quantization technique yet. You may want to use Mixtral-8x7B-Instruct-v0.1-GPTQ tough, as GPTQ and AWQ quantization techniques are already supported.
2
0
78,607,139
2024-6-11
https://stackoverflow.com/questions/78607139/how-to-calculate-and-plot-prediction-and-confidence-intervals-for-linear-regress
I need to plot prediction and confidence intervals and need to use python and only the following packages. How do I plot both intervals in the same model. I managed to plot the prediction intervals with the help of ChatGPT. this is the code including the data set. import statsmodels.api as sm import statsmodels.formula...
Explanation: The summary_frame method provides both the prediction intervals (obs_ci_lower, obs_ci_upper) and the confidence intervals (mean_ci_lower, mean_ci_upper). The fill_between function is used twice to plot both intervals: once for the prediction interval and once for the confidence interval. import statsmode...
2
4
78,599,664
2024-6-9
https://stackoverflow.com/questions/78599664/after-pushing-log-out-button-the-app-is-forwarding-me-to-empty-page
After pushing log out button the app is forwarding me to https://it-company-task-manager-uzrc.onrender.com/accounts/login/ But there is an empty page and after log out I'm still logged in and can do things (create task etc) I tried to solve it in different ways, but nothing changes. You can check it by yourself: https:...
If you're using Django 5, it's possible you're running into the same issue that is addressed in these questions: Django built in Logout view `Method Not Allowed (GET): /users/logout/` Problem with Django class-based LogoutView in Django 5.0 Essentially, you can no longer access the built-in logout view with a GET req...
2
1
78,610,026
2024-6-11
https://stackoverflow.com/questions/78610026/dirichlet-boundary-conditions-using-odeint
I am trying to edit the Gray-Scott 1D equation example (last example on the page) in the odeint documentation. I have the code below and it works for the Neumann boundary conditions but I want a Dirichlet boundary condition on the left at x=0 and retain Neumann on the right at x=L. I tried to reduce the dimension of y0...
You can fix the value of u and v at x = 0 and then keep the Neumann conditions at x = L: Code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import time from scipy.integrate import odeint def G(u, v, f, k): return f * (1 - u) - u * v**2 def H(u, v, f, k): return -(f + k) * v...
2
2
78,609,465
2024-6-11
https://stackoverflow.com/questions/78609465/animating-yearly-data-from-pandas-in-geopandas-with-matplotlib-funcanimation
Using this dataset of % change by state, I have merged it with a cartographic boundary map of US states from the Census department: https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_state_500k.zip df.head() Year 2017 2018 2019 2020 2021 2022 2023 State Alabama 0.00 0.00 0.00 0.00 0.00 0.00 0.00 Arizona 0.24 0.0...
In the following animation, only states in data are plotted since how='right' is used for pd.merge. Tested in python v3.12.3, geopandas v0.14.4, matplotlib v3.8.4. import geopandas as gpd import pandas as pd import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation, PillowWriter # Sample data data ...
4
4
78,608,557
2024-6-11
https://stackoverflow.com/questions/78608557/color-coded-time-series-plot-based-on-value-sign
I have a dataframe containing positive,negative and zero values. import pandas as pd import numpy as np import matplotlib.pyplot as plt df1 = pd.DataFrame({'A': [-1, 3, 9, 5, 0, -1, -1], 'B': [4, -5, 5, 7, 9, 8, 6], 'C': [7, 5, -3,-1, 5, 9, 3], 'D': [-3, 6, 7, 4, 0, -2, -1], 'date':['01-02-2020', '01-06-2020', '01-03-2...
The original post requested the use of a line plot with markers but was changed because a comment suggested that wasn't possible. The following answer color-codes the markers, and the line from its marker. Tested in python v3.12.3, pandas v2.2.2, matplotlib v3.8.4. import pandas as pd import matplotlib.pyplot as plt # ...
2
2
78,608,434
2024-6-11
https://stackoverflow.com/questions/78608434/cartesian-coordinates-to-label
Using coordinates for labelling? I was asked it was possible and to see for myself, I am trying to program it and read up more on it. I do not know what it is called or where to look but the general idea is as follows: labels are converted into an N-dimensional space and trajectories are calculated along the N-dimensio...
You are most probably referring to something called Embedding and uses dimensionality reduction techniques, such as PCA. Those are often used in ML for tasks such as classification and clustering. If I were you, I would investigate Word Embeddings first: Word2Vec from the modeule gensim.models is a really good candidat...
2
2
78,598,087
2024-6-9
https://stackoverflow.com/questions/78598087/creating-blended-transform-with-identical-data-dependent-scaling
I am trying to create a circle that displays a circle regardless of axis scaling, but placed in data coordinates and whose radius is dependent on the scaling of the y-axis. Based on the transforms tutorial, and more specifically the bit about plotting in physical coordinates, I need a pipeline that looks like this: fro...
It appears that the approach I proposed in the question is supposed to work. To create a transform that has data scaling in the y-direction and the same scaling regardless of data in the x-direction, we can do the following: Create a transform that scales vertically with ax.transData Create a simple reflection transfo...
2
1
78,607,218
2024-6-11
https://stackoverflow.com/questions/78607218/cant-fix-the-same-fontsize-for-both-axis-ticks-in-a-log-plot
I'm trying to do a simple log plot using the matplotlib library, but I can't seem to get the x-axis ticks to have the same fontsize. My example code is: import numpy as np import matplotlib.pyplot as plt fontsize = 8 x = np.linspace(5.6e-5,6.5e-5, 120) y = np.logspace(-10, 10, 120) fig = plt.figure(figsize=(3.5, 2.65),...
It seems the ticks on the x axis are minor ones and are not affected the way you tried. If you also provide 'both' for the which parameter as in plt.tick_params(axis='both', which='both', labelsize=fontsize) it should work.
4
3
78,604,018
2024-6-10
https://stackoverflow.com/questions/78604018/importerror-cannot-import-name-packaging-from-pkg-resources-when-trying-to
I was trying to install "causal_conv1d" using: pip install --no-cache-dir -t /scratch/ahmed/lib causal_conv1d==1.0.0 The error I got is: Collecting causal_conv1d==1.0.0 Downloading causal_conv1d-1.0.0.tar.gz (6.4 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info...
I don't know the exact problem, but it seems this problem happened when I used two directories for Python "lib": one was the default Anaconda lib, and I had another separate one. The problem disappeared when I used only the default Anaconda lib. It works fine now.
8
0
78,606,466
2024-6-11
https://stackoverflow.com/questions/78606466/regex-pattern-to-allow-alphanumeric-and-square-brackets-with-text-insde-it
I am using regex to allow alphanumeric, underscore, hyphen and square brackets in a text box. regex i am using to validate input is r'^[a-zA-Z0-9_\-\[\] ]*$. I need to modify the regex such that if empty brackets are given it should return false. Sample cases "Your message here" - Valid "Your [text] message here" - V...
Can it go like this? ^(?!.*\[\s*\].*)[a-zA-Z0-9_\-\[\] ]*$
2
1
78,599,924
2024-6-9
https://stackoverflow.com/questions/78599924/how-to-diagnose-an-28x-slowdown-in-containerized-vs-host-pythonnumpy-execution
I'm doing some number-crunching in a docker container. On an 8 cpu machine the dockerized execution is around 28x slower than the host? I've examined: warm-up costs: I've tried running the test on the second execution in the same process (below the warmup costs appear negligble anyway) numpy optimization options: impo...
FastDTW contains both a fast path implemented in Cython, and a slow path implemented in Python. It tries the fast path first, and if it gets an ImportError, it falls back to the slow path. You are probably hitting the fast path in the host, and the slow path in the container. Some evidence for this idea: The functions...
3
2
78,605,817
2024-6-11
https://stackoverflow.com/questions/78605817/how-to-replace-an-individual-level-in-a-multi-level-column-index-in-pandas
Consider the following multi-level column index dataframe: import numpy as np import pandas as pd arrays = [ ["A", "A", "B", "B"], ["one", "two", "one", "two"], ["1", "2", "1", "pd.NA"], ] idx = pd.MultiIndex.from_arrays(arrays, names=["level_0", "level_1", "level_2"]) data = np.random.randn(3, 4) df = pd.DataFrame(dat...
You could convert the MultiIndex.to_frame then back to MultiIndex.from_frame, change the values with replace and as_type: df.columns = pd.MultiIndex.from_frame(df.columns.to_frame() .replace({'level_2': {'pd.NA': pd.NA}}) .astype({'level_2': 'Int64'})) Output: level_0 A B level_1 one two one two level_2 1 2 3 <NA> 0 0...
4
2
78,601,319
2024-6-10
https://stackoverflow.com/questions/78601319/why-is-my-basic-gekko-ode-solver-much-slower-than-scipy
In this minimal example I want to solve the basic integrator ODE dT/dt = k[F(t) - T(t)] where F(t) is a forcing vector, which is selected to be a square wave. I have implemented two procedures to solve the ODE: Using Scipy's solve_ivp and using Gekko. The former takes 6 milliseconds to run, the latter takes 8 seconds t...
Switch to remote=False to solve locally and avoid the overhead due to network communication to the public server. Switching to IMODE=4 solves all 1000 time steps simultaneously instead of sequentially and can improve solve time. Here are 10 trials with the 1 original and 9 modified versions. I'm on Ubuntu Linux. Timing...
2
1
78,604,895
2024-6-10
https://stackoverflow.com/questions/78604895/python-typeerror-not-supported-between-instances-of-str-and-int
import random elements = { "normal": {"strong_against": ["None"], "weak_against": ["None"]}, "fire": {"strong_against": ["earth", "ice"], "weak_against": ["water", "ice"]}, "water": {"strong_against": ["fire", "poison"], "weak_against": ["earth", "electric"]}, "earth": {"strong_against": ["water", "poison"], "weak_agai...
The error message says '<=' not supported between instances of 'str' and 'int'. This means you used the <= operator trying to compare a string and an integer. Your function is_dead() has only one line, return self.health <= 0. We know that 0 is an integer. Therefore, at some point you are assigning a string to a Person...
2
2
78,601,579
2024-6-10
https://stackoverflow.com/questions/78601579/asyncio-create-task-executed-even-without-any-awaits-in-the-program
This is a followup question to What does asyncio.create_task() do? There, as well in other places, asyncio.create_task(c) is described as "immediately" running the coroutine c, when compared to simply calling the coroutine, which is then only executed when it is awaited. It makes sense if you interpret "immediately" as...
Let's try to put it in these words: the event loop enters execution with one task to be performed: the main(). When "main()" is complete, there are other two tasks ready to be processed - so before returning to main() caller, those are executed up the next await statement inside each one. (either an await or an async f...
3
3
78,604,299
2024-6-10
https://stackoverflow.com/questions/78604299/how-to-change-a-pydantic-list-of-objects-into-list-of-strings
I'm using SQLModel for an API. I want the object to be like this: class Post(SQLModel): id: int categories: list[str] # category.name instead of nested objects: class Post(SQLModel): id: int categories: list[Category] Do I have to change the serialization function or is there a way to do this automatically?
As far as I understood Post is your db model. I would highly recommend to separate you db model (should reflect the database structure) from dto (should be used for comfortable data transfer between application components) class PostDTO(pydantic.BaseModel): id: int categories: list[str] @classmethod def from_db_model(c...
2
3
78,603,690
2024-6-10
https://stackoverflow.com/questions/78603690/information-schema-invalid-identifier-from-snowflake-when-trying-to-access-query
I am currently working with Snowflake to view the query history. However, when I attempt to execute the same command in Python, following its syntax rules, I encounter an error stating ‘INVALID IDENTIFIER’ for ‘information_schema’. select * from table(information_schema.query_history())
Usually these things can be resolved by simply advising the documentation, and reviewing the query profile from within Snowflake. In this case, please try using the following code, with snowflake specified instead of directly targeting the information_schema. Other than that, also ensure your user has the correct and s...
2
2
78,600,352
2024-6-10
https://stackoverflow.com/questions/78600352/cannot-read-parquet-file-of-multi-level-complex-index-data-frame
I can create a sample data frame with the following code and save it as parquet. When I try to read it throws "TypeError: unhashable type: 'numpy.ndarray'". Is it possible to save an index comprised of tuples or do I have to reset the index before saving to parquet? Thanks import pandas as pd # Creating sample data dat...
You must specify the levels: import pandas as pd data = { 'A': [1, 2, 3], 'B': [6, 7, 8], 'C': [11, 12, 13], } index = pd.MultiIndex.from_tuples( [ (str((10, 30)), str((0.75, 1.0))), (str((10, 30)), str((0.75, 1.25))), (str((10, 30)), str((1.0, 1.25))) ], names=['level_0', 'level_1'] ) df = pd.DataFrame(data, index=ind...
2
0
78,600,172
2024-6-10
https://stackoverflow.com/questions/78600172/skip-downloading-files-if-the-docker-build-process-is-interrupted
I'm new to Docker and want to build a Dockerfile with the following snippet: RUN \ cur=`pwd` && \ wget http://www.coppeliarobotics.com/files/CoppeliaSim_Edu_V4_1_0_Ubuntu20_04.tar.xz && \ tar -xf CoppeliaSim_Edu_V4_1_0_Ubuntu20_04.tar.xz && \ export COPPELIASIM_ROOT="$cur/CoppeliaSim_Edu_V4_1_0_Ubuntu20_04" && \ export...
Put the download command of .tar files on a separate command. RUN wget ttp://www.coppeliarobotics.com/files/CoppeliaSim_Edu_V4_1_0_Ubuntu20_04.tar.xz && \ tar -xf CoppeliaSim_Edu_V4_1_0_Ubuntu20_04.tar.xz RUN # rest of your code Each instruction in the Dockerfile translates to a layer in your final image. You can thi...
2
0
78,587,497
2024-6-6
https://stackoverflow.com/questions/78587497/bezier-surface-matrix-form
I have a problem with constructing a Bezier surface following an example from a book, using mathematical formulas in matrix form. Especially when multiplying matrices. I'm trying to use this formula I have a matrix of control points B = np.array([ [[-15, 0, 15], [-15, 5, 5], [-15, 5, -5], [-15, 0, -15]], [[-5, 5, 15], ...
Generally, Bezier surface are plotted this way (as the question is posted in matplotlib). import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.special import comb def bernstein_poly(i, n, t): return comb(n, i) * (t**i) * ((1 - t)**(n - i)) def bernstein_matrix(n, t): ret...
2
2
78,596,486
2024-6-8
https://stackoverflow.com/questions/78596486/mypy-displays-an-error-when-inheriting-from-str-and-adding-metaclass
Here's simple example of code: class meta(type): pass class Test(str, metaclass = meta): pass When I run mypy on it (just from cli, without any flags or other additional setup) I'm seeing next output: test.py:2: error: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclas...
str is statically-typed as a subclass of typing.Protocol, whose metaclass is special-cased by mypy as typing._ProtocolMeta (typing.Protocol is actually an instance of typing._ProtocolMeta at runtime, but this isn't reflected in the typing stubs, so normally mypy wouldn't know about this). Therefore, to accurately refle...
2
1
78,590,309
2024-6-7
https://stackoverflow.com/questions/78590309/why-does-int-class-give-type-in-python
From what I've read, the built-in types such as int, float, dict, etc have been implemented in C, and they used to be different from user-defined classes before Python 2.2 However, the built-in types and user defined classes have long been unified now, and the following happens >>> int.__class__ <class 'type'> Why doe...
Classes created in C are still classes and share the same core structure in memory as classes created in pure Python code. The same mechanisms used from Python to create a class can be used to create a class from C code. The only thing is that they don't "have to": a class in C can have all its inner fields hard coded,...
2
2
78,591,534
2024-6-7
https://stackoverflow.com/questions/78591534/matplotlib-add-image-in-top-left-corner-of-figure
I tried various methods found online but can't add an image at the correct location in the top left corner of my figure. Here's one on my attempts, where I try to set exact the size of the generated figure in pixels, and then add a 48x48 px image in top left corner. Issues: The figures are not created with the chosen ...
Are you using a notebook? When you show in a notebook the figure is automatically resized to fit around the artists on it. This is equivalent to passing bbox_inches='tight' when you call savefig. It is possible to turn that off in a notebook, but I just tried replacing plt.show() in your example with plt.savefig(f'simp...
2
1
78,593,047
2024-6-7
https://stackoverflow.com/questions/78593047/tcl-issue-while-running-a-python-script-from-another-python-app-converted-to-ex
I made an app in tkinter which helps creating tkinter app/scripts, (when I export the file it is stored as a .py) I want to run this .py script from my app so that we can preview it immediately after export. I used subprocess.run method and it works perfectly within the python app. But when I converted the app to exe w...
Finally got an answer, we can delete the tcl environment variables before running the subprocess import os import subprocess file_path = "C:/----/test.py" def run_script(): env = os.environ.copy() if 'TCL_LIBRARY' in env: del env['TCL_LIBRARY'] if 'TK_LIBRARY' in env: del env['TK_LIBRARY'] subprocess.run(["python",file...
2
1
78,593,700
2024-6-7
https://stackoverflow.com/questions/78593700/langchain-community-langchain-packages-giving-error-missing-1-required-keywor
All of sudden langchain_community & langchain packages started throwing error: TypeError: ForwardRef._evaluate() missing 1 required keyword-only argument: 'recursive_guard' The error getting generated somewhere in pydantic I strongly suspect it is version mismatch. So I tried upgrading packages langchain, langchain_com...
I am having the same issue. The stack is different, but the error comes from the same line pydantic\v1\typing.py", line 66 This is referring to the python typing module (v3.12.4) that has an additional mandatory parameter 'recursive_guard'. There are other areas of the code in pydantic where this has been fixed (recurs...
10
11
78,594,171
2024-6-7
https://stackoverflow.com/questions/78594171/cost-function-increases-then-stops-growing
I understand the zig-zag nature of the cost function when applying gradient descent, but what bothers me is that the cost started out at a low 300 only to increase to 1600 in the end. The cost function would oscillate between 300 and 4000 to end up at 1600. I thought I should get a number that is 300 or lower. I have t...
In your cost_function, the average cost is inside the loop, which results in a cost value that is m times smaller than it should be, preventing the data set from converging. You should sum up all data before averaging. def cost_function(x, y, w, b): # 1) Number of training examples m = x.size cost = 0 # 2) Index the tr...
2
2
78,586,028
2024-6-6
https://stackoverflow.com/questions/78586028/vs-code-closes-after-opening
I just installed ubuntu 24. I'm a django developer and I've been working fine with Visual Studio Code, but today when I tried to open my vscode, while it was opening it closed without any error or message! :( I restarted my computer and reinstalled Vscode. But nothing that nothing:( note: I installed vscode from app ce...
I've faced the same issue. I think you've installed it from snap store. You need to install it with deb package. Uninstall the current code(remove it). Go to official website of Visual Studio Code, download the latest version and install it with command: sudo dpkg -i code_1.90.0-1717531825_amd64.deb In fact, the comma...
2
5
78,592,406
2024-6-7
https://stackoverflow.com/questions/78592406/group-pandas-dataframe-on-criteria-from-another-dataframe-to-multi-index
I have the following two DataFrames: df 100 101 102 103 104 105 106 107 108 109 0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 2 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 3 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 4 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 5 1.0 1.0 1.0 1.0 1.0 1.0 1.0...
You can reindex, set_axis with MultiIndex.from_frame then groupby.sum: out = (df.reindex(columns=df2.index) .set_axis(pd.MultiIndex.from_frame(df2), axis=1) .groupby(axis=1, level=[0, 1]).sum() ) For the latest version of pandas, using the transpose as intermediate: out = (df.T .reindex(df2.index) .set_axis(pd.MultiIn...
2
3
78,584,013
2024-6-6
https://stackoverflow.com/questions/78584013/how-to-chain-multiple-with-columns-in-polars
I'm using Polars to transform my DataFrame, and I want to chain multiple with_columns transformations. However, I encounter an issue when trying to perform operations on a newly created column within the same with_columns context. I end up needing to save the DataFrame after each transformation and then reapply with_co...
For performance reasons, all expressions in a single pl.DataFrame.with_columns context are evaluated in parallel. Especially, it is not possible to use a column resulting from an expression in a different expression in the same context.1 1 This does not mean that polars performs duplicate work for expressions with comm...
3
3
78,589,001
2024-6-6
https://stackoverflow.com/questions/78589001/trying-to-get-input-from-dataframe-and-using-values-cell-by-cell-to-output-into
I have an excel sheet with data in following format Bus num Bus name POI bus 20000 J874 0 20001 J976 0 10000 J1000 333333 I want to divide dataframe into two dataframes for value within POI bus column, hence one dataframe will have rows 1 and 2, and other will have row 3. After this, I am trying to get da...
One approach is to do this: import pandas as pd data = { 'Bus num': [20000, 20001, 10000], 'Bus name': ['J874', 'J976', 'J1000'], 'POI bus': [0, 0, 333333] } df = pd.DataFrame(data) df1 = df[df['POI bus'] == 0] df2 = df[df['POI bus'] != 0] def gen_sub(output_file1, df1): with open(output_file1, 'w') as file: for i in r...
2
1
78,587,580
2024-6-6
https://stackoverflow.com/questions/78587580/how-do-i-reduce-repetitive-imports-from-subfolders
I am working on a large project in VSCode. I have various subfolders with plenty of .py files, and a main.py in the project root. I want to import various functions from various files that exist in different subfolders. I find from x import y a very redundant process. What is the efficient way to do it? How does a prof...
From a practical standpoint (if the folder representation you gave is accurate to your project) if you find yourself with lots of folders with one file each in them, you may want to reassess whether the categories/groupings you've chosen are realistic - too granular and you get a lot of the repetitive, snakey imports t...
4
2
78,588,656
2024-6-6
https://stackoverflow.com/questions/78588656/django-rest-framework-custom-filter-with-default-search-and-ordering-filter
I have a project in Django Rest Framework where I need have endpoint where I'm able to search Document objects by title and text and possibility to search object is active and inactive, using to this URL address. I am using to achieve this Django_filters package. Example: https://localhost:8000/?is_active=True. This is...
since you want to use the DocumentBackendFilter, you must add the DjangoFilterBackend from django_filters.rest_framework to the filter_backends list in your view class. Besides, If you set filterset_class, the view class will ignore the value list of filterset_fields, so you should provide one of them. class DocumentsL...
2
1
78,588,269
2024-6-6
https://stackoverflow.com/questions/78588269/can-a-python-program-find-orphan-processes-that-it-previously-created
I'm using popen() to create potentially long-running processes in Python. If the parent program dies and then restarts, is there a way to retrieve the previously created processes that are still running? I'd probably have to use start_new_session=True, which I'm not doing now. Essentially, I want to get a re-constructe...
First of all, if one of the processes connected with a pipe dies, any read/write from/to that pipe will result in SIGPIPE -- which by default terminates the process. So your orphan process is very likely to die promptly, too, if the parent crashes. As per Can I share a file descriptor to another process on linux or ar...
3
1
78,586,783
2024-6-6
https://stackoverflow.com/questions/78586783/how-to-use-pycountry-db-country-objects-as-a-pd-dataframe-index
I am creating a dataset collecting data for a given set of countries. To avoid any ambiguity, I would like to use a pycountry.db.Country object to represent each country. However, when setting the country as the index of my pd.DataFrame, I can't select (.loc[]) a record by passing a country, I'm getting this type of er...
Explanation Pandas treats your object as a list-like object, which is why you cannot use it as a key for loc, since it will try to iterate over the objects in the list. >>> from pandas.core.dtypes.common import is_list_like, is_scalar >>> is_scalar(belgium) False >>> is_list_like(belgium) True See What datatype is con...
2
2
78,587,067
2024-6-6
https://stackoverflow.com/questions/78587067/how-to-refactor-similar-functions-in-python
I have defined multiple functions where I search for a specific pydantic model in a list of pydantic models based on some attribute value. SocketIOUserSessionID = str RoomWithIndex = tuple[Room, RoomIndex] RSStateWithIndex = tuple[RSState, int] RSPacketSavedRecordWithIndex = tuple[RSPacketSavedRecordsContainer, int] de...
I tried to generalize the four functions as much as possible - here's where I ended up: def find_model( self, iid: UUID | str, where: list[Any], filter_attr: str, ) -> tuple[Any, int] | None: if ( model := next( filter(lambda model: iid == getattr(model, filter_attr), where) ) ): return model, where.index(model) The f...
3
1
78,586,128
2024-6-6
https://stackoverflow.com/questions/78586128/surprising-behaviour-for-numpy-float16-when-testing-equality
I'm passing various bits of data to a function that computes variance along the first dimension. Sometimes the variance is zero, which is fine, but then the following strange thing happens: >> sigma = data.var(axis=0) + 1e-7 # data has zero variance so all entries should equal 1e-7 >> sigma array([1.e-07, 1.e-07, 1.e-0...
This comes from the fact that numpy type promotion treats scalars and arrays differently. You can see this with np.result_type: >>> np.result_type(sigma, 1E-7) dtype('float16') >>> np.result_type(sigma[0], 1E-7) dtype('float64') Essentially, when an array value is compared to a scalar value (the first case), the dtype...
4
8
78,585,754
2024-6-6
https://stackoverflow.com/questions/78585754/tight-subplot-axes-without-their-plot-to-the-figure
I have made a subplot in matplotlib and managed to to put the different cmap I have on the same column. For a minimal working example (with dummy cmaps): import matplotlib.pyplot as plt import numpy as np # Generate sample data data1 = np.random.rand(10, 10) data2 = np.random.rand(10, 10) data3 = np.random.rand(10, 10)...
Using add_axes works much better than sublots. It gives me much more freedom on the placement. Here is a minimal working example with dummy cbars: fig_bandwidth = plt.figure(figsize=(12, 6)) # Creating three axes: add_axes([xmin,ymin,dx,dy]) ax1 = fig_bandwidth.add_axes((0.75, 0.05, 0.1, 0.3)) ax2 = fig_bandwidth.add_a...
2
0
78,581,797
2024-6-5
https://stackoverflow.com/questions/78581797/how-can-i-create-an-in-memory-file-object-that-has-a-file-descriptor-in-python
I plan to use subprocess.Popen (in Python 3.11.2) to implement git mktree < foo.txt. Now I face the question. In order to reproduce my situation, here is the script that creates the environment. #!/bin/bash export GIT_AUTHOR_NAME=foo export GIT_AUTHOR_EMAIL=foo@bar.com export GIT_AUTHOR_DATE="Tue Jun 4 21:40:15 2024 +0...
Unless I am missing something, you can set stdin=PIPE when building the Popen object, and pass the input as the argument to communicate. Here’s what I used as a "smoke test": import subprocess with subprocess.Popen(['cat'], encoding='utf-8', stdin=subprocess.PIPE, stdout=subprocess.PIPE) as p: o, e = p.communicate('foo...
2
3
78,584,847
2024-6-6
https://stackoverflow.com/questions/78584847/convert-count-row-to-one-hot-encoding-efficiently
I have a table with rows in this format where the integers are a count: A B C D E 0 a 2 0 3 x 1 b 1 2 0 y I'd like to convert it into a format where each count is a one hot encoded row: A B C D E 0 a 1 0 0 x 1 a 1 0 0 x 2 a 0 0 1 x 3 a 0 0 1 x 4 a 0 0 1 x 5 b 1 0 0 y 6 b 0 1 0 y 7 b 0 1 0 y I wrote inefficient code...
Here is a full numpy solution, I would expect this to be faster than reshaping: import numpy as np num_cols = ['B', 'C', 'D'] # convert to numpy array a = df[num_cols].to_numpy() # build indices to repeat idx = np.repeat(np.arange(a.shape[0]), a.sum(1)) # array([0, 0, 0, 0, 0, 1, 1, 1]) # build column indices to repeat...
3
6
78,583,009
2024-6-5
https://stackoverflow.com/questions/78583009/typeerror-unhashable-type-arrayimpl-when-trying-to-use-equinox-module-with-j
I'm new to Equinox and JAX but wanted to use them to simulate a dynamical system. But when I pass my system model as an Equinox module to jax.lax.scan I get the unhashable type error in the title. I understand that jax expects the function argument to be a pure function but I thought an Equinox Module would emulate tha...
Owen Lockwood (lockwo) has provided an explanation and answer in this issue thread, which I will re-iterate below. I believe your issue is happening because jax tries to hash the function you are scanning over, but it can't hash the arrays that are in the module. There are probably a number of things that you could do...
3
1
78,582,450
2024-6-5
https://stackoverflow.com/questions/78582450/check-if-a-string-contains-all-words-in-a-phrase-from-a-list-in-python
I have a list of phrases and I need to be able to identify whether each row in a dataset contains all the words from any of the phrases in my list. Take my example problem below. I have a dataset where the column "Search" contains some browser searches. I also have a list called "phrases" that contains the phrases I'm ...
You have to loop over all phrase until you find a match. An efficient option would be to use sets (set.issubset) combined with any: # convert the phrases to set sets = [set(s.split()) for s in phrases] # [{'screenshot', 'mac'}, {'until', 'christmas', 'days'}, # {'google', 'pixel', '7a'}] # for each string, check if one...
2
2
78,580,737
2024-6-5
https://stackoverflow.com/questions/78580737/understanding-the-details-of-equality-in-python
When trying to construct an example where a == b is not the same as b == a, it seems that I have accidentally constructed an example where a == b is not the same as a.__eq__(b): class A: def __eq__(self, other: object) -> bool: return type(other) is A class B(A): pass if __name__ == '__main__': a = A() b = B() assert n...
The relevant quote explaining what happens is located in the documentation: If the operands are of different types, and the right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual...
3
5
78,579,128
2024-6-5
https://stackoverflow.com/questions/78579128/how-can-i-randomly-replace-the-values-remaining-at-least-one-value-using-python
I tried to replace the some of major values in the tensor with the unique value while maintaining at least one value. For example, given edge_index, I want to change it as below. edge_index = torch.as_tensor([[0, 0, 1, 2, 3, 4, 6, 7, 7, 8], [1, 2, 2, 4, 4, 5, 0, 1, 3, 7]]) result = torch.as_tensor([[5, 0, 1, 2, 3, 8, 6...
Your issue arises because you're replacing some of the major nodes with unique nodes randomly, without checking if the major node still appears elsewhere. Create a list of nodes that appear twice, then for each node find all its occurrences. Finally, randomly select one occurrence to keep and replace the rest with uniq...
2
2
78,574,125
2024-6-4
https://stackoverflow.com/questions/78574125/how-to-making-async-calls-to-amazon-bedrock
We were trying to make calls in parallel to LLMs hosted in Bedrock, from a lambda layer (in python) only to discover that boto3 does not support async. Is there any workaround? I am looking into aiobotocore / aioboto3, but I do not find any example with Bedrock. Any hint appreciated and thank you very much! This is a m...
If you are using Anthropic, you can use the AsyncAnthropicBedrock API. from anthropic import AsyncAnthropicBedrock model_id = "my_model_id" user_message = "Hello Claude!" client = AsyncAnthropicBedrock() message = await client.messages.create( model=model_id, max_tokens=1024, messages=[ {"role": "user", "content": user...
4
1
78,562,640
2024-6-1
https://stackoverflow.com/questions/78562640/how-to-filter-polars-dataframe-by-first-maximum-value-while-using-over
I am trying to filter a dataframe to find the first occurrence of a maximum value over a category column. In my data there is no guarantee that there is a single unique maximum value, there could be multiple values, but i only need the first occurance. Yet I can't seem to find a way to limit the max part of the filter,...
You can add .is_first_distinct() to the filter to keep only the first max. df.filter( pl.all_horizontal( pl.col("max_col") == pl.col("max_col").max(), pl.col("max_col").is_first_distinct() ) .over("cat") ) shape: (3, 3) ┌─────┬─────────┬───────────┐ │ cat ┆ max_col ┆ other_col │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │...
4
2
78,569,761
2024-6-3
https://stackoverflow.com/questions/78569761/type-hint-for-an-object-that-can-be-used-as-a-type-hint-itself
I have following code from typing import TypeVar, Type, overload T = TypeVar('T') @overload def foo(bar: Type[T]) -> T: ... @overload def foo(bar: Type[T] | None) -> T | None: ... def foo(bar: Type[T] | None) -> T | None: # implementation goes here ... class Bar: ... bar = foo(Bar) bar2 = foo(Bar | None) # No overload ...
Only concrete classes are assignable to type[T]: [...] the actual argument passed in at runtime must [...] be a concrete class object [...] — Special types in annotations § type[] | Python typing spec (Admittedly, the spec isn't completely clear about this. However, the following paragraph holds true.) It is thus und...
1
4
78,576,727
2024-6-4
https://stackoverflow.com/questions/78576727/how-can-i-make-the-x-axis-of-my-2d-histogram-use-dates-while-avoiding-overflow-e
I am working with a set of monthly averaged time-series data that spans 20+ years and have put the data into a pandas dataframe. The index of the dataframe is composed of the datetime objects that span the time range of the dataset. I have successfully created a 2D histogram subplot of both time and another parameter, ...
I could reproduce your issue. Why xedges returns such high numbers (in the 10^17) has to see with how matplotlib reads datetime objects, in what unit of time since epoch. Indeed prior reformating such as in Format of datetime in pyplot axis seems a valid option but there may be better ones, e.g. using date2num (Conver...
1
2
78,574,357
2024-6-4
https://stackoverflow.com/questions/78574357/given-argument-of-listint-liststr-cant-i-be-sure-that-the-list-is-listi
I have a python script and trying to add type hints to the code, Following is the sample code (without type hints the code works) using mypy. values_int: list[int] = [1, 2, 3, 4] values_str: list[str] = ["1", "2", "3", "4"] def bar(*, x: list[int]) -> bool: # processing return True def baz(*, y: list[str]) -> bool: # p...
isinstance(a[b], ...) is not (yet) supported as a type narrowing construct. For what it's worth, Pyright also doesn't support it. Perhaps you want a custom TypeIs: (playgrounds: Mypy, Pyright) from typing_extensions import TypeIs def is_list_of_ints(v: list[Any]) -> TypeIs[list[int]]: return isinstance(v[0], int) def i...
2
2
78,546,844
2024-5-29
https://stackoverflow.com/questions/78546844/why-is-it-vscode-python-could-not-find-debugpy-path-when-running-without-debuggi
I'm relatively new to platforms like vscode, and I seem to run into problems whenever I try to run a python program without debugging (Ctrl + F5). A window pops up saying "Could not find debugpy path" and gives me the option of either opening launch.json or cancelling. Running from the "run file" button on the right w...
Turns out I needed to download a Python debugger in the VSCode extensions. I used Python Debugger from Microsoft.
3
12
78,572,914
2024-6-4
https://stackoverflow.com/questions/78572914/on-this-conditional-expression-what-the-syntax-error-about
I get: return r.group() if r := re.match(rx,l) else None ^ SyntaxError: invalid syntax whereas return r.group() if (r := re.match(rx,l)) else None is accepted. What is invalid about the first's syntax? And what other interpretation of it is there, than the second, such that it is not unambiguous?
Limiting the valid places in which the walrus operator ("assignment expression" for those who have killed their inner child) can be used was a mostly elective thing. They didn't want it replacing = for assignment, or getting used constantly to condense multiple lines of code down to one for the fun of it, so they put l...
2
5
78,577,960
2024-6-4
https://stackoverflow.com/questions/78577960/handle-logarithmic-and-exponential-objective-function-in-gurobi
I am working with a very complex optimization problem which basically uses medical parameters to calculate the risk of a certain person developing a cardiovascular disease. I want to, of course, minimize such probability, which is described by the following objective function: where: and beta will always be a float. ...
here are some snippets that I would recommend to use in the model: Split variable X3 into multiple binary variables. This is need to later get variable specific constants from the beta matrix: from gurobipy import Model, GRB, Var, quicksum # race variables... # Map: gurobi_var -> var_index(int) x3 = {} for i in range...
2
1
78,574,898
2024-6-4
https://stackoverflow.com/questions/78574898/how-to-find-base-line-of-curved-text
Attached is a picture with curved lines, how can you find the Baseline of the text? The goal is to get lines like I drew by hand in the following picture: I tried the following code, but letters like g p q y and similar break the line. import cv2 as cv import numpy as np src = cv.imread("boston_cooking_a.jpg", cv.IMR...
I found an approach which is a possibility to find your lines in „pure“ opencv. The suggested solution is not perfect, but demonstrates a first direction. Maybe you should use pytesseract to follow up your overall goal ? In general the suggested solution below is quite sensitive to the parameters of the first filter A....
19
10
78,560,728
2024-5-31
https://stackoverflow.com/questions/78560728/evaluation-metric-for-parameter-tuning-for-outlier-detection-unsupervised-learn
I'm working on implementing parameter tuning for outlier detection in time-series data using the DBSCAN algorithm. To maximize the Silhouette score (as evaluation), I'm leveraging optuna for tuning. However, after parameter tuning, the model's performance seems to be underperformed. Below is the complete code, which en...
DBSCAN relies on distance measurements to find clusters, thus it is sensitive to the scale and distribution of the data. Even, in your case, you have just one feature vector, I don't think you need to scale it for outlier detection. Just use residual variable in hyper-parameter and final prediction. You may also need t...
3
1
78,562,406
2024-5-31
https://stackoverflow.com/questions/78562406/multiplying-chains-of-matrices-in-jax
Suppose I have a vector of parameters p which parameterizes a set of matrices A_1(p), A_2(p),...,A_N(p). I have a computation in which for some list of indices q of length M, I have to compute A_{q_M} * ... * A_{q_2} * A_{q_1} * v for several different q s. Each q has a different length, but crucially doesn't change! W...
The main issue here is that JAX does not support string inputs. But you can use NumPy to manipulate string arrays and turn them into integer categorical arrays that can then be used by jax.jit and jax.vmap. The solution might look something like this: import numpy as np def gates_func_int(params, gate_list_vals): g = g...
2
1
78,576,233
2024-6-4
https://stackoverflow.com/questions/78576233/how-do-you-get-additional-combinations-when-adding-items-to-a-list-that-i-have
Using python I would like to calculate all combinations of 3 from a list. For example, list = [a,b,c,d] and combinations would be - [a,b,c], [a,b,d], [a,c,d], [b,c,d]. And then I would like to add some items to the original list and get only the additional combinations of 3. For example, adding items [e,f] would genera...
Add the new items one by one: from itertools import combinations old = ['a', 'b', 'c', 'd'] new = ['e', 'f'] for item in new: for comb in combinations(old, 2): print(*comb, item) old.append(item) Output (Attempt This Online!): a b e a c e a d e b c e b d e c d e a b f a c f a d f a e f b c f b d f b e f c d f c e f d ...
4
4
78,569,685
2024-6-3
https://stackoverflow.com/questions/78569685/why-does-count-method-return-the-wrong-number-of-items
I'm using pySpark and using count() on a dataFrame I seem to get the incorrect results; I made a csv, and I want to filter the rows with an incorrect type. Everything works (I use .show() to check), however when i call count(), the results I get are incorrect. I found out columnPruning is part of the problem, however d...
This issue was first raised here - SPARK-21610 which was subsequently 'fixed' by disallowing filtering the dataframe when only internal corrupt record column was used in the filter (via this PR 19199). Consequently, the error message "Since Spark 2.3, the queries from raw JSON/CSV files are disallowed when the referenc...
2
1
78,575,305
2024-6-4
https://stackoverflow.com/questions/78575305/attributeerror-trainingarguments-object-has-no-attribute-model-init-kwargs
While finetuning Gemma2B model using QLoRA i'm getting error as AttributeError: 'TrainingArguments' object has no attribute 'model_init_kwargs' Code: Loading the libraries from enum import Enum from functools import partial import pandas as pd import torch from transformers import AutoTokenizer, AutoModelForCausalLM, T...
Just replace your TrainingArguments constructor with SFTConfig constructor, and pass this to SFTTrainer. from trl import SFTConfig training_arguments = SFTConfig(your training args ...) trainer = SFTTrainer(args=training_arguments, rest of the args...)
3
3
78,573,180
2024-6-4
https://stackoverflow.com/questions/78573180/how-can-i-create-a-qlineedit-in-pyqt6-that-displays-truncated-text-similar-to-ho
I created a custom QLineEdit with a fixed size so that when the user types in text larger than the QLineEdit, the text gets truncated. When the user clicks out of the QLineEdit, the cursor jumps back to the beginning of the QLineEdit. Below is my code: from PyQt6.QtWidgets import QLineEdit class CustomLineEdit(QLineEdi...
The only way to achieve this is by manually changing the geometry of the line edit. Unfortunately, it's not that simple, especially when layout managers are used (which, by the way, should be mandatory). Most importantly, we need to ensure that the geometry change is: applied when the "something else" is trying to res...
2
1
78,577,834
2024-6-4
https://stackoverflow.com/questions/78577834/numpy-get-a-matrix-of-distances-between-values
If I have a set of points: points = np.random.randint(0, 11, size=10) print(points) Output: [ 5 4 9 7 4 1 2 10 4 2] And if I want to get a matrix representing the distance from each point to each other point, I can do so like this: def get_diff_array(values): dX = values - values[0] tmp = [dX] for i in range(1, len(d...
You can use values[:, np.newaxis] - values[np.newaxis, :]: import numpy as np def diff(A): return A[:, np.newaxis] - A[np.newaxis, :] print(diff(np.random.randint(0, 11, size=10))) Prints [[ 0 -7 -8 -3 -6 -6 -4 -5 -10 -3] [ 7 0 -1 4 1 1 3 2 -3 4] [ 8 1 0 5 2 2 4 3 -2 5] [ 3 -4 -5 0 -3 -3 -1 -2 -7 0] [ 6 -1 -2 3 0 0 2 ...
2
4
78,577,950
2024-6-4
https://stackoverflow.com/questions/78577950/pandas-dataframe-check-relation-of-variable-and-rolling-mean
I have a DataFrame df with one time series variable, call it X. I can find the rolling mean over the last (say) n observations with df['rolling_mean'] = df.X.rolling(window=n).mean() Now I want a new column with a boolean value that applies the following logic to each row and returns true if either: X > rolling_mean ...
A nice solution I came up with: df['rolling_max'] = df.X.rolling(k, min_periods=0).max().shift(-k) df['rolling_min'] = df.X.rolling(k, min_periods=0).min().shift(-k) df['will_drop_below_mean'] = (df.X > df.rolling_mean) & (df.rolling_min < df.rolling_mean) df['will_rise_above_mean'] = (df.X < df.rolling_mean) & (df.rol...
2
0
78,577,752
2024-6-4
https://stackoverflow.com/questions/78577752/copy-specific-values-from-a-cells-and-then-add-them-above
I have the following dataframe with large amounts of data. C1 C2 C3 C4 t # 0 e 10001 252207 CAT t # 1 e 100018 219559 DOG t # 2 e 100068 251102 CAT t # 3 e 100089 107320 LION t # 4 e 100110 250975 TIGER t # 5 e 100111 28540 TIGER t # 6 e 100112 252253 COW t # 7 e 100157 17883 COW t # 8 e 100158 106226 DOG t # 9 e 1001...
You can iterate through the rows and use startswith() on row C2, in addition to the other condition: import pandas as pd def get_rows(df): Vs, res = 1, [] for _, r in df.iterrows(): if r['C2'].startswith('t #'): Vs = 1 elif r['C1'] == 'e': res.append(['v', r['C2'], str(Vs), None]) Vs += 1 res.append([r['C1'], r['C2'], ...
2
2
78,575,922
2024-6-4
https://stackoverflow.com/questions/78575922/replace-3d-array-elements-with-numpy
I have a 3D array filled with RGB values and I need to replace some "pixels" with another value as fast as possible. The array looks like this: [[[ 78 77 75] [ 72 70 67] [ 72 70 67] ... [ 73 74 73] [ 71 72 71] [ 66 67 67]]] I used numpy select to replace some values but this is not what I need as it doesn't check for ...
You can define your two conditions, combine it using logical_or(), and then use where(): import numpy as np array = np.array([[[78, 77, 75], [72, 70, 67], [72, 70, 67]], [[78, 77, 75], [72, 70, 67], [72, 70, 67]], [[73, 74, 73], [71, 72, 71], [66, 67, 67]]]) color = [30, 30, 57] cond_a = array[:, :, 0] > 77 cond_b = ar...
2
2
78,577,205
2024-6-4
https://stackoverflow.com/questions/78577205/multi-column-and-row-matching-and-removal
I am trying to remove rows based on if the previous row was "added" and the current row is "removed". My goal is to identify the rows that are only "added". import pandas as pd df = pd.DataFrame({'Event_Time': ['2024-05-28 12:37:00', '2024-05-28 12:41:00', '2024-05-28 16:12:00','2024-05-08 09:40:00'], 'Name': ['Kenzie ...
You can use a mask: ~(same & (rem | rem_add)): import pandas as pd df = pd.DataFrame({'Event_Time': ['2024-05-28 12:37:00', '2024-05-28 12:41:00', '2024-05-28 16:12:00', '2024-05-08 09:40:00'], 'Name': ['Kenzie Doe', 'Kenzie Doe', 'Kenzie Doe', 'Abby Stone'], 'Action': ['Added', 'Removed', 'Added', 'Added']}) df['Event...
2
2
78,560,578
2024-5-31
https://stackoverflow.com/questions/78560578/aws-textract-asynchronous-operations-within-multiprocessing
I am working in a Lambda function within AWS. I have two functions which asynchronously call on Textract to return the extracted text from an image. By switching to this asynchronous operation from a singular call one at a time (which must wait for the result to complete before submitting a new request), given the volu...
In a well-architected, scalable setup for running Amazon Textract, the callback itself should be event-driven through SNS (which it looks from your snippet like you're already using?)... So your Lambdas will just be 1) kicking off jobs and 2) reading the results. If you're considering spiky workloads with very high con...
3
1
78,574,363
2024-6-4
https://stackoverflow.com/questions/78574363/why-fastapi-isnt-validating-post-body
I'm working on a webserver built with FastAPI version 0.111.0 and SQLModel version 0.0.18. When I'm calling the POST endpoint with partial data or with keys I don't specify in my class, it doesn't trigger the unprocessable entity or bad request error. I'm using the method POST only for inserting data and not updating i...
Use this model for response validation from pydantic import BaseModel from typing import Optional class JobRead(BaseModel): job_id: int title: str start_time: str end_time: Optional[str] = Field(default=None) pipeline_id: int prj_path: str branch_tag: str user: str status: str log: Optional[str] = Field(default="") re...
2
1
78,574,047
2024-6-4
https://stackoverflow.com/questions/78574047/python-setattr-and-getattr-best-practice-with-flexible-mutable-object-variable
I have a class that holds an unspecified number of dicts as variables. I want to provide methods that allow the user to easily append to any of the dicts while naming the corresponding variable, without having to check whether the variable was already created. Example for my goal: >>> c = Container() >>> c.add_value(va...
You can initialize and access each sub-dict with the setdefault method of the object's attribute dict: class Container: def add_value(self, variable, key, value): vars(self).setdefault(variable, {})[key] = value
2
2
78,573,638
2024-6-4
https://stackoverflow.com/questions/78573638/reindex-to-expand-and-fill-value-only-across-one-level-of-multi-index
I have a dataframe with an index of (month, A, B): foo N month A B 1983-03-01 3 9 0 1 1983-06-01 3 9 0 1 1983-09-01 3 9 0 1 1983-11-01 4 5 0 1 1984-05-01 4 5 0 1 1984-06-01 3 9 0 1 1984-09-01 3 9 0 2 I would like to fill all missing dates, provided that a certain (A, B) combination exists in the index. What I do not ...
Assuming: df = pd.DataFrame({'month': pd.to_datetime(['1983-03-01', '1983-06-01', '1983-09-01', '1983-11-01', '1984-05-01', '1984-06-01', '1984-09-01']), 'A': [3, 3, 3, 4, 4, 3, 3], 'B': [9, 9, 9, 5, 5, 9, 9], 'foo': [0, 0, 0, 0, 0, 0, 0], 'N': [1, 1, 1, 1, 1, 1, 2]} ) You could use a groupby.apply: cols = df.columns....
2
2
78,573,321
2024-6-4
https://stackoverflow.com/questions/78573321/mutual-exclusivity-pairs-using-dataframe
How to check are the attributes mutually exclusive? That is, can a word have more than one non-zero entry in the sentiment attributes? Would like to check if each attribute is mutually exclusive of one another and to enumerate through all pairs to compare each. N | P | U | L | S | W 0 1 ... 0 2 ... 1 0 ... 0 0 ... N P,...
Check all pairs. The pair is mutually exclusive, if (df[ii] * df[jj] != 0).sum() == 0: import pandas as pd def get_mut_ex(D): df = pd.DataFrame(D) cols = df.columns res, n = [], len(cols) for i in range(n): for j in range(i + 1, n): ii, jj = cols[i], cols[j] print(df[jj], df[ii]) if (df[ii] * df[jj] != 0).sum() == 0:...
2
0
78,571,618
2024-6-3
https://stackoverflow.com/questions/78571618/selenium-how-to-select-a-value-form-a-select-box
I try to select the option "Psychatrie" on a website using the following code: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expecte...
You have made a typo in the word "Psychatrie". It should have been "Psychiatrie". In addition, I've modified the code so that you first click on the drop-down menu and then search for the exact string from the options. Finally, by executing javascript, you can click on the item as the click() method throws an error. fr...
2
1
78,571,907
2024-6-3
https://stackoverflow.com/questions/78571907/creating-a-new-column-by-multiplying-the-value-of-row-above-with-the-value-of-th
I am trying to create a new columns of percentages which is a product of value in a row above and the value in the same row of another column. I have tried using shift and loc with no luck. I have tried using: df.at[0,'new_col'] = df.at[0,'other_col'] This first part works well and then df['new_col'] = df['new_col'].sh...
You cannot achieve the desired result with shift. shift will give you access to the previous row before any computation is performed, but you need the new value to become the next reference. What you want is a cumulative product, there is already a method for that in pandas: cumprod: df['adj_val'] = df['val'].cumprod()...
3
4
78,561,921
2024-5-31
https://stackoverflow.com/questions/78561921/how-would-i-implement-the-hausdorff-distance-using-gekko
If the following function took in arrays A and B that contain arrays of Gekko variables instead of floats, how would I find the Hausdorff distance, aka, how would I define np.inf and modify the rest of the code? def hausdorff_distance(A, B): """ Compute the Hausdorff distance between two sets of points A and B. """ dis...
Use the m.min2() function to calculate the minimum of two values. Here is an example implementation of the minimum distance function with Gekko operators. from gekko import GEKKO import numpy as np def hausdorff_distance(A, B): """ Compute the Hausdorff distance between two sets of points A and B, where A and B contain...
2
1
78,570,861
2024-6-3
https://stackoverflow.com/questions/78570861/smarter-way-to-create-diff-between-two-pandas-dataframes
I have two pandas dataframes which represent a directory structure with file hashes like import pandas as pd dir_old = pd.DataFrame([ {"Filepath": "dir1/file1", "Hash": "hash1"}, {"Filepath": "dir1/file2", "Hash": "hash2"}, {"Filepath": "dir2/file3", "Hash": "hash3"}, ]) dir_new = pd.DataFrame([ # {"Filepath": "dir1/fi...
I'd do it first by merging only by Filepath and then compare Hash_x/Hash_y and indicator accordingly (seems straightforward to me): df = dir_new.merge(dir_old, on="Filepath", how="outer", indicator=True) hash_changed = df["Hash_x"] != df["Hash_y"] deleted = df["_merge"] == "right_only" created = df["_merge"] == "left_o...
4
1
78,571,193
2024-6-3
https://stackoverflow.com/questions/78571193/avoiding-iteration-in-pandas-when-i-want-to-update-the-value-in-a-column-x-when
I have the following pandas dataframe: key1 key2 col_name bool col_1 col_2 col_3 a1 a2 col_1 0 5 10 20 b1 b2 col_3 1 10 10 5 c1 c2 col_1 1 5 15 5 Where bool==1, I would like to update the value in the column given by the col_name column to be 100. Expected output: key1 key2 col_name bool col_1 col_2 co...
Build a boolean mask with numpy and update: # identify cells for which the col_name matches the column name # only keep those that have a bool of 1 in the row m = ((df['col_name'].to_numpy()[:, None] == df.columns.to_numpy()) & df['bool'].eq(1).to_numpy()[:, None] ) df[m] = 100 Output: key1 key2 col_name bool col_1 c...
4
3
78,569,897
2024-6-3
https://stackoverflow.com/questions/78569897/survey-data-many-periods-transformation-to-current-and-previous-period-wide-to
I have a data frame (survey data) called df that looks like this (this is sample data): respondent_id r1age r2age r3age r4age r1smoke r2smoke r3smoke r4smoke r1income r2income r3income r4income 16178 35 38 41 44 1 1 1 1 60 62 68 70 161719 65 68 71 74 0 0 0 1 50 52 54 56 161720 47 50 53 56 0 1 0 1 80 82 85 87...
There are many ways to approach that, wide_to_long is an option but you would need to pre-process the column names (it expects the stubnames as prefixes, not suffixes). I'd suggest to use a MultiIndex and stack, here is an example that doesn't require to know the stubnames: # set aside respondent_id and create a MultiI...
4
3
78,570,583
2024-6-3
https://stackoverflow.com/questions/78570583/store-methods-in-class-in-order-they-are-written
This might be a two part question. First is the context if better alternatives can be suggested. Second part is the (probably) XY problem for my solution. xy - Have a method in the class which returns a list of all functions in the class in order they were written/typed. My projects typically involve long sequences of ...
I would advise against source code order dictating execution order, but if you really need to, you can use inspect.getsourcelines() to get the line number where an object starts at. import inspect class Funcs: def func_8(self): pass def func_5(self): pass def func_4(self): pass instance = Funcs() funcs = [getattr(insta...
1
2
78,556,850
2024-5-30
https://stackoverflow.com/questions/78556850/attributeerror-emailaddressmanager-object-has-no-attribute-is-verified
I get the following error while attempting to a register a user with the help of DRF, dj-rest-auth and django-allauth: AttributeError at /api/v1/dj-rest-auth/registration/ 'EmailAddressManager' object has no attribute 'is_verified' Here is the templates part of settings.py file: TEMPLATES = [ { 'BACKEND': 'django.tem...
This issue occurs when there is a version mismatch between your django, django-allauth, or dj-rest-auth packages. In my case, I was using the following versions: django = “^4.2.4” django-allauth = “^0.54.0” dj-rest-auth = “^5.0.2” To resolve the issue, I downgraded dj-rest-auth to version “^5.0.1”. I recommend upgradi...
2
1