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,334,657 | 2024-4-16 | https://stackoverflow.com/questions/78334657/how-to-run-mypy-on-3rd-party-package-version-sensitive-code | I'm currently responsible to write library code that is both compatible with pydantic v1 and v2. Getting the code functional is more or less straightforward since you can make version sensitive choices in your code to satisfy your test suite, e.g. using patterns like this: import pydantic PYDANTIC_VERSION = packaging.v... | --always-true and --always-false exist, so you can make a boolean flag named PYDANTIC_V1 and run Mypy twice on the same code: $ pip install "pydantic==1.*" $ mypy file.py --always-true=PYDANTIC_V1 $ pip install -U pydantic $ mypy file.py --always-false=PYDANTIC_V1 | 3 | 3 |
78,335,103 | 2024-4-16 | https://stackoverflow.com/questions/78335103/overload-typing-for-variable-amount-of-arguments-args-or-kwargs | Example is below, need to make sure IDE type checker or reveal_type would identify k, j and i types correctly. Perhaps there is some way to suggest the typing that args is an empty tuple and kwargs empty dict and the return value then would be tuple[int]? from typing import Union, overload def test(*args: int, **kwargs... | Here's a possible solution that allows mypy to infer the correct types for k, j, and i. This approach does result in mypy complaining about the overload signatures overlapping. I'm not sure if it's possible to address that besides simply suppressing the errors. from typing import Union, overload @overload def test() ->... | 2 | 3 |
78,334,193 | 2024-4-16 | https://stackoverflow.com/questions/78334193/pandas-rolling-sum-with-a-maximum-number-of-valid-observations-in-a-window | I am looking for help to speed up a rolling calculation in pandas which would compute a rolling average with a predefined maximum number of most recent observations. Here is code to generate an example frame and the frame itself: import pandas as pd import numpy as np tmp = pd.DataFrame( [ [11.1]*3 + [12.1]*3 + [13.1]*... | One idea is use numba for faster count output in Rolling.apply by parameter engine='numba': (tmp.rolling(window=3, min_periods=1) .apply(lambda x: x[~np.isnan(x)][-2:].mean(), engine='numba', raw=True)) Test performance: tmp = pd.concat([tmp] * 100000, ignore_index=True) In [88]: %timeit tmp.rolling(window=3, min_peri... | 2 | 3 |
78,332,877 | 2024-4-16 | https://stackoverflow.com/questions/78332877/typeerror-cannot-unpack-non-iterable-multipoint-object | In my python app I am using Shapely. Invoking the function below: def get_t_start(t_line: geometry.LineString): print('get_t_start', t_line.boundary) p1, p2 = t_line.boundary t_start = p1 if p1.y < p2.y else p2 return t_start produces the following output: get_t_start MULTIPOINT (965 80, 1565 1074) Traceback (most re... | That's most likely because your apps are running different versions of shapely. Starting with Shapely 1.8, iteration over multi-part geometries (like a MultiPoint) is deprecated and was removed in Shapely 2.0 (read more). So, you just need to access the boundary's geoms : from shapely import LineString, Point def get_t... | 2 | 3 |
78,332,814 | 2024-4-16 | https://stackoverflow.com/questions/78332814/find-all-differences-between-groups-in-polars-dataframe | I have one polars dataframe and I am trying to find the differences (fields that have their values changed) on multiple columns between groups on one key. There can be multiple groups in the dataframe and more than one column. The groups is essentially a datetime in int format (YYYYMMDD) How can I find the rows where t... | Your approach is slightly over-complicating things. What I suggest is that you first sort the data by id and update_time, then shift the data to prepare for comaparison. After that, you can identify the rows where id is the same but where there is a difference: import polars as pl def find_updated_field_differences(df)... | 3 | 1 |
78,327,110 | 2024-4-15 | https://stackoverflow.com/questions/78327110/install-gmp-library-on-mac-os-and-pycharm | I'm trying to run my Cython project. And one of the header is gmpxx.h. Even though I already installed the gmp library using brew install gmp. I could not run my cython file with python3 setup.py build_ext --inplace. fatal error: 'gmpxx.h' file not found #include <gmpxx.h> ^~~~~~~~~ 1 error generated. error: command '... | So I added the library location directly into setup.py file. from setuptools import setup, Extension, find_packages from Cython.Build import cythonize extension = Extension( "Class Name", sources=["Something" ], include_dirs=[ "/opt/homebrew/Cellar/gmp/6.3.0/include", # Include directory for GMP headers "/opt/homebrew/... | 2 | 2 |
78,326,026 | 2024-4-15 | https://stackoverflow.com/questions/78326026/how-to-log-output-of-script | I want to log the output of my python file into a txt. I also want to still see it in the terminal too. I tried using sys.stdout, but it did not still have terminal output. To log it I open my log file with f = open("log.txt", "r+"), then set sys.stdout = f. When the code ended, I said f.close() to write changes. Here ... | You can set sys.stdout to a file-like object with a write method that writes to both the original sys.stdout and a given file: import sys class Tee: def __init__(self, file): self.file = file def write(self, text): self.orig_stdout.write(text) self.file.write(text) def start(self): self.orig_stdout = sys.stdout sys.std... | 2 | 1 |
78,331,504 | 2024-4-16 | https://stackoverflow.com/questions/78331504/list-comprehension-to-return-list-if-value-is-non-existent | I'm aiming to use list comprehension to return values in a list. Specifically, if 'x' is in a list, I want to drop all other values. However, if 'x' is not in the list, I want to return the same values (not return an empty list). list1 = ['d','x','c'] list2 = ['d','b','c'] list1 = [s for s in list1 if s == 'x'] list2 =... | This would keep all elements that aren't x list2 = [x for x in list2 if x != 'x'] However, if x is in the list, it'll still return all other elements. So, you'd need two passes to check whether x does exist since list comprehension alone cannot return that information def filter_x(lst): if 'x' in lst: return [x for x ... | 2 | 3 |
78,329,495 | 2024-4-15 | https://stackoverflow.com/questions/78329495/what-is-the-equivalent-of-numpy-accumulate-ufunc-in-pytorch | In numpy, I can do the following: >>> x = np.array([[False, True, False], [True, False, True]]) >>> z0 = np.logical_and.accumulate(x, axis=0) >>> z1 = np.logical_and.accumulate(x, axis=1) This returns the following: >>> z0 array([[False, True, False], [False, False, False]]) >>> z1 array([[False, False, False], [ True... | The logical and corresponds to a product in binary terms. You can use cumprod for that: >>> x.cumprod(dim=0).bool() tensor([[False, True, False], [False, False, False]]) >>> x.cumprod(dim=1).bool() tensor([[False, False, False], [ True, False, False]]) | 2 | 2 |
78,329,714 | 2024-4-15 | https://stackoverflow.com/questions/78329714/pandas-groupby-string-field-and-select-by-time-of-day-range | I have a dataset like this index Date_Time Pass_ID El 0 3/30/23 05:12:36.36 A 1 1 3/30/23 05:12:38.38 A 2 1 3/30/23 05:12:40.40 A 3 1 3/30/23 05:12:42.42 A 4 1 3/30/23 05:12:44.44 A 4 1 3/30/23 12:12:50.50 B 3 1 3/30/23 12:12:52.52 B 4 1 3/30/23 12:12:54.54 B 5 1 3/30/23 12:12:56.56 B 6 1 3/30/23 12:12:58.58 B 7 1 3/30... | Try: # to datetime if necessary # df["Date_Time"] = pd.to_datetime(df["Date_Time"]) out = df.set_index("Date_Time").between_time("10:00", "13:00")["Pass_ID"].unique() print(out) Prints: ['B'] OR: If you want to filter whole groups between time 10:00-13:00: out = ( df.groupby("Pass_ID") .filter( lambda x: len(x.set_i... | 2 | 3 |
78,315,455 | 2024-4-12 | https://stackoverflow.com/questions/78315455/fastapi-error-when-using-annotated-in-class-dependencies | FastAPI added support for Annotated (and started recommending it) in version 0.95.0. Additionally, FastAPI has a very powerful but intuitive Dependency Injection system (documentation). Moreover, FastAPI support Classes as Dependencies. However, it seams like Annotated cannot be used in class dependencies, but on funct... | Remove the following and it will work. from __future__ import annotations | 3 | 2 |
78,328,020 | 2024-4-15 | https://stackoverflow.com/questions/78328020/derotation-algorithm-in-2d-space | I have an array of coordinates in x and y, relative to the movement of an object in a constantly rotating circular environment (10 rpm). How can I disentangle between the movement of the object from that of the environment? I tried polar coordinates, speed and movement vectors, and I get results, but I'd like to know i... | This is a really nice area and a good question about matrix transformations. If you wish to know about this, do read this course: https://graphics.stanford.edu/courses/cs248-01/ Now, Let's start by creating some sample data: import numpy as np import matplotlib.pyplot as plt import pandas as pd rpm = 10 omega = rpm * 2... | 2 | 1 |
78,314,966 | 2024-4-12 | https://stackoverflow.com/questions/78314966/drag-image-to-another-image | I write this code to move image to another place but when I moving the image each point create new box so I get like this view: Image box duplicate each moving step. But I cant find the solution for this. import sys from PyQt5.QtCore import QRect from PyQt5.QtGui import QPixmap, QPainter, QPen, QColor from PyQt5.QtWid... | I solved my problem with this code: import sys from PyQt5.QtCore import QRect from PyQt5.QtGui import QPixmap, QPainter, QPen, QColor from PyQt5.QtWidgets import * from test import Ui_MainWindow from PyQt5.QtCore import Qt, QRect, QPoint class MainWindow(QMainWindow): def __init__(self,parent = None): QMainWindow.__ini... | 3 | 0 |
78,324,913 | 2024-4-14 | https://stackoverflow.com/questions/78324913/problem-when-running-terminal-command-pip-install-anonympy | I'm on an MacBook Pro w/ M1 Pro Chip running macOS Venture 13.0.1 and have Python 3.9.6 installed. When trying to run the following command(s): pip install anonympy pip3 install anonympy I get the following output: Collecting anonympy Using cached anonympy-0.3.7.tar.gz (5.8 MB) Installing build dependencies ... done ... | It seems it's an error in the package that is not compatible with the last PyPi version. You can install it directly with pip+git : pip install git+https://github.com/ArtLabss/open-data-anonymizer.git Related Github Issue : https://github.com/ArtLabss/open-data-anonymizer/issues/26 | 2 | 0 |
78,324,285 | 2024-4-14 | https://stackoverflow.com/questions/78324285/how-can-i-find-the-first-row-that-meets-conditions-of-a-mask-for-each-group | This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'a': ['x', 'x', 'x', 'x', 'x', 'y', 'y', 'y', 'y', 'y', 'y', 'y'], 'b': [1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2], 'c': [9, 8, 11, 13, 14, 3, 104, 106, 11, 100, 70, 7] } ) Expected output: Creating column out: a b c out 0 x 1 9 NaN 1 x 1 8 NaN 2 x 1 11 NaN 3 x... | One option with groupby.idxmax: mask = (df['c'] > 10) & (df['a'].ne('x') | df['b'].eq(2)) idx = mask.groupby(df['a']).idxmax() df.loc[idx[mask.loc[idx].values], 'out'] = 'found' Another with groupby.transform: mask = (df['c'] > 10) & (df['a'].ne('x') | df['b'].eq(2)) df.loc[mask & mask.groupby(df['a']) .transform(lamb... | 2 | 3 |
78,324,061 | 2024-4-14 | https://stackoverflow.com/questions/78324061/str-replace-method-for-pandas-series-does-not-work-as-expected | I have encountered the issue in one particular stage of my project. Replicate with following: import pandas as pd # Recreated a sample data data = { "FailCodes": ['4301,4090,5003(1)'], } df = pd.DataFrame(data) # Want to replace the '(1)' with 'p1q' print(df.FailCodes.str.replace('(1)','p1q'),'\n') # Not giving expecte... | You probably use older version of Pandas, where default argument is regex=True (and (1) is regular pattern). Put regex=False to .str.replace: print(df.FailCodes.str.replace("(1)", "p1q", regex=False)) Prints: 0 4301,4090,5003p1q Name: FailCodes, dtype: object | 2 | 1 |
78,322,637 | 2024-4-14 | https://stackoverflow.com/questions/78322637/langchain-how-to-view-the-context-my-retriever-used-when-invoke | I am trying to make a private llm with RAG capabilities. I successfully followed a few tutorials and made one. But I wish to view the context the MultiVectorRetriever retriever used when langchain invokes my query. This is my code: from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts im... | You can tap into langchains with a RunnableLambda and print the state passed from the retriever to the prompt from langchain_core.runnables import RunnableLambda def inspect(state): """Print the state passed between Runnables in a langchain and pass it on""" print(state) return state # RAG pipeline chain = ( {"context"... | 2 | 4 |
78,302,031 | 2024-4-10 | https://stackoverflow.com/questions/78302031/stable-diffusion-attributeerror-module-jax-random-has-no-attribute-keyarray | When I run the stable diffusion on colab https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/stable_diffusion.ipynb with no modification, it fails on the line from diffusers import StableDiffusionPipeline The error log is AttributeError: module 'jax.random' has no attribute 'KeyArray' Ho... | jax.random.KeyArray was deprecated in JAX v0.4.16 and removed in JAX v0.4.24. Given this, it sounds like the HuggingFace stable diffusion code only works JAX v0.4.23 or earlier. You can install JAX v0.4.23 with GPU support like this: pip install "jax[cuda12_pip]==0.4.23" -f https://storage.googleapis.com/jax-releases/j... | 7 | 10 |
78,321,025 | 2024-4-13 | https://stackoverflow.com/questions/78321025/why-is-this-trivial-numba-function-with-a-list-input-so-slow | import numba from typing import List @numba.njit def test(a: List[int]) -> int: return 1 test([i for i in range(2_000_000)]) takes 2s and scales linearly with the size of the list. Wrapping the input argument with numba.typed.List takes even longer. (all the time is spent on the numba.typed.List call. The timings don'... | Numba only operates on typed variables. It needs not only to check the types of all the items but also convert the whole list into a typed list. This implicit conversion can be particularly expensive since CPython lists, a.k.a. reflected lists contain pointers on allocated objects and each objects is reference counted.... | 3 | 3 |
78,320,762 | 2024-4-13 | https://stackoverflow.com/questions/78320762/how-to-destructure-nested-structs-in-polars-python-api | I am unfortunately having to work with some nested data in a polars dataframe. (I know it is bad practice) Consider data: data = { "positions": [ { "company": { "companyName": "name1" }, }, { "company": { "companyName": "name2" }, }, { "company": { "companyName": "name3" }, } ] } positions is a column in the dataframe... | Structs You can use .struct.field() or .struct[] syntax to extract struct fields. https://docs.pola.rs/user-guide/expressions/structs/#extracting-individual-values-of-a-struct df = pl.DataFrame(data) df.with_columns( pl.col("positions").struct["company"].struct["companyName"] ) shape: (3, 2) ┌─────────────┬─────────... | 4 | 4 |
78,319,421 | 2024-4-13 | https://stackoverflow.com/questions/78319421/min-from-columns-from-dict | I have a dict with item\column name and a df with columns from dict and other columns. How can I add column to df with min value for every item just from columns corresponding from dict? import pandas as pd my_dict={'Item1':['Col1','Col3'], 'Item2':['Col2','Col4'] } df=pd.DataFrame({ 'Col0':['Item1','Item2'], 'Col1':[2... | You can use apply with a function that reads the appropriate column names out of the dictionary (returning an empty list if there is no match) and then takes the minimum of the specified columns: my_dict = { 'Item1': ['Col1', 'Col3'], 'Item2': ['Col2', 'Col4'] } df['min'] = df.apply(lambda r:r[my_dict.get(r['Col0'], []... | 2 | 4 |
78,313,586 | 2024-4-12 | https://stackoverflow.com/questions/78313586/python-library-optionally-support-numpy-types-without-depending-on-numpy | Context We develop a Python library that contains a function expecting a numlike parameter. We specify this in our signature and make use of python type hints: def cool(value: float | int | List[float | int]) 🏳 Problem & Goal During runtime, we noticed it's fine to pass in numpy number types as well, e.g. np.float16(... | Defer evaluation of annotations, and only import numpy conditionally. from __future__ import annotations import typing as t if t.TYPE_CHECKING: import numpy as np def cool(value: int | np.floating | etc ...): ... Now the numpy dependency is only necessary when type-checking. See PEP 563 – Postponed Evaluation of Annot... | 7 | 2 |
78,318,586 | 2024-4-12 | https://stackoverflow.com/questions/78318586/propagating-true-entries-along-axis-in-an-array | I have to perform the operation below many times. Using numpy functions instead of loops I usually get a very good performance but I have not been able to replicate this for higher dimensional arrays. Any suggestion or alternative would be most welcome: I have a boolean array and I would like to propagate the true inde... | I just leave here numba version so you can compare the speed against the proposed numpy solution: import numba import numpy as np @numba.njit(parallel=True) def propagate_true_numba(arr, n=2): out = np.zeros_like(arr, dtype="uint8") for i in numba.prange(arr.shape[0]): prop = 0 for j in range(arr.shape[1]): if arr[i, j... | 2 | 1 |
78,317,383 | 2024-4-12 | https://stackoverflow.com/questions/78317383/np-unique-after-np-round-unrounds-the-data | This code snippet describes a problem I have been having. For some reason rounded_data seems to be rounded, but once passed in np.unique and np.column_stack the result_array seems to be unrounded, meanwhile the rounded_data is still rounded. rounded_data = data_with_target_label.round(decimals=2) unique_values, counts ... | this is because your dataframe is in float32 while default number format in numpy is float64. So the number that is rounded in float32 won't be visibly rounded in float64, because number representation is a bit different. Solution is to convert either input array to float64 or the result_array into float 32. Solution 1... | 2 | 1 |
78,316,919 | 2024-4-12 | https://stackoverflow.com/questions/78316919/polars-replace-parts-of-dataframe-with-other-parts-of-dataframe | I'm looking for an efficient way to copy / replace parts of a dataframe with other parts of the same dataframe in Polars. For instance, in the following minimal example dataframe pl.DataFrame({ "year": [2020,2021,2020,2021], "district_id": [1,2,1,2], "distribution_id": [1, 1, 2, 2], "var_1": [1,2,0.1,0.3], "var_N": [1,... | You could filter the 1 columns, change their id to 2 and discard the unneeded columns. df.filter(distribution_id = 1).select( "year", "district_id", "^var_.+$", distribution_id = pl.lit(2, pl.Int64) ) shape: (2, 5) ┌──────┬─────────────┬───────┬───────┬─────────────────┐ │ year ┆ district_id ┆ var_1 ┆ var_N ┆ distribu... | 3 | 4 |
78,316,845 | 2024-4-12 | https://stackoverflow.com/questions/78316845/counting-number-of-unique-values-in-groups | I have data where for multiple years, observations i are categorized in cat. An observation i can be in multiple categories in any year, but is unique across years. I am trying to count unique values for i by year, by cat, and by year and cat. I'm learning Python (v3.12) & Pandas (v2.2.1). I can make this work, but onl... | You could use a simple loop and groupby.transform: groups = ['cat', 'year', ['cat', 'year']] for g in groups: df[f"n_by_{''.join(g)}"] = df.groupby(g)['i'].transform('nunique') Output: year cat i n_by_cat n_by_year n_by_catyear 0 2020 1 a 2 2 1 1 2020 1 a 2 2 1 2 2020 2 b 3 2 1 3 2021 2 c 3 2 1 4 2021 3 d 3 2 1 5 202... | 2 | 2 |
78,316,200 | 2024-4-12 | https://stackoverflow.com/questions/78316200/how-to-connect-mariadb-running-inside-docker-compose-with-python-script-running | I wrote a docker compose file and used docker compose up -d command. Then I wrote a simple python script to connect with maria db but I get error everytime. mariadb version in my virtual environment is 1.0.11 pip install mariadb==1.0.11 version: '3.8' services: mariadb: image: mariadb:latest container_name: my_mariadb ... | version: '3.8' services: mysql: image: mysql:latest container_name: db_mysql restart: always environment: MYSQL_ROOT_PASSWORD: r_pass MYSQL_AUTHENTICATION_PLUGIN: 'mysql_native_password' # ... other environment variables volumes: - mysql-data:/var/lib/mysql ports: - "3306:3306" mariadb: image: mariadb:latest container... | 4 | 1 |
78,312,866 | 2024-4-11 | https://stackoverflow.com/questions/78312866/remove-all-whitespaces-from-the-headers-of-a-polars-dataframe | I'm reading some csv files where the column headers are pretty annoying: they contain whitespaces, tabs, etc. A B C D E CD E 300 0 0 0 CD E 1071 0 0 0 K E 390 0 0 0 I want to read the file, then remove all whitespaces and/or tabs from the column names. Currently I do import polars as pl file_df = pl.read_csv(csv_file,... | The solution is to use a function as you have shown. However, in the case of .strip() without arguments it can be simplified slightly. Another way to write the strip is by using str.strip() >>> " A ".strip() # 'A' >>> str.strip(" A ") # 'A' str.strip and the lambda in this case do the same thing: one = lambda column: ... | 2 | 3 |
78,314,829 | 2024-4-12 | https://stackoverflow.com/questions/78314829/how-to-effectively-use-put-and-delete-http-methods-in-django-class-based-views | I'm setting up a CRUD system with Django, using Class-Based Views. Currently I'm trying to figure out how to handle HTTP PUT and DELETE requests in my application. Despite searching the Django documentation extensively, I'm having trouble finding concrete examples and clear explanations of how to submit these types of ... | Beware that HTML does not support PUT, PATCH, DELETE "out of the box". You can use AJAX, but <form method="delete"> does not work, simply because the browser does not make a DELETE request. So you will need AJAX to make the request. Another problem is the routing: your view sits behind categories/, so that is where you... | 3 | 2 |
78,314,168 | 2024-4-12 | https://stackoverflow.com/questions/78314168/how-to-filter-dataframe-column-names-containing-2-specified-substrings | I need the column names from the dataframe that contain both the term software and packages. I'm able to filter out columns containing one string.. for eg: software_cols = df.filter(regex='Software|software|SOFTWARE').columns How do I achieve the same by mentioning 'Packages/packages/PACKAGES' as well. Eligible column ... | Keep things simple as you don't need a regex here, just use two boolean masks and a case independent comparison: # does the column name contain "software"? m1 = df.columns.str.contains('software', case=False) # does it contain "package"? m2 = df.columns.str.contains('package', case=False) # if both conditions are met, ... | 3 | 5 |
78,313,700 | 2024-4-12 | https://stackoverflow.com/questions/78313700/create-a-dataframe-from-numpy-array-and-parameters | Running Elastic Net simulations by varying a couple parameters and looking to save output coefficients to a dataframe for potential review later. Ultimately looking to save off a dataframe with two parameter identifier columns (ie, 'alpha', 'l1_ratio') and a number of other columns for the resulting coefficients for th... | I imagine you will generate all data points iteratively. However, DataFrames don't like to be grown this way. Performance of adding new rows repeatedly is terrible. Assuming logic the function that will produce the new data points, I would use a dictionary to collect them, and create the DataFrame once in the end: data... | 2 | 1 |
78,312,849 | 2024-4-11 | https://stackoverflow.com/questions/78312849/how-to-enumerate-pandigital-prime-sets | Project Euler problem 118 reads, "Using all of the digits 1 through 9 and concatenating them freely to form decimal integers, different sets can be formed. Interestingly with the set {2,5,47,89,631} all of the elements belonging to it are prime. How many distinct sets containing each of the digits one through nine exac... | The flaw is this. Consider the set {2,5,47,89,631}. Different initial splits can lead to it. One is {1,2,3,6}, {4,5,7,8,9} and another is {1,3,6,8,9} {2,4,5,7}. There are many more. And therefore you are overcounting. To leave you the fun of the problem, I won't tell you how to fix this overcounting. I'll just tell you... | 2 | 4 |
78,312,648 | 2024-4-11 | https://stackoverflow.com/questions/78312648/python-inheritance-with-dataclasses-dataclass-and-annotations | I am very confused by the following code: import dataclasses @dataclasses.dataclass() class Base(): x: int = 100 @dataclasses.dataclass() class Derived(Base): x: int = 200 @dataclasses.dataclass() class DerivedRaw(Base): x = 300 base = Base() derived = Derived() derived_raw = DerivedRaw() print(base.x) print(derived.x)... | From the dataclass documentation: The @dataclass decorator examines the class to find fields. A field is defined as a class variable that has a type annotation. ... So to have proper dataclass field must have type annotation. | 2 | 2 |
78,311,305 | 2024-4-11 | https://stackoverflow.com/questions/78311305/how-can-i-get-the-program-to-print-each-line-on-a-new-paragraph | I wrote this shopping program myself and I'm trying to get it to print to the shell and to the text file with each shopping list item on a new line. Please can you help me with this? #By Simeon Beckford-Tongs BSc MSc Copyright © 2024. All rights reserved. By Simeon Beckford-Tongs BSc MSc Copyright © 2024. All rights re... | So, you are appending each item to the items variable, but you're not adding any newline characters (\n) between them, which results in them being concatenated together into one long string. items = "" items += input('What is the first item on your shopping list:\n') + '\n' items += input('What is the second item on yo... | 2 | 1 |
78,307,173 | 2024-4-10 | https://stackoverflow.com/questions/78307173/dealing-with-duplicates-cols-on-duckdb-with-gaps-nulls-and-filling-them-effici | I'm new to duckdb (v0.10.1) so this question comes from my lack of knowledge of the built-in functionality that duckdb has. I have a special use case that I haven't found a cleaver way to do this with duckdb with timeseries data. Sometimes there are some rare occurrences where we get duplicate values for a timestamp in... | It looks like you want the first non-NULL per timestamp group? any_value(): Returns the first non-null value from arg. This function is affected by ordering. >>> df shape: (4, 3) ┌────────────┬──────┬──────┐ │ timestamp ┆ A ┆ B │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞════════════╪══════╪══════╡ │ 2022-01-01 ┆ 1 ┆ ... | 2 | 0 |
78,309,756 | 2024-4-11 | https://stackoverflow.com/questions/78309756/mistral-model-generates-the-same-embeddings-for-different-input-texts | I am using pre-trained LLM to generate a representative embedding for an input text. But it is wired that the output embeddings are all the same regardless of different input texts. The codes: from transformers import pipeline, AutoTokenizer, AutoModel import numpy as np PRETRAIN_MODEL = 'mistralai/Mistral-7B-Instruct-... | You're not slicing it the dimensions right at outputs.last_hidden_state[0, 0, :].numpy() Q: What is the 0th token in all inputs? A: Beginning of sentence token (BOS) Q: So that's the "embeddings" I'm slicing is the BOS token? A: Try this: from transformers import pipeline, AutoTokenizer, AutoModel import numpy as np P... | 3 | 3 |
78,309,847 | 2024-4-11 | https://stackoverflow.com/questions/78309847/how-to-stop-otherwise-in-python-polars-when-using-a-when-expression | This is my dataframe: ┌─────────────────────┬──────────┐ │ date ┆ price │ │ --- ┆ --- │ │ datetime[μs] ┆ f64 │ ╞═════════════════════╪══════════╡ │ 2023-12-20 14:10:00 ┆ 2039.105 │ │ 2023-12-21 14:45:00 ┆ 2045.795 │ │ 2023-12-22 15:10:00 ┆ 2069.708 │ │ 2023-12-26 06:45:00 ┆ 2064.885 │ │ 2023-12-27 18:00:00 ┆ 2083.865 │... | Alternatively to @DeanMacGregor's solution, you could use pl.coalesce instead. This leverages that pl.when().then() evaluates to None if the when case is not True. ( df .with_columns( pl.coalesce( pl.when(pl.col("price").is_in(group)).then(index+1) for index, group in enumerate(resistance_groups) ) .alias("groups") ) )... | 3 | 3 |
78,309,010 | 2024-4-11 | https://stackoverflow.com/questions/78309010/remove-everything-in-string-after-the-first-occurrence-of-a-word | I have a dataframe with a column consisting of strings. I want to trim the strings in the column such that everything is removed after the first appearance of a given word. The words are in this list: words_to_trim_after = ['test', 'hello', 'very good'] So if I have a dataframe such as the following df = pd.DataFrame(... | You can use split def trim_after_first_word(s, words): for word in words: parts = s.split(word, maxsplit=1) if len(parts) > 1: return word return None | 2 | 2 |
78,307,146 | 2024-4-10 | https://stackoverflow.com/questions/78307146/selenium-in-python-unable-to-locate-element-error-404 | I am trying to use selenium in python to click the load more button to show all the reviews in a specific webpage, however, I am encountering some issues when finding the button element in selenium which always return an ** Error: 404 - No Such Element: Unable to locate element** import requests from urllib.parse impor... | I'd simplify the code and use their Ajax API to get more reviews: import requests url = "https://api.bazaarvoice.com/data/reviews.json" params = { "resource": "reviews", "action": "REVIEWS_N_STATS", "filter": [ "productid:eq:300409806", # <--- change this to product ID "contentlocale:eq:en,en_AU,en_CA,en_GB,en_US,en_US... | 2 | 1 |
78,306,681 | 2024-4-10 | https://stackoverflow.com/questions/78306681/pyspark-repeat-value-until-change-in-column | I have a dataframe with this structure Order Number Line Number Item Type 12345 1 1001 Parent 12345 2 1002 Child 12345 3 1003 Child 12345 4 1004 Child 12345 5 1005 Parent 12345 6 1006 Child I would like to add a column which shows the "Parent Item" for each item. The parent item is the first parent ... | Try this: from pyspark.sql import functions as F from pyspark.sql.window import Window df = df.withColumn( "Parent_Item", F.last(F.when(F.col("Type") == "Parent", F.col("Item")), ignorenulls=True).over( Window.partitionBy("Order Number").orderBy("Line Number") ), ) df.show() Output: +------------+-----------+----+----... | 2 | 2 |
78,304,744 | 2024-4-10 | https://stackoverflow.com/questions/78304744/how-to-detect-usb-on-raspberry-pi-and-access-it-using-python | I want to detect USB on Raspberry Pi and access USB to copy some data. I used pyudev and get some info from USB but I can't access it. What should I do? This is my code: import pyudev context = pyudev.Context() for device in context.list_devices(subsystem='block', DEVTYPE='disk'): for props in device.properties: if dev... | The reason that you can't find the mount point of the usb drive is that device.properties doesn't include the mount point. You could however get the disk name (/dev/sdx) from device.properties and then use subprocess.check_output(['findmnt', '/dev/sdx1', '-no', 'TARGET']) you can find your mount point in the return of ... | 2 | 2 |
78,302,788 | 2024-4-10 | https://stackoverflow.com/questions/78302788/how-can-i-make-fastest-calculation-speed-for-given-condition-for-numpy-array | I made category as below. 1~4 : 0 5~9 : 1 10~15 : 2 I have a numpy array as below. np.array([2, 5, 10, 13, 7, 9]) How can I make fastest way to change above numpy array based on given conditioin as below? np.array([0, 1, 2, 2, 1, 1]) Because I think 'for loop' will consume lots of time. Is there any way to make fast... | You can also use np.searchsorted as below: a = np.array([2, 5, 10, 13, 7, 9]) np.searchsorted([4, 9, 15], a) array([0, 1, 2, 2, 1, 1], dtype=int64) labels = np.array([23, 45, 87]) labels[np.searchsorted([4, 9, 15], a)] array([23, 45, 87, 87, 45, 45]) | 2 | 4 |
78,302,095 | 2024-4-10 | https://stackoverflow.com/questions/78302095/trying-to-concatenate-a-row-to-a-matrix-in-tensorflow | I have time series data in 4 channels and am trying to generate a sequence of length N using my model. I am determining N from the input data supplied to my sequence generation function: def generate_sequence(self, input_data): predicted_sequence = tf.convert_to_tensor(input_data, dtype=tf.float32) data_shape = predict... | Everything is good except the axis of concatenation. It should be axis=1. def generate_sequence(self, input_data): predicted_sequence = tf.convert_to_tensor(input_data, dtype=tf.float32) data_shape = predicted_sequence.shape for i in range(len(predicted_sequence)): model_input = tf.reshape(predicted_sequence, shape=dat... | 2 | 1 |
78,285,959 | 2024-4-6 | https://stackoverflow.com/questions/78285959/how-do-you-select-fields-from-all-structs-in-a-list-in-polars | I'm working with a deeply nested DataFrame (not good practice, I know), and I'd like to express something like "select field X for all structs in list Y". An example of the data structure: import polars as pl data = { "a": [ [{ "x": [1, 2, 3], "y": [4, 5, 6] }, { "x": [2, 3, 4], "y": [3, 4, 5] } ] ], } df = pl.DataFram... | Update: Perhaps a simpler approach using .unstack() (df.select(pl.col("a").flatten().struct.field("x")) .unstack(1) ) shape: (1, 2) ┌───────────┬───────────┐ │ x_0 ┆ x_1 │ │ --- ┆ --- │ │ list[i64] ┆ list[i64] │ ╞═══════════╪═══════════╡ │ [1, 2, 3] ┆ [2, 3, 4] │ └───────────┴───────────┘ Original answer: df.select(... | 4 | 5 |
78,279,136 | 2024-4-5 | https://stackoverflow.com/questions/78279136/importerror-cannot-import-name-triu-from-scipy-linalg-when-importing-gens | I am trying to use Gensim, but running import gensim raises this error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.10/dist-packages/gensim/__init__.py", line 11, in <module> from gensim import parsing, corpora, matutils, interfaces, models, similarities, utils # ... | I found the issue. The scipy.linalg functions tri, triu & tril are deprecated and will be removed in SciPy 1.13. — SciPy 1.11.0 Release Notes § Deprecated features So, I installed SciPy v1.10.1 instead of the latest version and it was working well. pip install scipy==1.10.1 | 45 | 65 |
78,268,633 | 2024-4-3 | https://stackoverflow.com/questions/78268633/clean-way-to-check-if-variable-is-list-of-lists-using-pattern-matching | In my code, I need to distinguish a list of records from a list of lists of records. The existing code does it like so: if isinstance(input_var, list): if len(input_var) > 0: if all(isinstance(item) for item in input_var): return list_of_lists_processing(input_var) elif not any(instance(item, list) for item in input_va... | You can match the set of item types inside your list. class Constants: set_of_list = {list} match set(type(elem) for elem in input_var): case Constants.set_of_list: return list_of_lists_processing(input_var) case types if list in types: raise ValueError(f"Unexpected input_var value {input_var}") case _: return list_of_... | 5 | 2 |
78,293,639 | 2024-4-8 | https://stackoverflow.com/questions/78293639/visualizing-time-series-data-with-heatmaps-and-3d-surface-plots | I need to visualize different indices as a heatmap or image. The goal is to plot hours on the y-axis, dates on the x-axis, and intensity values for each day. The attached figure illustrates the desired output: I aim to create a figure using pcolormesh, pcolor, imshow, or Seaborn's heatmap. For context, KP > 40 indicat... | The following code is an adaptation of the excellent answer by @Muhammed Yunus. This updated version organizes the management of space weather data into a Class called SpaceWeather. A more detailed discussion of the changes is at my blog Visualizing Space Weather Data: From Procedural to Object-Oriented Approach. Key e... | 2 | 2 |
78,282,930 | 2024-4-6 | https://stackoverflow.com/questions/78282930/why-are-there-double-parentheses-around-my-python-virtual-environment-in-visual | After updating Visual Studio Code to version 1.88.0, I opened one of my Python projects and noticed that there are double parentheses in my virtual environment: ((env) ). I'm using the Python extension v2024.4.0 Previously, in the same and all other projects, I had only one pair of parentheses like (env). I have check... | It's an issue with the Python extension v2024.4.0. Reverting to the previous version, v2024.2.1, fixed this issue for me. | 5 | 2 |
78,284,486 | 2024-4-6 | https://stackoverflow.com/questions/78284486/pil-creates-gifs-with-less-images-than-the-input-despite-save-all-true | I was trying to make plots using matplotlib into GIFs for further analysis, when during the analysis I noticed that the output of the analysis consisted of less images than expected. I created and saved 3956 plots with axes turned off (this would make my analysis simpler) then proceeded to create GIFs in the easiest wa... | I do not have enough reputation to make this a comment, so I respond without solving the issue completely, sorry for that. I was running into the same issue until now. Does your list of frames contain duplicates or very similar frames? In this git issue it is outlined that it is intended behaviour from pillow to remove... | 2 | 1 |
78,292,857 | 2024-4-8 | https://stackoverflow.com/questions/78292857/gunicorn-workers-on-google-app-engine-randomly-sending-sigkill-leading-to-timeou | This happens randomly, sometimes when a new instance is spun up (example below), sometimes when an instance is already been running for some time. This error cycle of "Boot worker - SIGKILL - TIMEOUT" can last anywhere from 10s to more than an hour. This can also happen to any endpoint in my application, it has happene... | For anyone else who faces this issue in the future, I eventually moved to running my application in a docker container on Google Cloud Run, with the preload_app=True setting in my gunicorn config file and have completely eliminated the issue. For some reason, any other configuration causes the TIMEOUT issue. Eg, runnin... | 2 | 0 |
78,295,801 | 2024-4-9 | https://stackoverflow.com/questions/78295801/numpy-convolve-with-valid | I am working on convolving chunks of a signal with a moving average type smoothing operation but having issues with the padding errors which affects downstream calculations. If plotted this is the issue that is caused on the chunk boundaires. To fix this I am adding N samples from the previous chunk to the beginning o... | I assume (1) the reader has a basic understanding of what a convolution is and (2) a kernel with an odd number > 1 of elements is used. Short answer: Use np.convolve(…, mode="valid"). Before convolving, pad your chunks … at their start with the (len(kernel) - 1) / 2 last elements from the preceding chunk, … at their... | 2 | 4 |
78,287,158 | 2024-4-7 | https://stackoverflow.com/questions/78287158/modulenotfounderror-no-module-named-scipy-special-cdflib-with-scipy-1-13-0 | platform:windows server 2019 python:3.12.2 scipy:1.13.0 When I upgraded scipy from 1.12 to 1.13 there was No module named scipy.special._cdflib.This doesn't happen when I use 1.12.0. Traceback (most recent call last): File "src\predict.py", line 14, in <module> from src.utils.calc_utils import * File "PyInstaller\loade... | Appenrently this is a known issue in pyinstaller, look at which version you have. In the changelog it states Update scipy.special._ufuncs hook for compatibility with SciPy 1.13.0 (add scipy.special._cdflib to hidden imports). (#8394) So using version 6.6.0 of pyinstaller might work | 5 | 3 |
78,280,741 | 2024-4-5 | https://stackoverflow.com/questions/78280741/multiple-colors-of-matplotlib-single-xtick-label | I am fairly new to Matplotlib and appreciate your help with my question: I am looking to generate a figure that each label has 2 colors. For example, a label named 'first_color\nsecond_color', first and second color are different. If I use label.set_color(colors[0]), the whole color of label will be changed. If I use l... | If the tick labels need a different color on different lines, you can explicit place text at the tick positions. With an x-axis transform, the x-position can be given in "data coordinates" (0 for the first label, 1 for the second, etc.) and the y-position in "axes coordinates" (0 at the bottom, 1 at the top of the "ax"... | 2 | 1 |
78,300,493 | 2024-4-9 | https://stackoverflow.com/questions/78300493/osmnx-shortest-path-returns-none-for-valid-origin-and-destination-nodes | Description When calculating the shortest path between two locations with OSMnx, ox.shortest_path() failed to get any route and returns None origin_lat=42.482, origin_lon=-70.910, dest_lat=42.472, dest_lon=-70.957 The points I am querying are quite normal, i.e. they are not super far/close to each other, and there are ... | What is the root cause for this issue? The reason is this OSM way: https://www.openstreetmap.org/way/1243001416 It is digitized as a one-way street inbound into this community. There is no outbound way digitized. Therefore, you can solve routes inbound to the community, but you cannot solve routes outbound from it du... | 2 | 0 |
78,298,579 | 2024-4-9 | https://stackoverflow.com/questions/78298579/building-a-pypi-package-using-setuptools-pyproject-toml-with-a-custom-director | I have a custom directory structure which is not the traditional "src" or "flat" layouts setuptools expects. This is a sample of the directory tree: my_git_repo/ ├── Dataset/ │ ├── __init__.py │ ├── data/ │ │ └── some_csv_file.csv │ ├── some_ds1_script.py │ └── some_ds2_script.py └── Model/ ├── __init__.py ├── utils/ │... | I ended up re-structuring my project in a "src" layout where "src" is replaced by my package name | 2 | 0 |
78,300,949 | 2024-4-9 | https://stackoverflow.com/questions/78300949/how-to-unpack-a-string-into-multiple-columns-in-a-polars-dataframe-using-express | I have a Polars DataFrame containing a column with strings representing 'sparse' sector exposures, like this: df = pl.DataFrame( pl.Series("sector_exposure", [ "Technology=0.207;Financials=0.090;Health Care=0.084;Consumer Discretionary=0.069", "Financials=0.250;Health Care=0.200;Consumer Staples=0.150;Industrials=0.400... | There are potentially two ways to do it that I can think of. Regex extract df.with_columns(pl.col('sector_exposure').str.extract(x+r"=(\d+\.\d+)").cast(pl.Float64).alias(x) for x in ["Technology", "Financials", "Health Care", "Consumer Discretionary", "Consumer Staples","Industrials"]) shape: (2, 7) ┌────────────────┬─... | 5 | 6 |
78,299,167 | 2024-4-9 | https://stackoverflow.com/questions/78299167/is-there-a-way-to-extract-text-from-python-datacompy-comparison-result | I am using datacompy to compare all columns from two dataframe. My goal is to extract the column(s) name with unmatched values. In the below example, I used inventory_id as a join column to compare df1 and df2. One column shows unmatched value, which is 'indinv_vari_ware_uid'. This is a simple example, in real work sit... | You can use compare.column_stats for this: a list with dictionaries that contain the relevant information per column. Sample setup: import pandas as pd import datacompy data = {'id': [1, 2], 'col1': [1, 2]} df1 = pd.DataFrame(data) data2 = {'id': [1, 2], 'col1': ['A', 'B']} df2 = pd.DataFrame(data2) compare = datacom... | 2 | 2 |
78,298,555 | 2024-4-9 | https://stackoverflow.com/questions/78298555/how-to-add-columns-to-a-pandas-dataframe-containing-max-of-each-row-and-corresp | This is a revisit to the question Add columns to pandas dataframe containing max of each row, AND corresponding column name where a solution was provided using the now deprecated method ix. How can you do the same thing using iloc or loc instead? I've tried both, but I'm getting: IndexError: boolean index did not matc... | Here ix is used to select the columns up to c, you can do the same with loc: df['maxcol'] = (df.loc[:, :'c'].eq(df['maxval'], axis=0) .apply(lambda x: ','.join(df.columns[:3][x==x.max()]),axis=1) ) Or, since [:3] is used later with iloc: df['maxcol'] = (df.iloc[:, :3].eq(df['maxval'], axis=0) .apply(lambda x: ','.join... | 3 | 3 |
78,288,162 | 2024-4-7 | https://stackoverflow.com/questions/78288162/how-to-turn-a-dynamically-allocated-c-array-into-a-numpy-array-and-return-it-to | So I have found similar problems in threads on here, but I haven't been able to find a solution that works for me. I am building a C extension module for Python in Visual Studio 2022 with Python 3.9. The module takes numpy arrays as inputs and returns numpy arrays. Right now, I just have it read the shape of the input ... | Here's my solution with a few other fixes. The above code in the OP does not get the data from the array properly (the calculations did not depend on the actual values of the elements, and only the shape). It also does not calculate the index properly. However the crux of the solution is that I am instantiating the arr... | 3 | 0 |
78,295,126 | 2024-4-8 | https://stackoverflow.com/questions/78295126/polars-cumsum-on-column-if-value-changes | I'm stuck with a cum_sum problem where I only want tot cumulatively sum unique values over a column. Here's an example of what I want to achieve: ┌─────┬─────┬─────┐ │ a ┆ b ┆ d │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╡ │ 1 ┆ 1 ┆ 1 │ │ 1 ┆ 2 ┆ 2 │ │ 1 ┆ 3 ┆ 3 │ │ 1 ┆ 1 ┆ 1 │ │ 2 ┆ 1 ┆ 4 │ │ 2 ┆ 2 ┆ ... | You might be looking for pl.Expr.rank with method="dense". df.with_columns( pl.struct("a", "b").rank("dense").alias("id") ) shape: (8, 3) ┌─────┬─────┬─────┐ │ a ┆ b ┆ id │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ u32 │ ╞═════╪═════╪═════╡ │ 1 ┆ 1 ┆ 1 │ │ 1 ┆ 2 ┆ 2 │ │ 1 ┆ 3 ┆ 3 │ │ 1 ┆ 1 ┆ 1 │ │ 2 ┆ 1 ┆ 4 │ │ 2 ┆ 2 ┆ 5 │ │ ... | 3 | 3 |
78,295,116 | 2024-4-8 | https://stackoverflow.com/questions/78295116/conditional-multiplication-of-dataframes-with-nan | I have two DataFrames A = 0 1 2 0 0.5 0 0.1 0 0.2 0.2 0 0 and B = 0 1.0 1.0 NaN I need to multiply each row of A by B element-wise, but I need the computation done so that the resulting dataframe shows a NaN only if the original element of A is 0. If I do A * B.transpose() I get 0 1 2 ... | IIUC you can try: out = A * B.T.values out[out.isna() & ~A.eq(0)] = A print(out) Prints: 0 1 2 0 0.0 0.5 NaN 1 0.1 0.0 0.2 2 0.2 0.0 NaN | 2 | 1 |
78,295,104 | 2024-4-8 | https://stackoverflow.com/questions/78295104/pandas-change-multiple-level-column-name-to-one-level | I have a dataframe with two-level column names as: ID Value A B ---------------- 1 6 2 5 3 4 4 3 5 2 6 1 I want to change the column head with: column_mapping = { ('ID', 'A') : 'ID:A', ('Value', 'B'): 'Value:B' } I tried rename: df.rename(columns=column_mapping, inplace=True) which does not work. Any idea how? | Try: df.columns = df.columns.map(":".join) print(df) Prints: ID:A Value:B 0 1.0 6.0 1 2.0 5.0 2 3.0 4.0 3 4.0 3.0 4 5.0 2.0 5 6.0 1.0 | 2 | 1 |
78,294,477 | 2024-4-8 | https://stackoverflow.com/questions/78294477/create-a-conditional-cumulative-sum-in-polars | Example dataframe: testDf = pl.DataFrame({ "Date1": ["2024-04-01", "2024-04-06", "2024-04-07", "2024-04-10", "2024-04-11"], "Date2": ["2024-04-04", "2024-04-07", "2024-04-09", "2024-04-10", "2024-04-15"], "Date3": ["2024-04-07", "2024-04-08", "2024-04-10", "2024-05-15", "2024-04-21"], 'Value': [10, 15, -20, 5, 30] }).w... | I'll need to think about it a bit more to understand whether a solution relying purely on polars' native expression API is possible. However, here is a preliminary solution relying on the discouraged pl.Expr.map_elements. ( testDf .with_columns( pl.col("Date1") .map_elements( lambda x: \ ( testDf .filter( pl.col("Date2... | 3 | 4 |
78,290,363 | 2024-4-8 | https://stackoverflow.com/questions/78290363/question-about-python-asynchronous-programming-using-asyncio-and-await-async-def | I am currently studying the differences between synchronous programming in Python and asynchronous programming using asyncio by looking at example code. While doing so, I have a question. Since my current job is a machine learning engineer, I wrote the example code using analogies to a server logic that serves machine ... | To make my comments an answer: async doesn't make your synchronous Python functions automagically asynchronous; async really is a form of cooperative multitasking. Here's a simplified example with f doing asynchronous work (in the form of an asyncio.sleep) and f2 doing synchronous work (in the form of time.sleep). impo... | 2 | 2 |
78,290,178 | 2024-4-8 | https://stackoverflow.com/questions/78290178/how-can-i-change-a-streaks-of-numbers-according-to-the-previous-streak | This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'a': [1, 1, 1, 2, 2, 2, 2, 2, -1, -1, 2, 2, 2], } ) Expected output: Changing column a: a 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 -1 9 -1 10 2 11 2 12 2 The process is as follows: a) Finding streaks of 1s and 2s b) If a streak of 2 comes after a streak of 1, t... | You can use shift and ffill to access the previous group, then boolean indexing: # previous value s = df['a'].shift() # check if previous group is 1 m1 = s.where(df['a'].ne(s)).ffill().eq(1) # is value 2? m2 = df['a'].eq(2) df.loc[m1&m2, 'a'] = 1 Output: a 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 -1 9 -1 10 2 11 2 12 2 Int... | 2 | 2 |
78,289,206 | 2024-4-7 | https://stackoverflow.com/questions/78289206/how-do-i-get-this-star-pattern-to-work-with-only-one-for-loop-in-python | Very new to python and coding in general! Trying to get a star pattern that looks like this: * ** *** **** ***** **** *** ** * to work using a for loop, but I'm only allowed to use a single for loop, and embed an if/else statement inside to get it to work. If I could use 2 for loops I'd know how to do it but not sure ... | As others have mentioned in the comments, your range() structure is flawed. You can simplify the approach by using > and < in your if else like this: print("Pattern: ") star = "*" for i in range(9): if i < 5: print(star * (i + 1)) else: print(star * (9 - i)) | 2 | 1 |
78,288,578 | 2024-4-7 | https://stackoverflow.com/questions/78288578/problem-with-pip-install-filenotfounderror-errno-2-no-such-file-or-directory | I wanted to use contributions graph in my Django project, so after quick research I decided to use 'contributions-django' library. But when I tried to install it, I got stuck with this error:: FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt' [end of output] note: This error originates from a ... | See https://github.com/vsoch/contributions-django/issues/3 . The bug was reported in 2020, still open. The last commit also was 4 years ago. The project seems to be abandoned. This command works, though: pip install git+https://github.com/vsoch/contributions-django.git You need Git installed and git command present in... | 2 | 2 |
78,288,826 | 2024-4-7 | https://stackoverflow.com/questions/78288826/dataframe-that-is-a-partial-view | Is it possible to create a dataframe where one fragment is a view of another df and the remaining fragment is not a view? I am unable to create such a df, but I want to know if it is possible. If this is possible, can you give an example of such a dataframe? | I think you can make something like this when you construct the dataframe with copy=False parameter. Consider this: arr = np.array([[1, 2, 3], [4, 5, 6]]) df1 = pd.DataFrame(arr, columns=["a1", "b1", "c1"], copy=False) df2 = pd.DataFrame(arr, columns=["a2", "b2", "c2"], copy=False) df2["d"] = 999 print(df1) print(df2) ... | 2 | 2 |
78,288,206 | 2024-4-7 | https://stackoverflow.com/questions/78288206/django-queryset-how-to-aggregate-repeated-elements-and-add-quantity-field-to-it | I have a feeling the solution to this is very simple, but as new to Django I am not able to figure it out... Given the following QuerySet: <QuerySet [ {'id': 2, 'prodclassQuery_id': 1, 'prodDescription': 'Hofbräu Kellerbier 500 ml', 'prodPrice': Decimal('6.50')}, {'id': 1, 'prodclassQuery_id': 1, 'prodDescription': 'To... | You can also use a combination of values() and annotate(), so: from django.db.models import Count def display_orders(request): orders = Order.objects.values( 'id', 'orderTable', 'menuQuery' ).annotate( poQty_=Count('id') ).order_by( 'id', 'orderTable', 'menuQuery' ) context = { 'orders': orders, } return render(reques... | 2 | 1 |
78,279,823 | 2024-4-5 | https://stackoverflow.com/questions/78279823/how-exactly-the-forward-and-backward-hooks-work-in-pytorch | I am trying to understand how exactly code-wise the hooks operate in PyTorch. I have a model and I would like to set a forward and backward hook in my code. I would like to set a hook in my model after a specific layer and I guess the easiest way is to set a hook to this specific module. This introductory video warns t... | How does a hook work? A hook allows you to execute a specific function - referred to as a "callback" - when a particular action has been performed. In this case, you are expecting self.get_attention to be called once the forward function of module has been accessed. To give a minimal example of how a hook would look li... | 11 | 9 |
78,287,528 | 2024-4-7 | https://stackoverflow.com/questions/78287528/python-gspread-formatting-set-vertical-alignment-to-middle-for-range-of-cells | I'm trying to format some cells of a google sheet. Since I'm using new line characters in certain cells of the first row, I noticed vertical alignment is automatically set to bottom, whereas I would like to have a centered vertical alignment for a range of cells in this first row. I've omitted quite a few columns from ... | For vertical alignment, you don't use a boolean. You should use a string specifying the alignment type: import gspread from google.oauth2.service_account import Credentials scopes = ["https://www.googleapis.com/auth/spreadsheets"] creds = Credentials.from_service_account_file('your_credentials_file.json', scopes=scopes... | 2 | 2 |
78,287,484 | 2024-4-7 | https://stackoverflow.com/questions/78287484/stacked-bar-chart-from-dataframe | Program Here's a small Python program that gets tax data via the treasury.gov API: import pandas as pd import treasury_gov_pandas # ---------------------------------------------------------------------- df = treasury_gov_pandas.update_records( url = 'https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v1/ac... | I have create dummy df and tested it worked This code creates a DataFrame with random transaction data grouped by date and category. It then pivots the data to display a stacked bar chart where each bar represents a date, and the stack segments represent transaction amounts for different categories. I hope that solutio... | 2 | 1 |
78,285,182 | 2024-4-6 | https://stackoverflow.com/questions/78285182/why-is-numpys-vectorized-evaluation-slower-when-storing-vectors-as-class-attrib | I am writing a helper class to evaluate a parametrized function over a grid. Since the grid does not change with the parameter, I chose to create it once and for all as a class attribute. However, I realized having the grid as a class attribute causes a significant performance drop as compared to having it as a global ... | You aren't consistent with setting the datatype of your grid. Compare self.x_2d_values = np.linspace(x_min, x_max, grid_2d_size, dtype=np.float128) self.y_2d_values = np.linspace(y_min, y_max, grid_2d_size, dtype=np.float128) With: x_2d_values = np.linspace(x_min, x_max, grid_2d_size) y_2d_values = np.linspace(y_min, ... | 2 | 2 |
78,285,601 | 2024-4-6 | https://stackoverflow.com/questions/78285601/rolling-standard-deviation-of-all-columns-ignoring-nans | I have the following dataframe: data = {'a': {1: None, 2: 1, 3: 7, 4: 2, 5: 4}, 'b': {1: None, 2: 2, 3: 2, 4: 9, 5: 6}, 'c': {1: None, 2: 2.0, 3: None, 4: 7.0, 5: 4.0}} df = pd.DataFrame(data).rename_axis('day') a b c day 1 NaN NaN NaN 2 1.0 2.0 2.0 3 7.0 2.0 NaN 4 2.0 9.0 7.0 5 4.0 6.0 4.0 I want to get a new column ... | You can use numpy.nanstd for working with missing values: #source https://stackoverflow.com/a/77704074/2901002 from numpy.lib.stride_tricks import sliding_window_view as swv N = 3 df.loc[df.index[N-1:], 'std'] = np.nanstd(swv(df.to_numpy(), N, axis=0), (1,2), ddof=1) print (df) a b c std day 1 NaN NaN NaN NaN 2 1.0 2.0... | 2 | 4 |
78,284,936 | 2024-4-6 | https://stackoverflow.com/questions/78284936/using-group-by-in-pandas-but-with-condition | I have dataframe data = {'time': ['10:00', '10:01', '10:02', '10:02', '10:03','10:04', '10:06', '10:10', '10:15'], 'price': [100, 101, 101, 103, 101,101, 105, 106, 107], 'volume': [50, 60, 30, 80, 20,50, 10, 40, 40]} I need to group by this df by every 5 minutes and price, sum up the volume df.groupby([df['time'].dt.f... | It looks like you want the cumulated sum of the volume with groupby.cumsum: df['cum_volume'] = (df.groupby([df['time'].dt.floor('5min'), 'price']) ['volume'].cumsum() ) Updated df: time price volume cum_volume 0 2024-04-06 10:00:00 100 50 50 1 2024-04-06 10:01:00 101 60 60 2 2024-04-06 10:02:00 101 30 90 3 2024-04-06... | 2 | 3 |
78,284,642 | 2024-4-6 | https://stackoverflow.com/questions/78284642/driver-find-element-cant-find-an-element-by-class-name | I tried to use driver.find_element, by "class_name" to find button and click on it for expanding rooms on - https://www.qantas.com/hotels/properties/18482?adults=2&checkIn=2024-04-16&checkOut=2024-04-17&children=0&infants=0#view-rooms , but received error message raise exception_class(message, screen, stacktrace) sele... | It should be like that. If there is only one class then use find_element(By.CLASS_NAME," #what is class name"). However, button has 2 different class so u need to use CSS_SELECTOR instead CLASS_NAME. Finally fyi "class name" doesn't work in find_elements as an argument. Button = driver.find_element(By.CSS_SELECTOR,".cs... | 2 | 1 |
78,284,506 | 2024-4-6 | https://stackoverflow.com/questions/78284506/how-to-update-python-to-the-latest-version-3-12-2-in-wsl2 | My Python version in my WSL Ubuntu is 3.10.12 and it's not upgrading through these commands even though 3.12.2 is released now. (My WSL Ubuntu version is 22.04) sudo apt update sudo apt install python3 python3-pip Will a particular distribution have control over how much you can upgrade a package? and is it recommend... | Linux distros normally have a Python version tied to the distro and used for various admin scripts. You should not expect that to follow the latest releases of Python. And don't try to force change it because you could break your OS. If you need newer Python versions for your work, install it in user space. | 6 | 1 |
78,284,077 | 2024-4-6 | https://stackoverflow.com/questions/78284077/iterate-over-values-of-nested-dictionary | Nested_Dict = {'candela_samples_generic': {'drc_dtcs': {'domain_name': 'TEMPLATE-DOMAIN', 'dtc_all':{ '0x930001': {'identification': {'udsDtcValue': '0x9300', 'FaultType': '0x11', 'description': 'GNSS antenna short to ground'}, 'functional_conditions': {'failure_name': 'short_to_ground', 'mnemonic': 'DTC_GNSS_Antenna_S... | Much, much better 🤓 You'll need to make sure that for each part of the Header dictionary structure, we're not only iterating over the keys but also get into their nested structure to retrieve udsDtcValue, FaultType, description and failure_name from Nested_Dict. def get_value_from_nested_dict(nested_dict, path): for k... | 2 | 4 |
78,283,909 | 2024-4-6 | https://stackoverflow.com/questions/78283909/pandas-percentage-from-total-in-pivot-table | I used to tackle this kind of thing reasonably quickly within DAX, but being new to pandas, I have been stuck for a while on this: I am trying to output a pivot table showing the % of visa sales per month (columns) and per city (rows). Here is the output I am looking for: Jan Feb London 50.055991 56.435644 Paris 15.11... | Using a pivot_table, pipe to compute the ratio, and unstack to reshape: df['Amount'] = pd.to_numeric(df['Amount'].str.strip(' $')) out = (df .pivot_table(index=['Month', 'City'], columns='Card', values='Amount', aggfunc='sum') .pipe(lambda x: x['Visa']/x.sum(axis=1)*100) .unstack('Month') ) Output: Month Feb Jan City ... | 4 | 2 |
78,283,840 | 2024-4-6 | https://stackoverflow.com/questions/78283840/sqlalchemy-like-all-orm-analog | I need to find documents that satisfy the entire list of passed parameters. I did it using raw query, but for my project specs, raw query can't be used, and I should use ORM. Raw query is: SELECT * FROM outbox_document WHERE document_summary like all(array['%par1%', '%par2%', '%par3%']); It's works well, but I can't f... | You can use sqlalchemy.all_. OutBoxDocument.document_summary.like(all_(["%par1%", "%par2%", "%par3%"])) This generates the following query SELECT outbox_document.id, outbox_document.document_summary FROM outbox_document WHERE outbox_document.document_summary LIKE ALL (%(param_1)s) Complete code from sqlalchemy import... | 2 | 2 |
78,275,255 | 2024-4-4 | https://stackoverflow.com/questions/78275255/how-can-i-make-it-so-that-when-i-click-an-icon-a-window-with-information-appear | There is an icon in the program; by clicking on it, a window with information should appear on top of the program. How can this be implemented? import flet as ft def main(page: ft.page): page.title = "Тренировка интуиции" page.window_width = 400.00 page.window_height = 500.00 page.window_resizable = False def info(e): ... | import flet as ft def main(page: ft.page): page.title = "Тренировка интуиции" page.window_width = 400.00 page.window_height = 500.00 page.window_resizable = False Build info dialog with using AlertDialog. Add action to close your dialog. Content is the main content in pop-up. def info(e): diaolog = ft.AlertDialog(tit... | 2 | 1 |
78,281,668 | 2024-4-5 | https://stackoverflow.com/questions/78281668/nonlocal-variable-not-updated-when-return-value-from-recursive-function-is-not-b | Came across some pattern similar to this for a leetcode problem. Basically, both functions sums a list a recursively using a nonlocal value. The unassigned value only updates res once it seems. def assigned_sum(l: list[int]): res = 0 def recurse(i: int): nonlocal res if i >= len(l): return 0 assigned = recurse(i+1) res... | The difference can be seen more clearly between these two variants: (a): res = res + recurse(i+1) and (b): res = recurse(i+1) + res For your test run, (a) will return 1, while (b) will return the intended 15. The difference is caused by the moment when the value of res is taken: before the recursive call or after. If... | 2 | 5 |
78,276,174 | 2024-4-4 | https://stackoverflow.com/questions/78276174/post-a-pandas-dataframe-from-jupyter-notebooks-into-a-stack-overflow-problem | What are the steps to post a Pandas dataframe in a Stack Overflow question? I found: How to make good reproducible pandas examples. I followed the instructions and used pd.read_clipboard, but I still had to spend a significant amount of time formatting the table to make it look correct. I also found: How to display a p... | .to_markdown() The easiest method I found was to use print(df.to_markdown()). This will convert the data into mkd format which can be interpreted by SO. For example with your dataframe, the output is: first_name last_name age 0 Captain Crunch 72 1 Trix 36 Rabbit 2 Count Chocula 41 3 Tony 54 Tiger 4 Buzz... | 4 | 5 |
78,280,954 | 2024-4-5 | https://stackoverflow.com/questions/78280954/add-timezone-based-on-column-value | I have a polars Dataframe with two columns: a string column containing datetimes and an integer column containing UTC offsets (for example -4 for EDT). Essentially the Dataframe looks like this: >>> data shape: (2, 2) ┌─────────────────────┬──────────┐ │ Datetime ┆ Timezone │ │ --- ┆ --- │ │ str ┆ i64 │ ╞══════════════... | If you're ok with keeping things in UTC, you can use df = pl.DataFrame( {"Datetime": ["2022-01-01 12:52:23", "2023-03-31 04:22:59"], "Timezone": [-4, -5]} ) df.with_columns( pl.col("Datetime") .str.to_datetime("%Y-%m-%d %H:%M:%S", time_zone="UTC") .dt.offset_by(pl.format("{}h", -pl.col("Timezone"))) .alias("dt_conv") )... | 2 | 2 |
78,278,272 | 2024-4-5 | https://stackoverflow.com/questions/78278272/error-installing-dlib-in-python-on-ubuntu | I want to use OpenCV for a python project and for that reason want to install dlib library. I ran the command pip install dliband it gave me following error: Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected pa... | Since you are using anacoda you probably have messed up your run environment. Your error doesn't provide insight on what actually has happened but a makeshift, however it is demotivated, can fix your error. After installing cmake as mentioned in link answered install packages in root directory using sudo pip install cm... | 2 | 1 |
78,278,746 | 2024-4-5 | https://stackoverflow.com/questions/78278746/plot-for-every-subgroup-of-a-groupby | data = {0: {'VAR1': 'A', 'VAR2': 'X', 'VAL1': 3, 'VAL2': 1}, 1: {'VAR1': 'A', 'VAR2': 'X', 'VAL1': 4, 'VAL2': 1}, 2: {'VAR1': 'A', 'VAR2': 'X', 'VAL1': 5, 'VAL2': 1}, 3: {'VAR1': 'A', 'VAR2': 'Y', 'VAL1': 3, 'VAL2': 2}, 4: {'VAR1': 'A', 'VAR2': 'Y', 'VAL1': 4, 'VAL2': 2}, 5: {'VAR1': 'A', 'VAR2': 'Y', 'VAL1': 5, 'VAL2... | I would use seaborn.relplot, which would work as a one-liner: import seaborn as sns sns.relplot(df, col='VAR1', hue='VAR2', x='VAL1', y='VAL2') Output: | 3 | 4 |
78,278,680 | 2024-4-5 | https://stackoverflow.com/questions/78278680/why-is-the-scraped-html-different-from-browser-inspected-element | I am currently working on a web scraping project and encountered an issue while scraping data from https://foundersfund.com/portfolio. I managed to retrieve all the links to each company's page successfully. However, upon testing some of these links, I noticed that the output HTML differs from what is shown in the insp... | Content is loaded / rendered dynamically by JavaScript - Sometimes you can also see it on the page by refreshing it, then spacex is displayed for a short time, because the resource is first loaded and rendered. Only fractions of a second later the actual company information is rendered. So try to use the api instead fo... | 2 | 2 |
78,278,506 | 2024-4-5 | https://stackoverflow.com/questions/78278506/how-to-select-first-n-number-of-groups-based-on-values-of-a-column-conditionally | This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'a': [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 10, 22], 'b': [1, 1, 1, -1, -1, -1, -1, 2, 2, 2, 2, -1, -1, -1, -1], 'c': [25, 25, 25, 45, 45, 45, 45, 65, 65, 65, 65, 40, 40, 30, 30] } ) The expected output: Grouping df by c and a condition: a b... | You can use custom masks for boolean indexing: # identify groups with all 1 m1 = df['b'].eq(1).groupby(df['c']).transform('all') # identify groups with all -1 m2 = df['b'].eq(-1).groupby(df['c']).transform('all') # keep rows of first 2 groups with all -1 m3 = df['c'].isin(df.loc[m2, 'c'].unique()[:2]) # select m1 OR m3... | 4 | 4 |
78,274,221 | 2024-4-4 | https://stackoverflow.com/questions/78274221/use-caplog-in-autouse-fixture-in-pytest | I'd like to wrap all my tests with a fixture where the logs logged with loguru are checked for error messages. I tried this: @pytest.fixture(autouse=True) def assert_no_log_error(caplog): yield assert "ERROR" not in caplog.text But caplog.text is always empty. I assume, caplog is cleared after the test and before the ... | I found the answer with the help of this post. First, since pytest uses the standard python logging module under the hood, the logs from loguru need to be captured properly. This can be done using the pytest-loguru module, according to the loguru docs. Install pytest-loguru with: pip install pytest-loguru Then the fixt... | 2 | 0 |
78,277,628 | 2024-4-5 | https://stackoverflow.com/questions/78277628/create-a-dataframe-from-a-series-and-specifically-how-to-re-name-a-column-in-it | New to Python. I come from a SQL world where I'm used to running queries and applying them. It's handy to take a list of things, get their count and then use a subset of that count (like the top 5) and apply it to other data. With Python/Pandas, I still have not quite grokked the process. By way of example: A simple da... | IIUC, you can just use groupby with as_index=False and then take the group size: out = nan_df.groupby(['A','B', 'C', 'D','E', 'F'], as_index=False).size() Output: A B C D E F size 0 False False False False False False 1 1 False False False False False True 2 2 False False True False False False 2 3 False True False F... | 2 | 1 |
78,275,253 | 2024-4-4 | https://stackoverflow.com/questions/78275253/best-way-to-create-serializable-data-model | somewhat inexperienced in python. I am coming from C# world, and I am trying to figure out what is the best practice to create a data structure in python that: can have empty fields (None) can have default values assigned to some fields can have aliases assigned to fields that would be used during serialization to cl... | Hard to say what is "best practice", I personally would say that just working with dictionaries is very common unless you have a good reason to define a class instead (limitation: no default values, no aliases). If that works for you depends on how you intend to use the data. If you have a dictionary, serializing it is... | 2 | 3 |
78,276,558 | 2024-4-4 | https://stackoverflow.com/questions/78276558/pandas-dataframe-fillna-with-booleans | I have 2 dataframes, one that contains data and one that contains exlusions that need to be merged onto the data and marked as included(True or False). I have been doing this as follows for a couple of years by simply adding a new column to the exclusions data frame and setting everything to True, then merging that ont... | You can use (for pandas 2.2.1 etc) : dfMainData['excluded'] = dfMainData['excluded'].fillna(0).astype('bool') which gives name other reason excluded 0 apple blah NaN False 1 pear blah pears suck True 2 orange blah NaN False 3 watermelon blah too messy! True | 4 | 4 |
78,276,184 | 2024-4-4 | https://stackoverflow.com/questions/78276184/filling-an-empty-data-frame-or-array-with-values-from-the-column-of-another-data | I need to creat an empty data frame that stores values from a column of another data frame base on some conditions being met in two columns of the same second data frame. I have a data frame test_mob_df = pd.DataFrame( {"geoid_o": [10002, 18039, 18039, 18182, 10006, 18111, 18005, 17001], "geoid_d": [10005, 18039, 18111... | You can do: test_mob_df = pd.DataFrame( { "geoid_o": [10002, 18039, 18039, 18182, 10006, 18111, 18005, 17001], "geoid_d": [10005, 18039, 18111, 18182, 18005, 17004, 18050, 15001], "pop_flows": [20, 10, 9, 15, 2, 1, 6, 30], } ) state_county_fip = [18182, 18111, 18005, 18039, 18050, 18001] out = pd.crosstab( test_mob_df.... | 3 | 2 |
78,274,097 | 2024-4-4 | https://stackoverflow.com/questions/78274097/group-cluster-polars-dataframe-by-substring-in-string-or-string-in-substring | Given this Polars DataFrame: df = pl.DataFrame( { "id": [1, 2, 3, 4, 5], "values": ["A", "B", "A--B", "C--A", "D"], } ) 1, How can I group/cluster it so that 1,2 and 3 ends up in the same group? 2. Can I even achieve having 4 in the same group/cluster? | Assuming you want to merge groups based on the substrings (separated by --), this is unfortunately not straightforward. You can't vectorize this since a member of a group can link to another group that links to another, etc. One option is to use graph theory to identify the connected components. You can do this with ne... | 2 | 1 |
78,272,574 | 2024-4-4 | https://stackoverflow.com/questions/78272574/what-is-the-best-way-to-slice-a-dataframe-up-to-the-first-instance-of-a-mask | This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'a': [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70], 'b': [1, 1, 1, -1, -1, -2, -1, 2, 2, -2, -2, 1, -2], } ) The mask is: mask = ( (df.b == -2) & (df.b.shift(1) > 0) ) Expected output: slicing df up to the first instance of the mask: a b 0 10 1 1 ... | You can filter by inverted mask with Series.cummax: out = df[~mask.cummax()] print (out) a b 0 10 1 1 15 1 2 20 1 3 25 -1 4 30 -1 5 35 -2 6 40 -1 7 45 2 8 50 2 How it working: print (df.assign(mask=mask, cumax=mask.cummax(), inv_cummax=~mask.cummax())) a b mask cumax inv_cummax 0 10 1 False False True 1 15 1 False Fal... | 2 | 5 |
78,271,090 | 2024-4-4 | https://stackoverflow.com/questions/78271090/why-do-i-get-valueerror-unrecognized-data-type-x-of-type-class-list | I tried to run the code below, taken from CS50's AI course: import csv import tensorflow as tf from sklearn.model_selection import train_test_split # Read data in from file with open("banknotes.csv") as f: reader = csv.reader(f) next(reader) data = [] for row in reader: data.append( { "evidence": [float(cell) for cell ... | https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit It appears you're giving Model.fit([X], [y]) the wrong type. What I almost always do before handing off data to train_test_split is converting my features and labels to np arrays. So you can either convert them before handing them off to train_test_split or ... | 5 | 10 |
78,269,252 | 2024-4-3 | https://stackoverflow.com/questions/78269252/concatenating-pandas-dataframe-with-multi-index-in-different-order | I have two data frames, which should be concatenated. Both are multi index data frames with identical indexes, but in a different order. So, the index of the first data frame (df) looks like: MultiIndex([(11, 1, 1), (11, 1, 2), (11, 1, 3), ... (11, 24, 5), (11, 24, 6), (11, 24, 7)], names=['id_a', 'id_b', 'id_c'], leng... | If your levels are in a different order, you first need to reorder them with reorder_levels: result = pd.concat([df, df2.reorder_levels(df.index.names)]) If you have more than 2 DataFrames to concatenate: dfs = [df, df2, df3, df4] levels = dfs[0].index.names result = pd.concat([d.reorder_levels(levels) for d in dfs]) ... | 2 | 5 |
78,271,102 | 2024-4-4 | https://stackoverflow.com/questions/78271102/improve-dataframe-performance-for-large-datasets | I have a large datasets need to filter out root packages as below: sort data(package column) by string length. start from beginning, scan the following data, if it starts with current data, then mark it as False. repeat step 2 till end. To improve performance, I add a flag column to keep track it's processed or not. ... | IIUC you can do: from functools import cmp_to_key from itertools import groupby def fn(g): out = [] for _, k in groupby(g.sort_values(), cmp_to_key(lambda a, b: not b.startswith(a))): out.append(next(k)) return pd.Series(out) out = df.groupby("name")["package"].apply(fn).droplevel(1).reset_index() print(out) Prints: ... | 3 | 4 |
78,268,258 | 2024-4-3 | https://stackoverflow.com/questions/78268258/attributeerror-sentencetransformer-object-has-no-attribute-embed-documents | I'm trying to build a RAG using the Chroma database, but when I try to create it I have the following error : AttributeError: 'SentenceTransformer' object has no attribute 'embed_documents'. I saw that you can somehow fix it by modifying the Chroma library directly, but I don't have the rights for it on my environment.... | Use SentenceTransformerEmbeddings instead of SentenceTransformer, or simply HuggingFaceEmbeddings Reference > https://python.langchain.com/docs/integrations/text_embedding/sentence_transformers | 4 | 2 |
78,270,330 | 2024-4-3 | https://stackoverflow.com/questions/78270330/how-to-find-linear-dependence-mod-2-in-python | I have a n+1 by n matrix of integers. I want to find a linear combination of the rows that reduces to zero mod 2. How would I do this in python? I could write gaussian elimination on my own, I feel there ought to be a way to do this using numpy or other library without writing it from scratch. Example: I have the matri... | You can use galois: from galois import GF2 import numpy as np A = [[1, 3, 0], [1, 1, 0], [1, 0, 1], [0, 1, 5]] A = GF2(np.array(A).T % 2) print(A.null_space()) It gives: [[1 0 1 1] [0 1 1 1]] The rows are a basis of the null space of the matrix over the field F_2. | 2 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.