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,570,018 | 2024-6-3 | https://stackoverflow.com/questions/78570018/bash-cannot-execute-required-file-not-found | I am having multiple problems with making my pythonscript dartsapp.py executable for my pi. At first i tried to use chmod +x dartsapp.py and ./dartsapp.py but i got the error: -bash: ./dartsapp.py: cannot execute: required file not found I also added the dir to PATH but still no luck. Afterwards i tried to use pyins... | head -n 3 dartsapp.py | cat -e outputs: #!/usr/bin/python3^M$ ^M$ # Python-App fM-CM-<r das PunktezM-CM-$hlen beim Darts^M$ and so those ^Ms at the end of each line tells us that dartsapp.py has DOS line endings, see linux-bash-shell-script-error-cannot-execute-required-file-not-found for more information on this spe... | 7 | 7 |
78,566,724 | 2024-6-2 | https://stackoverflow.com/questions/78566724/selecting-a-particular-set-of-strings-from-a-list-in-polars | df = pl.DataFrame({'list_column': [['a.xml', 'b.xml', 'c', 'd'], ['e.xml', 'f.xml', 'g', 'h']]}) def func(x): return [y for y in x if '.xml' in y] df.with_columns(pl.col('list_column').map_elements(func, return_dtype=pl.List(pl.String))) Is there a way to achieve the same without using map_elements? | There is an accepted request for list.filter() https://github.com/pola-rs/polars/issues/9189 You can emulate the behaviour using list.eval() df.with_columns( pl.col('list_column').list.eval( pl.element().filter(pl.element().str.ends_with('.xml')) ) ) shape: (2, 1) ┌────────────────────┐ │ list_column │ │ --- │ │ lis... | 2 | 2 |
78,565,591 | 2024-6-2 | https://stackoverflow.com/questions/78565591/load-jsonb-data-from-postgresql-to-pyspark-and-store-it-in-maptype | Products tables create and insert scripts: create table products (product_id varchar, description varchar, attributes jsonb, tax_rate decimal); insert into products values ('P1', 'Detergent', '{"cost": 45.50, "size": "10g"}', 5.0 ); insert into products values ('P2', 'Bread', '{"cost": 45.5, "size": "200g"}',3.5); I... | Short answer: You can't directly load a jsonb field into a MapType in Pyspark. Here's why: When you read data from a database using PySpark's JDBC data source, PySpark relies on the metadata provided by the JDBC driver to infer the data types of the columns. The JDBC driver maps database data types to Java data types, ... | 2 | 1 |
78,549,738 | 2024-5-29 | https://stackoverflow.com/questions/78549738/least-square-inaccurate-in-chemical-speciation | I'm having an issue using the least_squares function to solve a system of non-linear equation to obtain a chemical speciation (here of the system Nickel-ammonia). The system of equations is given here : def equations(x): Ni0, Ni1, Ni2, Ni3, Ni4, Ni5, Ni6, NH3 = x eq1 = np.log10(Ni1)-np.log10(Ni0)-np.log10(NH3)-K1 eq2 ... | Potential cause Optimization procedures in chemistry are inherently tricky because numbers involved span several decades leading to float errors and inaccuracies. You can see in your example than bounds are met but results are meaningless as they does not fulfill the mass balance (real constraint in eq7). Additionally ... | 4 | 3 |
78,564,771 | 2024-6-1 | https://stackoverflow.com/questions/78564771/alternative-to-df-renamecolumns-str-replace | I noticed that it's possible to use df.rename(columns=str.lower), but not df.rename(columns=str.replace(" ", "_")). Is this because it is allowed to use the variable which stores the method (str.lower), but it's not allowed to actually call the method (str.lower())? There is a similar question, why the error message o... | df.rename accepts a function object (or other callable). In the first case, str.lower is a function. However, str.replace(" ", "_") calls the function and evaluate to the result, although, in this case, the call is not correct so it raises an error. But you don't want to pass the result of calling the function, you wan... | 1 | 4 |
78,564,217 | 2024-6-1 | https://stackoverflow.com/questions/78564217/starting-container-process-caused-exec-fastapi-executable-file-not-found-in | I am trying to Dockerize my fastapi application, but it fails with the following error Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "fastapi": executable file not found in $PATH: unkn... | There's two things that are obvious problems in the setup you show. In the Compose file, you should delete: volumes: - ./navigation:/navigation This overwrites the /navigation directory in the image – everything the Dockerfile sets up other than the base image – with content from the host. That includes your virtual ... | 2 | 1 |
78,555,122 | 2024-5-30 | https://stackoverflow.com/questions/78555122/sqlalchemy-i-cant-execute-query-with-two-tables | My problem next: I can't execute query, where need to get list of Accounts with their Records by account_id as sum of Records. My query next: subq = ( select( func.sum(Record.amount).label('amount') ) .filter(Record.account_id == Account.uuid) .subquery() ) accounts = ( await self.session.execute( select(Account) .join... | I found the answer that solved my problem, this using join and mappings().all(): accounts = ( await self.session.execute( select( Account.uuid, Account.name, Account.creator_id, Account.is_private, func.coalesce(func.sum(Record.amount), 0).label('amount') ) .filter(Account.creator_id == uuid) .join(Record, Record.acco... | 2 | 0 |
78,561,796 | 2024-5-31 | https://stackoverflow.com/questions/78561796/cant-find-command-fastapi-for-python-on-msys2 | I want to make the Python fastapi work with MSYS2. I work from the MSYS2 MinGW x64 shell. I have the following installed using the commands: pacman -S mingw-w64-x86_64-python pacman -S mingw-w64-x86_64-python-pip pacman -S mingw-w64-x86_64-python-fastapi and I also ran pip install fastapi which gave the output imelf@... | fastapi doesn't ship with the CLI anymore by default, you can install it using pip install fastapi-cli | 1 | 5 |
78,552,387 | 2024-5-30 | https://stackoverflow.com/questions/78552387/optimizing-node-placement-in-a-2d-grid-to-match-specific-geodesic-distances | I'm working on a problem where I need to arrange a set of nodes within a 2D grid such that the distance between pairs of nodes either approximate specific values as closely as possible or meet a minimum threshold. In other words, for some node pairs, the distance should be approximately equal to a predefined value (≈).... | If you're not beholden to ortools, here is a solution using pyomo and HiGHS solver. Minimally, this might give you some insights on the correct ortools syntax to implement some of these types of constraints, if this formulation works. I'm not familiar w/ the ortools syntax, but this aligns with the context of what @Lau... | 3 | 1 |
78,561,392 | 2024-5-31 | https://stackoverflow.com/questions/78561392/how-to-substitute-each-regex-pattern-with-a-corresponding-item-from-a-list | I have a string that I want to do regex substitutions on: string = 'ptn, ptn; ptn + ptn' And a list of strings: array = ['ptn_sub1', 'ptn_sub2', '2', '2'] I want to replace each appearance of the regex pattern 'ptn' with a corresponding item from array. Desired result: 'ptn_sub1, ptn_sub2; 2 + 2' I tried using re.fin... | As stated, one just have to use the "callback" form of re.sub - but it is actually simple enough: import re string = 'ptn, ptn; ptn + ptn' array = ['ptn_sub1', 'ptn_sub2', '2', '2'] array_iter = iter(array) result = re.sub("ptn", lambda m: next(array_iter), string) | 2 | 3 |
78,558,385 | 2024-5-31 | https://stackoverflow.com/questions/78558385/python-sympy-partial-fraction-decomposition-result-not-as-expected | I am using the Python library Sympy to calculate the partial fraction decomposition of the following rational function: Z = (6.43369157032015e-9*s^3 + 1.35203404799555e-5*s^2 + 0.00357538393743079*s + 0.085)/(4.74334912634438e-11*s^4 + 4.09576274286244e-6*s^3 + 0.00334241812250921*s^2 + 0.15406018058983*s + 1.0) I am c... | The problem is to do with floats. Presumably something in the algorithm used by apart(full=True) or RootSum.doit() is numerically unstable for approximate coefficients. If you convert the coefficients to rational numbers before computing the RootSum then evalf gives the expected result: In [27]: apart(nsimplify(Z), ful... | 2 | 3 |
78,560,356 | 2024-5-31 | https://stackoverflow.com/questions/78560356/how-to-update-fields-with-previous-fields-value-in-polars | I have this dataframe: import polars as pl df = pl.DataFrame({ 'file':['a','a','a','a','b','b'], 'ru':['fe','fe','ev','ev','ba','br'], 'rt':[0,0,1,1,1,0], }) shape: (6, 3) ┌──────┬─────┬─────┐ │ file ┆ ru ┆ rt │ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 │ ╞══════╪═════╪═════╡ │ a ┆ fe ┆ 0 │ │ a ┆ fe ┆ 0 │ │ a ┆ ev ┆ 1 │ │... | Get first column values within each "file" group. This can be achieved using window functions (using pl.Expr.over in polars). df.with_columns( pl.col("ru").first().over("file"), pl.col("rt").first().over("file"), ) Polars also accepts multiple column names in pl.col and will evaluate the expressions independently of e... | 4 | 6 |
78,557,248 | 2024-5-30 | https://stackoverflow.com/questions/78557248/pandas-map-multiple-columns-based-on-specific-conditions | My organization uses special codes for various employee attributes. We are migrating to a new system and I have to map these codes to a new code based on certain logic. Here is my mappings df Mappings: State Old_Mgmt New_Mgmt Old_ID New_ID New_Site 01 A001 A100 0000 0101 123 01 A002 A100 0000 0102 01 A003 A105 0000 010... | Left-merge and update: EmployeeData.update(EmployeeData .rename(columns={'Management': 'Old_Mgmt', 'ID': 'Old_ID'}) .merge(Mappings.rename(columns={'New_Mgmt': 'Management', 'New_ID': 'ID', 'New_Site': 'Site'}), how='left', on=['State', 'Old_Mgmt', 'Old_ID'], suffixes=('_old', None)) .replace('', None)[EmployeeData.col... | 2 | 1 |
78,556,399 | 2024-5-30 | https://stackoverflow.com/questions/78556399/hide-pandas-column-headings-in-a-terminal-window-to-save-space-and-reduce-cognit | I am looping through the groups of a pandas groupby object to print the (sub)dataframe for each group. The headings are printed for each group. Here are some of the (sub)dataframes, with column headings "MMSI" and "ShipName": MMSI ShipName 15468 109080345 OYANES 3 [19%] 46643 109080345 OYANES 3 [18%] MMSI ShipName 199... | I don’t know about Styler, but you can print the data without headers like this. import pandas as pd df = pd.read_csv(r"/home/bera/GIS/data/Pandas_testdata/flights.csv") for month, subframe in df.groupby("month"): print(subframe.to_string(header=False)) print("\n") Output: 3 1949 April 129 15 1950 April 135 27 1951 Ap... | 3 | 2 |
78,552,542 | 2024-5-30 | https://stackoverflow.com/questions/78552542/how-to-decrypt-a-key-encrypted-using-the-sodium-r-package-in-python | I have he following R functions that use the sodium R package to encrypt and decrypt an access key with a password: encrypt_access_key <- function(access_key, password) { key <- sha256(charToRaw(password)) nonce <- random(24) # Generate a random nonce encrypted <- data_encrypt(charToRaw(access_key), key, nonce) list( e... | The R code for encryption derives the key from a password using SHA256 and performs authenticated encryption with SecretBox, which uses XSalsa20 and Poly1305 under the hood, see here. The result returns the (24 bytes) nonce and the concatenation of ciphertext and (16 bytes) tag separately. The posted Python code is not... | 1 | 4 |
78,555,894 | 2024-5-30 | https://stackoverflow.com/questions/78555894/find-all-columns-with-dateformat-in-dataframe | For the following df I would like to extract columns with "dates": import pandas as pd df = pd.DataFrame([["USD", 12.3, 1, 23.33, 33.1],["USD", 32.1, 2, 34.44, 23.1]],columns= ['currency', '1999-07-31', 'amount', '1999-10-31', '2000-01-31']) currency 1999-07-31 amount 1999-10-31 2000-01-31 USD 12.3 1 23.33 33.1... | You can't use select_dtypes in this context, this function filters based on the dtypes of the columns, not their names. You can however use pd.to_datetime with errors='coerce' and notna to form a boolean indexer: out = df.loc[:, pd.to_datetime(df.columns, errors='coerce', format='mixed') .notna()] Output: 1999-07-31 ... | 2 | 6 |
78,555,396 | 2024-5-30 | https://stackoverflow.com/questions/78555396/or-tools-cp-sat-python-example-terminates-after-creating-solver | I am new to Google OR-Tools and trying to start by running a basic example from OR-Tools example library found here https://github.com/google/or-tools/blob/stable/ortools/sat/samples/cp_sat_example.py. Every code example gets hung up on the same part after creating the solver. When I run the code I am not getting an ou... | Are you using or-tools 9.10 on windows ? If yes, check the known issues in the release notes: https://github.com/google/or-tools/releases You may need to update the visual studio redistributable libraries | 3 | 2 |
78,555,411 | 2024-5-30 | https://stackoverflow.com/questions/78555411/fillna-with-values-from-other-rows-with-matching-keys | In the dataframe I define below I want to use the features ID and ID2 to fill the cells of features val1 and val2 with values. I want all ID and ID2 cominations to have the same values for the features val1 and val2. df = pd.DataFrame({'ID':[0,0,0,1,1,1], 'DATE':['2021', '2022', '2023', '2021', '2022', '2023'], 'ID2':... | If need first non missing value per groups in columns val1 and val2 use GroupBy.transform with GroupBy.first: df[['val1','val2']] = df.groupby(['ID','ID2'])[['val1','val2']].transform('first') print (df) ID DATE ID2 val1 val2 val3 0 0 2021 23 NaN 55555.0 A 1 0 2022 34 200.0 66666.0 F 2 0 2023 54 300.0 77777.0 W 3 1 202... | 2 | 3 |
78,555,334 | 2024-5-30 | https://stackoverflow.com/questions/78555334/filter-a-pandas-dataframe-based-on-multiple-columns-with-a-corresponding-list-of | I have a DataFrame that looks a bit like this: A B C D ... G H I J 0 First First First First ... 0.412470 0.758011 0.066926 0.877992 1 First First First Third ... 0.007162 0.957042 0.601337 0.636086 2 First First Third First ... 0.956398 0.640909 0.602861 0.679656 3 First First Third Third ... 0.905421 0.199685 0.4713... | You need select columns by [[]] first for subset, compare by list and test if all values are Trues by DataFrame.all: expected = ['First', 'Third', 'First', 'Third'] rows = df[(df[['A', 'B', 'C', 'D']] == expected).all(axis=1)] print (rows) A B C D ... G H I J 5 First Third First Third ... 0.387706 0.247412 0.339593 0.4... | 2 | 3 |
78,554,950 | 2024-5-30 | https://stackoverflow.com/questions/78554950/polars-map-elements-doesnt-work-properly-with-isinstance | I have a polars dataframe with two columns, one contains lists of string and the other one string. I want to apply the following expression to both columns. However, for some reason isinstance(x, list) doesn't work properly. def process_column(column_name: str, alias_name: str) -> pl.Expr: return ( pl.col(column_name).... | I'd start by checking what is going on when applying pl.Expr.map_elements to a column of type List[pl.String] as follows. def check(x): print(x) return x df.with_columns( pl.col("lists").map_elements(check) ) shape: (2,) Series: '' [str] [ "hello" "World" ] shape: (3,) Series: '' [str] [ "polars" "IS" "fast" ] shape: ... | 2 | 2 |
78,554,836 | 2024-5-30 | https://stackoverflow.com/questions/78554836/group-by-specific-column-value-pandas | I have my dataframe set up like this Cus_ID Cus_Type Cost birthdate 123 Owner 50 01 Jan 1980 123 Spouse 50 10 Feb 1982 123 Father 300 01 Dec 1950 125 Owner 20 30 Jan 1990 125 Spouse 30 15 Jul 1994 125 Mother 100 06 Sep 1970 I am trying to do a groupby where I group by Cus_ID but return the cus_type ... | Sort the rows to have the Owner first or last, then use a custom groupby.agg: out = (df.sort_values(by='Cus_Type', key=lambda s: s.eq('Owner')) .groupby('Cus_ID', as_index=False) .agg({'Cus_Type': 'last', 'Cost': 'sum', 'birthdate': 'last'}) ) Another way that is more generic if you have many columns: d = dict.fromkey... | 2 | 2 |
78,551,982 | 2024-5-29 | https://stackoverflow.com/questions/78551982/why-is-unpacking-a-list-in-indexing-a-syntax-error-in-python-3-8-but-not-python | The following code import numpy as np x = np.arange(32).reshape(2,2,2,2,2) extra = [1 for _ in range(3)] print(x[*extra, 0, 0]) prints 28 as expected in Python 3.12 but results in the syntax error File "main.py", line 4 print(x[*extra, 0, 0]) ^ SyntaxError: invalid syntax in Python 3.8. Replacing the indexing with p... | This was a consequence of grammar changes in PEP 646 – Variadic Generics and somehow didn't get a mention in the changelog for 3.11. Minimal reproducer: $ python3.11 -c 'print({():42}[*()])' 42 $ python3.10 -c 'print({():42}[*()])' File "<string>", line 1 print({():42}[*()]) ^^^^^^^^^^^^ SyntaxError: invalid syntax. Pe... | 5 | 5 |
78,551,846 | 2024-5-29 | https://stackoverflow.com/questions/78551846/pandas-access-column-like-results-from-groupby-and-agg | I am using groupby and agg to summarize groups of dataframe rows. I summarize each group in terms of its count and size: >>> import pandas as pd >>> df = pd.DataFrame([ [ 1, 2, 3 ], [ 2, 3, 1 ], [ 3, 2, 1 ], [ 2, 1, 3 ], [ 1, 3, 2 ], [ 3, 3, 3 ] ], columns=['A','B','C'] ) >>> gbB = df.groupby('B',as_index=False) >>> Ca... | Don't use attributes to access the columns, this conflicts with the existing methods/properties. Go with indexing using square brackets: Cagg['count'] # 0 1 # 1 2 # 2 3 # Name: count, dtype: int64 Cagg['size'] # 0 1 # 1 2 # 2 3 # Name: size, dtype: int64 | 2 | 2 |
78,551,302 | 2024-5-29 | https://stackoverflow.com/questions/78551302/pandas-cannot-set-a-value-for-multiindex | It is not allowed to set a value for a MultiIndex. It works for the single index. Maybe becaause of the version of pandas. import pandas as pd df = pd.DataFrame() df.loc[('a', 'b'), 'col1'] = 1 print(df) KeyError: "None of [Index(['a', 'b'], dtype='object')] are in the [index]" | You can do either import pandas as pd index = pd.MultiIndex.from_tuples([], names=['level_1', 'level_2']) df = pd.DataFrame(columns=['col1'], index=index) df.loc[('a', 'b'), 'col1'] = 1 print(df) or import pandas as pd df = pd.DataFrame(columns=['col1'], index=pd.MultiIndex(levels=[[], []], codes=[[], []], names=['lev... | 2 | 2 |
78,546,847 | 2024-5-29 | https://stackoverflow.com/questions/78546847/how-do-you-get-the-stringvar-not-the-text-value-the-stringvar-itself-of-an-en | I'm trying to get the StringVar object associated with an Entry widget, but I can't figure out how. I found this question: get StringVar bound to Entry widget but none of the answers work for me. Both entry["textvariable"] and entry.cget("textvariable") return the name of the StringVar and not the StringVar itself (alt... | If you know the name of the variable, you can simply "create" a StringVar and set its parameter "name" to that name. This way you will simply get the variable you created earlier. So try this: ... string_name = entry["textvariable"] TheVarObjectYouNeed = var = tk.StringVar(name=string_name) print(f"The var {var} has a ... | 2 | 2 |
78,549,172 | 2024-5-29 | https://stackoverflow.com/questions/78549172/understanding-array-comparison-while-using-custom-data-types-with-numpy | i have a question regarding comparison with numpy arrays while using cusom data types. Here is my code: import numpy as np class Expr: def __add__(self, other): return Add(self, other) def __eq__(self, other): return Eq(self, other) class Variable(Expr): def __init__(self, name): self.name = name def __repr__(self): re... | == on arrays produces an output of boolean dtype. The result array physically cannot hold Eq instances; it can only hold booleans. Your Eq instances get converted to booleans, producing True, since that's the boolean value of any object that doesn't define __len__ or __bool__. If you want an array of Eq instances, you ... | 2 | 2 |
78,544,143 | 2024-5-28 | https://stackoverflow.com/questions/78544143/what-is-the-proper-way-to-handle-mypy-attr-defined-errors-due-to-transitions | MRE from transitions import Machine class TradingSystem: def __init__(self): self.machine = Machine(model=self, states=['RUNNING'], initial='RUNNING') def check_running(self) -> None: if self.is_RUNNING(): print("System is running") Example usage system = TradingSystem() system.check_running() Issue mypy transitions_... | The answer @Mark proposed won't work since transitions does not override already existing model attributes because that would be unexpected (mis)behaviour (as @Mark pointed out). If you enable logging, transitions will also tell you that: import logging logging.basicConfig(level=logging.DEBUG) The output should contai... | 2 | 1 |
78,518,903 | 2024-5-22 | https://stackoverflow.com/questions/78518903/reverse-flip-right-leftanti-diagonals-of-a-non-square-numpy-array | What I am after is Python code able to reverse the order of the values in each of the array anti-diagonals in a numpy array. I have already tried various combinations of np.rot90, np.fliplr, np.transpose, np.flipud but none is able to give me the original shape of the 5x3 array with all the anti-diagonals reversed. Any... | This one seems fairly fast, especially for wide matrices like your width=n=1920, height=m=1080 : def mirror(a): m, n = a.shape if m == n: return a.T.copy() if m > n: return mirror(a.T).T # Shear v = a.flatten() w = v[:-m].reshape((m, n-1)) # Flip the parallelogram w[:, m-1:] = w[::-1, m-1:] # Flip the triangles t = np.... | 9 | 2 |
78,537,075 | 2024-5-27 | https://stackoverflow.com/questions/78537075/why-is-dictint-int-incompatible-with-dictint-int-str | import typing a: dict[int, int] = {} b: dict[int, int | str] = a c: typing.Mapping[int, int | str] = a d: typing.Mapping[int | str, int] = a Pylance reports an error for b: dict[int, int | str] = a: Expression of type "dict[int, int]" is incompatible with declared type "dict[int, int | str]" "dict[int, int]" is incomp... | dict type was designed to be completely invariant on key and value. Hence when you assign dict[int, int] to dict[int, int | str], you make the type system raise errors. [1] Mapping type on the other hand wasn’t designed to be completely invariant but rather is invariant on key and covariant on value. Hence you can assi... | 29 | 29 |
78,515,406 | 2024-5-22 | https://stackoverflow.com/questions/78515406/changing-values-in-a-dataframe-under-growth-change-with-year-condition | Suppose I have sample = {"Location+Type": ["A", "A", "A", "A", "B", "B", "B", "B"], "Year": ["2010", "2011", "2012", "2013", "2010", "2011", "2012", "2013"], "Price": [1, 2, 1, 3, 1, 1, 1, 1]} df_sample = pd.DataFrame(data=sample) df_sample['pct_pop'] = df_sample['Price'].pct_change() df_sample.head(8) From say 2012, ... | Pandas Style We have 4 steps here that can be done using typical pandas tools: Sort data. Find where the percent change exceeds the limit. Calculate cumulative means. Replace the data with average values by masking. # Load data and define key variables data = pd.DataFrame({ 'Location+Type': ['A', 'A', 'A', 'A', 'B', ... | 3 | 1 |
78,542,042 | 2024-5-28 | https://stackoverflow.com/questions/78542042/cannot-install-chromadb-on-python3-12-3-alpine3-19-docker-image | I am trying to install python dependencies on a python:3.12.3-alpine3.19 Docker immage. When the requirements.txt file is processed I get the following error: 7.932 ERROR: Ignored the following versions that require a different python version: 0.5.12 Requires-Python >=3.7,<3.12; 0.5.13 Requires-Python >=3.7,<3.12; 1.21... | It seems that Chroma vector DB does not work (or not out of the box) with Alpine distributions of Python. I switched to Bookworm and was able to install Chroma and use it in the script running in my Docker container. | 2 | 2 |
78,540,724 | 2024-5-27 | https://stackoverflow.com/questions/78540724/how-to-convert-cugraph-directed-graph-to-undirected-to-run-mst | I'm trying to build MST from a directed graph by converting it to an undirected one. I followed cuGraph example here but getting NotImplementedError: Not supported for distributed graph. I tried doing G = cugraph.Graph(directed=False), but it still gave me an error. My code: columns_to_read = ['subject', 'object', 'pre... | cugraph does not currently have a multi-GPU (distributed) implementation of MST. This is the reason you are getting the NotImplementedError: Not supported for distributed graph message. The latest detail on what algorithms are supported for multi-GPU can be found here: https://docs.rapids.ai/api/cugraph/stable/graph_su... | 2 | 1 |
78,544,018 | 2024-5-28 | https://stackoverflow.com/questions/78544018/processing-csv-type-file-and-creating-new-output-using-python-or-awk | I have a file "linked_policies.txt" that looks like the following (small sample of data): 0000001G|11111111 0000002G|10000018 0000002G|10000320 0000002G|10000337 0000002G|10000343 101359B|10000018 101359B|16023380 504529A|10000018 504529A|15856008 504529A|16007139 504529A|16007151 504529A|16526483 620667G|16526483 0000... | OP has posted that the original awk answer (see 2nd half of this answer) ran for a few minutes and then ran out of memory (on a host with 23 GB of RAM). Here'a rewrite using 1-dimensional arrays: awk ' function get_customer (p, c, i, n) { n = split(pol_cus[p],c,",") for (i=1; i<=n; i++) get_policy(c[i]) } function get_... | 2 | 3 |
78,542,361 | 2024-5-28 | https://stackoverflow.com/questions/78542361/gekko-optimizer-converging-on-wrong-point | I am using the GEKKO optimization package (https://gekko.readthedocs.io/en/latest/index.html) in python. Since my problem sometimes includes integer variables I run with the following options to get optimization for a steady state mixed integer problem (APOPT): m.options.IMODE = 3 m.options.SOLVER = 1 The optimizer fi... | A contour plot verifies that there are two local maxima. Gekko solvers report local minima or maxima when the Karush Kuhn Tucker (KKT) conditions are satisfied. from gekko import GEKKO m = GEKKO(remote=False) # Define objective def obj(x1, x2): return x1*0.04824647331436083 + x2*0.1359023029124411 + x1*x2*(0.565957074... | 2 | 1 |
78,546,774 | 2024-5-28 | https://stackoverflow.com/questions/78546774/how-to-add-filename-to-polars-pl-scan-csv | I'm reading multiple files with Polars, but I want to add filename as identifier in a new column. #how to add filenames to polars lazy_dfs = (pl.scan_csv("data/file_*.tsv", separator="\t", has_header=False).fetch(n_rows= 500)) | You can take a couple of approaches here, if you are working off a local filesystem, then you can manually glob the files, add the column yourself, and concatenate the results. Polars concat + scan from pathlib import Path from tempfile import TemporaryDirectory from numpy.random import default_rng import polars as pl ... | 3 | 3 |
78,539,430 | 2024-5-27 | https://stackoverflow.com/questions/78539430/nearest-neighbor-for-list-of-arrays | `I have a list of arrays like this (in x, y coordinates): coordinates= array([[ 300, 2300], [ 670, 2360], [ 400, 2300]]), array([[1500, 1960], [1620, 2200], [1505, 1975]]), array([[ 980, 1965], [1060, 2240], [1100, 2250], [ 980, 1975]]), array([[ 565, 1940], [ 680, 2180], [ 570, 1945]])] I want the arrays to be sorted... | This looks like a traveling_salesman_problem. Compute the pairwise distance between all nodes, make the self distance NaN/Inf, then get the shortest path: from numpy import array import networkx as nx coordinates= [array([[ 300, 2300], [ 670, 2360], [ 400, 2300]]), array([[1500, 1960], [1620, 2200], [1505, 1975]]), arr... | 2 | 1 |
78,544,920 | 2024-5-28 | https://stackoverflow.com/questions/78544920/pywinauto-how-to-get-rid-of-delays-in-clicks | import time from pywinauto.application import Application import os #Installer path pycharm_exe = r"G:\Softwarewa\JetBrains PyCharm\JetBrains PyCharm Professional 2023.1 [FileCR]\JetBrains PyCharm Professional 2023.1\pycharm-professional-2023.1.exe" app = Application(backend="uia").start(pycharm_exe) # Wait for window ... | You need to modify global timings. See the bottom of this guide: https://pywinauto.readthedocs.io/en/latest/wait_long_operations.html#global-timings-for-all-actions But please be careful, especially about setting all timings to zero. It may affect reliability of the automation steps. Because often some time is needed t... | 3 | 1 |
78,516,686 | 2024-5-22 | https://stackoverflow.com/questions/78516686/calculation-of-the-rotation-matrix-between-two-coordinate-systems-with-python-in | I have a UR5 CB3 robotic arm that shall be trained to pick up watermelons. For that, I installed a camera that determines the location of the watermelon with respect to the TCP (or end effector / the gripping "hand"). This TCP coordinate system is called K1. I also know the location and orientation of the TCP with resp... | Well, guys, I solved it. Looks like the TCP position and orientation was calibrated wrong, before I started using this robot. The callibration was done on the robot itself, not in my code, so I could not find it directly. So my motions were actually correct, but the coordinate system K1 was not what I expected it to be... | 2 | 1 |
78,545,235 | 2024-5-28 | https://stackoverflow.com/questions/78545235/sorting-an-array-list-by-a-specific-item-in-an-array-attribute | I'm new to python/jmespath and am trying to sort the below students by their final grade in 2024. I'm sure I can come up with something in python to do it but was just wondering if there is any jmespath magic I can use. I have seen sort_by and know how to search/sort by simple attributes, but haven't yet found anything... | Assuming that you want to sort by the latest year (not specifically the value 2024), you could achieve it with this: jmespath.search("students | sort_by(@,&grades|max_by(@,&year).final)", data) That would result in: [{'id': 1, 'name': 'Joe', 'grades': [{'year': 2024, 'final': 85}, {'year': 2023, 'final': 73}]}, {'id':... | 2 | 3 |
78,541,706 | 2024-5-28 | https://stackoverflow.com/questions/78541706/how-to-computing-k-nearest-neighbors-from-rectangular-distance-matrix-i-e-sci | I want to calculate the k-nearest neighbors using either sklearn, scipy, or numpy but from a rectangular distance matrix that is output from scipy.spatial.distance.cdist. I have tried inputting into the kneighbors_graph and KNeighborsTransformer with metric="precomputed" but have not been successful. How can I achieve ... | Both kneighbors_graph and KNeighborsTransformer are intended to work for graphs within a single set of points; you are computing neighbors between two distinct arrays. I'm not aware of any built-in utility for this, but you could create such a graph manually using numpy and scipy routines. For example: import numpy as ... | 2 | 1 |
78,543,721 | 2024-5-28 | https://stackoverflow.com/questions/78543721/python-tkinter-with-oop-how-to-define-function-for-changing-button-attributes | I am learning Object Oriented Programming for Python using Tkinter. I want to create a Class for each type of widgets (right now considering only Buttons). I am passing the Button class to my main App class. Below is the code I have so far: import tkinter as tk from tkinter import ttk class Buttons: def __init__(self):... | There are many ways to perform this task, I've added comments inside the code for convenience reasons. import tkinter as tk from tkinter import ttk class MyButton(ttk.Button): def __init__(self, text, width, cmd, col, row): super().__init__() self.textvar = tk.StringVar() # create a StringVar object self.textvar.set(te... | 2 | 1 |
78,543,852 | 2024-5-28 | https://stackoverflow.com/questions/78543852/description-for-apirouter-in-fastapi | Suppose I have the following sample code: from fastapi import APIRouter, FastAPI router_one = APIRouter(tags=["users"]) router_two = APIRouter(tags=["products"]) app = FastAPI(description="## Description for whole application") @router_one.get("/users") async def fn1(): pass @router_one.post("/users") async def fn2(): ... | You can use the openapi_tags parameter of FastAPI class as below - from fastapi import APIRouter, FastAPI router_one = APIRouter(tags=["users"]) router_two = APIRouter(tags=["products"]) app = FastAPI( description="## Description for whole application", openapi_tags=[ {"name": "users", "description": "Operations with u... | 2 | 3 |
78,528,308 | 2024-5-24 | https://stackoverflow.com/questions/78528308/index-difference-is-not-working-in-the-pandas | I have the data for 1 year which is time series data hourly basis so few timestamps are missing in between them.The shape of this data is (8188, 3) sample data I have attached below. I am resampling timestamps according to my data duration which will generate all the timestamps of one year even which were missing in my... | pandas 2.2.1 Problem with resampling of non-uniform timestamps The issue is not with the code line you mentioned, but with your data. If you look at your time values, you will see that after a whole hour, a few seconds passed before a recording was made: '2023-05-22 02:00:04+00:00' - 4 seconds after 2:00 '2023-05-22 03... | 2 | 2 |
78,543,027 | 2024-5-28 | https://stackoverflow.com/questions/78543027/polars-how-to-drop-inf-rows | I have a polars dataframe containing some rows with infinite values (np.inf and -np.inf) which I'd like to drop. I am aware ofdrop_nans and drop_null but I don't see a similar drop_inf. As I want to handle nan values separately, I cannot just replace inf with nan and then call drop_nans. What's an idiomatic way of drop... | you can use DataFrame.filter() and Expr.is_infinite() to filter out rows you don't need: import numpy as np import polars as pl df = pl.DataFrame({ "a": [1, 2, 3, np.inf], "b": [1, 2, 3, 4] }) df.filter(~pl.col('a').is_infinite()) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ f64 ┆ i64 │ ╞═════╪═════╡ │ 1.0 ┆ 1 │ │ 2.0 ┆ 2 │... | 2 | 3 |
78,540,833 | 2024-5-27 | https://stackoverflow.com/questions/78540833/how-to-write-a-list-of-mixed-type-of-nested-elements-in-google-document-using-go | My first post here. My apologies in advance if I inadvertently break any rules. Prerequisites: Assume that I've created a Google service account, and obtained the credentials (JSON) file. I created a Google document, and I've its doc_ID available. My programming language is Python. Problem: Assume that I've a list of m... | Modification points: In your showing script, end_index_normal and start_index_normal are overwritten by another loop. In the case of deleteParagraphBullets, only one character is selected. Also, I guessed that in your situation, the last character might not be required to be included in createParagraphBullets. When t... | 2 | 2 |
78,525,287 | 2024-5-23 | https://stackoverflow.com/questions/78525287/flat-a-python-dict-containing-lists | I am trying to normalize a dictionary containing some lists. As an MVCE (Minimal, Verifiable, Complete Example), consider the following dictionary: test_dict = { 'name' : 'john', 'age' : 20, 'addresses' : [ { 'street': 'XXX', 'number': 123, 'complement' : [ 'HOUSE', 'NEAR MARKET' ] }, { 'street': 'YYY', 'number': 456, ... | It took me some time to get this right, but check this out. def flat(out, *kvs): match kvs: case []: yield out case (k, []), *kvs: yield from flat(out, *kvs) case (k, list(l)), *kvs: for v in l: yield from flat(out, (k, v), *kvs) case (_, dict(d)), *kvs: yield from flat(out, *d.items(), *kvs) case (k, v), *kvs: yield f... | 2 | 3 |
78,539,059 | 2024-5-27 | https://stackoverflow.com/questions/78539059/querying-root-main-tkinter-tcl-event-queue-depth | I have an application written with a tkinter UI that performs real world activities via a GPIO stack. As an example, imagine my application has a temperature probe that checks the room temp and then has an external hardware interface to the air conditioning to adjust the temperature output of the HVAC system. This is d... | There isn't really any way to know, unfortunately. At the point when you could ask the question, many event sources only know whether there is at least one event pending (that corresponds to a single OS event) and the system calls all are capable of accepting multiple events from the corresponding source at that point ... | 4 | 3 |
78,539,704 | 2024-5-27 | https://stackoverflow.com/questions/78539704/conda-update-flips-between-two-versions-of-the-same-package-from-the-same-channe | This is the continuation of my previous question. Now, with both channel_priority: flexible and channel_priority: strict, every conda update -n base --all flips between The following packages will be UPDATED: libarchive 3.7.2-h313118b_1 --> 3.7.4-haf234dc_0 zstd 1.5.5-h12be248_0 --> 1.5.6-h0ea2cb4_0 The following packa... | I cannot fully replicate the behavior that you are experiencing, so your mileage may vary with this solution. Conda has a config feature that allows you to pin package specs. This feature is still in beta according to the conda docs, so it may change in the future. First add the package pinning to your conda config: co... | 2 | 1 |
78,537,616 | 2024-5-27 | https://stackoverflow.com/questions/78537616/how-to-plot-rows-containing-nas-in-stacked-bar-chart-python | I am still an absolute beginner in python and I googled a lot to built code to make a stacked bar chart plot my df. I am using spyder and python 3.12 After some data preparation, I am left with this df: {'storage': {0: 'a', 2: 'a', 3: 'a', 4: 'b', 5: 'b'}, 'time': {0: '4h', 2: '4h', 3: '4h', 4: '4h', 5: '4h'}, 'Predict... | Since you are plotting the labels manually, an easy option is to add a continue in your loop when the height is null: for bar in bar_group: height = bar.get_height() if height == 0: continue text_x = bar.get_x() + bar.get_width() / 2 text_y = bar.get_y() + height / 2 ha = 'center' if height > 5 else 'left' va = 'cente... | 2 | 2 |
78,538,178 | 2024-5-27 | https://stackoverflow.com/questions/78538178/python-httpx-log-all-request-headers | How can I log all request headers of an httpx request? I use log level DEBUG nad response headers log fine but there are no request headers in the log. If it matters I'm using async api of httpx lib. | Use custom event hooks: import httpx import logging logging.basicConfig(level=logging.DEBUG) async def log_request(request): logging.debug(f"Request headers: {request.headers}") async with httpx.AsyncClient(event_hooks={'request': [log_request]}) as client: response = await client.get('https://httpbin.org/get') | 2 | 2 |
78,535,999 | 2024-5-26 | https://stackoverflow.com/questions/78535999/how-to-reorganize-data-to-correctly-lineplot-in-python | I have the following code that plots ydata vs xdata which is supposed to be a circle. The plot has two subplots -- a lineplot with markers and a scatter plot. import matplotlib.pyplot as plt xdata = [-1.9987069285852805, -1.955030386765729, -1.955030386765729, -1.8259096357678795, -1.8259096357678795, -1.61698787200044... | If the xy coordinates have a consistent zig-zag pattern (odd/even), you could do : def unzigzag(data): data = list(data) # just in case return data[::2] + data[::-2] + [data[0]] ax1.plot(*map(unzigzag, [xdata, ydata]), "bo-") NB: This plot is annotated with the physical position (starting from 1) of x/y in their lists... | 2 | 4 |
78,536,677 | 2024-5-26 | https://stackoverflow.com/questions/78536677/what-is-the-magic-behind-dataclass-decorator-type-hint-of-dataclasses-module | I'm trying to deepen my understanding of how Python's dataclasses module works, particularly the role of type hints in defining class attributes. When I define a dataclass like this: from dataclasses import dataclass @dataclass class Person: name: str age: int I notice that the type hints (str for name and int for age... | [sqlalchemy] no attributes appear either Well, there aren't any type hints involved. Rather we're assigning Column objects to those names, and each such object is storing a certain sql type (not a hint, not an annotation). the type hints ... are used by the dataclass decorator Yes. It accesses them via an API call.... | 3 | 1 |
78,532,738 | 2024-5-25 | https://stackoverflow.com/questions/78532738/how-can-i-optimize-the-code-of-inversion-mask-in-pygame | And so, I wrote a test function to invert an image in a specific area and shape with the ability to change the location and size. The only problem is that the larger the size of the mask, the slower the mask moves or enlarges. Are there any solutions to speed up the code? import pygame fps = pygame.time.Clock() pygame.... | You can achieve what you want with Pygame functions alone and without for loops: Use pygame.mask.from_surface and pygame.mask.Mask.to_surface to prepare the mask. The mask must consist of two colors, opaque white (255, 255, 255, 255) and transparent black (0, 0, 0, 0): mask = pygame.mask.from_surface(inversionMaskIma... | 3 | 2 |
78,535,203 | 2024-5-26 | https://stackoverflow.com/questions/78535203/find-one-value-between-two-lists-of-dicts-then-find-another-same-value-based-on | This is my code: from collections import defaultdict ip_port_device = [ {'ip': '192.168.1.140', 'port_number': 4, 'device_name': 'device1'}, {'ip': '192.168.1.128', 'port_number': 8, 'device_name': 'device1'}, {'ip': '192.168.1.56', 'port_number': 14, 'device_name': 'device1'}, {'ip': '192.168.1.61', 'port_number': 4,... | # loop both lists to match nodes with port_number and device_name for item in ip_port_device: for node in ip_per_node: if item["ip"] == node["ip_address"]: node.update( { "port_number": item["port_number"], "device_name": item["device_name"], "ips": [item["ip"]], } ) # loop both lists again to get ips that have no dire... | 2 | 1 |
78,524,575 | 2024-5-23 | https://stackoverflow.com/questions/78524575/importerror-cannot-import-name-get-column-indices-from-sklearn-utils | I am getting an import Error when trying to import imblearn.over_sampling for RandomOverSampler. I believe the issue is not with my code but with the libraries clashing, I'm not sure though. import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn.preprocessing import StandardScaler #actually... | This is a known issue (https://github.com/scikit-learn-contrib/imbalanced-learn/issues/1081#issuecomment-2127245933). You can either pip install git+https://github.com/scikit-learn-contrib/imbalanced-learn.git@master or downgrade scikit-learn to 1.5. | 3 | 0 |
78,530,673 | 2024-5-24 | https://stackoverflow.com/questions/78530673/how-to-update-the-text-of-a-list-element-within-a-ctklistbox | I am writing mass spec data reduction software. I want to provide the user with a list of all samples in the current sequence, next to a check box to show whether the analysis data has been reduced (viewing the analysis reduces the data). The user should be able to click on a sample in the list to jump to it, or use bu... | The solution was to only use insert, not delete. I also needed to unbind and rebind the listbox with every change. It also gave buggy behavior while using globals so I switched to passing the variables properly. Here's the updated code: # highlights the current analysis in the list def highlight_current_analysis(analys... | 2 | 1 |
78,534,210 | 2024-5-26 | https://stackoverflow.com/questions/78534210/plotly-convert-epoch-timestamps-with-ms-to-readable-datetimes | The below code uses Python lists to create a Plotly graph. The timestamps are Epoch milliseconds. How do I format the x-axis to readable datetime? I tried fig.layout['xaxis_tickformat'] = '%HH-%MM-%SS' but it didn't work. import plotly.graph_objects as go time_series = [1716693661000, 1716693662000, 1716693663000, 1716... | You can use fromtimestamp().strftime() from datetime: tdt = [datetime.fromtimestamp(ts / 1000).strftime('%Y-%m-%d %H:%M:%S') for ts in time_series] Code time_series = [1716693661000, 1716693662000, 1716693663000, 1716693664000] prices = [20, 45, 32, 19] tdt = [datetime.fromtimestamp(ts / 1000).strftime('%Y-%m-%d %H:%... | 2 | 1 |
78,534,106 | 2024-5-26 | https://stackoverflow.com/questions/78534106/how-to-decorate-instance-methods-and-avoid-sharing-closure-environment-between-i | I'm having trouble finding a solution to this problem. Whenever we decorate a method of a class, the method is not yet bound to any instance, so say we have: from functools import wraps def decorator(f): closure_variable = 0 @wraps(f) def wrapper(*args, **kwargs): nonlocal closure_variable closure_variable += 1 print(c... | In order to avoid sharing the cache across all instances, which may not be required or desired, it is best to have a cache for each instance with expiry time, etc. In other words, we don't need to have a "single source cache" for all instances. In the following implementation, each and every instance of a class initial... | 2 | 2 |
78,530,805 | 2024-5-24 | https://stackoverflow.com/questions/78530805/function-to-swap-top-right-and-bottom-left-squares-in-an-n-x-n-matrix | Given an n x n matrix, swap elements situated in two squares : top right and bottom left. As it is more an academic task, we can restrict size to 10x10. Moreover, we can't have extra space and must swap it in place. F.e. you are given: 0 3 1 2 9 2 3 4 5 6 5 7 7 8 9 9 You need to return: 0 3 5 6 9 2 7 8 1 2 5 7 3 4 9 9... | You don't need a loop, but with a (nested) loop you can avoid having an extra copy of part of the array temporarily, which can matter if your array is enormous and you have memory restrictions that matter. Note: in a comment, you noted that you couldn't use numpy, something that I missed about your question. I've added... | 3 | 3 |
78,530,503 | 2024-5-24 | https://stackoverflow.com/questions/78530503/solving-coupled-2nd-order-ode-numerical-in-python | I would like to solve the following DGL system numerically in python: The procedure should be the same as always. I have 2 coupled differential equations of the 2nd order and I use the substitution g' = v and f' = u to create four coupled differential equations of the 1st order. Here ist my code: from scipy.integrate... | Although you could try a "shooting" method using initial-value solvers, I find it best to go for a boundary-value problem directly. I do so by a method akin to the finite-volume method in computational fluid mechanics (CFD). Division by r creates singularities, so start by multiplying your equations by r2. Collecting t... | 2 | 7 |
78,531,808 | 2024-5-25 | https://stackoverflow.com/questions/78531808/sqlalchemy-and-postgresql-unexpected-timestamp-with-onupdate-func-now | In the following code after 5 seconds sleep I expect the second part of date_updated to be changed, but only the millisecond part is changed. If I use database_url = 'sqlite:///:memory:' it works as expected. Why? class Base(MappedAsDataclass, DeclarativeBase): pass class Test(Base): __tablename__ = 'test' test_id: Map... | PostgreSQL's now() function returns the time of the start of the current transaction. In the code in the question, the second transaction is triggered by the print statement, since a new transaction must be opened to retrieve the values expired by the previous commit. Thus the difference in the observed timestamps is o... | 3 | 4 |
78,526,105 | 2024-5-24 | https://stackoverflow.com/questions/78526105/is-there-a-compact-f-string-expression-for-printing-non-str-object-with-space-fo | f-string allows a very compact expression for printing str objects with spacing like so: a = "Hello" print(f'{a=:>20}') a= Hello Is there a way to do the same for other objects like so: from pathlib import Path b=Path.cwd() print(f'{b=:>20}') Traceback (most recent call last): File "/usr/lib/python3.10/idlelib/run.py"... | You can use !s and !r: >>> b = Path("/var") >>> f"{b=!s:>20}" 'b= /var' >>> f"{b=!r:>20}" "b= PosixPath('/var')" These are explicit conversion flags. To tabulate a namespace of keys and values: >>> d {'project': PosixPath('/home/user/project'), 'project_a': PosixPath('/home/user/project/project'), 'longer': PosixPath... | 3 | 3 |
78,531,096 | 2024-5-25 | https://stackoverflow.com/questions/78531096/how-to-get-the-maximum-number-of-consecutive-columns-with-values-above-zero-for | In a dataframe with 12 columns and 4 million rows, I need to add a column that gets the maximum number of consecutive columns with values above zero for each row. Here's a sample df = pd.DataFrame(np.array([[284.77, 234.37, 243.8, 84.36, 0., 0., 0., 55.04, 228.2, 181.97, 0., 0.], [13.78, 0., 38.58, 33.16, 0., 38.04, 74... | If performance is concern I'd consider to use numba: from numba import njit, prange @njit(parallel=True) def get_max(matrix, out): n, m = matrix.shape for row in prange(n): mx, cnt = 0, 0 for col in range(m - 1): # -1 because last column is OUT if matrix[row, col] > 0: cnt += 1 mx = max(mx, cnt) else: cnt = 0 out[row] ... | 3 | 3 |
78,530,305 | 2024-5-24 | https://stackoverflow.com/questions/78530305/python-how-can-i-call-the-original-of-an-overloaded-method | Let's say I have this: class MyPackage ( dict ) : def __init__ ( self ) : super().__init__() def __setitem__ ( self, key, value ) : raise NotImplementedError( "use set()" ) def __getitem__ ( self, key ) : raise NotImplementedError( "use get()" ) def set ( self, key, value ) : # some magic self[key] = value def get ( se... | You already have the solution in your code: use super(). This allows you to call methods on the parent class, in this case, dict: def set ( self, key, value ) : # some magic super().__setitem__(key, value) def get ( self, key ) : # some magic if not key in self.keys() : return "no!" return super().__getitem__(key) | 2 | 2 |
78,524,556 | 2024-5-23 | https://stackoverflow.com/questions/78524556/typeerror-cannot-convert-numpy-ndarray-to-numpy-ndarray | I'm not sure why but after getting a new install of windows and a new pycharm install I am having issues with running some previously functional code. I am now getting the above error with the code below. Is it a setup issue or has something changed that now makes this code not function? Error happens on the last line.... | I just had the same error today and solved it by updating numpy to 2.0.0rc2. | 2 | 4 |
78,529,922 | 2024-5-24 | https://stackoverflow.com/questions/78529922/dataframe-print-entire-row-s-where-keys-in-the-same-row-hold-equal-values | I would like to recovery the rows in a dataframe where, in the same row, differing keys hold equal values. I can display where, for instance, the rows where col2 == col3. I would like to get this code to track across col1 matching across col2, col3 and col4. Then col2 to match across col 3 and col4. Then finally col3 a... | Use nunique with axis=1 and compare it to the number of columns: import pandas as pd rows = { "col1": ["5412", "5148", "5800", "2122", "5645", "1060", "4801", "1039"], "col2": ["542", "512", "541", "412", "565", "562", "645", "152"], "col3": ["542", "3120", "3410", "2112", "5650", "5620", "4801", "152"], "col4": ["5800... | 2 | 4 |
78,525,821 | 2024-5-23 | https://stackoverflow.com/questions/78525821/handling-c2016-error-on-windows-using-visual-studio-code | I have to use someone else's C header files, which include empty structs. I have no control over these headers or I would change them as empty structs are not conventional C. The structs are throwing C2016 errors, as expected with the standard compiler in Visual Studio Code (on Windows). The original author of the head... | Visual studio will refuse to compile that, as it doesn't allow zero size structs in C, you need to use gcc instead to build that library. if you must use MSVC then you need to modify those structs to contain a simple char which is what gcc does, and hope that no one is depending on their size in the code. typedef struc... | 2 | 3 |
78,529,845 | 2024-5-24 | https://stackoverflow.com/questions/78529845/stop-process-from-another-process | Hi guys I have two different processes running at the same time. I'm trying to stop the other process which i have named loop_b but I have only managed to stop the current process and the other doesn't stop from multiprocessing import Process import time import sys counter=0 def loop_a(): global counter while True: pri... | One possible solution could be using multiprocessing.Event synchronization primitive to signal other process that it should exit, e.g.: import sys import time from multiprocessing import Event, Process def loop_a(evt): counter = 0 while True: print("a") time.sleep(1) counter += 1 if counter == 3: print("I want to stop ... | 2 | 2 |
78,525,564 | 2024-5-23 | https://stackoverflow.com/questions/78525564/find-matching-rows-in-dataframes-based-on-number-of-matching-items | I have two topic models, topics1 and topics2. They were created from very similar but different datasets. As a result, the words representing each topic/cluster as well as the topic numbers will be different for each dataset. A toy example looks like: import pandas as pd topics1 = pd.DataFrame({'topic_num':[1,2,3], 'wo... | You will have to compute all combinations in any case. You could use sets and broadcast the comparisons: # set the topic_num as index # convert the Series of lists to Series of sets s1 = topics1.set_index('topic_num')['words'].map(set) s2 = topics2.set_index('topic_num')['words'].map(set) # convert to numpy arrays # br... | 2 | 1 |
78,525,945 | 2024-5-23 | https://stackoverflow.com/questions/78525945/fit-same-model-to-many-datasets-in-python | Below I demonstrate a workflow for fitting the same model to many datasets in R by nesting datasets by test_id, and then fitting the same model to each dataset, and extracting a statistic from each model. My goal is to create the equivalent workflow in Python, using polars, but I will use pandas if necessary. Demonstra... | smf.glm() appears to want a Pandas DataFrame and the given formula can refer to column names. data = pd.DataFrame(dict(events=[630], fails=[370], recipe=["A"])) (smf.glm("events + fails ~ recipe", family=sm.families.Binomial(), data=data) .fit().pvalues) # Intercept 4.448408e-16 # dtype: float64 Struct When you pass a... | 2 | 3 |
78,523,591 | 2024-5-23 | https://stackoverflow.com/questions/78523591/how-to-connect-data-points-with-line-where-values-are-missing | I need to draw several biomarker changes by Date on one graph, but biomarker samples were measured in different dates and different times, so for example: data = { 'PatientID': [244651, 244651, 244651, 244651, 244652, 244653, 244651], 'LocationType': ['IP', 'IP', 'OP', 'IP', 'IP', 'OP', 'IP'], 'Date': ['2023-01-01', '2... | You can replace the code creating the plot with the following: # Plot all biomarkers plt.figure(figsize=(12, 8)) # Loop through each biomarker column to plot each one separately for column in filtered_df.columns: if column not in ['PatientID', 'LocationType']: biomarker = filtered_df[column].dropna() plt.plot(biomarker... | 2 | 1 |
78,527,843 | 2024-5-24 | https://stackoverflow.com/questions/78527843/des3-encryption-result-on-python-is-different-from-des-ede3-cbc-result-of-php | PHP code // php 8.1.13 $text = '1'; $key = base64_decode('3pKtqxNOolyBoJouXWwVYw=='); $iv = base64_decode('O99EDNAif90='); $encrypted = openssl_encrypt($text, 'des-ede3-cbc', $key, OPENSSL_RAW_DATA, $iv); $hex = strtoupper(bin2hex($encrypted)); echo $hex; The result is FF72E6D454B84A7C Python3.8 pycryptodome 3.20.0 im... | The reason for the different results is that different TripleDES variants are used in both codes. des-ede3-cbc in the PHP code specifies 3TDEA, which requires a 24 bytes key. Since the key used is only 16 bytes in size, PHP/OpenSSL silently pads it with 0x00 values to the required size of 24 bytes. With PyCryptodome, t... | 2 | 3 |
78,522,031 | 2024-5-23 | https://stackoverflow.com/questions/78522031/gaussian-fit-with-gap-in-data | I would like to fit a gaussian on an absorption band, in a reflectance spectra. Problem is, in this part of the spectra I have a gap in my data (blank space on the figure), between approximately 0.85 and 1.3 µm. I really need this gaussian, because after this I would like to compute spectral parameters such as the Full... | As lastchance said and as my comment suggested, you were fitting the wrong curve (or your initial guess was not compatible). The function that you wrote was a normal Gaussian and not a subtracted one. So the following can be used import numpy as np %matplotlib notebook import matplotlib.pyplot as plt from scipy.optimiz... | 2 | 2 |
78,526,797 | 2024-5-24 | https://stackoverflow.com/questions/78526797/how-to-distribute-pandas-dataframe-rows-unevenly-across-timestamps-based-on-valu | E.g. DF which contains number of executions across timestamps. DateTime Execution 0 2023-04-03 07:00:00 11 1 2023-04-03 11:00:00 1 2 2023-04-03 12:00:00 1 3 2023-04-03 14:00:00 3 4 2023-04-03 18:00:00 1 <class 'pandas.core.frame.DataFrame'> RangeIndex: 5080 entries, 0 to 5079 Below is the output I'm trying to achieve... | With asfreq/clip : N, C = 4, "Execution" asfreq = df.set_index("DateTime").asfreq("h") out = ( (gby:=asfreq.groupby(asfreq[C].notna().cumsum()))[C] .transform("first") .sub(gby.cumcount() * N) .clip(upper=N) .loc[lambda s: s.gt(0)] .reset_index(name=C) .convert_dtypes() ) Output : DateTime Execution 0 2023-04-03 07:0... | 4 | 7 |
78,516,650 | 2024-5-22 | https://stackoverflow.com/questions/78516650/perform-aggregation-using-min-max-avg-on-all-columns | I have a dataframe like ┌─────────────────────┬───────────┬───────────┬───────────┬───────────┬──────┐ │ ts ┆ 646150 ┆ 646151 ┆ 646154 ┆ 646153 ┆ week │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ datetime[μs] ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ i8 │ ╞═════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪══════╡ │ 20... | you can do something like this to get struct-typed columns: df.group_by("week").agg( pl.struct( pl.col(c).min().alias("min"), pl.col(c).max().alias("max"), pl.col(c).mean().alias("mean") ).alias(c) for c in df.columns if c not in ('week', 'ts') ) ┌──────┬───────────────────────────┬───────────────────────────┬─────────... | 4 | 4 |
78,525,590 | 2024-5-23 | https://stackoverflow.com/questions/78525590/tensorflow-model-cant-predict-on-polars-dataframe | I trained a TensorFlow model for text classification, but I can't use a Polars DataFrame to make my predictions on it. However, I can use a Pandas DataFrame. import pandas as pd import polars as pl import joblib from tensorflow.keras.models import load_model loaded_model =load_model('model.keras') load_Le = joblib.load... | As of late 2023, there were no plans to make Polars dataframes compatible with TensorFlow. In the meantime you can convert polar frames to pandas with the to_pandas() member and pass those to the models. | 2 | 1 |
78,525,518 | 2024-5-23 | https://stackoverflow.com/questions/78525518/python-pandas-create-lookup-table-of-items-bought-together | I'm struggling a bit trying to create a lookup table of items that are bought together. I have a solution in "brute force" Python iterating over a DataFrame, but I'd prefer one in pure Pandas using some kind of aggregate trick if possible. Here is what I have. I've made a small example with a list of invoice numbers an... | You can also do a self join and filter down: import pandas as pd df = pd.DataFrame({ "Invoice": [1, 1, 2, 3, 4, 4, 4, 5, 5], "Item": ["Apple", "Pear", "Banana", "Apple", "Apple", "Orange", "Pear", "Apple", "Orange"] }) lookup_table = ( df.merge(df, on='Invoice') .rename(columns={'Item_x': 'key', 'Item_y': 'value'}) .lo... | 2 | 2 |
78,523,337 | 2024-5-23 | https://stackoverflow.com/questions/78523337/how-is-it-possible-that-rpy2-is-altering-the-values-within-my-dataframe | I am trying to utilize some R based packages within a Python script using the rpy2 package. In order to implement the code, I first need to convert a Pandas dataframe into an R based data matrix. However, something incredibly strange is happening to the values within the code. Here is a minimally reproducible example o... | Your column is being coerced to a factor and then numeric When in Python you do df = df.replace(np.nan, "NA"), you are replacing with the literal string "NA". That means that the "NA" values are then stored as an object rather than float64. Unlike pandas, R does not have an object type. Columns (or vectors in R) need t... | 2 | 2 |
78,524,354 | 2024-5-23 | https://stackoverflow.com/questions/78524354/polars-for-processing-search-terms-in-text-data | I have a Python script that loads search terms from a JSON file and processes a Pandas DataFrame to add new columns indicating whether certain terms are present in the text data. However, I would like to modify the script to use Polars instead of Pandas and possibly remove the JSON dependency. Here is my original code:... | For non-regex matching, .str.contains_any() is probably a better option. It seems like you want to concat both lists: word_list = pl.read_json("word_list.json") """ for older versions without struct "*" expansion type1 = pl.concat_list( pl.col("type1").struct.field("words", "exact_phrases") ) """ word_list = word_list.... | 2 | 1 |
78,523,521 | 2024-5-23 | https://stackoverflow.com/questions/78523521/is-this-still-an-uncontrolled-command-line-which-can-execute-malicious-code | import os command = "conda run -n python3.5 python generate_handwriting.py -text '{}' -style {} -bias {} -stroke_color '{}' -stroke_width {} -output '{}'".format(text, style, bias, stroke_color, stroke_width, output_filename) os.system(command) I get the variables, for example text, directly from the user. I've been n... | Shell Injection The subprocess.run command, as opposed to os.system, doesn't allow for arbitrary shell execution, like redirections or multiple commands in one string, by default. You'd have to explicitely set shell=True for that. Also, you're putting the arguments in a list, which is pretty much the Python equivalent ... | 3 | 1 |
78,522,213 | 2024-5-23 | https://stackoverflow.com/questions/78522213/how-to-use-elements-created-in-a-kivy-file-to-create-another-element-in-another | I'm creating a button in StackLayout in file info_options.kv. Now I want to call a function in class InfoOptionsPanel whenever this button is pressed. I'm able to call this funtion when I'm replacing return MainPanel() with return InfoOptionsPanel() i.e. when I'm not using the layout created by MainPanel, but when I'm ... | You don't need to inherit from Kivy's layout classes in both main.py and kivy files. Either remove inheritance from main.py or from your kivy files. For main.py, class InfoPanel(): # don't inherit from BoxLayout pass class InfoOptionsPanel(): # don't inherit from StackLayout def on_press(self): print("Button pressed\n"... | 2 | 1 |
78,522,329 | 2024-5-23 | https://stackoverflow.com/questions/78522329/how-to-distribute-pandas-dataframe-rows-evenly-across-timestamps-based-on-value | E.g. DF which contains number of executions across timestamps. DateTime Execution 0 2023-04-03 07:00:00 4 1 2023-04-03 10:00:00 1 2 2023-04-03 12:00:00 1 3 2023-04-03 14:00:00 1 4 2023-04-03 18:00:00 1 <class 'pandas.core.frame.DataFrame'> RangeIndex: 5080 entries, 0 to 5079 Below is the output I'm trying to achieve ... | Use Index.repeat with DataFrame.loc for repeat rows, set 1 and add hours by to_timedelta with GroupBy.cumcount: #if string repr of datetimes df['DateTime'] = pd.to_datetime(df['DateTime']) out = (df.loc[df.index.repeat(df['Execution'])] .assign(Execution=1, DateTime = lambda x: x['DateTime'] + pd.to_timedelta(x.groupby... | 3 | 1 |
78,519,636 | 2024-5-22 | https://stackoverflow.com/questions/78519636/lookup-by-datetime-in-timestamp-index-does-not-work | Consider a date-indexed DataFrame: d0 = datetime.date(2024,5,5) d1 = datetime.date(2024,5,10) df0 = pd.DataFrame({"a":[1,2],"b":[10,None],"c":list("xy")}, index=[d0,d1]) df0.index Index([2024-05-05, 2024-05-10], dtype='object') Note that df0.index.dtype is object. Now, lookup works for date: df0.loc[d0] a 1 b 10.0 c x... | Looking at the source code it's how pandas implements .loc for DateTimeIndex: https://github.com/pandas-dev/pandas/blob/d9cdd2ee5a58015ef6f4d15c7226110c9aab8140/pandas/core/indexes/datetimes.py#L596 It's implemented for: datetime.datetime and np.datetime64 - https://github.com/pandas-dev/pandas/blob/d9cdd2ee5a58015e... | 2 | 2 |
78,519,562 | 2024-5-22 | https://stackoverflow.com/questions/78519562/can-we-print-a-text-only-once-that-is-inside-a-loop-without-making-it-print-agai | I am trying to make a countdown. Now when I use a while loop to achieve that, I also need to print count down, but what happens is that the countdown takes place in separate lines printing the text over and over again. I want the loop to print the text only once but keep changing the value of countdown until countdown ... | I am posting the answer from the comments: clearing = True countdown = 3 while clearing: while countdown > 0: print(f"Clearing console in {countdown} second(s)", end='\r', flush=True) time.sleep(1) countdown -= 1 os.system('clear') clearing = False I also found another way to achieve this effect: clearing = True coun... | 2 | 0 |
78,519,106 | 2024-5-22 | https://stackoverflow.com/questions/78519106/dataframe-replace-nan-whith-random-in-range | I have a Dataframe in Python whith NaN, as this: import pandas as pd details = { 'info1' : [10,None,None,None,None,None,15,None,None,None,5], 'info2' : [15,None,None,None,10,None,None,None,None,None,20], } df = pd.DataFrame(details) print(df) info1 info2 0 10 15 1 nan nan 2 nan nan 3 nan nan 4 nan 10 ... | For a vectorial solution, directly call np.random.uniform with the ffill/bfill as boundaries: import numpy as np df[:] = np.random.uniform(df.ffill(), df.bfill()) Output (with np.random.seed(0)): info1 info2 0 10.000000 15.000000 1 13.013817 12.275584 2 12.118274 11.770529 3 12.187936 10.541135 4 14.818314 10.000000 ... | 2 | 2 |
78,515,954 | 2024-5-22 | https://stackoverflow.com/questions/78515954/suppressing-recommendations-on-attributeerror-python-3-12 | I like to use __getattr__ to give objects optional properties while avoiding issues with None. This is a simple example: from typing import Any class CelestialBody: def __init__(self, name: str, mass: float | None = None) -> None: self.name = name self._mass = mass return None def __getattr__(self, name: str) -> Any: i... | The name recommendation logic is triggered only if the name attribute of the AttributeError is not None: elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \ getattr(exc_value, "name", None) is not None: wrong_name = getattr(exc_value, "name", None) suggestion = _compute_suggestion_error(exc_value,... | 2 | 2 |
78,515,236 | 2024-5-22 | https://stackoverflow.com/questions/78515236/longest-repeating-subsequence-edge-cases | Problem While solving the Longest Repeating Subsequence problem using bottom-up dynamic programming, I started running into an edge case whenever a letter was repeated an odd number of times. The goal is to find the longest subsequence that occurs twice in the string using elements at different indices. The ranges can ... | Actually, your initial algorithm and its answer are correct (... but this is a good question because others might confuse what an LRS means). Given your input (in), the subsequences (s1, s2) are: in: AXXXA s1: XX s2: XX So XX (length 2) is indeed the correct answer here. X would be the correct answer for the problem's... | 3 | 0 |
78,481,278 | 2024-5-15 | https://stackoverflow.com/questions/78481278/splitting-html-file-and-saving-chunks-using-langchain | I'm very new to LangChain, and I'm working with around 100-150 HTML files on my local disk that I need to upload to a server for NLP model training. However, I have to divide my information into chunks because each file is only permitted to have a maximum of 20K characters. I'm trying to use the LangChain library to do... | check this super amazing HTML chunking package :package: pip install html_chunking Our HTML chunking algorithm operates through a well-structured process that involves several key stages, each tailored to efficiently chunk and merge HTML content while adhering to a token limit. This approach is highly suitable for sce... | 2 | 1 |
78,498,481 | 2024-5-18 | https://stackoverflow.com/questions/78498481/userwarning-plan-failed-with-a-cudnnexception-cudnn-backend-execution-plan-des | I'm trying to train a model with Yolov8. Everything was good but today I suddenly notice getting this warning apparently related to PyTorch and cuDNN. In spite the warning, the training seems to be progressing though. I'm not sure if it has any negative effects on the training progress. site-packages/torch/autograd/gra... | June 2024 Solution: Upgrade torch version to 2.3.1 to fix it: pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 | 14 | 4 |
78,502,481 | 2024-5-19 | https://stackoverflow.com/questions/78502481/algorithm-for-transformation-of-an-1-d-gradient-into-a-special-form-of-a-2-d-gra | Assuming there is a 1-D array/list which defines a color gradient I would like to use it in order to create a 2-D color gradient as follows: Let's for simplicity replace color information with a single numerical value for an example of a 1-D array/list: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ] To keep the gradient prog... | General idea From what I can see, this can be done in three steps: Split the sequence in fragments as if they were diagonals of an array of a given shape. Separate the elements of each fragment by the parity of their index. Assemble a new array from the modified diagonal fragments. Step 1. Split the sequence into dia... | 5 | 4 |
78,501,763 | 2024-5-19 | https://stackoverflow.com/questions/78501763/how-to-put-a-python-numpy-array-back-together-from-diagonals-obtained-from-split | As I to my surprise failed to find a Python numpy method able to put an array split into its right to left diagonals in first place back together from the obtained diagonals, I have put some code together for this purpose, but have now hard time to arrive at the right algorithm. The code below works for the 4x3 array, ... | Numpy 1.25 Correcting the initial approach First, let's make the initial approach work. There are two important parts: splitting the data into diagonals and merging them back together. The smallest and largest diagonal offsets are -(hight-1) and width-1 respectively. So we can simplify splitting into diagonals as follo... | 2 | 2 |
78,483,318 | 2024-5-15 | https://stackoverflow.com/questions/78483318/building-python-packages-from-source-for-amd-gpu-hipcc-failed-with-exit-code-1 | I am trying to install Python packages, like lietorch or pytorch-scatter with AMD support. I download the repository, git clone --recursive https://github.com/repo If I just try to install the package, I'll get an error, stating clang: error: cannot find HIP runtime; provide its path via '--rocm-path', or pass '-nogp... | While searching for an answer I stumbled upon this Clang documentation. It mentions the Order of Precedence for HIP Path: Order of Precedence for HIP Path --hip-path compiler option HIP_PATH environment variable (use with caution) --rocm-path compiler option ROCM_PATH environment variable (use with caution) Defau... | 2 | 1 |
78,512,202 | 2024-5-21 | https://stackoverflow.com/questions/78512202/pytests-failing-on-teamcity-due-to-matplotlib-backend | I'm trying to run some Python unit tests on a remote build server using Teamcity. They fail when attempting to execute some matplotlib code. I get the following output in the Teamcity build logs, which seems to point towards the matplotlib backend as the culprit. XXXXX\stats.py:144: in PerformHypothesisTest fig, ax = ... | I had the same Issue, it has something to do with the missing physical video out (on a server with a nightly build, you usually have no monitor connected). This is why it works on your private machine. matplotlib.use('Agg') should work, but if you have completely automatic nightly builds, that pull down some kind of r... | 2 | 1 |
78,511,506 | 2024-5-21 | https://stackoverflow.com/questions/78511506/issues-with-publishing-and-subscribing-rates-for-h-264-video-streaming-over-rabb | I am working on a project to stream an H.264 video file using RabbitMQ (AMQP protocol) and display it in a web application. The setup involves capturing video frames, encoding them, sending them to RabbitMQ, and then consuming and decoding them on the web application side using Flask and Flask-SocketIO. However, I am e... | First i dont know so much about rabbitmq but i think it would be handle more then 10 Messages per Seconds. You have some Design issues, you Read the video file to rgb via cv2 and reencode it to h264. The file is already h264 encoded. Its just overhead. Use pyav to read Packet wise the file so you dont need reencode st... | 2 | 2 |
78,490,151 | 2024-5-16 | https://stackoverflow.com/questions/78490151/autotokenizer-from-pretrained-took-forever-to-load | I used the following code to load my custom-trained tokenizer: from transformers import AutoTokenizer test_tokenizer = AutoTokenizer.from_pretrained('raptorkwok/cantonese-tokenizer-test') It took forever to load. Even if I replace the AutoTokenizer with PreTrainedTokenizerFast, it still loads forever. How to debug or ... | The problem is resolved when downgrading transformers version to 4.28.1 from 4.41.0. Both pipeline() and from_pretrained() load the tokenizer successfully in seconds. | 4 | 1 |
78,510,670 | 2024-5-21 | https://stackoverflow.com/questions/78510670/fail-to-change-the-stacked-bar-chart-style-by-openpyxl-how-to-fix-it | Current Style Target Style When I generate a percentage stacked bar chart by openpyxl, I would like it as the target style in the image attached. But what I got is the current one. The code is as below. I tried change the chart.style number. It doesn't work. Environment: Window 10 + Python 3.10 (VS 2017) + Excel 365 ... | Referenced in the Openpyxl documentation, Stacked Bar Charts should have their overlap set to 100. Need to add the following setting; chart_A.overlap = 100 | 2 | 2 |
78,512,160 | 2024-5-21 | https://stackoverflow.com/questions/78512160/read-extensionobject-opc-ua-python | I'm trying to read an opc ua extension object in python with the following code: from opcua import Client from opcua import ua connessione= 'opc.tcp://10.1.17.21:4840/' client = Client(connessione) try: client.connect() var = client.get_node('ns=1;s=VARIABLE_OPC_first_coiling_machine_production_list') before = var.get_... | Try opcua-asyncio library and call the function load_data_type_definitions. | 4 | 1 |
78,506,890 | 2024-5-20 | https://stackoverflow.com/questions/78506890/how-can-i-clean-up-the-useless-python-packages | I tried to install the requirements for Grok on my server(I don’t have much disk space). dm_haiku==0.0.12 jax[cuda12-pip]==0.4.25 -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html numpy==1.26.4 sentencepiece==0.2.0 But I found they are so big that the disk quota exceeded. Thus, I wanted to uninstal... | pip uninstall will remove only the requirements you pass to it, not all other things they depend on. List the full set of installed packages in your environment, like this: pip freeze Choose the subset you want to uninstall, and pass them to pip uninstall. pip uninstall --yes -r requirements-to-remove.txt This could ... | 2 | 2 |
78,513,078 | 2024-5-21 | https://stackoverflow.com/questions/78513078/aggregation-on-sub-dataframes-defined-by-sets-of-indices-without-loop | Suppose I have a Pandas DataFrame, I take some easy example: import pandas as pd df = pd.DataFrame(columns=["A", "B"], data = [(1, 2), (4, 5), (7, 8), (10, 11)]) I have a set of indices, let's make it simple and random: inds = [(0, 1, 3), (0, 1, 2), (1, 2, 3)] I want to aggregate the data according to those indices, ... | Edit: showing how to achieve this with groupby, but surely "significantly simpler to think of this as a selection by index problem"; see the answer by @HenryEcker. Option 1 (reindex + groupby) s = pd.Series(inds).explode() out = df.reindex(s).groupby(s.index).mean() out A B 0 5.0 6.0 # i.e. A: (1+4+10)/3, B: (2+5+11)/... | 4 | 4 |
78,513,762 | 2024-5-21 | https://stackoverflow.com/questions/78513762/validate-additional-info-using-pydantic-model | I'm a new user of FastAPI. I'm writing a small web application and I'm wondering if it's good practice to validate additional information, which is not directly related to the object itself, using the Pydantic model itself? For example, checking if a user with such a name exists in the database. For example: class Crea... | In my opinion you shouldn't do that. In FastAPI, to me, Pydantic acts as a gateway to the path operation function(whether it is input or output). It deserializes, cleans(and/or converts) and validates the data so that you can count on that the data you receive is in the good shape. The rest is going to be passed to the... | 3 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.