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
76,036,074
2023-4-17
https://stackoverflow.com/questions/76036074/cannot-debug-test-case-in-vs-code-found-duplicate-in-env-path
I am using VS Code for developing in Python. I have been able to debug single test cases from the test module, which is very practical. Since recently, it no longer works. After a short waiting time, a dialog pops up: "Invalid message: Found duplicate in "env": PATH." with the buttons "Open launch.json" and "Cancel". O...
You can install different versions of the Python plugin (to whom it may concern: if this works unsatisfactorily, it may be because you have multiple instances of VS Code running). You will note: 2023.4.1 is the latest known stable version that works 2023.6.0 does not work v2023.7.11011538 (latest) works It seems it's...
3
0
76,040,332
2023-4-18
https://stackoverflow.com/questions/76040332/conda-install-cant-install-packages-from-requirements-txt
I have a conda environment set up with all of the packages I need (currently), and I wanted to make a new one from the requirements.txt file (formatted for conda, not pip) to make sure that someone else can use my project. This requirements file was generated from the other environment that I already have set up. Thus,...
It looks like you've used conda list --export to generate the list of packages. Unfortunately, when some packages are installed from PyPI using pip, this command isn't helpful. The command you need to export your environment is: conda env export > environment.yml Then to create a new environment from that spec: conda ...
4
4
76,020,838
2023-4-15
https://stackoverflow.com/questions/76020838/find-all-possible-sums-of-the-combinations-of-sets-of-integers-efficiently
I have an algorithm that finds the set of all unique sums of the combinations of k tuples drawn with replacement from of a list of tuples. Each tuple contains n positive integers, the order of these integers matters, and the sum of the tuples is defined as element-wise addition. e.g. (1, 2, 3) + (4, 5, 6) = (5, 7, 9) S...
You can actually encode your tuples as integers. Since you mention that the integers range [0, 50], and there may be up to 5 such integers, so that creates a range of 51^5 = 345,025,251 values, which is perfectly doable. To understand how we can do this encoding, think about how decimal numbers work- 123 means 1*100 + ...
8
5
76,031,309
2023-4-17
https://stackoverflow.com/questions/76031309/is-it-possible-to-hint-that-a-function-parameter-should-not-be-modified
For example, I might have an abstract base class with some abstract method that takes some mutable type as a parameter: from abc import * class AbstractClass(metaclass=ABCMeta): @abstractmethod def abstract_method(self, mutable_parameter: list | set): raise NotImplementedError Is there some way of hinting to the funct...
You might be able to find a structural superclass that provides the behaviors you want. There's a good summary of the available collections classes at collections.abc, but as a quick, non-exhaustive summary. If you're just planning to iterate over the collection in some order, you're looking for Iterable. If all you'r...
5
3
76,020,646
2023-4-15
https://stackoverflow.com/questions/76020646/python-planetscale-db-mysql-connection
I have been trying to make a Python program that connects to a Planetscale MySQL DB, I have used 2 libraries that are mysql-connector-python and mysqlclient. I think I have entered the correct details every time with both but it hasn't worked. I tried Planetscale's recommended way which is the following (it didn't work...
I have fixed the issue. The problem was the SSL and that I used a dictionary to store the details, then used **config to use the dictionary in the connection. Here is the correct and working code for me: import mysql.connector as sql conn = sql.connect(host="*Hidden For Security Purposes*", database="*Hidden For Securi...
4
2
76,018,208
2023-4-14
https://stackoverflow.com/questions/76018208/python-typing-equivalent-of-typescripts-keyof
In TypeScript, we have the ability to create a "literal" type based on the keys of an object: const tastyFoods = { pizza: '🍕', burger: '🍔', iceCream: '🍦', fries: '🍟', taco: '🌮', sushi: '🍣', spaghetti: '🍝', donut: '🍩', cookie: '🍪', chicken: '🍗', } as const; type TastyFoodsKeys = keyof typeof tastyFoods; // giv...
There is not. You need to define the Literal type statically: TastyFoodsKeys = Literal["pizza", "burger"] You can, however, use TastyFoodsKeys.__args__ to then define your dict. tasty_foods = dict(zip(TastyFoodsKeys.__args__, ['🍕', '🍔'])) The __args__ attribute is not documented, so use at your own risk. As pointed...
8
9
76,009,612
2023-4-13
https://stackoverflow.com/questions/76009612/numpy-matmul-performs-100-times-worse-than-dot-on-array-views
It was brought to my attention that the matmul function in numpy is performing significantly worse than the dot function when multiplying array views. In this case my array view is the real part of a complex array. Here is some code which reproduces the issue: import numpy as np from timeit import timeit N = 1300 xx = ...
These timings indicate the dot is doing a copy with real: In [22]: timeit np.dot(xx.real,xx.real) 232 ms ± 3.34 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [23]: timeit np.dot(xx.real.copy(),xx.real.copy()) 232 ms ± 4.18 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) Applying that to matmul produce...
5
1
76,012,644
2023-4-14
https://stackoverflow.com/questions/76012644/fastapi-uvicorn-or-hypercorn-where-is-my-root-path
Based on a few FastAPI tutorials, including this, I made a simple FastAPI app: from fastapi import FastAPI, Request app = FastAPI() # also tried FastAPI(root_path="/api/v1") @app.get("/app") def read_main(request: Request): return {"message": "Hello World", "root_path": request.scope.get("root_path")} Which i want to ...
As noted by @MatsLindh in the comments section, root_path (or --root-path) does not change your application's prefix path, but is rather designated for behind the proxy cases, where "you might need to use a proxy server like Traefik or Nginx with a configuration that adds an extra path prefix that is not seen by your a...
7
7
75,994,620
2023-4-12
https://stackoverflow.com/questions/75994620/windows-store-not-adding-python-to-path
I have installed Python 3.11 from Windows Store. I used to have Python 3.10 also installed from Windows store, but I changed the environment variables and could not use it from the terminal anymore. Therefore I decided to uninstall it and install the latest version, hoping that it would be added to PATH automatically, ...
I finally solved it by looking at another device where I had a similar configuration. I needed to add C:\Users\Usuario\AppData\Local\Microsoft\WindowsApps and C:\Users\Usuario\AppData\Local\Microsoft\WindowsApps\python3.11.exe to the path. That worked. Still don't know why Windows Store didn't add them automatically th...
3
2
76,012,206
2023-4-14
https://stackoverflow.com/questions/76012206/how-do-i-properly-handle-all-possible-exceptions-by-the-requests-module-if-a-sit
I live in China, behind the infamous Great Firewall of China, and I use VPNs. A simple observation is that while the VPN is connected, I can access www.google.com. And if the VPN isn't connected, then I cannot access Google. So I can check if I have an active VPN connection by accessing Google. My ISP really loves to d...
I think it would be better to use RequestException from requests.exception module. The hierarchy is the following: builtins.OSError(builtins.Exception) RequestException # <- Use this top level exception ChunkedEncodingError ConnectionError ConnectTimeout(ConnectionError, Timeout) ProxyError SSLError ContentDecodingErro...
3
3
76,009,318
2023-4-13
https://stackoverflow.com/questions/76009318/python-vectorization-split-string
I want to use vectorization to create a column in a pandas data frame that retrieve the second/last part of a string, from each row in a column, that is split on '_'. I tried this code: df = pd.DataFrame() df['Var1'] = ["test1_test2","test3_test4"] df['Var2'] = [[df['Var1'].str.split('_')][0]][0] df Var1 Var2 0 test1_t...
Use the .str.split('_') method along with .str[-1] to retrieve the second/last part of each string in the column. Following is the updated code: import pandas as pd df = pd.DataFrame() df['Var1'] = ["test1_test2", "test3_test4"] df['Var2'] = df['Var1'].str.split('_').str[-1] print(df) Output: Var1 Var2 0 test1_test2 ...
3
1
75,996,188
2023-4-12
https://stackoverflow.com/questions/75996188/ansible-how-to-execute-set-fact-module-from-within-ansible-action-plugin-python
I am writing a custom Action Plugin for Ansible which I use in my playbook and I am trying to set a variable that will be used in the next task, in the playbook, by a (custom) module. Effectively, the playbook equivalent of what I am trying to mimic is a set_fact task like so: - name: set_fact task set_fact: ansible_py...
The closest I can get is to return a dict containing the Ansible facts that I want to be set for the playbook simply by following the dev guide for Action Plugins on the Ansible docs. So, as I am returning an _execute_model() call in my plugin as well, my run() function in my plugin would look something like this: def ...
5
2
76,005,798
2023-4-13
https://stackoverflow.com/questions/76005798/numpy-svd-does-not-agree-with-r-implementation
I saw a question about inverting a singular matrix on Stack Overflow using NumPy. I wanted to see if NumPy SVD could provide an acceptable answer. I've demonstrated using SVD in R for another Stack Overflow answer. I used that known solution to make sure that my NumPy code was working correctly before applying it to th...
Thanks to Chrysophylaxs, here is the code that is now working correctly: # https://stackoverflow.com/questions/75998775/python-vs-matlab-why-my-matrix-is-singular-in-python import numpy as np def pseudo_inverse_solver(A, b): A_inv = np.linalg.pinv(A) x = np.matmul(A_inv, b) error = np.matmul(A, x) - b return x, error, ...
5
1
76,003,473
2023-4-13
https://stackoverflow.com/questions/76003473/how-to-disable-debugger-warnings-about-frozen-modules-when-using-nbconvert-execu
I am trying to run a python script to run all cells in all notebooks found a directory. It runs fine and I am getting the desired results in the notebook files. However, I want to disable the warnings that are printed to the VSCode cmd terminal when running the script. My code below: import nbformat from glob import gl...
Figured out how to "Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation". Adding a user or system environment variable called 'PYDEVD_DISABLE_FILE_VALIDATION' and setting the value to '1' did the job. Didn't know this is what it meant (newbie alert).
3
3
76,004,898
2023-4-13
https://stackoverflow.com/questions/76004898/how-to-convert-polars-dataframe-column-type-from-float64-to-int64
I have a polars dataframe, like: import polars as pl df = pl.DataFrame({"foo": [1.0, 2.0, 3.0], "bar": [11, 5, 8]}) How do I convert the first column to int64 type? I was trying something like: df.select(pl.col('foo')) = df.select(pl.col('foo')).cast(pl.Int64) but it is not working. In Pandas it was super easy: df['f...
Select your col, cast it to (int64) and add it back to the original DataFrame with_columns. df = df.with_columns(pl.col("foo").cast(pl.Int64)) Output : print(df) shape: (3, 2) ┌─────┬─────┐ │ foo ┆ bar │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 1 ┆ 11 │ │ 2 ┆ 5 │ │ 3 ┆ 8 │ └─────┴─────┘
4
8
76,001,787
2023-4-13
https://stackoverflow.com/questions/76001787/how-can-i-read-just-one-line-from-standard-input-and-pass-the-rest-to-a-subproc
If you readline() from sys.stdin, passing the rest of it to a subprocess does not seem to work. import subprocess import sys header = sys.stdin.buffer.readline() print(header) subprocess.run(['nl'], check=True) (I'm using sys.stdin.buffer to avoid any encoding issues; this handle returns the raw bytes.) This runs, but...
This is because sys.stdin is created using the built-in open function in the default buffered mode, which uses a buffer of size io.DEFAULT_BUFFER_SIZE, which on most systems is either 4096 or 8192 bytes. To make the parent process consume precisely one line of text from the standard input, you can therefore open it wit...
8
11
75,999,222
2023-4-12
https://stackoverflow.com/questions/75999222/how-to-plot-spiral-that-goes-around-circular-paraboloid
I have a 3D circular paraboloid surface and I would like to plot a spiral that starts from an arbitrary point on the surface and goes down while "hugging" the surface. This is my attempt so far: import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = plt.axes(projection='3d') # Surface --------------...
The formula in the second attempt is correct. I get what you want if I use the same formula in your first attempt. The line z = -0.15*u/np.pi*(x**2 + y**2) + r0**2 needs to be replaced with -(x**2 + y**2) + r0**2. For reproducibility: %matplotlib notebook import numpy as np import matplotlib.pyplot as plt fig = plt.fig...
3
2
76,001,604
2023-4-13
https://stackoverflow.com/questions/76001604/extracting-the-minimum-x-value-keys-from-dictionary
Suppose we wish to extract the minimum value from a dictionary like so scores = { 0:1.3399288498085087, 1:1.2672683347433629, 3:1.6999159970296505, 4:1.8410942584597279, 5:1.336658057628646 } #find minimum value in dictionary minimum_value = min(scores.values()) #get keys with minimal value using list comprehension min...
In fact, the problem is simpler than you think: scores = { 0:1.3399288498085087, 1:1.2672683347433629, 3:1.6999159970296505, 4:1.8410942584597279, 5:1.336658057628646 } # minimum key print(min(scores, key=scores.get)) # n minimum keys print(sorted(scores, key=scores.get)[:3]) Output: 1 [1, 5, 0] Both min and sorted a...
4
5
75,999,612
2023-4-12
https://stackoverflow.com/questions/75999612/why-is-a-pickled-object-with-slots-bigger-than-one-without-slots
I'm working on a program that keeps dying because of the OOM killer. I was hoping for some quick wins in reducing the memory usage without a major refactor. I tried adding __slots__ to the most common classes but I noticed the pickled size went up. Why is that? class Class: def __init__(self, a, b, c): self.a = a self....
So, on Python 3.11, let's define the following: class Foo: def __init__(self, a, b, c): self.a = a self.b = b self.c = c class Bar: __slots__ = ["a", "b", "c"] def __init__(self, a, b, c): self.a = a self.b = b self.c = c Now, let's see: >>> import pickle >>> import pickletools >>> len(pickle.dumps(Foo(1,2,3))), len(p...
5
4
75,998,924
2023-4-12
https://stackoverflow.com/questions/75998924/what-is-the-difference-between-manager-pool-and-pool-in-python-multiprocessing
Say I want to share a dictionary between processes. If I have defined a manager, what is the difference between instantiating a pool using manager.Pool() and multiprocessing.Pool()? Ex: What is the difference between the two with statements in main_1 and main_2? import multiprocessing as mp import time from random impo...
Both manager.Pool and multiprocessing.Pool in Python are used for creating a pool of worker processes to execute tasks in parallel. However, there are some differences between them. multiprocessing.Pool is a built-in class provided by the Python multiprocessing module. It creates a pool of worker processes, where each ...
4
4
75,999,147
2023-4-12
https://stackoverflow.com/questions/75999147/how-to-structurally-pattern-match-builtin-type-slice-in-python
How to structurally pattern match builtin type slice in python? Somewhy the following code does not work: def __getitem__(self, index): match index: case int(i): ... case slice(start, stop, step): ... case _: ... and I completely do not understand why.
Try: class Example: def __getitem__(self, index): match index: case int(i): print('int', i) case slice(start=start, stop=stop, step=step): print('slice', start, stop, step) case _: print('default') e = Example() e[1] e[1:2] Prints: int 1 slice 1 2 None
3
2
75,999,041
2023-4-12
https://stackoverflow.com/questions/75999041/pandas-how-to-check-if-column-not-empty-then-apply-str-replace-in-one-line-code
code: df['Rep'] = df['Rep'].str.replace('\\n', ' ') issue: if the df['Rep'] is empty or null ,there will be an error: Failed: Can only use .str accessor with string values! is there anyway can handle the situation when the column value is empty or null? If it is empty or null ,just ignore that row
By default the empty series dtype will be float64. You can do a workaround using the astype: df['Rep'] = df['Rep'].astype('str').str.replace('\\n', ' ') Test code: df = pd.DataFrame({'Rep': []}) # works df['Rep'] = df['Rep'].astype('str').str.replace('\\n', ' ') # doesn't work df['Rep'] = df['Rep'].str.replace('\\n', ...
5
3
75,998,784
2023-4-12
https://stackoverflow.com/questions/75998784/python-customtkinter-attributeerror-int-object-has-no-attribute-root
i just took over a project in python after a year and i wanted to rebuild it with customtkinter using the documentation. Here is the code: import customtkinter import tkinter from pytube import YouTube from PIL import Image customtkinter.set_appearance_mode("system") customtkinter.set_default_color_theme("blue") app = ...
tkinter.IntVar() already has a default value of 0. The documentation says the following about the arguments that tkinter.IntVar() can take: tkinter.IntVar(master=None, value=None, name=None) Since master comes first and you provided 0 as the first positional argument, it believes that it is the master argument. What ...
3
4
75,998,310
2023-4-12
https://stackoverflow.com/questions/75998310/converting-a-python-recursive-function-into-excel
So, I have to run a recursive function times but it's going to take too long to actually print out all the values. Thus, my professor recommended using Excel but I don't know Excel at all. I need help converting the code into Excel. It's probably easy for someone who knows Excel. def a(n): k=3.8 if n==0: return .5 else...
You don't need to use excel. You just need to use a better algorithm. The easiest way to prevent the exponential time complexity is don't re-calculate the same value twice: def a(n): k = 3.8 if n==0: return .5 else: x = a(n - 1) return k*x*(1-x) for i in range(100): print(a(i)) In Python, you should avoid recursion, t...
3
2
75,998,574
2023-4-12
https://stackoverflow.com/questions/75998574/how-to-implement-rolling-mean-ignoring-null-values
I am trying calculate RSI indicator. For that I need rolling-mean gain and loss. I would like to calculate rolling mean ignoring null values. So mean would be calculated by sum and count on existing values. Example: window_size = 5 df = DataFrame(price_change: { 1, 2, 3, -2, 4 }) df_gain = .select( pl.when(pl.col('pric...
I think the skipping of nulls is implied, see the min_periods description in the docs for this method. df_gain.select(pl.col('gain').rolling_mean(window_size=window_size, min_periods=1)) Gives me a column of 1.0, 1.5, 2.0, 2.0, 2.5. Note how the last two columns skips the null correctly.
5
1
75,955,739
2023-4-7
https://stackoverflow.com/questions/75955739/how-to-select-the-column-from-a-polars-dataframe-that-has-the-largest-sum
I have Polars dataframe with a bunch of columns I need to find the column with, for example, the largest sum. The below snippet sums all of the columns: df = pl.DataFrame( { "a": [0, 1, 3, 4], "b": [0, 0, 0, 0], "c": [1, 0, 1, 0], } ) max_col = df.select(pl.col(df.columns).sum()) shape: (1, 3) ┌─────┬─────┬─────┐ │ a ...
I would do this as a unpivot/filter. df \ .select(pl.all().sum()) \ .unpivot() \ .filter(pl.col('value')==pl.col('value').max()) If you want the original shape then a single chain is a bit tougher. I'd just do it like this instead. allcalc=df \ .select(pl.all().sum()) allcalc.select(allcalc.unpivot().filter(pl.col('v...
3
0
75,954,280
2023-4-6
https://stackoverflow.com/questions/75954280/how-to-change-the-position-of-a-single-column-in-python-polars-library
I am working with the Python Polars library for data manipulation on a DataFrame, and I am trying to change the position of a single column. I would like to move a specific column to a different index while keeping the other columns in their respective positions. One way of doing that is using select, but that requires...
Some attempts: df.drop("C").insert_column(1, df.get_column("C")) df.select(df.columns[0], "C", pl.exclude(df.columns[0], "C")) cols = df.columns cols[1], cols[2] = cols[2], cols[1] # cols[1:3] = cols[2:0:-1] df.select(cols) shape: (3, 4) ┌─────┬─────┬─────┬─────┐ │ A ┆ C ┆ B ┆ D │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i...
4
6
75,977,591
2023-4-10
https://stackoverflow.com/questions/75977591/mark-rows-of-one-dataframe-based-on-values-from-another-dataframe
I have following problem. Let's say I have two dataframes df1 = pl.DataFrame({'a': range(10)}) df2 = pl.DataFrame({'b': [[1, 3], [5,6], [8, 9]], 'tags': ['aa', 'bb', 'cc']}) print(df1) print(df2) shape: (10, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 0 │ │ 1 │ │ 2 │ │ 3 │ │ 4 │ │ 5 │ │ 6 │ │ 7 │ │ 8 │ │ 9 │ └─────┘ sh...
You could create the ranges and "flatten" the frame: .int_ranges() .explode() (df2 .with_columns(pl.int_ranges(pl.col("b").list.first(), pl.col("b").list.last() + 1)) .explode("b") ) shape: (7, 2) ┌─────┬──────┐ │ b ┆ tags │ │ --- ┆ --- │ │ i64 ┆ str │ ╞═════╪══════╡ │ 1 ┆ aa │ │ 2 ┆ aa │ │ 3 ┆ aa │ │ 5 ┆ bb │ │ 6 ┆...
3
3
75,987,622
2023-4-11
https://stackoverflow.com/questions/75987622/change-case-of-all-column-names-with-ibis
I have an Ibis table named t. Its column names are all lowercase. I want to change them all to uppercase. How can I do that?
The rename method of Ibis table objects renames columns. It can be used to make all the column names uppercase like this: t = t.rename(dict(zip([x.upper() for x in t.columns], t.columns))) rename also provides a shortcut for this: t = t.rename("ALL_CAPS") The above works in Ibis version 7.0.0 or newer. In older versi...
3
2
75,942,865
2023-4-5
https://stackoverflow.com/questions/75942865/async-solution-for-factory-boy-style-fixtures-in-fastapi
I really like the factory boy style of generated factories that can handle things like sequences, complex relationships etc. For a FastAPI app with fully async database access using factory boy seems likely problematic. There is dated discussion here and an old PR to add async support that seems stuck. Is there a good ...
I haven't seen further progress from factory boy on this issue, but ultimately implemented a solution using pytest fixtures as factories that is working well for me. The core idea is to build fixtures that return a factory method that can be used in tests. Here is a concrete example that generates users: @pytest.fixtur...
5
2
75,973,808
2023-4-10
https://stackoverflow.com/questions/75973808/concise-way-to-retrieve-a-row-from-a-polars-dataframe-with-an-iterator-of-column
I often need to retrieve a row from a Polars DataFrame given a collection of column values, like I might use a composite key in a database. This is possible in Polars using DataFrame.row, but the resulting expression is very verbose: row_index = {'treatment': 'red', 'batch': 'C', 'unit': 76} row = df.row(by_predicate=(...
(a == b) & (c == d) will return true if all of the conditions are true. Another way to express this is with pl.all_horizontal() pl.all_horizontal(a == b, c == d) pl.any_horizontal() can be used for "logical OR" To which you can pass your comprehension directly: expr = pl.all_horizontal( pl.col(k) == v for k, v in ro...
3
4
75,971,804
2023-4-9
https://stackoverflow.com/questions/75971804/what-should-i-do-with-user-installed-packages-on-debian-in-light-of-pep668
In light of some distributions (Debian at least) steering away from python3 -m pip install numpy what should I do with my user packages that I had installed with python3 -m pip install --user numpy (for instance)? They are located in python3 -m site --user-site : ~/.local/lib/python3.11/site-packages/. I don't want to:...
I decided to use pipenv to manage my packages, but to install it, I have to do a pip install. I wanted to do this just for my user, so I created a local venv for it, mkdir -p ~/.local/share/ apt install python3-pip python3 -m venv ~/.local/share/pipenv source ~/.local/share/pipenv/bin/activate and installed pipenv on ...
3
1
75,984,983
2023-4-11
https://stackoverflow.com/questions/75984983/polars-change-a-value-in-a-dataframe-if-a-condition-is-met-in-another-column
I have this dataframe df = pl.from_repr(""" ┌─────┬───────┐ │ one ┆ two │ │ --- ┆ --- │ │ str ┆ str │ ╞═════╪═══════╡ │ a ┆ hola │ │ b ┆ world │ └─────┴───────┘ """) And I want to change hola for hello: shape: (2, 2) ┌─────┬───────┐ │ one ┆ two │ │ --- ┆ --- │ │ str ┆ str │ ╞═════╪═══════╡ │ a ┆ hello │ # <- │ b ┆ wor...
You were really close with with_columns(pl.when(pl.col("one") == "a").then("hello")) but you needed to tell it which column that should be. When you don't tell it which column you're referring to then it has to guess and in this case it guessed the column you referred to. Instead you do (df .with_columns( two=pl.when(p...
12
20
75,985,726
2023-4-11
https://stackoverflow.com/questions/75985726/error-metric-for-backtest-and-historical-forecasting-in-darts-are-different
When using backtest and historical_forecast in darts I expect the same error. However, when doing a test, I get different MAPE values for the same input variables. Can somebody explain how this can happen? How can I make the two methods comparable? Example: import pandas as pd from darts import TimeSeries from darts.mo...
The reason the MAPEs are different is because the data used to compute them are different. Historical_forecast() and backtest() have different default values for the parameter "last_points_only". For historical_forecast(), the parameter is set to True, while for backtest() it is False. This means that historical_foreca...
5
4
75,979,676
2023-4-10
https://stackoverflow.com/questions/75979676/why-does-this-code-work-on-python-3-6-but-not-on-python-3-7
In script.py: def f(n, memo={0:0, 1:1}): if n not in memo: memo[n] = sum(f(n - i) for i in [1, 2]) return memo[n] print(f(400)) python3.6 script.py correctly prints f(400), but with python3.7 script.py it stack overflows. The recursion limit is reached at f(501) in 3.6 and at f(334) in 3.7. What changed between Python...
After some git bisecting between Python 3.6.0b1 and Python 3.7.0a1 I found bpo bug #29306 (git commits 7399a05, 620580f), which identified some bugs with the recursion depth counting. Originally, Victor Stinner reported that he was unsure that some new internal API functions for optimised calls (part of the reported ca...
8
12
75,968,376
2023-4-9
https://stackoverflow.com/questions/75968376/lowercase-text-with-regex-pattern
I use regex pattern to block acronyms while lower casing text. The code is # -*- coding: utf-8 -*- #!/usr/bin/env python from __future__ import unicode_literals import codecs import os import re text = "This sentence contains ADS, NASA and K.A. as acronymns." pattern = r'([A-Z][a-zA-Z]*[A-Z]|(?:[A-Z]\.)+)' matches = re...
The solution with r[\w\.] works in this case but will struggle if the acronym is at the end of a line with a dot after it (i.e. "[...] or ASDF." We use the pattern to identify every acronym, than lowercase the whole string and then replace the acronyms again with their original value. I changed the pattern a bit so tha...
3
1
75,936,149
2023-4-5
https://stackoverflow.com/questions/75936149/convert-tensorflow-to-onnx-current-implementation-of-rfft-or-fft-only-allows-co
I am trying to convert this TensorFlow model to onnx. But I get an error message: > python -m tf2onnx.convert --saved-model .\spice --output model.onnx --opset 11 --verbose ... 2023-04-08 18:33:10,811 - ERROR - tf2onnx.tfonnx: Tensorflow op [Real: Real] is not supported 2023-04-08 18:33:10,812 - ERROR - tf2onnx.tfonnx:...
The error mentioned above occurred because tf2onnx does not support Real and Imag operations. For a list of operations that can be used with tf2onnx, please refer to this link. This will also affect the TensorFlow model. I'm not sure what this means, but as far as I know, it has no relation whatsoever to what is refer...
3
2
75,983,462
2023-4-11
https://stackoverflow.com/questions/75983462/is-it-possible-to-interpolate-a-quarter-of-the-video-with-optical-flow
I am now trying to interpolate video using optical flow. I was able to interpolate the video by referring to this question and using it as a reference. So my question is: Is it possible to interpolate the video in 1/4 units even finer using the original frame and the optical flow frame? Thank you in advance. I tried ha...
I will try solving this problem with the help of an example. Suppose my previous image is and my next image is The next image was created by translating the previous image towards right (I hope it is visible). Now, let's calculate the optical flow between the two images and plot the flow vectors. optical_flow = cv2.c...
3
2
75,980,420
2023-4-10
https://stackoverflow.com/questions/75980420/upset-plot-python-list-row-names
The upset plot tutorials on the documentation have this example with movies: https://upsetplot.readthedocs.io/en/stable/formats.html#When-category-membership-is-indicated-in-DataFrame-columns I wanted to know, after creating data from memberships "Genre" and plotting how do I list the names of the movies as well? In th...
In the example on the documentation page, this information is contained in the dataframe movies_by_genre, which is defined as: movies_by_genre = from_indicators(genre_indicators, data=movies). Now, we can extract the required information from this data frame. We just need to make sure that the order of the boolean tupl...
3
2
75,982,081
2023-4-11
https://stackoverflow.com/questions/75982081/best-way-to-use-python-iterator-as-dataset-in-pytorch
The PyTorch DataLoader turns datasets into iterables. I already have a generator which yields data samples that I want to use for training and testing. The reason I use a generator is because the total number of samples is too large to store in memory. I would like to load the samples in batches for training. What is t...
PyTorch's DataLoader actually has official support for an iterable dataset, but it just has to be an instance of a subclass of torch.utils.data.IterableDataset: An iterable-style dataset is an instance of a subclass of IterableDataset that implements the __iter__() protocol, and represents an iterable over data sample...
5
2
75,939,770
2023-4-5
https://stackoverflow.com/questions/75939770/how-can-i-construct-a-dataframe-that-uses-the-pyarrow-backend-directly-i-e-wi
Pandas 2.0 introduces the option to use PyArrow as the backend rather than NumPy. As of version 2.0, using it seems to require either calling one of the pd.read_xxx() methods with type_backend='pyarrow', or else constructing a DataFrame that's NumPy-backed and then calling .convert_dtypes on it. Is there a more direct ...
If your data are known to be all of a specific type (say, int64[pyarrow]), this is straightforward: import pandas as pd data = {'col_1': [3, 2, 1, 0], 'col_2': [1, 2, 3, 4]} df = pd.DataFrame( data, dtype='int64[pyarrow]', # ... ) If your data are known to be all of the same type but the type is not known, then I don...
7
9
75,979,711
2023-4-10
https://stackoverflow.com/questions/75979711/reduced-dimensions-visualization-for-true-vs-predicted-values
I have a dataframe which looks like this: label predicted F1 F2 F3 .... F40 major minor 2 1 4 major major 1 0 10 minor patch 4 3 23 major patch 2 1 11 minor minor 0 4 8 patch major 7 3 30 patch minor 8 0 1 patch patch 1 7 11 I have label which is the true label for the id(not shown as it is not relevant), and predicte...
You may want to consider a small multiple plot with one scatterplot for each cell of the confusion matrix. If PCA does not work well, t-distributed stochastic neighbor embedding (TSNE) is often a good alternative in my experience. For example, with the iris dataset, which also has three prediction classes, it could loo...
4
2
75,939,141
2023-4-5
https://stackoverflow.com/questions/75939141/create-task-from-within-another-running-task
In Python I create two async tasks: tasks = [ asyncio.create_task(task1(queue)), asyncio.create_task(task2(queue)), ] await asyncio.gather(*tasks) Now, I have a need to create a third task "task3" within task1. So I have: async def task1(queue): # and here I need to create the "task3": asyncio.create_task(task3(queue)...
You can add a done callback to it, and just let the your task1 run forward. https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.add_done_callback A matter that could arise there, though, and that is buried in the docs: the asyncio loop avoids creating hard references (just weak) to the tasks, and when it i...
3
2
75,951,190
2023-4-6
https://stackoverflow.com/questions/75951190/sentence-transformer-use-of-evaluator
I came across this script which is second link on this page and this explanation I am using all-mpnet-base-v2 (link) and I am using my custom data I am having hard time understanding use of evaluator = EmbeddingSimilarityEvaluator.from_input_examples( dev_samples, name='sts-dev') The documentation says: evaluator – A...
Question 1 How is train_samples different from dev_samples in the context of the EmbeddingSimilarityEvaluator? One needs to have a "held-out" split of data to be used for evaluation during training to avoid over-fitting. This "held-out" set is commonly referred to as the "development set" as it is the set of data tha...
4
4
75,985,476
2023-4-11
https://stackoverflow.com/questions/75985476/is-there-a-way-to-use-private-fields-to-validation-in-pydantic
I want to set one field, which cannot be in response model in abstract method. I set this field to private. I want to use this field to validate other public field. class BaseAsset(BaseModel, ABC): amount: int precision: int nai: str _nai_pattern: str = None def __init__(self, **kwargs): super().__init__(**kwargs) obje...
I would suggest the following approach. Make nai_pattern a regular (not private) field, but exclude it from dumping by setting exclude=True in its Field constructor. In addition, hook into schema_extra of the model Config to remove the field from the schema as well. Make the method to get the nai_pattern a class metho...
3
3
75,956,534
2023-4-7
https://stackoverflow.com/questions/75956534/select-camera-programatically
My program should select three cameras and take pictures with each of it. I have the following code at the moment: def getCamera(camera): graph = FilterGraph() print("Camera List: ") print(graph.get_input_devices()) #tbd get right Camera try: device = graph.get_input_devices().index("HD Pro Webcam C920") except ValueEr...
You can use the index of the camera in the list to select it. For example, if you want to select the first camera in the list, you can use the following code: device = graph.get_input_devices().index("HD Pro Webcam C920") To select the second camera: device = graph.get_input_devices().index("HD Pro Webcam C920", 1) A...
3
6
75,990,745
2023-4-11
https://stackoverflow.com/questions/75990745/remove-timezone-from-timestamp-but-keep-the-local-time
I have a dataframe with epoch time. I convert the epoch time to a timestamp with my local timezone. I would like to remove the timezone information but keep my local timezone in the timestamp (subtract the timezone offset from the timestamp and then remove the timezone). This is the code I have: epochs = np.arange(1644...
Essentially you're trying to get whatever time it was locally after x seconds since the unix epoch in a tz-naive timestamp. Achieving this is a bit weird because: My experience with tz-naive timestamps in pandas says that they are usually "local" to the user's current timezone. Converting to timestamp from an epoch ti...
4
1
75,987,470
2023-4-11
https://stackoverflow.com/questions/75987470/remove-borders-of-a-n-dimensional-numpy-array
I am trying to replace all the values of the border of my n-dimensional array by False. So far, I have seen that numpy provides np.pad that allows me to grow an array in all dimensions with an arbitrary array. Is there an equivalent to do the opposite and "shrink" the array by cutting the borders? Here is an example in...
I would not use the approach of first cropping then padding, because like this you move a lot of memory around. Instead I would explicitly set the border indexes to the desired value: import numpy as np border_value = False nd_array = np.random.randn(100,100) > 0 # Iterate over all dimensions of `nd_array` for dim in r...
3
4
75,934,851
2023-4-5
https://stackoverflow.com/questions/75934851/how-to-make-sure-list-defined-in-class-variable-objects-are-not-shared-across-di
I have the following: class Loop: def __init__(self, group_class: Type[SegmentGroup], start: str, end: str): self.group_class = group_class self.start = start self.end = end self._groups: List[SegmentGroup] = [] def from_segments(self, segments): self._groups = [] # have to clear so this is not shared among other `Arti...
How to make sure list defined in class variable objects are not shared across different instances? TL;DR: make so that your class variables instances use the descriptor mechanisms in Python (like the __get__ method), so that it has control on which instance it is operating at each time. You can make your Loop class ...
3
1
75,989,725
2023-4-11
https://stackoverflow.com/questions/75989725/i-cant-install-tiktoken-on-python-with-pip
I am trying to run some python code which includes some tiktoken calls. I've tried to install tiktoken for python but i can't. I am trying to install with pip command but i am getting an error about rust. I am wondering if i should install some rust "thing" outside of python or pip. Collecting tiktoken Using cached tik...
Pip is trying to build the tiktoken library from source and you are missing the Rust compiler. You can either install the Rust compiler on your system, or install tiktoken from a wheel instead of building it from source. See this issue in the tiktoken GitHub repo for more help
4
2
75,975,807
2023-4-10
https://stackoverflow.com/questions/75975807/how-to-stop-a-loop-on-shutdown-in-fastapi
I have a route / which started an endless loop (technically until the websocket is disconnected but in this simplified example it is truly endless). How do I stop this loop on shutdown: from fastapi import FastAPI import asyncio app = FastAPI() running = True @app.on_event("shutdown") def shutdown_event(): global runni...
import signal import asyncio from fastapi import FastAPI app = FastAPI() running = True def stop_server(*args): global running running = False @app.on_event("startup") def startup_event(): signal.signal(signal.SIGINT, stop_server) @app.get("/") async def index(): while running: await asyncio.sleep(0.1) Source: https:/...
8
2
75,987,725
2023-4-11
https://stackoverflow.com/questions/75987725/using-webdav-to-list-files-on-nextcloud-server-results-in-method-not-supported
I'm trying to list files using webdab but I'm having issues. I can create directories and put files just fine but not list a directory or pull a file. I'm seeing the error, "Method not supported". from webdav3.client import Client options = { 'webdav_hostname': "https://___________.com/remote.php/dav/files/", 'webdav_l...
The client.list() method assumes the remote root directory by default. As you supply https://___________.com/remote.php/dav/files/ as your webdav_hostname the root directory it tries to access when you call client.list('/') is the top level files directory. As a Nextcloud user you don't have access to that level, so li...
4
2
75,968,081
2023-4-8
https://stackoverflow.com/questions/75968081/i-cant-install-anaconda-on-a-macbook-pro-m1-with-ventura-13-3-1
this is my first question here :) When i try to install Anaconda on my MacBook (M1) with Ventura 13.3.1 i receive the following error: "This package is incompatible with this version of macOS." I tried the arm64 installer and the x86 installer, both lead to the same error message. I used Anaconda on the same MacBook ju...
if you have homebrew installed you should be able to run "brew install anaconda"
4
5
75,980,399
2023-4-10
https://stackoverflow.com/questions/75980399/python-linear-getitem-for-a-pair-of-list-of-lists
I currently have a class which stores a list of lists. The inner lists are not of the same length. I made the class subscriptable with the following code (possibly not the best way of doing this, and perhaps overly fancy). class MyClass: def __init__(self): # self.instructions = [] # for demo purposes self.instructions...
While your implementation is nice, I would like to share my own way for iterating using chain.from_iterable. Because basically we're chaining the items whether from the beginning or at the end. For one list: The only part that needs explanation is map(reversed, reversed(self.instructions)). We not only need to reverse ...
4
2
75,983,861
2023-4-11
https://stackoverflow.com/questions/75983861/scrapy-crawl-only-first-5-pages-of-the-site
I am working on the solution to the following problem, My boss wants from me to create a CrawlSpider in Scrapy to scrape the article details like title, description and paginate only the first 5 pages. I created a CrawlSpider but it is paginating from all the pages, How can I restrict the CrawlSpider to paginate only t...
Solution 1: use process_request. from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor def limit_requests(request, response): # here we have the page number. # page_number = request.url[-1] # if int(page_number) >= 6: # return None # here we use a counter if not hasattr(limit_requ...
4
2
75,983,653
2023-4-11
https://stackoverflow.com/questions/75983653/how-to-save-a-yolov8-model-after-some-training-on-a-custom-dataset-to-continue-t
I'm training YOLOv8 in Colab on a custom dataset. How can I save the model after some epochs and continue the training later. I did the first epoch like this: import torch model = YOLO("yolov8x.pt") model.train(data="/image_datasets/Website_Screenshots.v1-raw.yolov8/data.yaml", epochs=1) While looking for the options ...
"I am currently working on a project using YOLOv8. After training on a custom dataset, the best weight is automatically stored in the runs/detect/train/weights directory as best.pt. When I retrain the model, I use the best.pt weight instead of yolov8x.pt to train the model."
4
6
75,954,655
2023-4-7
https://stackoverflow.com/questions/75954655/sequential-chaining-of-itertools-operators
I'm looking for a nice way to sequentially combine two itertools operators. As an example, suppose we want to select numbers from a generator sequence greater than a threshold, after having gotten past that threshold. For a threshold of 12000, these would correspond to it.takewhile(lambda x: x<12000) and it.takewhile(l...
One approach to writing a one-liner for the problem with the existing itertools library would be to use a flag variable with {0} as a default value to indicate which predicate to use. At first the flag evaluates to a truthy value so that the first predicate (x < 12000) is made effective, and if the first predicate fail...
4
3
75,981,635
2023-4-11
https://stackoverflow.com/questions/75981635/tkinter-zoom-with-text-and-other-elements-in-canvas
I'm trying to add support for zooming in and out inside a Canvas widget, containing both text element (created using create_text) and non-text elements, such as rectangles (created with create_rectangle), etc. So far, I made the following MRE using both part of this answer and this one: import tkinter as tk from tkinte...
That's because the zoom factor for the coordinates of the canvas items and the zoom factor for the font size are different in your implementation. Keep in mind the XSCALE and YSCALE parameters of the scale command of the canvas accumulate for repeated calls. Because the original coordinates of the items are transformed...
3
2
75,946,511
2023-4-6
https://stackoverflow.com/questions/75946511/creating-simple-video-player-using-pyqt6
I was trying to create a simple video player using PyQt6. I found this example on the internet: import sys from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QSlider from PyQt6.QtMultimedia import QMediaPlayer, QMediaContent from PyQt6.QtMultimediaWidgets import QVideoWidget from ...
PyQt5: QMediaPlayer(parent=None, flags=QMediaPlayer.Flags()) QMediaPlayer.media # property of type QMediaContent QMediaPlayer.setMedia(media, stream=None) PyQt6: The QMediaPlayer.Flags enum was removed, the QMediaContent class was removed, and the media property was replaced with source. QMediaPlayer(parent=None) QMed...
5
7
75,969,107
2023-4-9
https://stackoverflow.com/questions/75969107/multiaxis-system-of-equations-optimizations-in-python
My System is as follows: Optimize the value of O_t based on each value of L_t from 1 to 240 according to the below equations. O_t = O1+O2+O3+O4 O1= LS1+3×D O2=3×LS2+4×S O3=S+3×D O4= LS4×4+7×D L_t = LS1+LS2+LS3+LS4+LS5+LS6 L_t = (S+D)/5 Desired outputs: Values of S, D, LS1, LS2, LS3, LS4, LS5, LS6 that result in the hi...
Do not brute-force this problem. This is a classic (and somewhat easy) linear programming problem. Your written constraints fail to mention that L, S and D have a lower bound of 0, and S and D have an upper bound of 5Lt. If these constraints are not enforced then the problem is unbounded. You have not specified the upp...
3
3
75,975,064
2023-4-10
https://stackoverflow.com/questions/75975064/xml2js-is-vulnerable-to-prototype-pollution
xml2js <=0.4.23 Severity: high xml2js is vulnerable to prototype pollution - https://github.com/advisories/GHSA-776f-qx25-q3cc No fix available node_modules/xml2js aws-sdk * Depends on vulnerable versions of xml2js node_modules/aws-sdk 2 high severity vulnerabilities Upgraded aws-sdk npm package to latest version. But ...
delete your package-lock.json, add this to your package.json: "overrides": { "xml2js": "^0.5.0" } reinstall the deps : npm i
8
16
75,963,236
2023-4-8
https://stackoverflow.com/questions/75963236/why-cant-i-set-trainingarguments-device-in-huggingface
Question When I try to set the .device attribute to torch.device('cpu'), I get an error. How am I supposed to set device then? Python Code from transformers import TrainingArguments from transformers import Trainer import torch training_args = TrainingArguments( output_dir="./some_local_dir", overwrite_output_dir=True,...
From the docs of the TrainingArguments object doesn't have a settable device attribute. But interestingly device is initialized but non mutable: import torch from transformers import TrainingArguments args = TrainingArguments('./') args.device # [out]: device(type='cpu') args.device = torch.device(type='cpu') [out]: -...
4
0
75,965,051
2023-4-8
https://stackoverflow.com/questions/75965051/how-to-specify-constant-inputs-for-gradio-click-handler
If I have the following code: submit = gr.Button(...) submit.click( fn=my_func, inputs=[ some_slider_1, # gr.Slider some_slider_2, # gr.Slider some_slider_3, # gr.Slider ], outputs=[ some_text_field ] ) How can I substitute let's say some_slider_2 for a constant value like 2? If I simply write 2 in there, I get an err...
If you want a constant number input which is not visible on the UI you can pass gr.Number(value=2, visible=False)
3
3
75,943,880
2023-4-5
https://stackoverflow.com/questions/75943880/what-is-the-most-efficient-way-to-identify-text-similarity-between-items-in-larg
The following piece of code achieves the results I'm trying to achieve. There is a list of strings called 'lemmas' that contains the accepted forms of a specific class of words. The other list, called 'forms' contains a lot of spelling variations of words found in a large amount of texts from different periods and diff...
The following solution is based on your original code (Hamming distance) which offers an (almost) order of magnitude speed-up (~89.41%), averaged across five runs of each, as measured by line-profiler. Using this solution as a base for parallel processing may get you closer to the total processing times you are after. ...
3
1
75,968,070
2023-4-8
https://stackoverflow.com/questions/75968070/how-do-i-fix-the-return-type-of-a-django-model-managers-method
I'm using Django 4.1.7 with django-stubs 1.16.0, and mypy 1.1.1. I have code that looks like this: class ProductQuerySet(QuerySet): ... class ProductManager(Manager): def create_red_product(self, **kwargs) -> "Product": return self.model(color=Product.Color.RED, **kwargs) _product_manager = ProductManager.from_queryset...
I can't reproduce one to one your case, but please try to specify what exactly your manager is for by: class ProductManager(Manager["Product"]):
3
2
75,958,929
2023-4-7
https://stackoverflow.com/questions/75958929/image-with-hyperlink-in-borb-table
I am trying to create a pdf document that includes a table. For each row of the table, a transaction will be recorded, and I would like the 4th column to include a paperclip image (or emoji) with a hyperlink to a document stored online. I would also like the 6th column to include tag names with a specific background co...
disclaimer: I am the author of borb. import random import typing from _decimal import Decimal from borb.pdf import PDF, Document, Page, FlexibleColumnWidthTable, Table, Paragraph, Lipsum, HeterogeneousParagraph, \ ChunkOfText, HexColor, Color, PageLayout, SingleColumnLayout from borb.pdf.canvas.layout.annotation.remote...
3
1
75,943,441
2023-4-5
https://stackoverflow.com/questions/75943441/scrapy-playwright-scraper-does-not-return-page-or-playwright-page-in-respons
I am stuck in the scraper portion of my project, I continued troubleshooting errors and my latest approach is at least not crashing and burning. However, the response.meta I am getting for whatever reason is not returning a playwright page. Hardware/setup: intel-based MacBook pro running Monterey v12.6.4 python 3.11.2...
What you are shown in the browser is not always the same as what you might receive when using a headless browser. When in doubt it's a good idea to write the entire contents of the page to an html file and then inspect it either with a code editor or with your browser so you can see exactly what the page you are actual...
4
2
75,958,246
2023-4-7
https://stackoverflow.com/questions/75958246/how-to-check-if-a-dataclass-is-frozen
Is there a way to check if a Python dataclass has been set to frozen? If not, would it be valuable to have a method like is_frozen in the dataclasses module to perform this check? e.g. from dataclasses import dataclass, is_frozen @dataclass(frozen=True) class Person: name: str age: int person = Person('Alice', 25) if n...
Yes looks like you can retrieve parameters' information from __dataclass_params__. It returns an instance of _DataclassParams type which is nothing but an object for holding the values of init, repr, eq, order, unsafe_hash, frozen attributes: from dataclasses import dataclass @dataclass(frozen=True) class Person: name:...
6
6
75,958,222
2023-4-7
https://stackoverflow.com/questions/75958222/can-i-return-400-error-instead-of-422-error
I validate data using Pydantic schema in my FastAPI project and if it is not ok it returns 422. Can I change it to 400?
Yes, you can. For example, you can apply the next exception handler: from fastapi import FastAPI, Request, status from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(RequestValidationError) async def validation_exception_handler(request...
3
5
75,951,019
2023-4-6
https://stackoverflow.com/questions/75951019/unable-to-install-mysqlclient-package-on-ec2-instance
I am trying to install mysqlclient Python package on an Amazon EC2 instance running Amazon Linux 2023 AMI. When I run pip install mysqlclient, I get the following error message: Collecting mysqlclient==2.1.0 Downloading mysqlclient-2.1.0.tar.gz (87 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 87.6/87.6 kB 17.2 MB/s eta...
On fresh Amazon Linux 2023 you have to do: # install pip (AL 2023 does not have one by default) sudo dnf install -y pip # install dependencies sudo dnf install -y mariadb105-devel gcc python3-devel # install mysqlclient pip install mysqlclient
3
15
75,953,146
2023-4-6
https://stackoverflow.com/questions/75953146/unable-to-use-show-and-unable-to-perform-further-operations-on-a-spark-datafr
I was trying to use an UDF in spark. After applying the udf to a column, df.show() was not working neither I was able to apply any further operation on that dataframe. So, I ran the code which is given in the documentation here and got the same error The code was: from pyspark.sql.types import IntegerType slen = udf(la...
It's caused by the connection between PySpark and Python. You can either set the environment variable PYSPARK_DRIVER_PYTHON and PYSPARK_PYTHON to your python or spark.pyspark.driver and spark.pyspark.python when you use spark-submit commit.
5
2
75,955,276
2023-4-7
https://stackoverflow.com/questions/75955276/pyspark-json-to-pyspark-dataframe
I want to transform this json to a pyspark dataframe I have added my current code. json = { "key1": 0.75, "values":[ { "id": 2313, "val1": 350, "val2": 6000 }, { "id": 2477, "val1": 340, "val2": 6500 } ] } my code: I can get the expected output using my code. Hope someone improve this. import json from pyspark.sql imp...
You can try the spark inline function. df = df.selectExpr("key1", "inline(values)")
5
4
75,954,148
2023-4-6
https://stackoverflow.com/questions/75954148/tricky-conversion-of-field-names-to-values-while-performing-row-by-row-de-aggreg
I have a dataset where I would like to convert specific field names to values while performing a de aggregation the values into their own unique rows as well as perform a long pivot. Data Start Date End Area Final Type Middle Stat Low Stat High Stat Middle Stat1 Low Stat1 High Stat1 8/1/2013 9/1/2013 10/1/2013 NY 3/1/2...
One option is with pivot_longer from pyjanitor - in this case we use the special placeholder .value to identify the parts of the column that we want to remain as headers, while the rest get collated into a new column : # pip install pyjanitor import pandas as pd import janitor (df .pivot_longer( index = slice('Start', ...
4
1
75,954,211
2023-4-6
https://stackoverflow.com/questions/75954211/valueerror-source-code-string-cannot-contain-null-bytes
I'm originally an Ubuntu user, but I have to use a Windows Virtual Machine for some reason. I was trying to pip-install a package using the CMD, however, I'm getting the following error: from pip._vendor.packaging.utils import canonicalize_name ValueError: source code string cannot contain null bytes I used pip instal...
The error that occurred was while using "Python 3.10.11 (64-bit)". Though I reinstalled it the issue continued. When I downgraded to "Python 3.9.0 (64-bit)", the issue was solved.
3
2
75,953,279
2023-4-6
https://stackoverflow.com/questions/75953279/modulenotfounderror-no-module-named-pandas-core-indexes-numeric-using-metaflo
I used Metaflow to load a Dataframe. It was successfully unpickled from the artifact store, but when I try to view its index using df.index, I get an error that says ModuleNotFoundError: No module named 'pandas.core.indexes.numeric'. Why? I've looked at other answers with similar error messages here and here, which say...
This issue is caused by the new Pandas 2.0.0 release breaking backwards compatibility with Pandas 1.x, although I don't see this documented in the release notes. The solution is to downgrade pandas to the 1.x series: pip install "pandas<2.0.0"
39
46
75,945,689
2023-4-6
https://stackoverflow.com/questions/75945689/python-efficient-calculation-where-end-value-of-one-row-is-the-start-value-of
I would like to make simple calculations on a rolling basis, but have heavy performance issues when I try to solve this with a nested for-loop. I need to perform this kind of operations on very large data, but have to use standard Python (incl. Pandas). The values are floats and can be negative, zero or positive. I hav...
You can create helper Series for subtract plus and minus columns, create cumulative sums per groups by both columns and add first value of start for final end column, then for start column use DataFrameGroupBy.shift with replace first value by original values in Series.fillna: plusminus = df1['plus'].sub(df1['minus']) ...
4
2
75,945,832
2023-4-6
https://stackoverflow.com/questions/75945832/what-is-the-output-type-of-subprocess-communicate
I was going through official documentation of Popen.communicate(). p = subprocess.Popen('echo hello',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,universal_newlines=True) r,e = p.communicate() I want to know at which case it will return string output and which case it will return in bytes.(with example wou...
It depends on the text mode used as per the docs If encoding or errors are specified, or text (also known as universal_newlines) is true, the file objects stdin, stdout and stderr will be opened in text mode using the encoding and errors specified in the call or the defaults for io.TextIOWrapper... If text mode is not...
5
3
75,945,804
2023-4-6
https://stackoverflow.com/questions/75945804/tricky-long-pivot-by-reverse-aggregation-transformation-pandas
I have a dataset where I would like to de aggregate the values into their own unique rows as well as perform a pivot, grouping by category. Data updated Period Date Area BB stat AA stat CC stat DD stat BB test AA test CC test DD test BB re AA re CC re BB test2 AA test2 CC test2 DD test2 8/1/2016 9/1/2016 NY 5 5 5 1 1 1...
Try pd.wide_to_long: pd.wide_to_long(df, stubnames=['AA', 'BB','CC','DD'], i=['Period','Date','Area'], j='', sep=' ', suffix='(test|re|stat)' ).unstack(level=-1, fill_value=0).stack(level=0).reset_index() Output: Period Date Area type re stat test 0 8/1/2016 9/1/2016 CA AA 0.0 2.0 4.0 1 8/1/2016 9/1/2016 CA BB 0.0 2....
6
4
75,936,937
2023-4-5
https://stackoverflow.com/questions/75936937/python3-update-date-format
I have a tricky with date format with time series data. In my dataframe of over one hundred thousand rows I have a column datetime with date value but the format is %M:%S.%f. Example: datetime 0 59:57.7 1 00:09.7 2 00:21.8 What I want in output is to convert this format to %m/%d/%Y %H:%M:%S.%f with 01/01/2023 00:59:57...
The exact logic is unclear assuming a cumulated time You can convert to_timedelta (after adding the missing hours '00:'), then get the cumsum and add the reference date: df['ProcessTime'] = (pd.to_timedelta('00:'+df['datetime']).cumsum() .add(pd.Timestamp('2023-01-01 00:59:57.7')) .dt.strftime('%m/%d/%Y %H:%M:%S.%f') )...
3
2
75,935,256
2023-4-5
https://stackoverflow.com/questions/75935256/how-to-efficiently-apply-a-function-to-every-row-in-a-dataframe
Given the following table: df = pd.DataFrame({'code':['100M','60M10N40M','5S99M','1S25I100M','1D1S1I200M']}) that looks like this: code 0 100M 1 60M10N40M 2 5S99M 3 1S25I100M 4 1D1S1I200M I'd like to convert the code column strings to numbers where M, N, D are each equivalent to (times 1), I is equivalent to (times ...
Since pandas string methods are not optimized (although that seems to no longer be true for pandas 2.0), if you're after performance, it's better to use Python string methods in a loop (which are compiled in C). It seems a straightforward loop over each string might give the best performance. def evaluater(s): total, c...
3
2
75,935,363
2023-4-5
https://stackoverflow.com/questions/75935363/adding-a-column-based-on-condition-in-polars
Let's say I have a Polars dataframe like so: df = pl.DataFrame({ 'a': [0.3, 0.7, 0.5, 0.1, 0.9] }) And now I need to add a new column where 1 or 0 is assigned depending on whether a value in column 'a' is greater or less than some threshold. In Pandas I can do this: import numpy as np THRESHOLD = 0.5 df['new'] = np.wh...
The select([0, 1]) doesn't really make a lot of sense Polars-wise, you're just selecting a literal. Not quite sure why that's throwing a DuplicateError as is. Conditionals in polars are best done with when: df.with_columns(pl.when(pl.col("a") > 0.5).then(0).otherwise(1).alias("b"))
4
7
75,935,293
2023-4-5
https://stackoverflow.com/questions/75935293/pynecone-cannot-get-detail-information-from-item-in-the-cards-example-grid-fo
This is our expected output. And this is the current output. And this is the source code for the current output. import pynecone as pc def show_items(item): return pc.box( pc.text(item), bg="lightgreen" ) class ExampleState(pc.State): my_objects = [["item1", "desc1"], ["item2", "desc2"]] print(my_objects) def home():...
The key point is that the pc.foreach cannot use something like list[list] or list[dict]. The following code can answer our question. It run well and fit the expected output. After testing, It runs well on pynecone==0.1.20 and pynecone==0.1.21 import pynecone as pc class MyObject(pc.Model, table=True): title:str desc:st...
3
2
75,898,276
2023-3-31
https://stackoverflow.com/questions/75898276/openai-api-error-429-you-exceeded-your-current-quota-please-check-your-plan-a
I'm making a Python script to use OpenAI via its API. However, I'm getting this error: openai.error.RateLimitError: You exceeded your current quota, please check your plan and billing details My script is the following: #!/usr/bin/env python3.8 # -*- coding: utf-8 -*- import openai openai.api_key = "<My PAI Key>" com...
TL;DR: You need to upgrade to a paid plan. Set up a paid account, add a credit or debit card, and generate a new API key if your old one was generated before the upgrade. It might take 10 minutes or so after you upgrade to a paid plan before the paid account becomes active and the error disappears. Problem As stated in...
169
209
75,918,895
2023-4-3
https://stackoverflow.com/questions/75918895/is-there-a-way-to-implement-pandas-wide-to-long-in-polars
I use Pandas wide to long to stack survey data and it works beautifully with regex and stub names, is this possible to do in Polars ? e.g. in Pandas - import pandas as pd df = pd.DataFrame({ 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], 'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1]...
If we start with .unpivot() df.unpivot(index = ["famid", "birth"], variable_name = "age").head(1) shape: (1, 4) ┌───────┬───────┬────────┬───────┐ │ famid ┆ birth ┆ age ┆ value │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str ┆ f64 │ ╞═══════╪═══════╪════════╪═══════╡ │ 1 ┆ 1 ┆ ht_one ┆ 2.8 │ └───────┴───────┴────────┴──...
4
4
75,895,460
2023-3-31
https://stackoverflow.com/questions/75895460/the-error-was-re-error-global-flags-not-at-the-start-of-the-expression-at-posi
Can someone please assist how to fix this issue, why i am getting this error while running the Ansible playbook 2023-03-31 11:47:39,902 p=57332 u=NI40153964 n=ansible | An exception occurred during task execution. To see the full traceback, use -vvv. The error was: re.error: global flags not at the start of the expres...
The error message is saying you need to put the (?s) at the very beginning of the regex. Alternatively, try something like log_output: "{{log_data| regex_search('(?s:(?<=This task is to install package in target servers)(.*?)(?=This task is to enable kafka consumers and send mail of playbook log))" In some more detai...
6
8
75,900,239
2023-3-31
https://stackoverflow.com/questions/75900239/attributeerror-occurs-with-tikzplotlib-when-legend-is-plotted
I am trying to save a figure using tikzplotlib. However, I am encountering an AttributeError: 'Legend' object has no attribute '_ncol'. I am currently using tikzplotlib version 0.10.1 and matplotlib version 3.7.0. Without using "plt.legend()" everything works. Below is an example that is not working: import numpy as np...
Hey I have/had the same problem, the problem is that with matplotlib 3.6 the interface changed. There is already a fix (#558) for tikzplotlib on GitHub, but it looks like nothing will happen for now. However, there is a workaround for the issue on GitHub (Issue). It works quite well. I hope that this answer will soon b...
8
15
75,925,323
2023-4-4
https://stackoverflow.com/questions/75925323/how-can-i-fix-importlib-on-python3-10-so-that-it-can-call-entry-points-properl
I am using Python 3.10 on Ubuntu 22.04 working on a project that uses Farama Foundation's gymnasium library. When gymnasium is imported, it uses importlib to get entry points, but when I ran import gymnasium into IDLE I got the following error: Traceback (most recent call last): File "/usr/lib/python3.10/idlelib/run.py...
Try this: >>> import importlib_metadata as md >>> dists = md.distributions() >>> broken = [dist for dist in dists if dist.name is None] >>> for dist in broken: ... print(dist._path) It will list the paths of distributions that are the problem. Reinstalling or deleting them will stop the error. This guy had the same pr...
3
2
75,899,158
2023-3-31
https://stackoverflow.com/questions/75899158/shap-summary-plots-for-xgboost-with-categorical-data-inputs
XGBoost supports inputting features as categories directly, which is very useful when there are a lot of categorical variables. This doesn't seem to be compatible with Shap: import pandas as pd import xgboost import shap # Test data test_data = pd.DataFrame({'target':[23,42,58,29,28], 'feature_1' : [38, 83, 38, 28, 57]...
Unfortunately, generating shap values with xgboost using categorical variables is an open issue. See, f.e., https://github.com/slundberg/shap/issues/2662 Given your specific example, I made it run using Dmatrix as input of shap (Dmatrix is the basic data type input of xgboost models, see the Learning API. The sklearn a...
5
2
75,929,721
2023-4-4
https://stackoverflow.com/questions/75929721/how-to-show-full-column-width-of-polars-dataframe-in-python
I'm trying to display the full width of column in polars dataframe. Given the following polars dataframe: import polars as pl df = pl.DataFrame({ 'column_1': ['TF-IDF embeddings are done on the initial corpus, with no additional N-Gram representations or further preprocessing', 'In the eager API, the expression is eval...
I think you can use glimpse: > df.glimpse() Rows: 2 Columns: 2 $ column_1 <str> TF-IDF embeddings are done on the initial corpus, with no additional N-Gram representations or further preprocessing, In the eager API, the expression is evaluated immediately. The eager API produces results immediately after execution, sim...
8
10
75,930,508
2023-4-4
https://stackoverflow.com/questions/75930508/most-efficent-way-to-bulk-update-documents-using-mongoengine
So, I have a Collection of documents (e.g. Person) structured in this way: class Person(Document): name = StringField(max_length=200, required=True) nationality = StringField(max_length=200, required=True) earning = ListField(IntField()) when I save the document I only input the name and nationality fields because thi...
Using method from Mongoengine bulk update without objects.update(): from pymongo import UpdateOne from mongoengine import Document, ValidationError class Person(Document): name = StringField(max_length=200, required=True) nationality = StringField(max_length=200, required=True) earning = ListField(IntField()) japanese_...
3
3
75,933,975
2023-4-4
https://stackoverflow.com/questions/75933975/how-to-split-a-dataframe-column-into-more-columns-conditional-to-another-column
I am stuck because I can not split a dataframe column into more columns, conditional to another column value. I have a pandas dataframe which I generated straight from a '.csv' file with more than 100K rows. Excerpt1: I want to split column dca by ',' (comma) into more columns. The number of splits will be constrained...
Update They can have 0 to 11 elements and the split operation should filter only the 'n' first elements from left to right, where 'n' = row['n_mppts'] Since dca has variable length, you can use this code: # Part 0: fix special cases mask = df['dca'].isna() df.loc[mask, 'dca'] = df.loc[mask, 'dca'].apply(lambda x: [])...
3
1
75,925,524
2023-4-4
https://stackoverflow.com/questions/75925524/accessing-the-chrome-pages-inside-python-without-selenium
There's the requests and urllib page that can access http(s) protocol pages in Python, e.g. import requests requests.get('stackoverflow.com') but when it comes to chrome:// pages, e.g. chrome://settings/help, the url libraries won't work and this: import requests requests.get('chrome://settings/help') throws the erro...
You can use Pyppeteer as Selenium's alternative for accessing the chrome:// pages pip install pyppeteer asyncio Example for Windows OS: from pyppeteer import launch import time import asyncio import nest_asyncio nest_asyncio.apply() async def main(): browser = await launch({ "headless": False, "executablePath": "C:/Pr...
3
1
75,891,072
2023-3-30
https://stackoverflow.com/questions/75891072/valueerror-unable-to-infer-channel-dimension-format
When training model with transformers, the following error occurs and I do not know how to resolve it (my input is torch.Size([1, 3, 224, 224])) : --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /tmp/ipykernel_23/2337200543.py in 11 ) 12 # begin ...
I was using .png dataset for this training, once I converted to .jpg, all went well!
5
4
75,925,357
2023-4-4
https://stackoverflow.com/questions/75925357/plotly-hexbin-cutoff-within-specified-json-boundary
I'm plotting a separate hexbin figure and json boundary file. The hexbin grid overlaps the boundary file though. I'm interested in displaying the African continent only. I'm aiming to cut-off or subset the hexbin grid within the African continent. So no grid square should be visualised outside the boundary file. Is the...
If you look inside fig.data[0], it's a Choroplethmapbox with several fields including customdata and geojson. The geojson contains all of the information that plotly needs to draw the hexbins, including the coordinates and unique id for each hexagon. The customdata is an array of shape [n_hexbins x 3] where each elemen...
5
5
75,921,380
2023-4-3
https://stackoverflow.com/questions/75921380/python-segmentation-fault-in-interactive-mode
The python is installed with conda: (base) [kangl@login05]~% which python ~/miniconda3/bin/python When directly run python in iteractive mode, a segmentation fault will apear: (base) [kangl@login05]~% python Python 3.10.10 | packaged by conda-forge | (main, Mar 24 2023, 20:08:06) [GCC 11.3.0] on linux Type "help", "co...
After encountering similar errors, I have found that the following lines of code solve the segmentation fault: export LANGUAGE=UTF-8 export LC_ALL=en_US.UTF-8 export LANG=UTF-8 export LC_CTYPE=en_US.UTF-8 export LANG=en_US.UTF-8 export LC_COLLATE=$LANG export LC_CTYPE=$LANG export LC_MESSAGES=$LANG export LC_MONETARY=$...
4
6
75,915,809
2023-4-3
https://stackoverflow.com/questions/75915809/accuracy-value-more-than-1-with-nn-bcewithlogitsloss-loss-function-pytorch-in
I am trying to use nn.BCEWithLogitsLoss() for model which initially used nn.CrossEntropyLoss(). However, after doing some changes to the training function to accommodate the nn.BCEWithLogitsLoss() loss function the model accuracy values are shown as more than 1. Please find the code below. # Data augmentation and norma...
I didn't understand why you are using torch.max as you have one output. Anyway, you should use squeeze before comparing, so this line: running_corrects += torch.sum(preds == labels.data) should become running_corrects += torch.sum(preds == labels.squeeze()) to see why: labels = torch.tensor([[0], [0], [0], [1]]) pre...
4
3
75,920,755
2023-4-3
https://stackoverflow.com/questions/75920755/why-does-the-parameter-disabledwidth-of-a-tkinter-canvas-rectangle-not-work
I want the outline of a rectangle in a canvas to get a bigger width, when the rectangle is in state "disabled". Therefore I use the parameter "disabledwidth=4". But when the rectangle is in state "disabled", the outline has still a width of 1 instead of 4. This is my code, which shows the problem: When I move the mouse...
This is due to a very old but simple bug in Tcl/Tk which causes -disabledwidth to not be parsed properly for rectangle and oval canvas items, causing it to be silently ignored (at least in some cases). I reported it to Tcl/Tk along with the fix: https://core.tcl-lang.org/tk/info/f4d9d74df628 So hopefully this will be f...
6
0
75,907,716
2023-4-1
https://stackoverflow.com/questions/75907716/add-column-with-current-date-and-time-to-polars-dataframe
How can I add a column to a Polars DataFrame with current date and time as value on every row? With Pandas, I would do something like this: df["date"] = pd.Timestamp.today()
EDIT: Better answer from @jqurious: df.with_columns(date = datetime.now()) My original solution: Use pl.lit() and Python's datetime to create a literal of the current date: from datetime import datetime import polars as pl df = pl.DataFrame( ... ) df.with_columns(pl.lit(datetime.now()).dt.datetime().alias("date"))
5
7
75,931,752
2023-4-4
https://stackoverflow.com/questions/75931752/how-to-add-an-empty-facet-to-a-relplot-or-facetgrid
I have a relplot with columns split on one variable. I'd like to add one additional column with no subplot or subpanel. To give a clear example, suppose I have the following plot: import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns x = np.random.random(10000) t = np.random.randi...
Add a value not observed in the data to col_order, e.g. g = sns.relplot(df, x='x', y='y', col='t', col_order=[0, 1, 2, ""]) g.axes.flat[-1].set_title("")
4
7
75,893,753
2023-3-30
https://stackoverflow.com/questions/75893753/how-to-write-decorator-without-syntactic-sugar-in-python
This question is rather specific, and I believe there are many similar questions but not exactly like this. I am trying to understand syntactic sugar. My understanding of it is that by definition the code always can be written in a more verbose form, but the sugar exists to make it easier for humans to handle. So there...
def func(arg1, arg2, ...): pass func = dec2(dec1(func)) In the example [...] there is an intermediate assignment. But how does the syntactic sugar work without the intermediate assignment? Actually, the "non syntactic sugar" version, as you call it, is not exactly the same as using the decorator syntax, with an @dec...
4
3