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 |
|---|---|---|---|---|---|---|
77,128,073 | 2023-9-18 | https://stackoverflow.com/questions/77128073/python-numpy-invert-boolean-mask-operation | When I have an array a and a boolean mask b, I can find the 'masked' vector c. a = np.array([1, 2, 4, 7, 9]) b = np.array([True, False, True, True, False]) c = a[b] Now suppose, it's the other way around. I have c and b and would like to arrive at d (below). What is the easiest way to do this? c = np.array([1, 4, 7]) ... | You could use: d = np.zeros_like(b, dtype=c.dtype) d[b] = c Output: array([1, 0, 4, 7, 0]) | 3 | 7 |
77,098,444 | 2023-9-13 | https://stackoverflow.com/questions/77098444/disable-font-colour-formatting-for-negetive-values-in-python-polars-generated-ex | I would like to disable automatic font colouring of negetive values in polars write_excel. Any tip? import polars as pl import xlsxwriter df2 = pl.DataFrame(data=np.random.randint(-10, 10, 5*3).reshape(-1, 3), schema=['x', 'y', 'z']) with xlsxwriter.Workbook(r'_out_.xlsx') as workbook: df2.write_excel(workbook=workbook... | column_formats={cs.numeric():'General'} or column_formats={x:'[Black]' for x in df2.columns} will do the trick. import numpy as np import polars as pl import polars.selectors as cs import xlsxwriter df2 = pl.DataFrame(data=np.random.randint(-10, 10, 5*3).reshape(-1, 3), schema=['x', 'y', 'z']) with xlsxwriter.Workbook(... | 2 | 1 |
77,123,568 | 2023-9-17 | https://stackoverflow.com/questions/77123568/how-to-plot-grouped-bars-overlaid-with-lines | I am trying to create a chart below created in excel based on the table below using matplotlib.. Category %_total_dist_1 event_rate_%_1 %_total_dist_2 event_rate_%_2 00 (-inf, 0.25) 5.7 36.5 5.8 10 01 [0.25, 4.75) 7 11.2 7 11 02 [4.75, 6.75) 10.5 5 10.5 4.8 03 [6.75, 8.25) 13.8 3.9 13.7 4 04 [8.25, 9.25... | Solution To fix the overlapping bars you can assign offsets for each bar which are equal to half the width of the bar. This centers them without overlapping. To rotate the x-axis labels, you should call plt.xticks(...) before creating ax2. This is because the x-labels come from the first axis. Finally, to create the gr... | 3 | 1 |
77,122,159 | 2023-9-17 | https://stackoverflow.com/questions/77122159/about-gravity-option-for-marks-in-tkinter | I am using the Text widget in python / tkinter. I want to use the left and right option for marks so that text inserted immediately before or immediately after already tagged text is in the same tag range. In the code below, I don’t understand why inserted text does not appear in red. import tkinter as tk main = tk.Tk(... | I don’t understand why inserted text does not appear in red. This is how the text widget is designed to work. The gravity of a mark does not affect the tags that are applied when inserting text. The gravity only defines what happens to the mark when text is inserted at the mark. From the canonical documentation on ma... | 3 | 2 |
77,104,702 | 2023-9-14 | https://stackoverflow.com/questions/77104702/tls-communication-between-python-3-11-and-micropython-1-20-fails-with-ssl-no | I'm trying to send text between this to devices. One has a Python 3.11 (Server) and the other one a Micropython 1.20 (Client). Both devices have their own key and the server has a server-cert. Both Keys where created with: openssl req -new -newkey rsa:1024 -days 365 -nodes -x509 -keyout server-key.pem -out server-cert.... | It's because the server doesn't accept weak algorithms that the client suggested. You can check algorithms that the server supports using the SSLContext API like the following, instead of using the deprecated ssl.wrap_socket(). ... from ssl import SSLContext ... def main(): ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SER... | 3 | 1 |
77,118,636 | 2023-9-16 | https://stackoverflow.com/questions/77118636/attributeerror-nonetype-object-has-no-attribute-to-capabilities-getting-th | import unittest from appium import webdriver from appium.webdriver.common.appiumby import AppiumBy capabilities = dict( platformName='Android', automationName='uiautomator2', deviceName='Samsung S9', appPackage='com.android.settings', appActivity='.Settings', language='en', locale='US' ) appium_server_url = 'http://loc... | import unittest from appium import webdriver from appium.webdriver.common.appiumby import AppiumBy # Import Appium UiAutomator2 driver for Android platforms (AppiumOptions) from appium.options.android import UiAutomator2Options capabilities = dict( platformName='Android', automationName='uiautomator2', deviceName='Sams... | 8 | 6 |
77,102,707 | 2023-9-14 | https://stackoverflow.com/questions/77102707/type-hinting-of-dependency-injection | I'm creating a declarative http client and have a problem with mypy linting. Error: Incompatible default for argument "user" (default has type "Json", argument has type "dict\[Any, Any\]") I have a "Dependency" class that implements the logic of: value validation agains type, request modification: class Dependency(abc... | Solved using typing.Annotated, declaration has been changed a bit, but it works correctly and mypy has no errors to show. @http("GET", "/example") def test_get(data: Annotated[DataclassModel, Json()]): ... Then I'm using a function signature to extract dependency, type hint and do magic... def extract_dependencies(fun... | 3 | 1 |
77,120,647 | 2023-9-17 | https://stackoverflow.com/questions/77120647/given-an-array-of-n-integers-return-the-max-sum-of-3-non-adjacent-elements | I got this question for a coding interview (mock, part of my uni's competitive programming club since a few people are curious lol), and I got stuck on finding the optimal solution. Extra details/constraints: minimum array has to be 5 (because the elements at index 0,2,4 summed would be the answer) And some examples:... | You can solve this problem in O(n), being n the size of the array. The idea is to use Dynamic Programming to save the following information: 1 - What is the best you can make using the first i elements, if you were to pick exactly 1 element. 2 - What is the best you can make using the first i elements, if you were to p... | 3 | 2 |
77,116,907 | 2023-9-16 | https://stackoverflow.com/questions/77116907/diamond-pattern-using-python | I'm trying to print out a diamond shape using star characters and additional characters using python. I tried a lot to get the result I wanted, but not successful. I want to write a function that receives a parameters and according to that parameter it should determine the height of the diamond shape. For example : If ... | The top and bottom halves of the diamond are effectively mirror images of each other. Therefore you only need to write code to format one half. The other half is just the reverse. Something like this: def diamond(n): def rows(c, mc='#'): return [f'{c: >{i+2}}{mc: >{m-i-1}}{c: >{m-i-1}}' for i in range(n-3)] if n > 2: m... | 2 | 4 |
77,117,483 | 2023-9-16 | https://stackoverflow.com/questions/77117483/iterator-for-k-combinations | LeetCode 77. Combinations: Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. You may return the answer in any order. My code using backtracking is given below. def combine(n: int, k: int) -> list[list[int]]: def backtrack(i: int, comb: list[int]) -> None: if len(c... | You can pass yielding through recursion with minimal changes to your code. Yield comb if length is appropriate instead of appending it to ans. Yield everything backtrack(j + 1, comb) yields after each recursive call. Return backtrack(1, []) from combine_iterator. def combine_iterator(n: int, k: int) -> list[list[int]... | 2 | 2 |
77,116,419 | 2023-9-16 | https://stackoverflow.com/questions/77116419/match-only-if-following-string-matches-pattern | I'm trying to match an entire string that starts with a certain string and then match any number of characters except ::, if :: was matched then only accept if followed by the string CASE. So for example: A string that starts with Linus:: followed by 0 or more 1 characters except if :: then CASE has to follow else only... | Use a tempered greedy token: ^ # Match at the start of the string Linus:: # 'Linus::', literally, (?:(?!::).)+ # followed by a sequence of characters that doesn't contain '::' (?:::CASE)? # and, optionally, '::CASE'. Try it on regex101.com. Depending on your use case, you might want to add a \b (word boundary) at the ... | 4 | 5 |
77,109,398 | 2023-9-15 | https://stackoverflow.com/questions/77109398/failing-to-import-files-compiled-from-protobuf-in-python | My directory structure is as follows: test |-test.py |-test.proto |-test_pb2.py |-__init__.py |-comm |-comm.proto |-comm_pb2.py |-__init__.py both __init__.py is empty and test.proto is like this: package test; import "comm/comm.proto"; message Test{ optional comm.Foo foo = 1; } and comm.proto is like this: package ... | So, I think how protoc works with Python is more complicated|confusing than the average bear! My recourse is to use Golang to see what its SDK does and then reverse engineer that back into Python. The documentation says that protoc ignores Protocol Buffers packages. See Defining your Protocol Format and the note: The ... | 3 | 6 |
77,114,815 | 2023-9-15 | https://stackoverflow.com/questions/77114815/pylint-is-not-suggesting-the-walrus-operator-why | I was going to ask if there is a pylint-style code analyzer capable of suggesting the use of the := operator in places were it might improve the code. However, it looks like such test has been added to the pylint two years ago -> github PR (merged). Anyway I never saw such suggestion, not even for this example like in ... | The consider-using-assignment-expr check in pylint can be enabled by Adding the following line to your pylint configuration file. I am using a configuration file named pylint.toml: [tool.pylint.main] load-plugins="pylint.extensions.code_style" Then you can run the linter using pylint --rcfile <config_file> <python_fil... | 3 | 3 |
77,111,833 | 2023-9-15 | https://stackoverflow.com/questions/77111833/align-two-dataframe-columns-and-preserve-the-order-no-lexicographical-reorder | Let A and B two dataframes columns: Hello Foo Hey Bar World Hello Bar Doo World Star I want to obtain the columns of a dataframe C containing all the unique columns in their concatenation BUT the columns must be in the same order as before. Hello Foo Bar Hey Doo World Star In other words: "If A i... | Assuming you really want to keep the original order in both Indexes (and assuming there is no circular pattern), you can use the following algorithm: A = pd.DataFrame(columns=['Hello', 'Foo', 'Hey', 'Bar', 'World']) B = pd.DataFrame(columns=['Hello', 'Bar', 'Doo', 'World', 'Star']) def merge(A, B): sA = set(A) sB = set... | 3 | 3 |
77,111,774 | 2023-9-15 | https://stackoverflow.com/questions/77111774/how-to-hide-horizontal-monotonic-sequence-of-numbers | My input is df : COLUMN_1 COLUMN_2 COLUMN_3 COLUMN_4 0 0 1 0 2 1 1 1 2 3 2 1 2 3 2 3 1 2 4 5 4 4 5 8 8 And I wish I can hide (horizontally, from left to the non inclusive right) monotonic sequences with a difference equal to 1. For example if in a row we have [4, 5, 8, 8] (like in the last one), the concerned sequenc... | You need to use a negative period in diff, combined with mask: out = df.mask(df.diff(-1, axis=1).eq(-1), '') or, for in place modification: df[df.eq(df.shift(-1, axis=1)-1)] = '' Variant with shift: out = df.mask(df.eq(df.shift(-1, axis=1)-1), '') Output: COLUMN_1 COLUMN_2 COLUMN_3 COLUMN_4 0 1 0 2 1 1 3 2 3 2 3 2 ... | 2 | 1 |
77,111,178 | 2023-9-15 | https://stackoverflow.com/questions/77111178/running-a-docker-login-with-python-subprocess-securely | I want to run a docker login from python3 without asking for user input. I have three global variables REGISTRY_URL, USERNAME, PASSWORD. I want to run: os.system(f"echo '{PASSWORD}' | docker login {REGISTRY_URL} -u {USERNAME} --password-stdin") The problem is that my three global variables are user controllable which ... | You can supply the password using the input argument to subprocess.run: import subprocess def docker_login(registry_url, username, password): command = ["docker", "login", registry_url, "-u", username, "--password-stdin"] completed_process = subprocess.run(command, input=password.encode() + b'\n', capture_output=True) ... | 2 | 6 |
77,097,844 | 2023-9-13 | https://stackoverflow.com/questions/77097844/how-to-rename-samples-based-on-dictionary-values | I have some trouble writing a snakemake rule to change the name of my samples. After demultiplexing with Porechop and some basic trimming with Filtlong, I would like to change the names of my samples from e.g. BC01_trimmed.fastq.gz to E_coli_trimmed.fastq.gz. The idea is that in my config file there is a dictionary whe... | Let's try again... I would reverse the dictionary since in your input function you want to retrieve the barcode given a sample name. (You can reverse key-values using python code, of course). To resolve the cyclic dependency or similar errors, I think you need to either constraint the wildcard values to the ones you ha... | 2 | 2 |
77,110,775 | 2023-9-15 | https://stackoverflow.com/questions/77110775/ipython-doesnt-allow-creating-of-classmethods | I tried using ipython to create a class method with the class method decorator. When I press enter I get the following error: I tried using the same decorator in a normal python script and it worked. Why can't I do the same in Ipython? | Upgrade your ipython package to the latest version, e.g. $ python3 -m pip install -U ipython It works fine for ipython==8.1.0 (released Feb 25, 2022) or later: $ ipython Python 3.11.4 (main, Jun 20 2023, 16:52:35) [Clang 13.0.0 (clang-1300.0.29.30)] Type 'copyright', 'credits' or 'license' for more information IPython... | 2 | 3 |
77,108,924 | 2023-9-14 | https://stackoverflow.com/questions/77108924/does-scipy-optimize-minimize-use-parallelization | scipy.optimize.minimize function with method="BFGS" (based on this) doesn't seem to use parallelization when computing the cost function or numerical gradient. However, when I run an optimization on a Macbook Air 8 core Apple M1 (see below for minimal reproducible example), using top command I get 750% to 790% CPU usag... | No, but the function being evaluated can use parallelization. You might think that you're not using parallelization in this program. And you're not - at least not explicitly. However, many NumPy operations call out to your platform's BLAS library. Matrix multiplication is one of the operations that can be parallelized ... | 3 | 4 |
77,106,998 | 2023-9-14 | https://stackoverflow.com/questions/77106998/polars-use-is-in-with-durations | I have a dataframe with a column containing a set of durations, like 5m, 15m, etc... df = pl.DataFrame({ "duration_m": [5, 15, 30] }) df = df.with_columns( duration = pl.duration( minutes = pl.col("duration_m")) ) df shape: (3, 2) ┌────────────┬──────────────┐ │ duration_m ┆ duration │ │ --- ┆ --- │ │ i64 ┆ duration[ns... | I'm not sure why, even though pl.duration is an Expr and .is_in accepts expressions that it errors out. My best guess is that it sees a python list first so it assumes away getting an expression. From there it doesn't get a python type that it knows what to do with and just sees an object. Causes aside, you have two wa... | 3 | 2 |
77,104,513 | 2023-9-14 | https://stackoverflow.com/questions/77104513/why-is-numba-popcount-code-twice-as-fast-as-equivalent-c-code | I have this simple python/numba code: from numba import njit import numba as nb @nb.njit(nb.uint64(nb.uint64)) def popcount(x): b=0 while(x > 0): x &= x - nb.uint64(1) b+=1 return b @njit def timed_loop(n): summand = 0 for i in range(n): summand += popcount(i) return summand It just adds the popcounts for integers 0 t... | TL;DR: the performance gap between the GCC and the Clang version is due to the use of scalar instructions versus SIMD instructions. The performance gap between the Numba and the Clang version comes from the size of the integers that is not the same between the two version : 64-bit versus 32-bits. Performance Results F... | 7 | 9 |
77,105,233 | 2023-9-14 | https://stackoverflow.com/questions/77105233/how-do-i-get-an-element-from-shadow-dom-in-selenium-in-python | could someone please explain to me how to get an element from shadow DOM in Selenium4 in Python? I want to element.click() to Accept the cookies - but I fail at the very first step! I've tried driver.find_element(By.CSS_SELECTOR, '#shadow_host') ... driver.find_element(By.CSS_SELECTOR, '#shadow_root') Every time "no su... | To get element's shadow-root, you should first get it's host and then get property shadowRoot. In your case, host tag is cmm-cookie-banner. So, you get this element and then execute JS script on it. def get_shadow_root(element): return driver.execute_script('return arguments[0].shadowRoot', element) shadow_host = drive... | 2 | 8 |
77,103,883 | 2023-9-14 | https://stackoverflow.com/questions/77103883/how-to-import-a-library-in-python-for-firebase-functions | Hello StackOverflow community. I am trying to deploy Firebase functions written in Python from a React-Native project. My code snippet looks like this: from firebase_functions import firestore_fn, https_fn import fitz import re import requests import io from datetime import datetime # The Firebase Admin SDK to access C... | I found the solution to my problem when I checked the firebase-debug.log. It appears that there was an issue with the "fitz" library from Pymupdf, which I had imported in my code. There's a trouble in fitz library from Pymupdf (I'm using it in the import above) I had initially added the library to my Python Firebase ... | 3 | 6 |
77,102,860 | 2023-9-14 | https://stackoverflow.com/questions/77102860/how-to-use-native-popcount-with-numba | I am using numba 0.57.1 and I would like to exploit the native CPU popcount in my code. My existing code is too slow as I need to run it hundreds of millions of times. Here is a MWE: import numba as nb @nb.njit(nb.uint64(nb.uint64)) def popcount(x): b=0 while(x > 0): x &= x - nb.uint64(1) b+=1 return b print(popcount(4... | Try: import numba as nb from numba import types from numba.cpython import mathimpl from numba.extending import intrinsic @intrinsic def popcnt(typingctx, src): sig = types.uint64(types.uint64) def codegen(context, builder, signature, args): return mathimpl.call_fp_intrinsic(builder, "llvm.ctpop.i64", args) return sig, ... | 3 | 4 |
77,101,575 | 2023-9-14 | https://stackoverflow.com/questions/77101575/python-3-10-type-hinting-for-decorator-to-be-used-in-a-method | I'm trying to use typing.Concatenate alongside typing.ParamSpec to type hint a decorator to be used by the methods of a class. The decorator simply receives flags and only runs if the class has that flag as a member. Code shown below: import enum from typing import Callable, ParamSpec, Concatenate P = ParamSpec("P") Wr... | You have two major issues here, and more detailed warnings would have been given if you had strict on: Your type alias, Wrappable = Callable[Concatenate["Foo", P], None], has a type variable (here, the ParamSpec P), but you're not providing the type variable when you're using the alias. This means you've lost all sign... | 4 | 4 |
77,101,192 | 2023-9-14 | https://stackoverflow.com/questions/77101192/cannot-import-name-randn-tensor-from-diffusers-utils | I was using this autotrain collab and when i labbelled and put my images into images folder and tried to run it , It says this error how do i solve this ? to reproduce : click link of ipynb make a new folder name images add some images and replace the prompt to something which describes your images go to runtime a... | This is happening due to the newer version of diffusers library. At the very start, run pip install diffusers==0.20.2 and then execute the cells. | 5 | 7 |
77,099,610 | 2023-9-13 | https://stackoverflow.com/questions/77099610/polars-fill-null-using-rule-of-three-based-of-filtered-set | Goal I want to fill the nulls in a series by distributing the difference between the next non-null and previous non-null value. The distribution is not linear but uses the values in another column to calculate the portioning Example df = pl.DataFrame({ "id": ["a", "a", "a", "b", "b", "b", "b", "b"], "timestamp": ["2023... | ( df .join_asof( df .filter(pl.col('value').is_not_null()) .with_columns( gap_time=(pl.col('timestamp')-pl.col('timestamp').shift().over('id')) .dt.seconds(), prev_good_time=pl.col('timestamp').shift().over('id'), prev_good_value=pl.col('value').shift().over('id') ) .drop('value'), on='timestamp', by='id', strategy='fo... | 4 | 1 |
77,099,794 | 2023-9-13 | https://stackoverflow.com/questions/77099794/why-cant-you-use-bitwise-with-numba-and-uint64 | I have the following MWE: import numba as nb @nb.njit(nb.uint64(nb.uint64)) def popcount(x): b=0 while(x > 0): x &= x - 1 b+=1 return b print(popcount(43)) It fails with: numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend) No implementation of function Function(<built-in function ... | At first, I thought this was NumPy uint64 awkwardness. Turns out it's slightly different Numba uint64 awkwardness. By NumPy dtype rules, a standard Python int is handled as numpy.int_ dtype, which is signed. There's no integer dtype big enough to hold all values of both uint64 dtype and a signed dtype, so in mixed uint... | 2 | 4 |
77,096,912 | 2023-9-13 | https://stackoverflow.com/questions/77096912/python-polars-elegant-way-to-add-a-month-to-a-date | I need to carry out a very simple operation in Polars, but the documentation and examples I have been finding are super convoluted. I simply have a date, and I would like to create a range running from the first day in the following month until the first day of a month twelve months later. I have a date: date = 2023-01... | You can use dt.offset_by For example pl.select(pl.lit(datetime.fromisoformat("2023-01-15")).dt.offset_by("1mo")).item() To avoid that error you can suffix "_saturating" to the offset like this... pl.select(pl.lit(datetime.fromisoformat("2023-01-31")).dt.offset_by("1mo_saturating")).item() It'll produce an error if th... | 2 | 7 |
77,093,787 | 2023-9-13 | https://stackoverflow.com/questions/77093787/pandas-how-to-flag-rows-between-a-start-1-and-multiple-ends-2-or-3 | I have the following dataframe: import numpy as np import pandas as pd df = pd.DataFrame([]) df['Date'] = ['2020-01-01','2020-01-02','2020-01-03','2020-01-04','2020-01-05', '2020-01-06','2020-01-07','2020-01-08','2020-01-09','2020-01-10', '2020-01-11','2020-01-12','2020-01-13','2020-01-14','2020-01-15', '2020-01-16','2... | A simple approach would be to map the known statuses, then to groupby.ffill them: df['Status'] = (df['Signal'] .map({1:1, 2:0, 3:0}) .groupby(df['Machine']).ffill() .fillna(0, downcast='infer') ) Output: Date Machine Signal Status 0 2020-01-01 A 0 0 1 2020-01-02 A 1 1 2 2020-01-03 A 2 0 3 2020-01-04 A 0 0 4 2020-01-0... | 4 | 7 |
77,069,773 | 2023-9-8 | https://stackoverflow.com/questions/77069773/how-can-i-install-ipython-in-debian-12-or-ubuntu-23-04-where-pip3-prevents-insta | python3 is a system wide program, just as pip3 is. I want to install IPython on Debian 12 (Bookworm). (This information is also relevant to newer Ubuntu versions, since these are derived directly from Debian and contain the same policy change.) I would probably expect this to also be a system-wide available program, ju... | The actual solution I used, thanks to others for directing me to venv. python3 -m venv .venv source .venv/bin/activate # do this every time to use the venv created above pip3 install ipython FYI for convenience one can also do ln -s .venv/bin/activate . . activate | 2 | 2 |
77,091,944 | 2023-9-12 | https://stackoverflow.com/questions/77091944/polars-flatten-rows-into-columns-aggregating-by-column-values | I'm trying to write a script in Polars that would flatten a list of prices per date and minute. The catch is I want to incrementally aggregate into columns and zero out values in the future. For example. Idea is to make this solution vectorized if possible to make it performant. df = pl.DataFrame({ "date": ["2022-01-01... | This seems to work df.join( df.pivot('minute', index='date'), on='date') \ .select("date", "minute", **{f"{x}_price":pl.when(pl.lit(x)<=pl.col('minute')) .then(pl.col(f"{x}")) .otherwise(0) for x in df['minute'].unique().sort()}) shape: (8, 5) ┌────────────┬────────┬─────────┬─────────┬─────────┐ │ date ┆ minute ┆ 1_pr... | 4 | 0 |
77,087,197 | 2023-9-12 | https://stackoverflow.com/questions/77087197/is-there-a-way-to-group-by-in-polars-while-keeping-other-columns | I am currently trying to achieve a polars group_by while keeping other columns than the ones in the group_by function. Here is an example of an input data frame that I have. df = pl.from_repr(""" ┌─────┬─────┬─────┬─────┐ │ SRC ┆ TGT ┆ IT ┆ Cd │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 ┆ f64 │ ╞═════╪═════╪═════╪═══... | # Your data data = { "SRC": [1, 2, 3, 3], "TGT": [1, 1, 1, 2], "IT": [2, 2, 2, 1], "Cd": [3.0, 4.0, 3.0, 8.0] } df = pl.DataFrame(data) # Perform the group_by and aggregation result = ( df.group_by('TGT', 'IT', maintain_order=True) .agg( pl.col('SRC').first(), pl.col('Cd').min() ) .select('SRC', 'TGT', 'IT', 'Cd') # to... | 3 | 5 |
77,071,244 | 2023-9-9 | https://stackoverflow.com/questions/77071244/python-polars-calculate-rolling-mode-over-multiple-columns | I have a polars.DataFrame like: data = pl.DataFrame({ "col1": [3, 2, 4, 7, 1, 10, 7], "col2": [3, 4, None, 1, None, 1, 9], "col3": [3, 1, None, None, None, None, 4], "col4": [None, 5, None, None, None, None, None], "col5": [None, None, None, None, None, None, None]}) ┌──────┬──────┬──────┬──────┬──────┐ │ col1 ┆ col2 ┆... | .rolling() can be used to aggregate over the windows. Using .concat_list() inside .agg() will give us a nested list, e.g. [[col1, col2, ...], [col1, col2, ...]] Which we can flatten, remove nulls, and calculate the mode. .flatten() .drop_nulls() .mode() (df.with_row_index() .rolling( index_column = "index", period ... | 4 | 3 |
77,059,630 | 2023-9-7 | https://stackoverflow.com/questions/77059630/python-polars-conditional-join-by-date-range | First of all, there seem to be some similar questions answered already. However, I couldn't find this specific case, where the conditional columns are also part of the join columns: I have two dataframes: df1 = pl.DataFrame({"timestamp": ['2023-01-01 00:00:00', '2023-05-01 00:00:00', '2023-10-01 00:00:00'], "value": [2... | .join_where() was added in Polars 1.7.0 (df1 .join_where(df2, pl.col.timestamp >= pl.col.date_start, pl.col.timestamp <= pl.col.date_end ) ) shape: (2, 5) ┌─────────────────────┬───────┬─────────────────────┬─────────────────────┬───────┐ │ timestamp ┆ value ┆ date_start ┆ date_end ┆ label │ │ --- ┆ --- ┆ --- ┆ --- ┆ ... | 3 | 1 |
77,090,789 | 2023-9-12 | https://stackoverflow.com/questions/77090789/a-problem-with-building-scatterplot-using-dates-and-int-values | import pandas as pd import seaborn as sn import matplotlib.pyplot as plt from datetime import datetime import numpy as np path = r'C:\Users\bossd\OneDrive\Документы\datarn.csv' df = pd.read_csv(path) path2 = r'C:\Users\bossd\OneDrive\Документы\pipirka.csv' df2 = pd.read_csv(path2) x = (df2.loc[df2['timestamp'].str.star... | The 'timestamp' column should first be converted to a datetime dtype with pd.to_datetime, otherwise the datetime x-ticks will not be correctly positioned and formatted. The typical process should begin with cleaning the data, and then selecting. x = (df2.loc[df2['timestamp'].str.startswith('2015')]) is the cause of... | 2 | 2 |
77,071,473 | 2023-9-9 | https://stackoverflow.com/questions/77071473/where-can-i-import-dataclassinstance-for-mypy-check | I have been using custom-defined DataclassProtocol to annotate the arg of function which takes dataclass type. It was something like this: import dataclasses from typing import Type class DataclassProtocol(Protocol): """Type annotation for dataclass type object.""" # https://stackoverflow.com/a/55240861/11501976 __data... | You may import it from _typeshed: from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from _typeshed import DataclassInstance Note that types from _typeshed do not exist at runtime. You may read more about them here: _typeshed _typeshed.DataclassInstance | 7 | 13 |
77,079,524 | 2023-9-11 | https://stackoverflow.com/questions/77079524/how-to-expect-count-bigger-or-smaller-than | Using Playwright and Python, how can I expect for count bigger or smaller than? For example, this code expect for count of 2. How do I achieve count >= 2 (Only bigger) expect(self.page.locator('MyLocator')).to_have_count(2, timeout=20 * 1000) | This doesn't seem to be possible in the current Python Playwright API, but you could use wait_for_function as a workaround: page.wait_for_function("document.querySelectorAll('.foo').length > 2") This is web-first and will wait for the predicate, but the error message once it throws won't be as clear as the expect fail... | 4 | 2 |
77,086,128 | 2023-9-12 | https://stackoverflow.com/questions/77086128/how-to-pass-worker-options-parameters-in-gunicorn | I am running an app which needed uvicorn's asycio loop, by default it uses auto and some time it randomly assign it to uvloop whihc breaks the behavior. So I use the following command uvicorn myapp.server.api:app --loop asyncio --port 7474 This forces uvicorn to use asyncio loop. This works as expected. Now I am tryin... | The problem is gunicorn does not support passing options directly to uvicorn workers. So, basically, you can create a custom UvicornWorker class where you override the default loop policy. Here's an example: # myapp/server/custom_worker.py from uvicorn.workers import UvicornWorker class CustomUvicornWorker(UvicornWorke... | 4 | 5 |
77,076,597 | 2023-9-10 | https://stackoverflow.com/questions/77076597/is-it-possible-to-get-pydantic-v2-to-dump-json-with-sorted-keys | In the pydantic v1 there was an option to add kwargs which would get passed to json.dumps via **dumps_kwargs. However, in pydantic v2 if you try to add extra kwargs to BaseModel.json() it fails with the error TypeError: `dumps_kwargs` keyword arguments are no longer supported. Here is example code with a workaround usi... | I'm not sure whether it is an elegant solution but you could leverage the fact that dictionaries (since python 3.7) preserve an order of elements: from typing import Any, Dict from pydantic import BaseModel, model_serializer class JsonTest(BaseModel): b_field: int c_field: int a_field: str @model_serializer(when_used='... | 6 | 6 |
77,052,622 | 2023-9-6 | https://stackoverflow.com/questions/77052622/memory-issue-creating-bigrams-and-trigrams-with-countvectorizer | I am trying to create a document term matrix using CountVectorizer to extract bigrams and trigrams from a corpus. from sklearn.feature_extraction.text import CountVectorizer lemmatized = dat_clean['lemmatized'] c_vec = CountVectorizer(ngram_range=(2,3), lowercase = False) ngrams = c_vec.fit_transform(lemmatized) count_... | Solution: Here is one way to get the final table your looking for with frequency and bigram/trigram without generating the entire document term matrix. We can take the sum of a sparse matrix and use that to create a dataframe. This removes the need to create space in RAM for all of those missing values. # Here we creat... | 2 | 2 |
77,088,781 | 2023-9-12 | https://stackoverflow.com/questions/77088781/how-to-write-and-read-dataframe-to-parquet-where-column-contains-list-of-dicts | I have a column that contain a list of dictionaries and I'm trying to write it to disk using parquet and reading it back into the same original object. However I'm not able to get the same exact object back. Here's the minimal code example to reproduce the issue: import pyarrow as pa from pyarrow import parquet import ... | The problem is that the dataframe that is read back contains repeating dicts where each value is None (one at a time). I'm not sure what your intention is. Do you want individual values to be a dictionary? If so I'd suggest sending the schema to this (no need for list_): COLUMN1_SCHEMA = pa.struct([('Id', pa.string()... | 3 | 0 |
77,092,112 | 2023-9-12 | https://stackoverflow.com/questions/77092112/how-to-apply-weight-curve-with-curve-fit | I have two variables, and I am trying to use curve_fit in scipy optimize to fit the data. It looks alright, but the red line on the left portion does not fit so well to the data (green dots). How can I put some weights on the curve_fit() to shift the red line on left towards the blue line? Here is the code: import pan... | You can use the parameter sigma in curve_fit. From the docs: sigma: None or M-length sequence or MxM array, optional Determines the uncertainty in ydata. If we define residuals as r = ydata - f(xdata, *popt), then the interpretation of sigma depends on its number of dimensions: A 1-D sigma should contain values of sta... | 3 | 1 |
77,074,865 | 2023-9-10 | https://stackoverflow.com/questions/77074865/how-to-convert-a-string-mixed-with-infix-and-prefix-sub-expressions-to-all-prefi | Consider I have a string formula which is written in this format: "func(a+b,c)", where func is a custom function, this string contains both infix(i.e. the +) and prefix(i.e. the func) representations, I'd like to convert it to a string with all prefix representations, "func(+(a,b), c)", how can I do that? Another examp... | If the language you are parsing is that similar to Python, you can just use the Python parser as provided by the built-in ast module, and implement a visitor over the nodes that interest you, in order to build up the prefix expression. For example, you could try this: import ast def printc(*args): print(*args, end='') ... | 2 | 2 |
77,093,266 | 2023-9-12 | https://stackoverflow.com/questions/77093266/how-to-clear-input-field-after-hitting-enter-in-streamlit | I have a streamlit app where I want to get user input and use it later. However, I also want to clear the input field as soon as the user hits Enter. I looked online and it seems I need to pass a callback function to text_input but I can't make it work. I tried a couple different versions but neither works as I expect.... | You can slightly adjust the solution provided by @MathCatsAnd : if "my_text" not in st.session_state: st.session_state.my_text = "" def submit(): st.session_state.my_text = st.session_state.widget st.session_state.widget = "" st.text_input("Enter text here", key="widget", on_change=submit) my_text = st.session_state.my... | 2 | 10 |
77,092,114 | 2023-9-12 | https://stackoverflow.com/questions/77092114/numba-typeerror-on-higher-dimensional-structured-numpy-datatypes | The following code compiles and executes correctly: import numpy as np from numba import njit Particle = np.dtype([ ('position', 'f4'), ('velocity', 'f4')]) arr = np.zeros(2, dtype=Particle) @njit def f(x): x[0]['position'] = x[1]['position'] + x[1]['velocity'] * 0.2 + 1. f(arr) However, making the datatype more highl... | You can try to use [:] to set values of the array: import numpy as np from numba import njit Particle = np.dtype([("position", "f4", (2,)), ("velocity", "f4", (2,))]) arr = np.zeros(2, dtype=Particle) @njit def f(x): pos_0 = x[0]["position"] pos_0[:] = x[1]["position"] + x[1]["velocity"] * 0.2 + 1.0 #x[0]["position"][:... | 2 | 3 |
77,089,361 | 2023-9-12 | https://stackoverflow.com/questions/77089361/what-do-ellipses-do-when-they-are-the-default-argument-of-a-function | In pandas source code, here's a snippet of the to_csv function: @overload def to_csv( self, path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str], sep: str = ..., na_rep: str = ..., float_format: str | Callable | None = ..., What does the ... mean? EDIT: A couple of users have suggested this answer. Though app... | The short answer: in this particular case, the ellipsis (...) is used as a placeholder for the default values in an overloaded method signature, following PEP 484 ("In stubs it may be useful to declare an argument as having a default without specifying the actual default value. … In such cases the default value may be ... | 5 | 5 |
77,091,788 | 2023-9-12 | https://stackoverflow.com/questions/77091788/regex-to-match-only-the-second-ip-address-in-a-range | I'm trying to match only the second valid ip address in a string with a range of ip addresses. Sometimes it's written without a space between addresses and something it has one or more spaces. Also sometimes the ip isn't valid so it shouldn't match. test = ''' 1.0.0.0-1.0.0.240 2.0.0.0 - 1.0.0.241 3.0.0.0 -1.0.0.242 4.... | Change regex pattern to the following: pattern = r"(?<=[-\s])((?:\d{1,3}\.){3}\d{1,3})$" r = re.compile(pattern, re.M) print(r.findall(test)) (?<=[-\s]) - lookbehind assertion to match either - or \s as a boundary before IP address (which is enough in your case) (?:\d{1,3}\.){3} - matches the 3 first octets each fol... | 3 | 3 |
77,070,305 | 2023-9-8 | https://stackoverflow.com/questions/77070305/how-to-distribute-a-python-package-where-import-name-is-different-than-project-n | I am trying to package my project in order to upload it in PyPI. I have the following directory structure: . ├── docs ├── LICENSE ├── pyproject.toml ├── README.md ├── src │ ├── package_name │ │ ├── __init__.py │ │ ├── data.json │ │ ├── __main__.py │ │ ├── utils.py └── tests My package is in under src named src/package... | I found the solution to my problem by simply switching to setuptools as backend and modifying the pyproject.toml as following: [build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [tool.setuptools.packages.find] where = ["src"] [tool.setuptools.dynamic] version = {attr = "package_name.__vers... | 4 | 2 |
77,090,701 | 2023-9-12 | https://stackoverflow.com/questions/77090701/add-new-rate-column-base-previous-column | I would like to add a rate column base on row before current row, just like a diff() but need do some calculation just like below: import pandas as pd import numpy as np df = pd.DataFrame(np.random.random((5,2)),columns=['v1','v2']) print(df) rate = [] rate.append(0) prev = 0 for index, row in df.iterrows(): if index =... | You can use the pandas shift function. df['rate'] = (df['v2'] - df['v2'].shift(1)) / (df['v1'].shift(1) - df['v1']) df['rate'].iloc[0] = 0 df['rate'] = df['rate'].fillna(0) The shift() method is used to shift the data by one row, which allows you to easily calculate differences between the current row and the previous... | 2 | 0 |
77,089,742 | 2023-9-12 | https://stackoverflow.com/questions/77089742/how-to-stop-non-digit-input-causing-my-python-program-to-crash | I am trying to create a program for a class that will have a conversation. I want to force the user to input an int for the variables your_age and my_age. I've done a lot of research and this I've tried to code the program the way I believe I'm being told but it's not running if I put 'one' instead of '1'. If the user ... | Just convert input into integer inside of Try block and implement error handling for both variables. your_age and my_age. name = input('Salutations what is your name?') #user will input their name and it will be saved in the variable name print('That is a nice name ' + name + ' whats your favorite color') #genorate a s... | 2 | 1 |
77,081,746 | 2023-9-11 | https://stackoverflow.com/questions/77081746/fastapi-multiple-examples-for-body-in-response | I need to create multiple examples for the Response Body, to display it in API documentation http://127.0.0.1:8000/docs. I found an example for the Request Body in the documentation (there is drop-down list of: "A normal example", "An example with converted data", etc.), but I require the same approach for the Response... | You can achieve this by adding the response parameter in the decorator method. import uvicorn from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): message: str get1_responses = { 200: { "description": "Success", "content": { "application/json": { "examples": { "Normal": {"va... | 2 | 3 |
77,088,341 | 2023-9-12 | https://stackoverflow.com/questions/77088341/removing-unwanted-values-from-a-pandas-data-frame | I'm creating a data frame and want to drop entries in it that are not relevant. I'm looking to drop the values that are not numbers. I have created the data frame using the following code (credit): import pandas as pd import os os.chdir('/pathdirectory/files') csv_files = [f for f in os.listdir() if f.endswith('.csv')]... | You should set the first columns of the CSVs as index: pd.read_csv(csv, header=None, index_col=0) Alternatively: cols = ['DC energy', 'AC energy', 'Capacity factor', 'Inverter Loss'] final_df = pd.concat([pd.read_csv(csv, header=None, index_col=0) for csv in csv_files], axis=1, ignore_index=True).T.set_axis(cols) Not... | 2 | 3 |
77,087,929 | 2023-9-12 | https://stackoverflow.com/questions/77087929/how-to-print-a-array-with-numbered-columns-and-rows-nicely-in-python | Currently strugging with nicely printing a array of "O"'s, where the columns and rows should be numbered. So I have a array which is just a nxn-matrix full of the string "O". Now I tried using the following method: def __repr__(self) : Matrix = self.Spielstand #this is just the mentioned array of length n: Ausgabe = "... | You can calculate margin size by counting the length of the number converted to string. Margin = len(str(len(Matrix))) Martix -> (array of 12 "O") len(Martix) -> 12 str(12) -> "12" len("12") -> 2 I have created demo, with a solution to your problem: def generateMatrix(n): return [["O"] * n] * n def draw(n): Matrix = ... | 2 | 2 |
77,086,913 | 2023-9-12 | https://stackoverflow.com/questions/77086913/how-to-get-split-months-from-two-intervals | I've two dates in YYYYmm format start : 202307 end : 202612 want to split them in interval wise, based on provided interval for example split_months ('202307,'202405',5), will give me ((202307,202311), (202312,202404), (202405,202405)) tried with below code, bot stuck in the logic def split_months(start, end, intv): ... | What about using a simple while loop? def split_months(start, end, intv): from datetime import datetime from dateutil import relativedelta periodList = [] start = datetime.strptime(start, '%Y%m') end = datetime.strptime(end, '%Y%m') step = relativedelta.relativedelta(months=intv-1) start_ = start while (end_:=start_+st... | 2 | 3 |
77,087,129 | 2023-9-12 | https://stackoverflow.com/questions/77087129/converting-characters-like-%c2%b3-to-integer-in-python | I have this character '³' in my dataset that I'm processing on top of. Generic Idea is to detect if a character is an integer, convert it into an integer and process on top of it. >>> x = '³' >>> x.isdigit() # Returns True True Python detects this character as a digit. But raises the following error when I try to conv... | You can use unicodedata and NFKC to convert it here is a detailed code with some error handling import unicodedata x = '³' try: regular_digit = unicodedata.normalize('NFKC', x) integer_value = int(regular_digit) print(integer_value) except ValueError: print(f"'{x}' is not a convertible superscript digit.") | 4 | 6 |
77,085,731 | 2023-9-12 | https://stackoverflow.com/questions/77085731/python-how-to-groupby-one-column-and-then-calculate-a-trailing-mean-and-cumulat | I want to groupby one column (for example, 'country'). Each row has an associated 'start_date' and 'end_date'. For every row in the groupby, I want to increment the counter if the 'start_date' in the current row occurs after the most recent 'end_date' in the prior rows (and not increment otherwise). I want the same log... | IIUC, you can apply a custom function to generate your counts and trailing means for each group: def count_and_avg(df): mask = [df['end_date'] < start for start in df['start_date']] df = df.assign(count=[sum(m) for m in mask], trailing_mean=[df[m]['value'].sum() / sum(m) if sum(m) else 0 for m in mask] ) return df out ... | 3 | 2 |
77,083,986 | 2023-9-11 | https://stackoverflow.com/questions/77083986/imap-tools-access-raw-message-data | How do you access the raw message data of an email when using imap-tools? Specifically so it can then be loaded into the email.message_from_bytes() function for forwarding? from imap_tools import MailBox, AND with MailBox('imap.gmail.com').login('asdf@gmail.com', '123456', 'INBOX') as mailbox: # get unseen emails from ... | According to the source it looks like the msg.obj property contains the value after message_from_bytes has been run. class MailMessage: """The email message""" def __init__(self, fetch_data: list): raw_message_data, raw_uid_data, raw_flag_data = self._get_message_data_parts(fetch_data) self._raw_uid_data = raw_uid_data... | 3 | 4 |
77,082,451 | 2023-9-11 | https://stackoverflow.com/questions/77082451/python-polars-apply-function-to-two-columns-and-an-argument | Intro In Polars I would like to do quite complex queries, and I would like to simplify the process by dividing the operations into methods. Before I can do that, I need to find out how to provide these function with multiple columns and variables. Example Data # Libraries import polars as pl from datetime import dateti... | This should work with expressions reference_date = datetime(2020, 1, 2) ( test_data .group_by('class', maintain_order=True) .agg( point_in_time_status = ( (pl.col('date').dt.month_start() == pl.lit(reference_date).dt.month_start()) & (pl.col('status')==1) ).any(), reference_date = pl.lit(reference_date) ) ) I'm using ... | 3 | 1 |
77,079,865 | 2023-9-11 | https://stackoverflow.com/questions/77079865/recreate-randperm-matlab-function-in-python | I have searched on stackoverflow for people facing similar issues and this topic Replicating MATLAB's `randperm` in NumPy is the most similar. However, although it is possible to recreate the behavior of randperm function from Matlab in Python using numpy random permutation, the numbers generated are not the same, even... | It seems that Matlab and Numpy use the same random number generators by default, and the discrepancy is caused by the inner workings of randperm being different in the two languages. In old Matlab versions, randperm worked by generating a random array and outputting the indices that would make the array sorted (using t... | 3 | 3 |
77,082,895 | 2023-9-11 | https://stackoverflow.com/questions/77082895/vectorizing-an-apply-function-in-pandas | I have a dataframe grouped by issue_ids where i want to apply a custom function. The grouped dataframe looks as follows import pandas as pd import numpy as np sub_test=pd.DataFrame(columns=['issue_id','step','conversion_rate'],data=[['01-abc-234',0,0.45],['01-abc-234',1,0.35],['01-abc-234',2,0.15],['01-abc-234',3,1],['... | import numpy as np cond0, cond1, cond2 = sub_test['step'].eq(0), sub_test['step'].eq(1), sub_test['step'].eq(2) s1 = sub_test.groupby('issue_id')['conversion_rate'].transform(lambda x: x.where(cond1 | cond2).prod()) s2 = sub_test.groupby('issue_id')['conversion_rate'].transform(lambda x: x.where(cond2).sum()) sub_test[... | 2 | 1 |
77,081,815 | 2023-9-11 | https://stackoverflow.com/questions/77081815/element-wise-average-in-dictionary-of-lists | I have a very large python dictionary. I want to perform an element-wise averaging for each element in each list. Let's say: dict = { "a": [2,5,3], "b": [1,0,2], "c": [5,2,5] } The output should be: [2.6 2.3 3.3] where each element is the average of all the elements at that index in all the lists in dictionary. This n... | This seems 2-3 times faster than mozway's fastest (for size 1000x1000): avg = [sum(column) / len(column) for column in zip(*d.values())] Benchmarked on Attempt This Online!: 19.09 ± 0.03 ms Kelly 26.33 ± 0.19 ms Kelly_fmean 51.09 ± 0.25 ms mozway_numpy 249.17 ± 1.17 ms bart_original 266.40 ± 5.85 ms mozway_mean Pytho... | 2 | 1 |
77,077,529 | 2023-9-10 | https://stackoverflow.com/questions/77077529/how-can-i-resolve-userwarning-the-palette-list-has-more-values-10-than-neede | I am using "tab10" palette because of its distinct colors blue, green, orange and red. k_clust = KMeans(n_clusters=4, random_state= 35, n_init=1).fit(df_normal) palette = sns.color_palette("tab10") sns.pairplot(new_df, hue="clusters", palette=palette) The number of clusters are only 4 and the palette "tab10" has more ... | The docs for color_palette() say that you can pass n_colors=4 to the call. Try this: ... palette = sns.color_palette("tab10", n_colors=4) # equal to n_clusters ... | 3 | 4 |
77,071,266 | 2023-9-9 | https://stackoverflow.com/questions/77071266/ravendb-python-client-useoptimisticconcurrency-does-this-option-exist | Recently I have started to work with python RavenDB client, and found out that documentation for the python client is not full. Official page even does not contain Python as an option for the doceumentation. Anyhow, official client is there and I wanted to understand if it contains something like "session.Advanced.UseO... | This option can be set in your DocumentConventions. You can set a property of your DocumentStore with your custom document conventions. Then upon internal/automatic RequestExecutor creation, the conventions will be passed forward to be processed. | 2 | 2 |
77,061,254 | 2023-9-7 | https://stackoverflow.com/questions/77061254/how-to-deploy-to-aws-elastic-beanstalk-using-python-3-11-64bit-amazon-linux-2023 | I am trying to deploy a simple Flask app to Elastic beanstalk. I am able to deploy the sample version. However, I am currently struggling to deploy my own. My Python app is already named application.py and changed flask name in the code to "application" in the code. Inside my .ebextension files are the following: postg... | The documents for Elastic Beanstalk is not updated for AL2023 and still uses AL2, so don't just follow elastic beanstalk docs if you want to use AL2023. I don't think they have postgresql-devel package for AL2023, based on this link for installed package list. Also, they changed package manager from yum to dnf, even th... | 3 | 2 |
77,076,663 | 2023-9-10 | https://stackoverflow.com/questions/77076663/rng-challenge-python | I am trying to solve a CTF challenge in which the goal is to guess the generated number. Since the number is huge and you only have 10 attempts per number, I don't think you can apply binary search or any kind of algorithm to solve it, and that it has something to do with somehow getting the seed of the random function... | Don't try guessing the first 624 numbers, just give up on them. You're told what they were, feed them into randcrack as shown in its example. Ask it to predict the next 32-bit number and guess that. For a bigger challenge, you could try it without that tool. Here's some insight, "predicting" the next number, i.e., show... | 5 | 6 |
77,076,966 | 2023-9-10 | https://stackoverflow.com/questions/77076966/headers-to-column-pandas-dataframe | for example I have a pandas DataFrame of the test results in some class. It could look like this table: Name English French History Math Physic Chemistry Biology Mike 3 3 4 5 6 5 4 Tom 4 4 3 4 4 5 5 Nina 5 6 4 3 3 3 5 Anna 4 3 4 5 5 3 3 Musa 5 5 4 4 4 6 5 Maria 4 3 5 4 3 2 3 Chris 6 5 5 5 5 5 6 ... | Another possible solution : tmp = df.set_index("Name") # a DataFrame bre = tmp.max(axis=1) # a Series bsu = ( ((tmp.columns + "|") @ tmp.eq(bre, axis=0).T) .str.strip("|").str.split("|", expand=True) .rename(lambda x: f"Best subject {x+1}", axis=1) ) out = tmp.assign(**{"Best result": bre}).join(bsu).reset_index()#.fil... | 2 | 1 |
77,076,223 | 2023-9-10 | https://stackoverflow.com/questions/77076223/python-copying-rows-with-same-id-values | I have a big dataframe with columns including ID and multiple values and different rows can have same or different ID values. I would like to create a new dataframe so, that every row has only one ID and the specific column values are just appended next to the ID. The Dataframe also has other columns with additional va... | You can melt and groupby.agg: group = ['ID', 'type1', 'type2'] out = df.melt(group).groupby(group, as_index=False)['value'].agg(list) Output: ID type1 type2 value 0 1 dog yellow [1, 5, 1, 2, 6, 2, 3, 7, 3] 1 2 cat brown [1, 1, 1] 2 3 mouse blue [1, 1, 1] If order matters: out = (df.set_index(group).stack().groupby(g... | 3 | 2 |
77,074,676 | 2023-9-10 | https://stackoverflow.com/questions/77074676/importerror-cannot-import-name-deprecated-from-typing-extensions | I want to download spacy, but the version of typing-extensions is lowered in the terminal: ERROR: pydantic 2.3.0 has requirement typing-extensions>=4.6.1, but you'll have typing-extensions 4.4.0 which is incompatible. ERROR: pydantic-core 2.6.3 has requirement typing-extensions!=4.7.0,>=4.6.0, but you'll have typing-ex... | You should use typing_extensions==4.7.1 try : pip install typing_extensions==4.7.1 --upgrade I also suggest you to upgrade your python version from 3.7 to 3.10 or 3.11 See a relevant answer: https://github.com/tiangolo/fastapi/discussions/9808 | 14 | 17 |
77,075,446 | 2023-9-10 | https://stackoverflow.com/questions/77075446/subset-pandas-dataframe-to-get-specific-number-of-rows-based-on-values-in-anothe | I have a pandas dataframe as follows: df1 site_id date hour reach maid 0 16002 2023-09-02 21 NaN 33f9fad6-20c5-426c-962f-bc2fbb82aecb 1 16002 2023-09-04 17 NaN 33f9fad6-20c5-426c-962f-bc2fbb82aecb 2 16002 2023-09-04 19 NaN 4a676aeb-6f6f-4622-934b-59b8f149aad7 3 16002 2023-09-04 17 NaN 35363191-c6aa-49fb-beb1-04a98898be... | You can merge the count from df2 to df1, and then using .groupby to reduce the count of groups: cols = ["site_id", "date", "hour"] df1 = df1.merge(df2, on=cols, how="right") df1 = df1.groupby(cols, group_keys=False).apply(lambda x: x[: x["count"].iloc[0]]) df1.pop("count") print(df1.head()) Prints: site_id date hour ... | 2 | 2 |
77,072,922 | 2023-9-9 | https://stackoverflow.com/questions/77072922/python-opencv-template-matching-and-feature-detection-not-working-properly | I'm attempting to identify specific shapes in an image using a template. I've edited the original image by adding two stars to it. Now, I'm trying to detect the positions of these stars, but it doesn't seem to be recognizing them. I've employed two methods, template matching and feature detection, but neither is yieldi... | I have cropped your star from your image to use as a template in Python/OpenCV template matching. I then use a technique of masking the correlation image in a loop to find the two matches. Each top match is masked out with zeros in the TM_CCORR_NORMED (normalized cross correlation) surface before searching for the next... | 2 | 4 |
77,072,374 | 2023-9-9 | https://stackoverflow.com/questions/77072374/classify-input-numbers-into-fixed-ranges-several-million-of-times | I have a few ranges (that can overlap) as parameter; for example: # tuple[0] <= n < tuple[1] ranges = [(70, 80), (80, 120), (120, 130), (120, 2000), (1990, 2000), (2000, 2040), (2040, 2050)] And I have a list of tuples as input, where the second element of each tuple is the number that determines the range(s) the tupl... | Given the sizes you mentioned, your code in UPDATE seems speed-wise rather optimal already, as it takes time proportional to the size of your desired outputs. It's just incorrect, since it accumulates the input list data instead of computing the members list for each input alone. Since you said you don't need the membe... | 4 | 1 |
77,071,445 | 2023-9-9 | https://stackoverflow.com/questions/77071445/convert-plotly-express-graph-into-json | I am using plotly express to create different graphs. I am trying to convert graphs into json format to save in json file. While doing so I am getting error using different ways as below: Way-1 code gives error as below Error-2 Object of type ndarray is not JSON serializable Way-2 code gives error as below Error-2 Obje... | You were close with way-2, you need to : Convert the figure (go.Figure) to a JSON string using pio.to_json(), so that ndarray and other python types used in the figure's data are properly converted into their javascript equivalent. Deserialize the JSON string using json.loads() in order to get the figure as a standar... | 2 | 2 |
77,070,883 | 2023-9-9 | https://stackoverflow.com/questions/77070883/performance-comparison-mojo-vs-python | Mojo, a programming language, claims to be 65000x faster than python. I am eager to understand if is there any concrete benchmark data that supports this claim? Also, how does it differ in real world problems? I am primarily encountered this claim on their website and have watched several videos discussing Mojo's speed... | TL;DR: The claim directly comes from a blog on the Mojo website. The benchmark is a computation of the Mandelbrot set. It is not a rigorous benchmark nor one representative of most Python applications. It is also clearly biased (e.g. sequential VS parallel codes). They choose it because it has the following properties:... | 15 | 26 |
77,069,769 | 2023-9-8 | https://stackoverflow.com/questions/77069769/running-a-python-script-using-schedule-library | My company blocks the Windows Task Scheduler (along with many other Python libraries), so I need to use the schedule library. My script imports several flat files, performs some grouping and simple calculations using dataframes, and then saves one final TXT file. I've read up on how schedule works, but how do I use it ... | The do function only registers the job, but it will not actually execute it. You need to use the run_pending function to execute the job. import pandas as pd import time import schedule def daily(): #dataframe creation/manipulation etc... schedule.every().day.at("16:30").do(daily) while True: schedule.run_pending() tim... | 2 | 5 |
77,068,908 | 2023-9-8 | https://stackoverflow.com/questions/77068908/how-to-install-pytorch-with-cuda-support-on-windows-11-cuda-12-no-matching | I'm trying to install PyTorch with CUDA support on my Windows 11 machine, which has CUDA 12 installed and python 3.10. When I run nvcc --version, I get the following output: nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2023 NVIDIA Corporation Built on Tue_Aug_15_22:09:35_Pacific_Daylight_Time_2023 Cuda comp... | To install PyTorch using pip or conda, it's not mandatory to have an nvcc (CUDA runtime toolkit) locally installed in your system; you just need a CUDA-compatible device. To install PyTorch (2.0.1 with CUDA 11.7), you can run: pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu117 ... | 3 | 13 |
77,068,488 | 2023-9-8 | https://stackoverflow.com/questions/77068488/how-to-efficiently-convert-a-markdown-table-to-a-dataframe-in-python | I need to convert a markdown table into a pandas DataFrame. I've managed to do this using the pd.read_csv function with '|' as the separator, but it seems like there's some additional cleanup required. Specifically, I need to remove the row containing '-----', which is used for table separation, and I also want to get ... | Like this import re import pandas as pd text = """ | Some Title | Some Description | Some Number | |------------|------------------------------|-------------| | Dark Souls | This is a fun game | 5 | | Bloodborne | This one is even better | 2 | | Sekiro | This one is also pretty good | 110101 | """ pattern = r"\| ([\w\s... | 7 | 3 |
77,068,855 | 2023-9-8 | https://stackoverflow.com/questions/77068855/specifying-multiple-possible-criteria-at-one-level-of-a-multi-index-cross-sectio | I'm newly working with a MultiIndex, and am struggling with how to get certain cross-sections of data. Specifically, when I want to specify more than one category within an index level, but not all categories at that level. Borrowing from pandas documentation for the data: d = {'num_legs': [4, 4, 2, 2], 'num_wings': [0... | For these cases, I recommend just to use .loc: out = df.loc[(["mammal", "bird"], slice(None), slice(None))] print(out) Prints: num_legs num_wings class animal locomotion mammal cat walks 4 0 dog walks 4 0 bat flies 2 2 bird penguin walks 2 2 EDIT: For multi-index columns: Initial df: num_legs num_wings A B A B cla... | 2 | 1 |
77,067,644 | 2023-9-8 | https://stackoverflow.com/questions/77067644/jax-errors-unexpectedtracererror-only-when-using-jax-debug-breakpoint | My jax code runs fine but when I try to insert a breakpoint with jax.debug.breakpoint I get the error: jax.errors.UnexpectedTracerError. I would expect this error to show up also without setting a breakpoint. Is this intended behavior or is something weird happening? When using jax_checking_leaks none of the reported t... | There is currently a bug in jax.debug.breakpoint that can lead to spurious tracer leaks in some situations: see https://github.com/google/jax/issues/16732. There's not any easy workaround at the moment, unfortunately, but hopefully the issue will be addressed soon. | 2 | 2 |
77,067,011 | 2023-9-8 | https://stackoverflow.com/questions/77067011/scipy-optimize-linprog-doesnt-return-minimal-solution-id-expect-it-to | I read that linprog from scipy returns minimal solutions and one could get the optimal by multiply the objective function by -1. I read it here: https://realpython.com/linear-programming-python/ And I've tested the example they provided to see if i could get the minimal solution too -- I could. Regarding the problem i... | The "issue" here is that there are an infinite number of minima and maxima for this problem, with the objective function equal to the same value for all optimal solutions (ignoring the sign flip for maximization). This can be seen by examining your equality constraint relative to your objective function and noting that... | 2 | 6 |
77,066,397 | 2023-9-8 | https://stackoverflow.com/questions/77066397/duckdb-whats-the-difference-between-sql-and-execute-function | I am a newbie using DuckDb library in python and while going through docs I stumbled upon 2 functions to execute sql instructions, namely execute() and sql(). What's the difference between the 2? I am really scratching my head with this. | While sql and execute can be used to achieve the same results, they have slight differences which may impact which function you use. The sql function runs the query as-is. It will return a DuckDBPyRelation which allows "constructing relationships". duckdb.sql(query: str, alias: str = 'query_relation', connection: duck... | 9 | 6 |
77,064,579 | 2023-9-8 | https://stackoverflow.com/questions/77064579/module-numpy-has-no-attribute-no-nep50-warning | When load HuggingFaceEmbeddings, always shows error like below. --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-27-04d1583103a5> in <cell line: 2>() 1 get_ipython().system('pip install --force-reinstall numpy==1.24.0') ----> 2 e... | Open fresh collab editor and run each command #this is minimum pre-requisites pip install langchain pip install sentence-transformers Code from langchain.embeddings import HuggingFaceEmbeddings embeddings = HuggingFaceEmbeddings( model_name="intfloat/multilingual-e5-large" ) | 3 | 3 |
77,063,818 | 2023-9-8 | https://stackoverflow.com/questions/77063818/how-to-wait-for-user-input-for-5-seconds-in-python | I am trying to process the contents of a file. I need ideas as to how to interact with the user and to wait for a press of a key (s) to write the current line into another file. Thank you in advance. with open(srcFile) as f: line = f.readline().strip() #- do something with line #- part where I need help if s is press, ... | you can use the time and keyboard package for this case: import time import keyboard start_time = time.time() # Start the timer key_pressed = False while True: if keyboard.is_pressed("s"): key_pressed = True break if time.time() - start_time >= 5: break if key_pressed: # write the current line to file You might test w... | 2 | 2 |
77,062,348 | 2023-9-7 | https://stackoverflow.com/questions/77062348/modulenotfounderror-no-module-named-pycaret-arules | I want to use the Association Rule Mining package from PyCaret. I installed the same using: pip install pycaret[full] However, when I try to import the arules module, I get the ModuleNotFoundError: >>> from pycaret.arules import * Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundErr... | Arules module was removed from Pycaret versions 3.x. If you really need to use Arules, then you need to downgrade your Pycaret to at least 2.3.10. I tested with Pycaret 2.3.5 and it works fine: pip install pycaret==2.3.5 | 2 | 2 |
77,061,365 | 2023-9-7 | https://stackoverflow.com/questions/77061365/creating-a-list-of-dictionaries-from-two-nested-lists-with-repeated-keys | I have two key/value inputs, both in the form of nested lists. Any given key may have multiple values, as with K1 and K2 here: key_in = [['K1', 'K1', 'K2', 'K3'], ['K1', 'K2', 'K2', 'K3']] val_in = [['V1', 'V2', 'V3', 'V4'], ['V5', 'V6', 'V7', 'V8']] I would like to merge / consolidate these into a list of nested dict... | You can use a double zip-loop to feed the nested dicts with sets and form your list : from collections import defaultdict out = [] for ink, inv in zip(key_in, val_in): d = defaultdict(set) for k, v in zip(ink, inv): d[k].add(v) out.append(dict(d)) Another variant, as suggest by @mozway, you can use : out = [] for ink,... | 2 | 3 |
77,061,417 | 2023-9-7 | https://stackoverflow.com/questions/77061417/how-to-make-long-format-using-one-column-has-a-list-of-items-in-pandas-python | I am working with a data frame that has one column, values, with a list of items within it. Below is data frame I have: | uniqId | DeptId | Date | values | | -------- | ------- | ---------- | ---------- | | 1234 | BKNG | 2023-09-05 | [VGM, FJK] | | 2534 | FINA | 2023-09-04 | [GTD, WEH] | | 3469 | ASKG | 2023-09-05 | [M... | Try: cp = df["values"] df = df.explode("values") df = df.rename(columns={"values": "values_1"}).assign(values=cp) print(df) Prints: uniqId DeptId Date values_1 values 0 1234 BKNG 2023-09-05 VGM [VGM, FJK] 0 1234 BKNG 2023-09-05 FJK [VGM, FJK] 1 2534 FINA 2023-09-04 GTD [GTD, WEH] 1 2534 FINA 2023-09-04 WEH [GTD, WEH]... | 2 | 2 |
77,060,728 | 2023-9-7 | https://stackoverflow.com/questions/77060728/sorting-a-list-in-specific-order-using-substrings | I have a list of some strings that looks like this: my_list = ['0123_abcd', '1234_bcde', '2345_cdef', '3456_defg', '4567_efgh'] I want to sort this list by using another list containing only substrings of the first list: ordering = ['3456', '2345', '0123'] Every Element which is in my_list but not in ordering shall be ... | If the strings in ordering are unique, then this is a possible solution: ordering_dict = {s: i for i, s in enumerate(ordering)} sorted_list = sorted( my_list, key=lambda x: ordering_dict.get(x.split("_")[0], len(ordering_dict)), ) This has the advantage over other methods to not have quadratic complexity! | 2 | 2 |
77,059,223 | 2023-9-7 | https://stackoverflow.com/questions/77059223/opencv-get-framerate-and-frame-timestamp-from-live-webcam-stream | I'm struggling a bit trying to read/set the fps for my webcam and to read the timestamp for specific frames captured from my webcam. Specifically when I try to use vc.get(cv2.CAP_PROP_POS_MSEC), vc.get(cv2.CAP_PROP_FPS), vc.get(cv2.CAP_PROP_FRAME_COUNT) they return respectively -1, 0, -1. Clearly there's something that... | Apparently the OpenCV backend for cameras on your operating system (DSHOW) does not keep track of frame timestamps. After a read(), just use time.perf_counter() or a sibling function. It'll be close enough, unless you throttle the reading, in which case the frames would be stale. You could open an issue on OpenCV's git... | 2 | 2 |
77,060,299 | 2023-9-7 | https://stackoverflow.com/questions/77060299/join-elements-of-a-nested-list-based-on-condition | I have a nested array called element_text in the form of for example: [[1, 'the'], [1, 'quick brown'], [2, 'fox jumped'], [2, 'over'], [2, 'the'], [3, 'lazy goat']] And would like to concatenate the elements in the array and return a new array called page_text as so: [[1, 'the quick brown'], [2, 'fox jumped over the']... | Solution: You can use pandas by grouping the records by your number and joining all the strings together into a new column. import pandas as pd data = [[1, 'the'], [1, 'quick brown'], [2, 'fox jumped'], [2, 'over'], [2, 'the'], [3, 'lazy goat']] df = pd.DataFrame(data, columns=['num','text']) df['full_text'] = df.group... | 3 | 3 |
77,059,938 | 2023-9-7 | https://stackoverflow.com/questions/77059938/whats-the-logic-behind-cumsum-to-make-flags-compute-counts-and-form-groups | Without further ado, my input (s1) & expected-output (df) are below : #INPUT s1 = pd.Series(['a', np.nan, 'b', 'c', np.nan, np.nan, 'd', np.nan]).rename('col1') #EXPECTED-OUTPUT s2 = pd.Series([1, 2, 3, 3, 4, 4, 5, 6]).rename('col2') # flag the transition null>notnull or vice-versa s3 = pd.Series([0, 1, 0, 0, 2, 3, 0, ... | You can use isna with cumsum and where for "col3". For "col2" a classical ne+shift/cumsum: m = df['col1'].isna() # if the flag is different from the previous one, increment df['col2'] = m.ne(m.shift()).cumsum() # increment on each True, mask the False df['col3'] = m.cumsum().where(m, 0) Output: col1 col2 col3 0 a 1 0... | 2 | 2 |
77,049,666 | 2023-9-6 | https://stackoverflow.com/questions/77049666/deploying-fastapi-in-azure | I am trying to deploy my application which is built using Python and FastAPI for backend and the HTML for the frontend. Using the student login i created an app service and uploaded my code using github. My project directory is like Frontend/ |- file.html |- x.css FastAPI/ |- main.py |- other.py |- requirements.txt in... | I have deployed a simple Fast API project with HTML and CSS as frontend: My project structure: - FastAPI - templates - index.html -static - style.css - main.py - requirements.txt Create Azure App Service with Python as Runtime stack, Linux as OS and Consumption hosting Plan in Azure Portal: Configure Deployment du... | 3 | 4 |
77,059,419 | 2023-9-7 | https://stackoverflow.com/questions/77059419/split-up-column-value-into-empty-column-values-in-a-dataframe | I am having a dataframe df: columnA columnB columnC A A 10 A B NaN A C 20 B A 30 B C NaN A D NaN D C 15 How can I fill the NaNvalues in that case, that the next non `NaN´ value is diveded by the missing entries before and splitted (including the already filled row)? So in my case that the output is: columnA columnB co... | Another one-chained variation using pd.Series.shift: df['columnC'] = (df['columnC'].fillna(0).groupby(df['columnC'].notna().cumsum() .shift().fillna(0)).transform('mean')) columnA columnB columnC 0 A A 10.0 1 A B 10.0 2 A C 10.0 3 B A 30.0 4 B C 5.0 5 A D 5.0 6 D C 5.0 | 2 | 3 |
77,059,331 | 2023-9-7 | https://stackoverflow.com/questions/77059331/y-parameters-to-z-parameters-in-python | Is there any function in python that converts y parameters to z parameters like matlab's y2z function? Here is matlab's y2z() function documentation. | No built-in Python function for Y-to-Z conversion like MATLAB's y2z. However, you can easily implement it. MATLAB Code Y = [1, 2; 3, 4]; Z = y2z(Y); disp('Y Parameters:'); disp(Y); disp('Z Parameters:'); disp(Z); Python Code You can use NumPy for matrix operations. import numpy as np def y2z(Y): Y11, Y12, Y21, Y22 = Y... | 2 | 2 |
77,058,813 | 2023-9-7 | https://stackoverflow.com/questions/77058813/can-a-pytest-fixture-know-whether-a-test-has-passed-or-failed | I'm writing some tests in pytest, and I'd like to make the fixture do something only if the test passes (update a value in a DB). It doesn't seem like fixtures in general know about whether the tests they run pass or fail -- is there a way to make them? import pytest @pytest.fixture def my_fixture(request): ... yield [... | You can introspect the test context by requesting the request object in the fixture. There you can get request.session.testsfailed @pytest.fixture def my_fixture(request): failed_count = request.session.testsfailed yield if request.session.testsfailed > failed_count: print("this test failed") | 2 | 4 |
77,058,208 | 2023-9-7 | https://stackoverflow.com/questions/77058208/pyopengl-flickering-points-and-lines | I'm trying to visualize 3D human keypoints in PyOpenGL, the code works fine if one human is present. more than one, the points and lines starts to flicker. while True: # Grab an image time_temp=time.time() def points(keypoints_3d): glEnable(GL_POINT_SMOOTH) glEnable(GL_BLEND) glEnable(GL_FRAMEBUFFER_SRGB) glPointSize(1... | You need to update the display once after you have drawn all the geometry, instead of updating it after each geometry. So call pygame.display.flip() after the loop, but not in the loop: while True: # [...] # clear display glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) # draw all the geometry for body in bodies_list: ... | 2 | 2 |
77,056,035 | 2023-9-7 | https://stackoverflow.com/questions/77056035/why-would-you-want-to-create-more-than-one-event-loops-in-asyncio | Why not just use the default one always? are there any usecases for creating multiple event loops? | I don't know the exact reason behind your question. But there are certainly use cases for using multiple loops. e.g. To increase scalability. We know, CPU-bound code will interfere with event-loops in a process. This will reduce throughput. Not if we have loops in other processes, event-loops in other processes will no... | 2 | 1 |
77,056,341 | 2023-9-7 | https://stackoverflow.com/questions/77056341/how-do-you-modify-styled-data-frame-in-pandas | I have this data frame: df Server Env. Model Percent_Utilized server123 Prod Cisco. 50 server567. Prod Cisco. 80 serverabc. Prod IBM. 100 serverdwc. Prod IBM. 45 servercc. Prod Hitachi. 25 Avg 60 server123Uat Uat Cisco. 40 server567u Uat Cisco. 30 serverabcu Uat IBM. 80 serverdwcu Uat IBM. 45 serverccu Uat Hitachi 15 A... | df.style returns a pd.Styler object, not a pd.DataFrame object. So you cannot use .astype. You can use Styler.format like this: df_new = df.style.applymap(color, subset=["Percent_Utilized"])\ .format('{:.0f}%', subset=['Percent_Utilized'], na_rep='nan') You'd get something like this, ignore the Avg rows as they are no... | 2 | 2 |
77,053,457 | 2023-9-6 | https://stackoverflow.com/questions/77053457/how-could-i-extract-all-digits-and-strings-from-the-first-list-into-other-list | I have the first list call OGList that have a list of strings, after that I want to extract all digits and strings from the OGList into a list of string and a list of digits. My Input: OGList = ['A10', 'BMW320i', 'Nissan NSX200', 'Benz 220c'] numlist = [] strlist = [] otherlist = [] for i in OGList: for x in i: if x.is... | Since you tagged the question with regex, here's an alternative approach using the same to separate the three groups: import re OGList = ['A10', 'BMW320i', 'Nissan NSX200', 'Benz 220c'] types = {"chars": "[a-zA-Z]", "nums": "[0-9]", "other": "[^a-zA-Z0-9]"} res = {k: [''.join(re.findall(types[k], s)) for s in OGList] f... | 2 | 5 |
77,049,524 | 2023-9-6 | https://stackoverflow.com/questions/77049524/selenium-isnt-using-my-own-chrome-driver-i-set-and-is-using-the-default-one | So I'm trying to get the source of a webpage in Python, and for compatability reasons, I have to use Google Chrome 114 instead of the latest 116. I used a service to create it and downloaded my own version that should work, however it just seems to be completely ignoring it and using my system one. from selenium import... | You can use https://github.com/seleniumbase/SeleniumBase to mix any Chrome browser version with any chromedriver version. After pip install seleniumbase, you can run the following script with python to force a specific chromedriver version for the already-installed Chrome version: from seleniumbase import Driver driver... | 3 | 2 |
77,051,578 | 2023-9-6 | https://stackoverflow.com/questions/77051578/convert-dataframe-of-dictionary-entries-to-dataframe-of-all-entries-based-on-exi | I have a pandas dataframe that consists of an id and an associated count of different encoded words. For instance: Original = pd.DataFrame(data=[[1,'1:2,2:3,3:1'],[2,'2:2,4:3']], columns=['id','words']) I have a dictionary that has the mapping to the actual words, for instance: WordDict = {1:'A',2:'B',3:'C',4:'D'} Wh... | You can use a regex, a list comprehension, and the DataFrame constructor: import re Final = pd.DataFrame([{WordDict.get(int(k), None): v for k,v in re.findall('([^:,]+):([^:,]+)', s)} for s in Original['words']], index=Original['id'] ).fillna(0).astype(int) Or with split: Final = pd.DataFrame([{WordDict.get(int(k), No... | 4 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.