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,511,875 | 2024-5-21 | https://stackoverflow.com/questions/78511875/stripe-promocode-how-to-verify-that-user-have-redeemed-the-promocode-before-or | I have a Django project configured with Stripe for payments. I have created promocodes for discounts, which can only be redeemed once per customer. The problem is that I want to validate whether a given customer has already redeemed a specific promocode. If they haven't redeemed it, I want to proceed to the next step; ... | You would need to either: create individual one-time Promotion Code objects for each customer, and then list them by customer and code (in case you want to use the same code) to check if it was used, or update Customer's metadata field, to record if a given promo code was used. | 3 | 2 |
78,502,897 | 2024-5-19 | https://stackoverflow.com/questions/78502897/reduce-the-sum-of-differences-between-adjacent-array-elements | I came across a coding challenge on the internet the question is listed below: Have the function FoodDistribution(arr) read the array of numbers stored in arr which will represent the hunger level of different people ranging from 0 to 5 (0 meaning not hungry at all, 5 meaning very hungry). You will also have N sandwic... | The sum of the absolute differences only goes down when you reduce a local maximum. If you reduce a maximum on either end, the sum of differences goes down by one, like [3,2,1] -> [2,2,1]. If you reduce a maximum in the middle, the sum of differences goes down by two, like [1,3,2] -> [1,2,2]. If a maximum gets reduced,... | 5 | 2 |
78,508,381 | 2024-5-20 | https://stackoverflow.com/questions/78508381/pivot-dataframe-values-and-its-unit | I have the input dataframe in the following format: id city state date param value unit 1 Phoenix AZ 4-21-2024 temp 100 F 2 Phoenix AZ 4-21-2024 prec 0 mm 3 Phoenix AZ 4-21-2024 wind 2 mph 4 Phoenix AZ 4-20-2024 temp 101 F 5 Phoenix AZ 4-20-2024 prec 0 NaN 6 Phoenix AZ 4-20-2024 wind 4 mph 7 Seattle WA 4-20-2024 temp 8... | You can pivot, flatten the MultiIndex, then reset_index: out = df.pivot(index=['city', 'state', 'date'], columns='param', values=['value', 'unit']) out.columns = out.columns.map(lambda x: f'{x[0]}_{x[1]}' if x[0]!='value' else x[1]) out.reset_index(inplace=True) Output: city state date prec temp wind unit_prec unit_t... | 2 | 2 |
78,505,563 | 2024-5-20 | https://stackoverflow.com/questions/78505563/is-it-possible-to-use-docker-compose-watch-with-an-image-created-by-earthfile | So I have this simple code to run. import streamlit as st st.title("hellobored") I created a docker image of this code with a simple earthfile with the command earthly +all VERSION 0.8 streamlit: FROM python:3.11-slim WORKDIR /src/app RUN apt-get update && apt-get install -y curl RUN python -m pip install --upgrade pi... | In your initial setup, the docker-compose-watch command failed because there was no build context specified. Docker Compose requires a build context to track changes and trigger rebuilds. Without a build context, the watch command cannot determine which files to monitor for changes. build: context: . | 2 | 1 |
78,507,768 | 2024-5-20 | https://stackoverflow.com/questions/78507768/create-new-dataframe-from-aggregate-of-original-df-and-calculations | I want to create a new dataframe from my original dataframe that aggregates by two columns and has a calculated column dependent on the sum of selected rows from two other columns. Here is a sample df: df = pd.DataFrame([['A','X',2000,5,3],['A','X',2001,6,2],['B','X',2000,6,3],['B','X',2001,7,2],['C','Y',2000,10,4],['C... | Pre-compute value = val1*val2, perform a groupby.sum, then compute value/val1: out = (df.eval('value = val1*val2') .groupby(['rgn', 'year'], as_index=False) [['value', 'val2']].sum() .assign(value=lambda x: x['value']/x.pop('val2')) ) Less efficient, but more flexible, you can also use groupby.apply: out = (df.groupby... | 4 | 3 |
78,506,798 | 2024-5-20 | https://stackoverflow.com/questions/78506798/keep-build-a-map-when-doing-multiple-pandas-groupby-operations | Imagine a process, where we do several pandas groupbys. We start with a df like so: import numpy as np import pandas as pd np.random.seed(1) df = pd.DataFrame({ 'id': np.arange(10), 'a': np.random.randint(1, 10, 10), 'b': np.random.randint(1, 10, 10), 'c': np.random.randint(1, 10, 10) }) df Out[23]: id a b c 0 0 2 8 2 ... | This looks to me like a graph problem. You could build a directed graph from successive groupby using networkx, then pair the roots/leaves of each subgraph: import networkx as nx G = nx.DiGraph() ref = 'id' cols = ['a', 'b'] for col in cols: tmp = df.groupby(ref, as_index=False)[[ref, col]].max() G.add_edges_from((((re... | 2 | 1 |
78,505,815 | 2024-5-20 | https://stackoverflow.com/questions/78505815/polars-apply-by-several-columns | I have dataframe Polars with a lot of columns. I need to create new columnt with the result of my own function df = pl.DataFrame({ 'Stock_name': ['reserve', 'fullfilment', 'ntl', 'ntl'], 'doc_type': ['sales', 'moving', 'sales', 'corr'], }) def doc_check(row): if (row['Stock_name'] == 'reserve') or (row['Stock_name'] =... | You can use pl.struct to extract the two columns and then use map_elements to map over it: df = df.with_columns( doc_type_new=pl.struct("Stock_name", "doc_type").map_elements( doc_check, return_dtype=pl.String ) ) print(df) Output: shape: (4, 3) ┌─────────────┬──────────┬──────────────┐ │ Stock_name ┆ doc_type ┆ doc_t... | 2 | 1 |
78,505,196 | 2024-5-20 | https://stackoverflow.com/questions/78505196/syntaxerror-cannot-assign-to-function-call-here-maybe-you-meant-when-usin | I am creating a AI agent in my Jupyter Notebook on Anaconda. When I enter the following settings I get an error. import os os.environ("OPENAI_API_KEY")=openai_api_key os.environ("OPENAI_MODEL_NAME")="gpt-3.5-turbo" Cell In[47], line 1 os.environ("OPENAI_API_KEY")=openai_api_key ^ SyntaxError: cannot assign to function ... | Use Square brackets instead of parentheses. os.environ["OPENAI_API_KEY"]=openai_api_key os.environ["OPENAI_MODEL_NAME"]="gpt-3.5-turbo" It'll solve the issue. | 2 | 2 |
78,503,985 | 2024-5-19 | https://stackoverflow.com/questions/78503985/creating-a-categorical-data-from-two-columns-in-pandas | I'm trying to practice coding again and currently having problems with figuring out why my function doesn't work. Here's my sample Table for reference: diastolic systolic 80.0 130.0 77.0 126.0 92.0 152.0 76.0 147.0 70.0 127.0 64.0 119.0 72.0 135.0 84.0 137.0 85.0 165.0 81.0 156.0 and here's ... | A very simple approach would be to vectorize your function, for example by decorating the function: import numpy as np @np.vectorize def blood_pressure_cat(diastolic, systolic): """ diastolic: float systolic: float """ if systolic <= 90 and diastolic <= 60: return "Hypotension" elif systolic < 120 and diastolic < 80: r... | 2 | 1 |
78,504,305 | 2024-5-20 | https://stackoverflow.com/questions/78504305/filtering-row-with-same-column-date-value | I have a datetime field, and I want to filter the rows that has the same date value. models.py class EntryMonitoring(models.Model): student = models.ForeignKey('Student', models.DO_NOTHING) clockin = models.DateTimeField() clockout = models.DateTimeField(null=True) views.py def check_attendance(request, nid): day = En... | Yes, it is possible. You should use the TruncDate function: from django.db.models import F from django.db.models.functions import TruncDate entries = EntryMonitoring.objects.filter( clockout__isnull=False, student=nid, clockin__date=TruncDate(F("clockout")) ).annotate(...) | 2 | 3 |
78,503,255 | 2024-5-19 | https://stackoverflow.com/questions/78503255/how-can-i-get-the-left-edge-as-the-label-of-pandas-cut | This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'high': [110, 110, 101, 101, 115, 300], } ) And this is the expected output. Column bin should be created: high bin 0 110 105.0 1 110 105.0 2 101 100.0 3 101 100.0 4 115 111.0 5 300 220.0 Basically bin is created by using pd.cut: import numpy as np evalu... | Pass evaluation_bins to labels inside pd.cut, without the final edge (np.inf): df['bin'] = pd.cut(df['high'], bins=evaluation_bins, labels=evaluation_bins[:-1], include_lowest=True, right=False) Output: high bin 0 110 105 1 110 105 2 101 100 3 101 100 4 115 111 5 300 220 | 4 | 3 |
78,502,175 | 2024-5-19 | https://stackoverflow.com/questions/78502175/search-for-text-in-a-very-large-txt-file-50gb | I have a hashes.txt file that stores strings and their compressed SHA-256 hash values. Each line in the file is formatted as follows: <compressed_hash>:<original_string> The compressed_hash is created by taking the 6th, 13th, 20th, and 27th characters of the full SHA-256 hash. For example, the string alon when hashed: ... | You only have 65536 unique search keys. Why not just make 65536 files? You could use 256 directories with 256 files each to keep it manageable. Then you can entirely eliminate all of the lookup process. Bonus: your files are smaller because you don’t need to store the key at all. You’ll have to do some one-time process... | 2 | 4 |
78,498,583 | 2024-5-18 | https://stackoverflow.com/questions/78498583/web-scraping-a-dataframe-but-only-500-rows | My aim is to web-scrape the table on https://data.eastmoney.com/executive/list.html and save it to an excel. Please note that it has 2945 pages and I want to put all of them into one excel sheet. The easiest way of doing it is to see where the data is pulled. So I F12 the webpage to get the source code and saw a data c... | You can retrieve the next page using the pageNumber={page_number} parameter. The pageSize parameter determines how many data items are retrieved per request. The default and maximum value is 500. This is the access URL https://datacenter-web.eastmoney.com/api/data/v1/get?reportName=RPT_EXECUTIVE_HOLD_DETAILS&columns=AL... | 2 | 1 |
78,499,163 | 2024-5-18 | https://stackoverflow.com/questions/78499163/why-the-difference-in-checking-for-value-of-pd-dataframe-vs-pd-series-if-value-i | I'm working with a pandas DataFrame and I noticed a difference in behavior when using the in operator. Here’s an example to illustrate this: import pandas as pd df = pd.DataFrame({'a': [4, 5, 6], 'b': [7, 8, 9]}) print(1 in df) print(type(df)) print(1 in df["a"]) print(type(df["a"])) Output: False <class 'pandas.core.... | In both cases the in operator calls __contains__ to test membership. Both pd.DataFrame and pd.Series are subclasses of NDFrame, which has this method defined as follows: def __contains__(self, key) -> bool: """True if the key is in the info axis""" return key in self._info_axis So, under the hood the following happen... | 2 | 4 |
78,499,028 | 2024-5-18 | https://stackoverflow.com/questions/78499028/what-does-the-tempfile-mkstemptext-parameter-actually-do | Is the text=True|False parameter in mkstemp something Windows specific? I'm sorry that I have to ask, but I'm a UNIX/Linux person. At the low level of file descriptors - where the mkstemp operates - are all files just bytes. I was surprised to see the text= parameter. The only hint I found is a comment in os.open docs:... | It's a feature of the default C runtime library on Windows. When a file is opened in text mode – not through the Win32 CreateFile() API, but specifically through the POSIX open() API – writes to it will transparently convert LF line-endings to CR+LF (i.e. writing \n will actually write \r\n). https://learn.microsoft.c... | 3 | 1 |
78,498,832 | 2024-5-18 | https://stackoverflow.com/questions/78498832/how-to-use-sqlalchemy-hybrid-property-in-where-or-filter-method | I'm using SQLAlchemy v2 and have two models: User and Transaction. Here, Transaction refers to money transactions between users, not database transactions. I have defined a hybrid property in the User model that calculates the balance for each user based on their incoming and outgoing money transactions. However, I am ... | The User.balance hybrid property returns a Select object as defined in your _balance_expression function. Select is a subquery, and SQLAlchemy wouldn't know how to compare that subquery with an integer value (1 in your case). To solve this issue, you need to modify the _balance_expression method to return a scalar valu... | 2 | 1 |
78,496,873 | 2024-5-17 | https://stackoverflow.com/questions/78496873/how-to-write-csv-data-directly-from-string-or-bytes-to-a-duckdb-database-file | I would like to write CSV data directly from a bytes (or string) object in memory to duckdb database file (i.e. I want to avoid having to write and read the temporary .csv files). This is what I've got so far: import io import duckdb data = b'a,b,c\n0,1,2\n3,4,5' rawtbl = duckdb.read_csv( io.BytesIO(data), header=True,... | You can create the connection before you use read_csv and pass the connection into it. import io import duckdb from pathlib import Path data = b'a,b,c\n0,1,2\n3,4,5' db_path = 'some.db' Path(db_path).unlink(missing_ok=True) with duckdb.connect(db_path) as con: rawtbl = duckdb.read_csv( io.BytesIO(data), header=True, se... | 3 | 5 |
78,491,778 | 2024-5-16 | https://stackoverflow.com/questions/78491778/pytest-dependency-doesnt-work-when-both-across-files-and-parametrized | I'm running into a problem wherein pytest_dependency works as expected when EITHER Doing parametrization, and dependent tests are in the same file OR Not doing parametrization, and dependent tests are in a separate file But, I can't get the dependency to work properly when doing BOTH - parametrized dependent tests ... | I believe it's failing to find the dependency in the other file, because the depends() function uses scope='module' by default. Change that to depends(request, ["test_0.py::test_a[n{}-{}]".format(*perm_fixt)], scope='session') And the dependent tests work as expected. What helped me in finding this issue was displayin... | 3 | 4 |
78,496,560 | 2024-5-17 | https://stackoverflow.com/questions/78496560/is-there-a-way-to-shut-down-the-python-multiprocessing-resource-tracker-process | I submitted a question a week ago about persistent processes after terminating the ProcessPoolExecutor, but there have been no replies. I think this might be because not enough people are familiar with how ProcessPoolExecutor is coded, so I thought it would be helpful to ask a more general question to those who use the... | You may use an internal method _stop to achieve this, but ... it should be done with caution due to the potential risks involved while using internal and/or undocumented features, Below an example of code demonstrating what is said above: from concurrent.futures import ProcessPoolExecutor from multiprocessing import re... | 3 | 3 |
78,494,178 | 2024-5-17 | https://stackoverflow.com/questions/78494178/constructing-pointer-chains-with-ctypes | These are simple variable declarations in cpp, how do I do it in Python ctypes? B *C = (B *) A; D *E = (D *)(A + sizeof(B)); Assume that B and D are structs and A is uint8_t A[42];. Where do I start from here? I tried using cast functions but maybe I'm wrong, can you help me? from ctypes import POINTER, byref, address... | Listing [Python.Docs]: ctypes - A foreign function library for Python. In short, to: Dereference a pointer - cts_ptr_var.contents Reference a variable (to a pointer) - ctypes.pointer(cts_var) (to later pass it as an argument to a function - ctypes.byref(cts_var)) Get its (C) address - ctypes.addressof(cts_var) Now... | 4 | 4 |
78,494,262 | 2024-5-17 | https://stackoverflow.com/questions/78494262/skipping-dictionaries-that-contain-certain-keys | I'm looking for a good way to skip dictionaries that contain certain keys among multiple dictionaries that are different. Right now I'm chaining .get() methods on a dictionary object and continuing on whatever matches, which is working but its kinda messy. I'm doing something like: ... if my_dict.get('some_key', my_dic... | You can use any with a generator expression that iterates over the possible keys and tests if the dict has any of the keys: if any(key in my_dict for key in ('some_key', 'other_key', 'some_other_key')): continue Alternatively, you can use set.isdisjoint to test if the set of keys is disjoint with the dict keys: if not... | 2 | 4 |
78,488,359 | 2024-5-16 | https://stackoverflow.com/questions/78488359/nicegui-tree-with-toggle-buttons | I'm trying to create a tree in NiceGui where every element has a toggle button. This is what I got so far: from nicegui import events, ui def toggleUpdate(e: events.GenericEventArguments) -> None: print(tree._props['nodes']) tree = ui.tree([ {'id': 'numbers', 'description': 'Just some numbers', 'update': True, 'childre... | The Author of NiceGui found the solution. You have to use $parent.$parent.$parent.$emit() for the toggle. Full answer: https://github.com/zauberzeug/nicegui/discussions/3085#discussioncomment-9462868 | 2 | 2 |
78,492,616 | 2024-5-16 | https://stackoverflow.com/questions/78492616/why-is-the-image-result-flipped-by-90-degrees | I am trying to turn all of the white pixels in this image red, but when I run the program the shape is fine but the red pixels are rotated 90 degrees: This is the current code that I am using to do this: import cv2 as cv import numpy as np import os from matplotlib import pyplot as plt import cv2 as cv def get_white_p... | Change this line to: # image[loc_x,loc_y] = (0,0,255) image[loc_y,loc_x] = (0,0,255) along with # cartesian_y=height-indices[0]-1 cartesian_y=indices[0] You need to know that numpy and OpenCV arrays are y,x ones, where other image processing packages work the x,y way. Here the result of running the fixed code: As ... | 2 | 2 |
78,491,904 | 2024-5-16 | https://stackoverflow.com/questions/78491904/transpose-a-rolling-set-of-values-in-a-column-into-a-single-value-in-a-cell | I am having troubles with a data transformation I am trying to do. I have a column of data (Ex. 1,2,3,4,5,6,7,8,9)I want to create a new column that looks back n rows and concatenates the values into a new value, preferably an integer. For example, if the lookback window is 3 in my example, the new column would be Nan,... | One option would be to use numpy's sliding_window_view combined with agg: from numpy.lib.stride_tricks import sliding_window_view as svw df = pd.DataFrame({'Streak': [1,2,3,4,5,6,7,8,9]}) N = 3 df['Streak History'] = (pd.DataFrame(svw(df['Streak'].astype(str), N), index=df.index[N-1:]) .agg(''.join, axis=1) ) Output: ... | 2 | 1 |
78,484,610 | 2024-5-15 | https://stackoverflow.com/questions/78484610/fluent-pattern-with-async-methods | This class has async and sync methods (i.e. isHuman): class Character: def isHuman(self) -> Self: if self.human: return self raise Exception(f'{self.name} is not human') async def hasJob(self) -> Self: await asyncio.sleep(1) return self async def isKnight(self) -> Self: await asyncio.sleep(1) return self If all method... | Tricky - but can be done using some advanced properties in Python. Usually, the big problem, even with all Python capabilities, implementing an automated way to curry methods like you are doing is to know when the chain stops (i.e. when the result of the last method will be actually used, and no longer used with a . to... | 2 | 2 |
78,490,421 | 2024-5-16 | https://stackoverflow.com/questions/78490421/rename-a-variable-and-select-this-variable-using-a-string-store-in-a-vector | I am a R user trying to learn python. For some analysis, I used to rename dataframe variable like this library(dplyr) variable = "c" df = data.frame(a=c(8,5,7,8), b=c(9,6,6,8), c=c(0,7,8,9)) > df a b c 1 8 9 0 2 5 6 7 3 7 6 8 4 8 8 9 out = df %>% rename(variable := !!variable) > out a b variable 1 8 9 0 2 5 6 7 3 7 6 8... | You can do the same with rename and a dictionary, the order of the "parameters" is just reversed compared to R: variable = 'c' out = df.rename(columns={variable: 'variable'}) Or, without the intermediate: out = df.rename(columns={'c': 'variable'}) # df %>% rename(variable := c) Output: a b variable 0 8 9 0 1 5 6 7 2... | 3 | 2 |
78,489,776 | 2024-5-16 | https://stackoverflow.com/questions/78489776/gekko-solver-error-results-json-not-found-and-being-unable-to-pinpoint-the | I'm getting the following error message while executing a constrained regression by using Gekko: > ---------------------------------------------------------------- APMonitor, Version 1.0.1 APMonitor Optimization Suite ---------------------------------------------------------------- --------- APM Model Size ------------... | The solver crashed with a segmentation fault because it couldn't access the memory it needed. The size of the optimization problem: Number of state variables: 3535109 Number of total equations: - 3535080 Number of slack variables: - 0 --------------------------------------- Degrees of freedom : 29 shows that it is li... | 2 | 1 |
78,482,220 | 2024-5-15 | https://stackoverflow.com/questions/78482220/fixing-boundary-values-on-a-spline | I have data x and y which are noisy evaluations of a function f:[0,alpha] -> [0,1]. I know very little about my function except that f(0) = 0 and f(alpha) = 1. Is there any way to enforce these boundary conditions when fitting a spline? Here is a picture, where one sees that the spline fits nicely, but the approximatio... | What you're looking for is a function that constructs a clamped B-Spline that interpolates the given endpoints. Unfortunately, to the best of my knowledge, no scipy spline interface implements this exactly. Still, Unit 9 of this online course describes an algorithm to solve exactly this problem denoted "Curve Global Ap... | 2 | 4 |
78,489,029 | 2024-5-16 | https://stackoverflow.com/questions/78489029/pandas-dense-rank-with-same-values-in-order-by | I have the following DataFrame in Pandas: ID snapshot_date row_hash qwe Jan 01 2024 123 qwe Jan 03 2024 456 qwe Jan 05 2024 456 qwe Jan 07 2024 123 Note: that row_hash changed back on Jan 07 2024 I want to create 3 groups (like window function in SQL), but I can't get the desired rseult: ID snapshot_... | If need counter for change by columns ID and row_hash compare by shifted values by DataFrame.shift with DataFrame.any and Series.cumsum: cols = ['ID', 'row_hash'] df['dense_rank'] = df[cols].ne(df[cols].shift()).any(axis=1).cumsum() print (df) ID snapshot_date row_hash dense_rank 0 qwe Jan 01 2024 123 1 1 qwe Jan 03 20... | 2 | 1 |
78,489,949 | 2024-5-16 | https://stackoverflow.com/questions/78489949/python-merge-two-dataframes-based-on-created-time | I have two dfs, two df's has be to be merged by class and joining dates. Please check the below df's df1 class teacher age instructor_joining_date A mark 50 2024-01-20 07:18:29.599 A john 45 2024-05-08 05:31:21.379 df2 class count student_joining_date A 1 2024-05-17 01:05:58.072 A 50 2024-04-10 10:39:06.608 A 75 2024-0... | You have to use a merge_asof, then restore the original order with reindex: df1['instructor_joining_date'] = pd.to_datetime(df1['instructor_joining_date']) df2['student_joining_date'] = pd.to_datetime(df2['student_joining_date']) out = (pd.merge_asof(df2.sort_values(by='student_joining_date').reset_index(), df1.sort_va... | 2 | 2 |
78,488,599 | 2024-5-16 | https://stackoverflow.com/questions/78488599/unexpected-reversed-secondary-y-axis-on-dataframe-plot | I'm trying to plot a electrical consumption, first in mA with a date, and with secondary axis in W with julian day. I refered to this matplotlib article, and even if the example works perfectly, I can't figrure where mine differ of it. Because my secondary y axis is inverted as it's supposed to be. Here my prog : impor... | It is unclear what you are expecting, but here is what I would have done: import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime # Sample data data = { 'TIMESTAMP': [ '2024-05-13 00:00:00', '2024-05-13 00:01:00', '2024-05-13 00:02:00', '2024-05-13 00:03:00', '2024-05-13 00... | 2 | 1 |
78,486,620 | 2024-5-15 | https://stackoverflow.com/questions/78486620/can-t-get-exponential-curve-fit-to-work-with-dates | I’m trying to plot a curve_fit for the S&P 500. I’m successful (I think) at performing a linear fit/plot. When I try to get an exponential curve_fit to work, I get this error: Optimal parameters not found: Number of calls to function has reached maxfev = 800. import numpy as np import matplotlib.pyplot as plt import y... | In addition to normalizing the data, it is important to actually choose a good function. In your example you had: def func(x, a, b): return a * x + b # ?? return a * np.exp(-b * x) + c # ?? return a*(x**b)+c # ?? return a*np.exp(b*x) The correct one, when you say you want to fit an exponential, should be this, IMO: # ... | 2 | 2 |
78,485,825 | 2024-5-15 | https://stackoverflow.com/questions/78485825/width-parameter-not-affecting-dash-column | I'm trying to build a simple dashboard to display temperature and humidity on different days. I would like to have a dropdown to select the date and then have a row showing a graph of temperature throughout the day next to a graph showing humidity (two graphs in a single row). I can't get it to work even though I've tr... | Dash Bootstrap Components: Layout: Layout in Bootstrap is controlled using the grid system. The Bootstrap grid has twelve columns [...] The width of your columns can be specified in terms of how many of the twelve grid columns it should span [...] Each of your graph column spans across the whole 12-column sized row. ... | 2 | 4 |
78,486,428 | 2024-5-15 | https://stackoverflow.com/questions/78486428/is-it-possible-in-python-to-type-a-function-that-uses-the-first-elements-of-an-a | I have a Python function that retrieves the first element of an arbitrary number of *args: def get_first(*args): return tuple(a[0] for a in args) Lets say that I call this function as follows: b = (1, 2, 3) c = ("a", "b", "c", "d") x = get_first(b, c) I expect the type Tuple[int, str]. To me it seems impossible to ac... | The signature you're looking for is related to the signature of zip; in fact, you could implement your function as next(zip(*args)). Unfortunately, there is, at the moment, no good way to type such a function. It would require variadic generics which are not currently implemented. For example, you can see the type sign... | 3 | 6 |
78,484,792 | 2024-5-15 | https://stackoverflow.com/questions/78484792/python-polars-vectorized-operation-of-determining-current-solution-with-the-u | Let's say we have 3 variables a, b & c. There are n instances of each, and all but the first instance of c are null. We are to calculate each next c based on a given formula comprising of only present variables on the right hand side: c = [(1 + a) * (current_c) * (b)] + [(1 + b) * (current_c) * (a)] How do we go about ... | Using numba you can make ufuncs which polars can use seamlessly. from numba import guvectorize, int64 import polars as pl @guvectorize([(int64[:], int64[:], int64, int64[:])], '(n),(n),()->(n)', nopython=True) def make_c(a,b,init_c, res): res[0]=(1+a[0]) * init_c * b[0] + (1+b[0]) * init_c * a[0] for i in range(1,a.sha... | 3 | 2 |
78,483,440 | 2024-5-15 | https://stackoverflow.com/questions/78483440/polars-rolling-groups-with-starting-indices-set-by-a-different-column | I’m working on a dataset with Polars (Python), and I’m stumped on a “rolling” grouping operation. The data looks like this: updated_at last_trade_ts ask_price ask_qty bid_price bid_qty 2023-12-20 15:30:54 CET 2023-12-20 15:30:42 CET 114.2 1.2 109.49 0.1 2023-12-20 15:31:38 CET 2023-12-20 15:30:42 CET 112.0 15.... | I cannot come up with solution which would use .group_by_dynamic() cause you can only use single column for both every and period parameters. One possible way of doing it would be more classical pre-window functions sql-like style, with DataFrame.join(). So, first we create a separate DataFrame which gives us list of ... | 3 | 3 |
78,484,160 | 2024-5-15 | https://stackoverflow.com/questions/78484160/trying-get-a-table-from-a-website-valueerror-if-using-all-scalar-values-you-m | I'm trying to make a function that automatically takes a table from a website(Wikipedia) cleans it a bit and than displays it, everything worked well with my first 2 tables but the third one is giving me some troubles. This is the code to define the function: def createTable(url, match): data= pd.read_html(url, match= ... | Your script does not consistently yield Series for name/origin/type_/number, you sometimes have DataFrames, you can try to squeeze: name= data[0]["Name"].squeeze() origin= data[0]["Origin"].squeeze() type_= data[0]["Type"].squeeze() number= data[0]["Number"].squeeze() Side note: df_avIT = pd.DataFrame() is useless, yo... | 2 | 1 |
78,483,843 | 2024-5-15 | https://stackoverflow.com/questions/78483843/how-to-scrape-links-from-summary-section-link-list-of-wikipedia | update: many thanks for the replies - the help and all the efforts! some additional notes i have added. below (at the end) howdy i am trying to scrape all the Links of a large wikpedia page from the "List of Towns and Gemeinden in Bayern" on Wikipedia using python. The trouble is that I cannot figure out how to export ... | Your selector is wrong. The names of towns are in a tag which is in li tag which in turn is under a div with class column-multiple. First, get all divs with class column-multiple and then get all the li items from the gathered divs and then get the href attribute of all the a tags inside. url = "https://de.wikipedia.or... | 2 | 3 |
78,483,941 | 2024-5-15 | https://stackoverflow.com/questions/78483941/pandas-dataframe-with-counted-values | I have the following data: data = [{'Shape': 'Circle', 'Color': 'Green'}, {'Shape': 'Circle', 'Color': 'Green'}, {'Shape': 'Circle', 'Color': 'Green'}] Which I create a DataFrame from: df = pd.DataFrame(data) Giving: >>> df Shape Color 0 Circle Green 1 Circle Green 2 Circle Green The data is always received in this ... | Using pivot_table and reindex: data = [{'Shape': 'Circle', 'Color': 'Green'}, {'Shape': 'Circle', 'Color': 'Green'}, {'Shape': 'Circle', 'Color': 'Green'}] df = pd.DataFrame(data) shapes = ['Circle', 'Square'] colors = ['Green', 'Red'] pivot_table = df.pivot_table(index='Color', columns='Shape', aggfunc='size', fill_va... | 2 | 4 |
78,482,270 | 2024-5-15 | https://stackoverflow.com/questions/78482270/saving-and-dropping-a-dataframe-in-a-for-loop | I have a number of dataframes from which I have to take a sample. The samples taken from that dataframe, have to be excluded from the next dataframe in order to not have any 'double' samples as there is some overlap. my code is as follows df_list = [df1, df2, df3, df4, df5] samplesizes = [8, 2, 4, 4, 2] sample = [] for... | This is an interesting and not straightforward problem. I think you cannot/shouldn't: pre-filter the duplicates, since it might remove too many rows (it might remove a row in group 2 that was in group 1 even if it was not sampled from group 1) sample then post-filter, since removing rows after sampling would decrease ... | 2 | 2 |
78,482,381 | 2024-5-15 | https://stackoverflow.com/questions/78482381/how-to-restrict-pydantic-url-validation-to-specific-hosts-or-websites | I'm currently working with Pydantic's URL type for URL validation in my Python project. However, it seems that Pydantic does not currently provide a built-in mechanism for this. So what is the best approach to restrict a URL to a specific list of hosts in Pydantic? I have a pydantic model called Media which has an url ... | As you already mentioned there is no built-in support for doing so. Here an AfterValidator can do the job: from typing import Annotated, TypeAlias from pydantic import AfterValidator, AnyUrl, BaseModel valid_hosts = {"www.google.com", "www.yahoo.com"} def check_specific_hosts(url: AnyUrl) -> AnyUrl: if url.host in vali... | 2 | 3 |
78,482,107 | 2024-5-15 | https://stackoverflow.com/questions/78482107/how-to-loop-through-each-element-of-a-loop-and-filter-out-conditions-in-a-python | I have a list of subcategories and a dataframe. I want to filter out the dataframe on the basis of each subcategory of the list. lst = [7774, 29409, 36611, 77553] import pandas as pd data = {'aucctlg_id': [143424, 143424, 143424, 143388, 143388, 143430], 'catalogversion_id': [1, 1, 1, 1, 1, 1.2], 'Key': [1434241, 14342... | You could pre-filter with isin, then use groupby: lst = [7774, 29409, 36611, 77553] out = dict(list(df[df['subcategoryid'].isin(lst)].groupby('subcategoryid'))) Which will create a dictionary of the desired dataframes: {7774: aucctlg_id catalogversion_id Key item_id catlog_description catlog_start_date subcategoryid q... | 2 | 2 |
78,481,829 | 2024-5-15 | https://stackoverflow.com/questions/78481829/schedule-optimization-problem-dont-know-a-better-way-to-present-the-solution | So my music school runs a festival for all student bands to play together. Since there are some family members across diferent bands, I'm trying to create a solution to optimize the schedule of the bands - trying to minimize sum of time between bands that have relatives. Now I think I've found a solution. Don't know if... | You need to extract the band and slot numbers for each 1 in the matrix and sort the schedule by slot number: schedule = [(i+1, j+1) for i in range(n) for j in range(s) if x[i,j][0] == 1] schedule.sort(key=lambda x: x[1]) for band, slot in schedule: print(f"Band {band} is scheduled to play in slot {slot}") | 3 | 1 |
78,481,203 | 2024-5-15 | https://stackoverflow.com/questions/78481203/plotly-dash-function-to-toggle-graph-parameters-python | I'm trying to install a function that provides a switch or toggle to alter a plotly graph. Using below, I have a scatter plot and two buttons that intend to change the color and size of the points. The buttons are applied to the same scatter plot. I can use daq.BooleanSwitch individually on either color or size but I c... | It appears that you need the toggles for the Size and the Color. In that case, you can take advantage of dcc.checklist() in your html and style it. This code would most likely work, run it and see: app.layout = html.Div( [ html.P("Toggle for the Color"), dcc.Checklist( id="color_toggle", options=[{"label": "", "value":... | 3 | 3 |
78,461,651 | 2024-5-10 | https://stackoverflow.com/questions/78461651/why-arent-exceptions-caught-with-one-liner-while-statement | I have a code with a one-liner while and a try-except statement which behaves weirdly. This prints 'a' on Ctrl+C: try: while True: pass except KeyboardInterrupt: print("a") and this too: try: i = 0 while True: pass except KeyboardInterrupt: print("a") but this doesn't, and it throws a traceback: try: while True: pass... | Its a known CPython bug introduced in 3.11 and exists in 3.12. One of comments of the bug, mentioned that partial backport of this pull request looks to be the right direction to fix the bug. I built and tested following CPython versions from source using pyenv on Arch Linux with GCC 14.1.1 compiler: 3.11-dev: Python ... | 14 | 7 |
78,470,913 | 2024-5-13 | https://stackoverflow.com/questions/78470913/generate-new-column-in-dataframe-with-modulo-of-other-column | I would like to create a new column "Day2" which takes the second digit of column named "Days", so if we have Days equal to 35, we would take the number 5 to be in "Day2", I tried this but it's not working: DF["Day2"] = DF["Days"].where( DF["Days"] < 10, (DF["Days"] / 10 % 10).astype(int), ) It seems it's taking the f... | This is a very simple and pythonic solution: import pandas as pd data = [10,11,35,45,65] df = pd.DataFrame(data, columns=['Day1']) df['Day2'] = df['Day1'].mod(10) df Result Day1 Day2 0 10 0 1 11 1 2 35 5 3 45 5 4 65 5 | 2 | 2 |
78,472,764 | 2024-5-13 | https://stackoverflow.com/questions/78472764/langchain-workaround-for-with-structured-output-using-chatbedrock | I'm working with the langchain library to implement a document analysis application. Especifically I want to use the routing technique described in this documentation. i wanted to follow along the example, but my environment is restricted to AWS, and I am using ChatBedrock instead of ChatOpenAI due to limitations with ... | I found a solution in these two blog posts: here and here. The key is to use the instructor package, which is a wrapper around pydantic. This means langchain is not necessary. Here is an example based on the blog posts: from typing import List import instructor from anthropic import AnthropicBedrock from loguru import ... | 3 | 2 |
78,476,603 | 2024-5-14 | https://stackoverflow.com/questions/78476603/calculate-cmyk-spot-coverage-on-pdf-with-python | I don't find any free or open source libraries to calculate CMYK and spot color on pdf. I would be grateful if someone could guide me in the right direction as to what I should do to access color channels and calculate the percentage of color used ( C,M,Y,K and spot, Export each separately ) with Python. Point: Actuall... | I hope this will be useful for those who have a similar problem in the future. Dependencies : Ghostscript - Pillow How does it work ? Ghostscript will separated colors ( C,M,Y,K, Spots ) and save each one as .tiff and Pillow calculate the percentage of color ( In fact, the file saved by Ghostscript is in grayscale mode... | 2 | 1 |
78,481,022 | 2024-5-14 | https://stackoverflow.com/questions/78481022/error-no-matching-distribution-found-for-tensorflow-cygwin | I'm trying to install Tensorflow on Cygwin but i'm getting these Errors : $ /usr/bin/python3 -m pip install tensorflow==2.12.0 ERROR: Could not find a version that satisfies the requirement tensorflow==2.12.0 (from versions: none) ERROR: No matching distribution found for tensorflow==2.12.0 $ /usr/bin/python3 -m pip i... | It seems you're trying to install tensorflow 2.12.0 to python 3.7.0. According to release notes of tensorflow 2.12.0. It says that Support for Python 3.7 has been removed. We are not releasing any more patches for Python 3.7. I would suggest to upgrade python or downgrade tensorflow. | 2 | 1 |
78,471,617 | 2024-5-13 | https://stackoverflow.com/questions/78471617/python-keyring-does-not-overwrite-entry-but-creates-new-entry | I'm having trouble with the python keyring library. I want to extract passwords from an entry in the windows credential manager. After that I want to overwrite the password of that specific entry. Here is my Code. import keyring # The service name in the credentials manager is "User@Service", the username is "User" pas... | I ran into this problem today as well. Seems like the same thing mentioned here: https://github.com/jaraco/keyring/issues/545 I don't know if it was ever fixed or has been an issue since then. I can't get it to work, as it just creates a new credential unless both versions already exist (service and user@service). I am... | 2 | 1 |
78,471,354 | 2024-5-13 | https://stackoverflow.com/questions/78471354/slack-files-completeuploadexternal-no-uploading-files-to-the-slack | Since the slack file.upload is going to be depreciated, I was going to make new the methods work. The first one works as: curl -s -F files=@test.txt -F filename=test.txt -F token=xoxp-token -F length=50123 https://slack.com/api/files.getUploadURLExternal and returns {"ok":true,"upload_url":"https:\/\/files.slack.com\/... | You skipped a step. You have to send a POST to the URL that is returned to you on the first step. In that post you are also doing the file upload. 2nd step should be: curl -F filename="@$filename" -H "Authorization: Bearer $SLACK_KEY" -v POST $upload_url then your 2nd step should be the 3rd step. As far as getting the ... | 5 | 0 |
78,476,300 | 2024-5-14 | https://stackoverflow.com/questions/78476300/pip-install-fails-for-pandas | I am trying to install pandas on a Windows machine but get the following output: python -m pip install pandas Collecting pandas Using cached pandas-2.2.2.tar.gz (4.4 MB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pypro... | So I got past this, it was a stupid reason this was happening. I had another pip binary somewhere in a MinGW installation folder and it was always calling that one. I made sure change the environment variables to point to a proper, standalone installation of pip (also python). | 2 | 1 |
78,477,442 | 2024-5-14 | https://stackoverflow.com/questions/78477442/dynamic-update-of-add-qty-parameter-in-odoo-ecommerce-product-details-page | I'm customizing an Odoo eCommerce website and I need to modify the add_qty parameter in the product details page dynamically via a URL parameter. I'm extending the WebsiteSale class to achieve this. Here's my code snippet: class WebsiteSaleCustom(WebsiteSale): def _prepare_product_values(self, product, category, search... | To address issues related to outdated or incorrect data being fetched by Odoo due to caching, you can use the method request.env.registry._clear_cache() before applying your solution. This method clears the cache, ensuring that Odoo fetches fresh data. from odoo.http import request from odoo.addons.website_sale.control... | 3 | 2 |
78,480,187 | 2024-5-14 | https://stackoverflow.com/questions/78480187/how-do-i-delete-all-documents-from-a-marqo-index | I have a ton of documents that have been vectorized poorly / are using an old multimodal_field_combination. mappings={ 'combo_text_image': { "type": "multimodal_combination", "weights": { "name": 0.05, "description": 0.15, "image_url": 0.8 } } }, But I need to update to mappings={ 'combo_text_image': { "type": "multim... | Here is a code snippet that would delete all documents from the index: def empty_index(index_name): index = mq.index(index_name) res = index.search(q = '', limit=400) while len(res['hits']) > 0: id_set = [] for hit in res['hits']: id_set.append(hit['_id']) index.delete_documents(id_set) res = index.search(q = '', limit... | 2 | 3 |
78,478,825 | 2024-5-14 | https://stackoverflow.com/questions/78478825/numpy-slicing-on-a-zero-padded-2d-array | Given a 2D Numpy array, I'd like to be able to pad it on the left, right, top, bottom side, like the following pseudo-code. Is there anything like this already built into Numpy? import numpy as np a = np.arange(16).reshape((4, 4)) # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11] # [12 13 14 15]] pad(a)[-4:2, -1:3] # or any sy... | Some trickery: import numpy as np class PaddedArray: def __init__(self, arr): self.arr = arr def __getitem__(self, idx): idx = tuple( slice(s.start or 0, s.stop or size) for size, s in zip(self.arr.shape, idx) ) slices = tuple( slice(max(0, s.start), min(size, s.stop)) for size, s in zip(self.arr.shape, idx) ) paddings... | 2 | 6 |
78,474,769 | 2024-5-13 | https://stackoverflow.com/questions/78474769/how-to-terminate-async-process-in-python-in-case-of-failure | I am using asyncio to asynchronously launch a process, and then read data from the stdout, my code looks like the following: process = await asyncio.subprocess.create_subprocess_exe(subprocess_args, stderr=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE) I am then asynchronously reading from the stdout of this... | process.terminate() is a fast, synchronous call that sends a signal that the target process asynchronously handles; thus, the target doesn't shut down immediately when terminate is called, but somewhat later, after the OS next schedules it and invokes its signal handler. This means you still want to await process.wait(... | 4 | 2 |
78,477,934 | 2024-5-14 | https://stackoverflow.com/questions/78477934/how-to-pip-install-from-a-text-file-skipping-unreachable-libraries | I'm currently in a scenario where I need to install the following: pip install -r https://raw.githubusercontent.com/intro-stat-learning/ISLP_labs/v2.1.3/requirements.txt What happens is that the library scipy is not available for some reason, resulting in the following error: (test_islp) PS C:\Users\project> pip insta... | You can use this simple python script to loop through all the packages in the requirements.txt and install them. As far as I can tell, this works on Linux and Windows, not sure about Mac. import subprocess def install_packages(requirements_file): with open(requirements_file, 'r') as file: packages = file.readlines() fo... | 3 | 1 |
78,475,551 | 2024-5-14 | https://stackoverflow.com/questions/78475551/discontinuous-selections-with-pandas-multiindex | I have the following DataFrame with MultiIndex columns (the same applies to MultiIndex rows): import pandas as pd df = pd.DataFrame(columns=pd.MultiIndex.from_product([['A','B'],[1,2,3,4]]), data=[[0,1,2,3,4,5,6,7],[10,11,12,13,14,15,16,17], [20,21,22,23,24,25,26,27]]) Now I want to select the following columns into ... | Another idea with product: from itertools import product print (df.loc[:, list(product('A',(1,2,4))) + list(product('B',(1,2,3)))]) A B 1 2 4 1 2 3 0 0 1 3 4 5 6 1 10 11 13 14 15 16 2 20 21 23 24 25 26 | 2 | 1 |
78,474,573 | 2024-5-13 | https://stackoverflow.com/questions/78474573/extract-event-pairs-from-multiline-text | I would like to extract event pair (start and end marked by + and -). but the pairs maybe not match which means start happen two times then followed the end event. In below example, event B start happed 2 times, so I wish it output a mismatched pair with nil in the end event not found. import re import pandas as pd dat... | You can just modify your regex to have an optional trailing part: data = """ 00:00:00 +running A dummy data 00:00:01 -running 00:00:02 +running B dummy data 00:00:03 +running B 00:00:04 -running 00:00:05 +running C dummy data 00:00:06 -running 00:00:07 +running D 10:00:08 -running """ m = re.findall(r"(\d+:\d+:\d+) \+r... | 3 | 1 |
78,473,728 | 2024-5-13 | https://stackoverflow.com/questions/78473728/why-is-using-the-distance-cosine-function-from-scipy-faster-than-directly-exec | I am executing the below two code snippets to calculate the cosine similarity of two vectors where the vectors are the same for both executions and the code for the second one is mainly the code SciPy is running (see scipy cosine implementation). The thing is that when calling SciPy it is running slightly faster (~0.55... | It seems, scipy does at the beginning of correlation() function this which practically means: u = np.asarray(u, dtype=None, order="c") v = np.asarray(v, dtype=None, order="c") This ensures that the arrays are C_CONTIGUOUS (you can check this by printing u.flags and/or v.flags) I presume numpy uses different implementa... | 3 | 2 |
78,472,054 | 2024-5-13 | https://stackoverflow.com/questions/78472054/manually-color-columns-in-pandas | I have a list of colors that created manually; colmap = ['green', 'red', 'red', 'red', 'green'] and also have a pandas dataframe df with same length of my colmap Percent 0 -0.5 1 0.2 2 0.8 3 -0.3 4 0.6 I want to apply the colors to only Percent column, df.style.applymap doesn't work because it requires a function to ... | You could pass a DataFrame to style. The callable doesn't need to use the input data: df.style.apply( lambda x: pd.DataFrame( {'Percent': [f'background-color:{x}' for x in colmap]}, index=x.index ), axis=None, ) NB. since the styling DataFrame should be aligned, you still should pass the index. Output: Example with a... | 2 | 2 |
78,471,100 | 2024-5-13 | https://stackoverflow.com/questions/78471100/check-for-equality-across-n-n2-columns-horizontally-in-polars | Assume I have the following Polars DataFrame: all_items = pl.DataFrame( { "ISO_codes": ["fin", "nor", "eng", "eng", "swe"], "ISO_codes1": ["fin", "nor", "eng", "eng", "eng"], "ISO_codes2": ["fin", "ice", "eng", "eng", "eng"], "OtherColumn": ["1", "2", "3", "4", "5"], }) How can I implement a method like check_for_equa... | pl.n_unique_horizontal would probably be the answer, but it has not yet been added. https://github.com/pola-rs/polars/issues/9966 You can use the List API: df.with_columns(ISO_EQUALS = pl.concat_list(columns_to_check_for_equality).list.n_unique() == 1 ) shape: (5, 5) ┌───────────┬────────────┬────────────┬──────────... | 2 | 3 |
78,458,284 | 2024-5-10 | https://stackoverflow.com/questions/78458284/how-to-fix-line-bleeding-in-fpdf | I have these functions def investment_summary(pdf, text): pdf.set_font("Arial", size=8) pdf.write(5, text) for point in text.splitlines(): if point.startswith("-"): pdf.set_x(15) pdf.write(5, point) def create_report(county_and_state, llm_text, analytics_location_path=None): pdf = FPDF() pdf.add_page() pdf.set_text_col... | This is connected to Generating line break in FPDF and the write method of fpdf. As described in the answer to above mentioned question, try replacing pdf.write by pdf.multi_cell in the investment_summary function: def investment_summary(pdf, text, bullet_indent=15): pdf.set_font("Arial", size=8) for point in text.spli... | 2 | 1 |
78,449,471 | 2024-5-8 | https://stackoverflow.com/questions/78449471/how-to-most-efficiently-delete-a-tuple-from-a-list-of-tuples-based-on-the-first | I have a data structure as follows, data = { '0_0': [('0_0', 0), ('0_1', 1), ('0_2', 2)], '0_1': [('0_0', 1), ('0_1', 0), ('0_2', 1)], '0_2': [('0_0', 2), ('0_1', 1), ('0_2', 0)], } Each key of the dictionary is unique. The values corresponding to the key value in the dictionary structure are list of tuples, and each ... | def remove_all_acs_now(dictionary, delete_ac): for key in dictionary: acs = dictionary[key] for ac in acs: if ac[0] == delete_ac: acs.remove(ac) break return dictionary def remove_all_acs(dictionary, delete_ac): for i in dictionary.values(): # .items() / .values() are the fastest ways for dicts, always! for q in (i): i... | 2 | 1 |
78,469,600 | 2024-5-12 | https://stackoverflow.com/questions/78469600/pandasdata-frame-handeling-of-nested-list-within-json-in-pandas-table-for-subseq | So I've been working with a json.loads() of blockdevices for a small project that i'm working on. Presently, I'm trying to feed json data into a Pandas dataframe, then convert that dataframe into a numpy array to be processed by a third party project called CurseXcel, but I digress. What i'm presently having trouble wi... | Is this your expected output? code: df = pd.json_normalize(data=data.get("blockdevices")).explode(column="children") df = (pd .concat(objs=[df, df.children.apply(func=pd.Series)], axis=1) .drop(columns=[0, "children"]) .fillna("") .reset_index(drop=True) ) print(df) result: name size uuid mountpoint path fstype name ... | 2 | 3 |
78,469,541 | 2024-5-12 | https://stackoverflow.com/questions/78469541/get-periodic-updates-from-a-process | I have a function which will increment a number with time. This is given to a process; but it doesn't increment while the process runs. I want the incremented value of my global variable at regular intervals. But, I am not seeing the increment happening. Here is what I tried: from multiprocessing import Process from ti... | Note that each process is a separate object(). You should pass the vars in the process, to be locally saved in the memory. from multiprocessing import Process, Value from time import sleep def increment(x): while True: x.value += 1 sleep(1) if __name__ == '__main__': x = Value('i', 1) process_1 = Process(target=increme... | 2 | 2 |
78,457,389 | 2024-5-9 | https://stackoverflow.com/questions/78457389/auto-inherite-a-parent-class-with-decorator | I have a class decorator p() that can be used only on classes that inherite from some abstract class P. So anytime someone uses p it should be written as follows: @p() class Child(P): ... Is there any way to automatically inherite P using the decorator p() so it would simply be written as follows: @p() class Child: ..... | As I commented, it's tricky to apply a base class using a decorator the way you asked. However, it is a lot easier if you try an alternative approach, where the decorator's behavior is incorporated into the base class, rather than the other way around. Here's an example, that prints out a message before calling the chi... | 2 | 1 |
78,467,899 | 2024-5-12 | https://stackoverflow.com/questions/78467899/python-giving-different-response-when-called-via-async | Getting different output for the same logic? Was trying to learn async/await in python. Output for first Snippet : <class 'dict'> Output for second Snippet : <class 'list'> Snippet 1 : without async import urllib.request import json def get_response(user_url): resp = urllib.request.urlopen(user_url).read() resp_json =... | That <class 'list'> is the return value of the asyncio.gather(). If all awaitables are completed successfully, the result is an aggregate list of returned values. You'll then need to iterate through the list to access the result of the awaitables. If you only have that single URL, await get_response(user_url) is enou... | 2 | 2 |
78,467,626 | 2024-5-12 | https://stackoverflow.com/questions/78467626/is-there-a-way-to-remove-zombies-in-airflow | I'm making an airflow program that needs to convert .tsv to .parquet But I have an error: ERROR - Detected zombie job: {'full_filepath': '/opt/airflow/dags/formatting_data.py', 'processor_subdir': '/opt/airflow/dags', 'msg': "{'DAG Id': 'formatting_data', 'Task Id': 'format_imdb_data', 'Run Id': 'scheduled__2024-05-11T... | in airflow when the worker awaits for the operator to finish. If there’s a connection failure between worker and operator or worker kills off unexpectedly, while the operator is still running, it becomes a zombie process. i think in your case the format_imdb_files() is taking too much time to complete, you must increas... | 2 | 1 |
78,453,450 | 2024-5-9 | https://stackoverflow.com/questions/78453450/identifying-and-retrieving-particular-sequences-of-characters-from-within-text-f | I have a list named MAT_DESC that contains material descriptions in a free-text format. Here are some sample values from the MAT_DESC column: QWERTYUI PN-DR, Coarse, TR, 1-1/2 in, 50/Carton, 200 ea/Case, Dispenser Pack 2841 PC GREY AS/AF (20/CASE) CI-1A, up to 35 kV, Compact/Solid, Stranded, 10/Case MT53H7A4410WS5 WS W... | For the data you shared, I suggest using \b(?<!\d[,.])(?<!\d-)((?:\d+/)?\d+(?:[,.]\d+)*)\b(\s*(\w*)/)?\s*((?(2)\w+|\w+\s+per\s+\w+))(?=\s*(?:[,)]|$)) See the regex demo. In your code, since the regex contains 4 groups now, you need to use quantity, _, unit1, unit2 = match Just to skip Group 2 value that is technical ... | 2 | 1 |
78,467,544 | 2024-5-12 | https://stackoverflow.com/questions/78467544/how-to-add-two-pandas-dataframe-in-a-way-that-achieve-the-desired-behaviour-desc | the resulting dataframe will sum the value of matching index, but if an index is missing in one dataframe but present in the other, it will just carry them over instead of removing them. for example df1 = data index1 4.2 index2 5.0 index3 3.0 df2 = data index2 1.0 index3 7.0 index4 2.0 result = data index1 4.2 ( carr... | You can try pd.concat and sum along rows: out = pd.concat([df1, df2], axis=1).sum(axis=1).to_frame(name="data") print(out) Prints: data index1 4.2 index2 6.0 index3 10.0 index4 2.0 OR: using .merge: out = ( df1.merge(df2, left_index=True, right_index=True, how="outer") .sum(axis=1) .to_frame(name="data") ) print(ou... | 2 | 2 |
78,466,491 | 2024-5-12 | https://stackoverflow.com/questions/78466491/incremental-computation-of-total-value-over-dates-and-groups | Here is my dataframe. There is a date index and there are 4 symbols for each date. I want to loop over each date for each symbol. The 'quantity' column is calculated based on the 'tot_value' of the previous date. The 'tot_value' is computed for a specific date and is common for all symbols. The 'value' column varies fo... | Your computation is inherently iterative, therefore a loop is a valid approach. This is however not the classical type of pandas operation (usually vectorized). One option, assuming the data is sorted by date, then symbol, would be to loop over a groupby (ignoring the first date): # initial total tot = df['tot_value'].... | 2 | 1 |
78,464,072 | 2024-5-11 | https://stackoverflow.com/questions/78464072/what-is-the-best-way-to-merge-two-dataframes-that-one-of-them-has-overlapping-ra | My DataFrames are: import pandas as pd df_1 = pd.DataFrame( { 'a': [10, 12, 14, 20, 25, 30, 42, 50, 80] } ) df_2 = pd.DataFrame( { 'start': [9, 19], 'end': [26, 50], 'label': ['a', 'b'] } ) Expected output: Adding column label to df_1: a label 10 a 12 a 14 a 20 a 25 a 20 b 25 b 30 b 42 b 50 b df_2 defines the ranges ... | I'd try to concatenate generated labeled ranges using pandas.concat this way: template = df_1.set_index('a') ranges = df_2.values output = pd.concat( template.loc[start:end].assign(label=label) for start, end, label in ranges ).reset_index() It's close to your solution with two major differences: All iterations are c... | 4 | 2 |
78,464,719 | 2024-5-11 | https://stackoverflow.com/questions/78464719/recursive-backtracking-word-search-in-a-2d-array | I was attempting the word search problem here on leetcode. Leetcode seems to give me an error for the two test cases: board = [["a","a"]], word = "aa" and for : board = [["a"]], word = "a" But the following code seems to work fine on Google colab for both of these test cases. Could someone be able to please pinpoint th... | There are multiple issues with your code. First, you are relying on the default argument of seen_cells, but there is only one instance of that list, which is used across all calls to exist2. Multiple test cases will share the same state, which causes problems when there are tuples in seen_cells from previous calls of e... | 2 | 3 |
78,465,168 | 2024-5-11 | https://stackoverflow.com/questions/78465168/how-do-i-draw-text-thats-right-aligned-in-pygame | I am making a Math-thingy that requires numbers to be drawn to the screen right aligned. I'm using this function to draw text: def drawText(text, font, text_col, x, y): img = font.render(text, True, text_col) screen.blit(img, (x, y)) How do I draw the text right aligned instead of left aligned? I tried to use Python's... | The pygame.Rect object has a set of virtual attributes that can be used to define the position of surfaces and text. Align the text to its right by setting topright: def drawText(text, font, text_col, x, y): img = font.render(text, True, text_col) rect = img.get_rect(topright = (x, y)) screen.blit(img, rect) Minimal ... | 2 | 3 |
78,464,426 | 2024-5-11 | https://stackoverflow.com/questions/78464426/how-to-correctly-index-a-dataframe-with-a-function | Given a dataframe: a b c u 5 0 3 v 3 7 9 w 3 5 2 I'd like to select rows/columns in a dataframe using a function. This function gets the dataframe and returns a tuple of lists of labels, e.g. it returns ['v', 'u'], ['c'] using this lambda: get_labels = lambda df: (['v', 'u'], ['c']) If I use .loc with the label lite... | As noted in the loc documentation, you need to pass: A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index). A list or array of labels, e.g. ['a', 'b', 'c']. A slice object with labels, e.g. 'a':'f'. A boolean array of the same length as t... | 2 | 1 |
78,463,386 | 2024-5-11 | https://stackoverflow.com/questions/78463386/python-multiindex-dataframe-to-json-like-list-of-dictionaries | I want to store this data frame df = pd.DataFrame({ 'id':[1,1,2,2], 'gender':["m","m","f","f"], 'val1':[1,2,5,6], 'val2':[3,4,7,8] }).set_index(['id','gender']) as a json file that contains lists of dictionaries like this: d = [{'id':1, 'gender':"m", 'val1':[1,2], 'val2':[3,4]}, {'id':2, 'gender':"f", 'val1':[5,6], 'v... | You first need to aggregate as list with groupby.agg and reset_index: (df.groupby(['id', 'gender']).agg(list) .reset_index().to_json(orient='records') ) Output: [{"id":1,"gender":"m","val1":[1,2],"val2":[3,4]},{"id":2,"gender":"f","val1":[5,6],"val2":[7,8]}] | 4 | 3 |
78,460,161 | 2024-5-10 | https://stackoverflow.com/questions/78460161/find-length-of-sequences-of-identical-values-along-one-axis-in-a-3d-array-relat | I'm interested in finding the length of sequences of 1's along a single axis in a multi-dimension array. For a 1D array I have worked my way to a solution using the answers at this older question. E.g. [0,1,0,0,1,1,1,0,1,1] --> [nan,1,nan,nan,3,nan,nan,nan,2,nan] For a 3D array I can of course create a loop, but I'd ra... | For this task you can try to use numba, e.g.: import numba import numpy as np @numba.njit def calculate(arr): out = np.empty_like(arr, dtype="uint16") lat, lon, time = arr.shape for i in range(lat): for j in range(lon): curr = 0 for k in range(time): out[i, j, k] = 0 if arr[i, j, k] == 0: if curr > 0: out[i, j, k - cur... | 2 | 1 |
78,457,374 | 2024-5-9 | https://stackoverflow.com/questions/78457374/circular-imports-from-classes-whose-attributes-reference-one-another | I know there are a lot of questions that talk about circular imports. I've looked at a lot of them, but I can't seem to be able to figure out how to apply them to this scenario. I have a pair of data loading classes for importing data from an excel document with multiple sheets. The sheets are each configurable, so the... | Often times, answers to circular import questions fall into a couple of categories: Tricks to avoid the error and keep the design and... You need to rethink your redesign Usually however, the "rethink your design" is not accompanied with any suggested design patterns. Clearly, in my case, it was a design issue. I kne... | 2 | 1 |
78,461,650 | 2024-5-10 | https://stackoverflow.com/questions/78461650/save-and-restore-terminal-window-conent-using-curses-for-python | I'm making some console app on Python with Curses (window-curses) library. At some point I need to save window state (or maybe whole terminal state) to some object/variable and restore it in future. What's the proper way to do this? I found methods in module documentaion which do this via saving state to the file. But ... | As you found, you can use things like the putwin function to save a pad to a file and getwin to restore it from a file. If you want to keep this in memory, rather than a file on disk, you can use a BytesIO object in place of a real file handle. import io import curses curses.initscr() pad = curses.newpad(100, 100) # ..... | 2 | 2 |
78,458,753 | 2024-5-10 | https://stackoverflow.com/questions/78458753/how-to-receive-file-send-from-flask-with-curl | Here the server side code with python & flask: from flask import Flask, request, send_file import io import zipfile import bitstring app = Flask(__name__) @app.route('/s/', methods=['POST']) def return_files_tut(): try: f = io.BytesIO() f.write("abcd".encode()) return send_file(f, attachment_filename='a.ret.zip') excep... | When data is written, the pointer moves to the next position in the file. This means that before the data is read to make it available as a download, the pointer points to the end and no further data is read. So the download fails. In order to offer the file as a download, the pointer within the file must be reset to t... | 2 | 4 |
78,459,786 | 2024-5-10 | https://stackoverflow.com/questions/78459786/pandas-every-nth-row-from-each-group | Assume groups will have more than n memebers, I want to take every nth row from each group. I looked at https://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.core.groupby.GroupBy.nth.html but that only takes one row from each group. For example: import pandas as pd x = pd.DataFrame.from_dict({'a': [1, ... | Use GroupBy.cumcount with modulo and compare by 1: out = x[x.groupby('a').cumcount() % 2 == 1] print (out) a b 1 1 2 3 2 4 6 3 7 8 3 9 10 3 11 How it working: print (x.assign(counter=x.groupby('a').cumcount(), mod2 = x.groupby('a').cumcount() % 2, mask = x.groupby('a').cumcount() % 2 == 1)) a b counter mod2 mask 0 1 1... | 2 | 4 |
78,459,504 | 2024-5-10 | https://stackoverflow.com/questions/78459504/write-dictionary-to-excel | I'm trying to convert a python dictionary into an excel file. But I didn't manage to format the dataframe on a way that is how I want the excel file to look like. I have a dict in the shape as below: data = { 'Key 1': { 'PP': {'A': 105.08, 'B': 9.03, 'C': 0.12, 'D': 3.18, 'E': 0.5}, 'RP': {'A': 43.35, 'B': 6.92, 'C': -... | From your current approach, you can chain unstack and post-process the columns with swaplevel and sort_index: df = (pd.DataFrame.from_dict( {(i,j):data[i][j] for i in data.keys() for j in data[i]}, orient = 'index' ) .unstack().swaplevel(axis=1).sort_index(axis=1) ) Or, change the dictionary comprehension to: out = pd... | 2 | 3 |
78,459,217 | 2024-5-10 | https://stackoverflow.com/questions/78459217/keep-columns-and-rows-that-contains-fail-in-pandas-dataframe | I would like to keep columns that contains word "FAIL". Input data: Values1 Values2 Values3 Status1 Status2 Status3 1 1 1 PASS PASS FAIL 2 2 2 PASS PASS PASS 3 3 3 PASS PASS PASS 4 4 4 PASS FAIL PASS Expected output: Status2 Status3 PASS FAIL FAIL PASS Current Output: Status1 Status2 Stat... | Use boolean indexing with any: df.loc[:, df.eq('FAIL').any()] # or for multiple words # the mask doesn't matter as long # as you have True/False df.loc[:, df.isin(words_to_keep).any()] Output: Status2 Status3 0 PASS FAIL 1 PASS PASS 2 PASS PASS 3 FAIL PASS How it works: df.eq('FAIL').any() Values1 False Values2 Fals... | 3 | 1 |
78,459,085 | 2024-5-10 | https://stackoverflow.com/questions/78459085/django-serializer-is-not-validating-or-saving-data | I am trying to save data in the database, it works for most of my models but for few models I am not sure why but django is not serializing data. I hope someone can point out where I might be doing wrong. Here is my code Django Models class UserModel(AbstractUser): uuid = models.UUIDField(default=uuid.uuid4, editable=F... | Use a ModelSerializer [drf-doc]. For a simple serializer, you will have to write the boilerplate code yourself: class UserTakeBreakSerializer(serializers.ModelSerializer): class Meta: model = UserWorkBreakModel fields = '__all__' essentially what happened was that you defined an empty serializer: a serializer with no f... | 2 | 1 |
78,458,478 | 2024-5-10 | https://stackoverflow.com/questions/78458478/customtkinter-adding-additional-input-fields-to-form | I am creating a program in Customtkinter where I want to the user to input their ingredients one ingredient at a time- ideally I want to have the text field and then they have the option to add additional text fields below the original while retaining the original. I didn't want to set a fixed number of fields as I won... | Add a button that creates a new entry field each time it's clicked: class root(ctk.CTk): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Your already existing code self.ingredientEntries = [] # The list that stores all the ingredient entries self.addButton = ctk.CTkButton(self.tabview.tab("New ... | 2 | 1 |
78,457,093 | 2024-5-9 | https://stackoverflow.com/questions/78457093/pandas-map-multiple-columns-with-a-filter | I have a dataframe like so (simplified for this example) Site LocationName Resource# 01 Test Name 5 01 Testing 6 02 California 10 02 Texas 11 ... Each site has their own mapping for LocationName and Resource# For example: Site 01 has a mapping of {'Test Name': 'Another Test', 'Testing': 'RandomLocation'} for Locatio... | Yes there is. You can use the map function within the apply method on your dataframe. import pandas as pd data = { 'Site': ['01', '01', '02', '02'], 'LocationName': ['Test Name', 'Testing', 'California', 'Texas'], 'Resource#': [5, 6, 10, 11] } df = pd.DataFrame(data) mappings = { '01': { 'LocationName': {'Test Name': '... | 2 | 1 |
78,457,898 | 2024-5-10 | https://stackoverflow.com/questions/78457898/im-getting-no-matching-distribution-error-when-pip-installing-sourcedefender-fo | I have to pip install dependencies after setting up a virtual environment for an intro python course and I'm getting an error message: ERROR: Could not find a version that satisfies the requirement sourcedefender==10.0.13 (from versions: 12.0.2, 12.0.3) ERROR: No matching distribution found for sourcedefender==10.0.13 ... | I can't seem to comment as I dont have enough reputation so I will leave my answer here. Sometimes the right answer is the most obvious one. Someone probably made a mistake or typo. or this version used to be hosted on pypi and was recently taken down. Do you know what version you installed for your previous assign... | 2 | 1 |
78,457,216 | 2024-5-9 | https://stackoverflow.com/questions/78457216/how-to-add-a-new-column-with-different-length-into-a-existing-dataframe | I am trying to go over a loop to add columns into a empty dataframe. each column might have a different length. Look like the final number of rows are defined by lenght of first column added. The columns with a Longer length will be cut values. How to always keep all the values of each column when column length are dif... | You can use pd.concat to add another Series, e.g.: # you have already this dataframe: df_profile = pd.DataFrame() df_profile["A"] = pd.Series([1, 2, 3, 4]) # you can use pd.concat to add another Series: out = pd.concat([df_profile, pd.Series([10, 20, 30, 40, 50, 60], name="B")], axis=1) print(out) Prints: A B 0 1.0 1... | 4 | 5 |
78,456,849 | 2024-5-9 | https://stackoverflow.com/questions/78456849/recursive-r-function-and-its-python-translation-behave-differently | Here is a recursive R function involving a matrix S from the parent environment: f <- function(m, k, n) { if(n == 0) { return(100) } if(m == 1) { return(0) } if(!is.na(S[m, n])) { return(S[m, n]) } s <- f(m-1, 1, n) i <- k while(i <= 5) { if(n > 2) { s <- s + f(m, i, n-1) } else { s <- s + f(m-1, 1, n-1) } i <- i + 1 }... | Side-effects such as a function modifying external state are a code smell. Your R code doesn't do this but your Python code does. Assignment to outer scope variables within a function scope can behave differently in R to Python (and actually within R and Python depending on whether the object is mutable). Instinctively... | 2 | 2 |
78,455,501 | 2024-5-9 | https://stackoverflow.com/questions/78455501/checking-for-false-when-variable-can-also-be-none-or-true | Update: please see my discussion if you want to delve further into this topic! Thank you everyone for your feedback on this! I have a boolean(ish) flag that can be True or False, with None as an additional valid value. Each value has a different meaning. (Edit for clarification: the variable in question, bool_flag is ... | If you really want to do it : if bool_flag is False: pass PEP8 is a guideline. There may be style checkers which whine about it, and you may need to litter your code with #noqa to quiet them, but at the end of the day you need to decide what best represents what you are actually trying to do. In this case specifically... | 4 | 3 |
78,455,345 | 2024-5-9 | https://stackoverflow.com/questions/78455345/segmentation-faults-and-memory-leaks-while-calling-gmp-c-functions-from-python | Work was quiet today, and so the team was directed to do some "self-development". I decided to have some fun calling C functions from Python. I had already had a good time using Rust to speed up Python, but I kept hitting a brick wall whenever I wanted to work with integers greater than the u128 type could hold. I thou... | Although it reaches the print() statements and prints the correct result, it then hits a segmentation fault. Your factorial function uses mpz_get_str() incorrectly. Consider: char *factorial(int n) { char *result; mpz_t result_mpz; _factorial(n, result_mpz); mpz_get_str(result, BASE, result_mpz); mpz_clear(result_... | 4 | 3 |
78,452,284 | 2024-5-9 | https://stackoverflow.com/questions/78452284/keyboardinterrupt-in-asyncio-taskgroup | The docs on Task Groups say: Two base exceptions are treated specially: If any task fails with KeyboardInterrupt or SystemExit, the task group still cancels the remaining tasks and waits for them, but then the initial KeyboardInterrupt or SystemExit is re-raised instead of ExceptionGroup or BaseExceptionGroup. This m... | TL;DR This acutally isn't TaskGroup's fault. Try running this: >>> async def other_task(): ... try: ... await asyncio.sleep(10) ... except KeyboardInterrupt: ... print("Stopped") >>> >>> asyncio.run(other_task()) KeyboardInterrupt >>> This also doesn't print. Nor this: >>> async def other_task(): ... try: ... await as... | 4 | -2 |
78,454,457 | 2024-5-9 | https://stackoverflow.com/questions/78454457/pandas-read-json-future-warning-the-behavior-of-to-datetime-with-unit-when | I am updating pandas version from 1.3.5 to 2.2.2 on an old project. I am not very familiar with pandas, and I am stuck with a Future Warning: FutureWarning: The behavior of 'to_datetime' with 'unit' when parsing strings is deprecated. In a future version, strings will be parsed as datetime strings, matching the behavio... | This error is due to having a mix of number-like and strings in the index. A minimal reproducible example that triggers the error would be: s = '{"A":{"0":"X","Y":"Y"}}' pandas.read_json(StringIO(s), typ='frame', orient='records') Pandas uses to_datetime to infer the dtype of the index, which triggers the warning. Thi... | 3 | 1 |
78,453,990 | 2024-5-9 | https://stackoverflow.com/questions/78453990/how-to-present-uint16-as-float16 | I have a buffer of float16 elements in the memory I read this buffer to a list but since I use np.ctypeslib I can't read it as float16 so I read it as uint16 and now I want to represent it as float16 simple convert by list.astype(float16) won't help I found this table https://gist.github.com/gregcotten/9911bda086c5850c... | I found a solution by numpy uint16_list.view(np.float16) | 2 | 1 |
78,454,058 | 2024-5-9 | https://stackoverflow.com/questions/78454058/getting-503-service-unavailable-while-running-haproxy-in-docker | I'm new to HAProxy. I'm trying to run my Python Service's Docker Image in multiple instances and use HAProxy to Balance the Load. (python service is running at 8090 via fastapi) Firstly, I've created docker image of my python service. Then I've created docker-compose.yml: version : '3' services: elb: image: haproxy por... | There is no need to specify ports for pythonapp1 and pythonapp2 in docker compose Your docker compose should look like: version : '3' services: elb: image: haproxy ports: - "8100:8100" volumes: - ./haproxy:/usr/local/etc/haproxy pythonapp1: image: craft-text-detection-python-service:0.0.1 pythonapp2: image: craft-text-... | 3 | 1 |
78,452,601 | 2024-5-9 | https://stackoverflow.com/questions/78452601/add-sha1-to-signxml-python | I am using the library signxml to sign XML signatures for SAML authentication. One of our implementer partners requires that we send the signature in SHA1. The base configuration of XMLSigner does not support SHA1 because it has been deprecated because SHA1 is not secure. Unfortunately I still have to send it as SHA1 b... | You can overwrite function check_deprecated_methods in source to pass the error. from signxml import XMLSigner class XMLSignerWithSHA1(XMLSigner): def check_deprecated_methods(self): pass Now, you can use class XMLSignerWithSHA1 to sign: signer = XMLSignerWithSHA1(signature_algorithm=SignatureMethod.RSA_SHA1, digest_a... | 2 | 2 |
78,451,352 | 2024-5-8 | https://stackoverflow.com/questions/78451352/passing-parameters-to-a-pytest-fixture-that-also-needs-cleanup | I've defined a fixture that accepts arguments to be used in an integration style test that requires some teardown upon completion. It looks something like this: @pytest.fixture def create_user_in_third_party(): from clients import third_party_client def _create_user_in_third_party(user: User): third_party_client.create... | Using the docs that Andrej linked above: https://docs.pytest.org/en/7.1.x/how-to/fixtures.html#factories-as-fixtures , we can use the factory pattern approach to accrue created entities and delete them later. So it ends up looking like this: @pytest.fixture def create_user_in_third_party(): from clients import third_pa... | 2 | 2 |
78,450,478 | 2024-5-8 | https://stackoverflow.com/questions/78450478/pandas-rolling-sum-within-a-group | I am trying to calculate a rolling sum or any other statistic (e.g. mean), within each group. Below I am giving an example where the window is 2 and the statistic is sum. df = pd.DataFrame.from_dict({'class': ['a', 'b', 'b', 'c', 'c', 'c', 'b', 'a', 'b'], 'val': [1, 2, 3, 4, 5, 6, 7, 8, 9]}) df['sum2_per_class'] = [1, ... | As the error message conveys, the rolling sum operation returns a pandas Series with a MultiIndex, which can't be directly assigned to a single column in a dataframe. A possible fix is to use reset_index() to convert the MultiIndex to a normal index like the following: df['sum2_per_class'] = df[['class', 'val']].groupb... | 2 | 3 |
78,450,557 | 2024-5-8 | https://stackoverflow.com/questions/78450557/how-can-i-pass-a-namedtuple-attribute-to-a-method-without-using-a-string | I'm trying to create a class to represent a list of named tuples and I'm having trouble with accessing elements by name. Here's an example: from typing import NamedTuple class Record(NamedTuple): id: int name: str age: int class NamedTupleList: def __init__(self, data): self._data = data def attempt_access(self, row, c... | Interesting question. The field is a descriptor, so you can invoke it: class NamedTupleList: def __init__(self, data): self._data = data def attempt_access(self, row, column): r = self._data[row] try: val = r[column] except TypeError: val = column.__get__(r) return val Demo: >>> class_data.attempt_access(0, 2) 30 >>> ... | 4 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.