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
74,433,918
2022-11-14
https://stackoverflow.com/questions/74433918/apply-a-function-to-2-columns-in-polars
I want to apply a custom function which takes 2 columns and outputs a value based on those (row-based) In Pandas there is a syntax to apply a function based on values in multiple columns df['col_3'] = df.apply(lambda x: func(x.col_1, x.col_2), axis=1) What is the syntax for this in Polars?
In polars, you don't add columns by assigning just the value of the new column. You always have to assign the whole df (in other words there's never ['col_3'] on the left side of the =) To that end if you want your original df with a new column then you use the with_columns method. you would do df = ( df .with_columns(...
9
24
74,450,537
2022-11-15
https://stackoverflow.com/questions/74450537/how-to-efficiently-create-an-index-like-polars-dataframe-from-multiple-sparse-se
I would like to create a DataFrame that has an "index" (integer) from a number of (sparse) Series, where the index (or primary key) is NOT necessarily consecutive integers. Each Series is like a vector of (index, value) tuple or {index: value} mapping. (1) A small example In Pandas, this is very easy as we can create a...
Following your example, but only informing polars on the fact that the "index" column is sorted (polars will use fast paths if data is sorted). You can use align_frames together with functools.reduce to get what you want. This is your data creation snippet: import functools import polars as pl N, C = 300000, 20 pls = [...
6
5
74,372,173
2022-11-9
https://stackoverflow.com/questions/74372173/how-to-multiply-each-element-in-a-list-with-a-value-in-a-different-column
I have a dataframe with a certain number of groups, containing a weight column and a list of values, which can be of arbitrary length, so for example: df = pl.DataFrame( { "Group": ["Group1", "Group2", "Group3"], "Weight": [100.0, 200.0, 300.0], "Vals": [[0.5, 0.5, 0.8],[0.5, 0.5, 0.8], [0.7, 0.9]] } ) ┌────────┬─────...
EDIT - Polars update: As of the latest version of Polars, this is now a the correct syntax: df = pl.DataFrame( { "Group": ["Group1", "Group2", "Group3"], "Weight": [100.0, 200.0, 300.0], "Vals": [[0.5, 0.5, 0.8],[0.5, 0.5, 0.8], [0.7, 0.9]] } ) (df .explode('Vals') .with_columns(Weighted = pl.col('Weight')*pl.col('Vals...
6
3
74,429,898
2022-11-14
https://stackoverflow.com/questions/74429898/insert-or-update-upsert-multiple-objects-using-orm-session
I'm trying to upsert using SQLAlchemy. There's no upsert in SQL but SQLAlchemy provides this. The same thing I'm trying to perform with SQLAlchemy ORM session. My code: from sqlalchemy.orm import sessionmaker Session = sessionmaker(engine) with Session() as session: """Here upsert functionality""" session.insert_or_upd...
As you have noted, Session.merge() will accomplish the task on an object-by-object basis. For example, if we have class Thing(Base): __tablename__ = "thing" id: Mapped[int] = mapped_column(primary_key=True, autoincrement=False) txt: Mapped[str] = mapped_column(String(50)) my_thing = Thing(id=1, txt="foo") we can do wi...
5
0
74,392,324
2022-11-10
https://stackoverflow.com/questions/74392324/poetry-install-throws-winerror-1312-when-running-over-ssh-on-windows-10
I have an SSH connection from a Windows machine to another, and then trying to do a poetry install. My problem is: I get this error when executing poetry install through ssh: [WinError 1312] A specified logon session does not exist. It may already have been terminated. This command works perfectly when I execute it lo...
Based on similarities in the stack traces and your description, my guess is that you're facing the same bug from #1892 and #1917, where Poetry tries to use your keyring to access/publish modules, and hence fails when these credentials are invalid. But it appears that poetry tries to access the keyring even for install...
9
9
74,369,065
2022-11-9
https://stackoverflow.com/questions/74369065/obtaining-the-image-iterations-before-final-image-has-been-generated-stablediffu
I am currently using the diffusers StableDiffusionPipeline (from hugging face) to generate AI images with a discord bot which I use with my friends. I was wondering if it was possible to get a preview of the image being generated before it is finished? For example, if an image takes 20 seconds to generate, since it is ...
You can use the callback argument of the stable diffusion pipeline to get the latent space representation of the image: link to documentation The implementation shows how the latents are converted back to an image. We just have to copy that code and decode the latents. Here is a small example that saves the generated i...
6
8
74,389,487
2022-11-10
https://stackoverflow.com/questions/74389487/caching-python-venv-folder-with-codebuild
I am trying to cache the Virtual environment folder (.venv) for my Python project with CodeBuild. Here's my buildspec.yml file: version: 0.2 env: shell: bash phases: install: commands: - python3 -m venv .venv && source .venv/bin/activate - pip3 install -r requirements.txt build: commands: - pytest -v tests/ cache: path...
CodeBuild uses symlinks to link cached directories and python -m venv tries to create a new directory over a symlink, which isn't possible. Try to run python3 -m venv command inside the .venv directory: install: commands: - cd .venv && python3 -m venv . && cd - - source .venv/bin/activate - pip3 install -r requirements...
4
1
74,422,209
2022-11-13
https://stackoverflow.com/questions/74422209/jupyterlab-failed-to-load-model-class-hboxmodel
I am using JupyterLab and trying to run tqdm. I've had an error persist for quite a while that seems to be a JS error. Extensions: Other labextensions (built into JupyterLab) app dir: /opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/share/jupyter/lab @jupyter-widgets/jupyterlab-manager v5...
I had the same issue when upgrading to jupyterlab==3.6.3. After upgrading ipywidgets to the at that time latest version 8.0.6, it still failed. I managed to fix the issue by downgrading then to ipywidgets==7.7.5.
5
3
74,446,830
2022-11-15
https://stackoverflow.com/questions/74446830/how-to-fix-403-forbidden-errors-with-python-requests-even-with-user-agent-head
I am sending a request to some URL. I copied the curl command to python. So, all the headers are included, but my request is not working and I receive status code 403 and error code 1020 in the HTML output. The code is import requests headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:106.0) Gecko/...
The site is protected by cloudflare which aims to block, among other things, unauthorized data scraping. From What is data scraping? The process of web scraping is fairly simple, though the implementation can be complex. Web scraping occurs in 3 steps: First the piece of code used to pull the information, which we c...
14
15
74,448,717
2022-11-15
https://stackoverflow.com/questions/74448717/dash-choosing-an-id-and-then-make-plot-with-multiple-sliders
I have a dataset which is similar to below one. Please note that there are multiple values for a single ID. import pandas as pd import numpy as np import random df = pd.DataFrame({'DATE_TIME':pd.date_range('2022-11-01', '2022-11-05 23:00:00',freq='20min'), 'SBP':[random.uniform(110, 160) for n in range(358)], 'DBP':[ra...
The solution below only requires vey minor modifications to your example code. It essentially filters the original dataframe twice (once for TIME_OF_DAY='Night', and once for TIME_OF_DAY='Morning') and concatenates them before plotting. I've also modified the bins in the to_day_period function to only produce two label...
4
1
74,447,766
2022-11-15
https://stackoverflow.com/questions/74447766/tkinter-use-characters-bytes-offset-as-index-for-text-widget
I want to delete part of a text widget's content, using only character offset (or bytes if possible). I know how to do it for lines, words, etc. Looked around a lot of documentations: https://www.tcl.tk/man/tcl8.6/TkCmd/text.html#M24 https://tkdocs.com/tutorial/text.html https://anzeljg.github.io/rin2/book2/2405/docs/...
Based on my own relentless testing and other answers here, I managed to get to a solution. import tkinter as tk from tkinter import messagebox # https://stackoverflow.com/a/29780454/12349101 root = tk.Tk() main_text = tk.Text(root) box_text = tk.Text(root, height=1, width=10) box_text.pack() txt = """hello world""" len...
8
1
74,425,218
2022-11-13
https://stackoverflow.com/questions/74425218/how-to-configure-mypy-to-ignore-a-stub-file-for-a-specific-module
I installed a "dnspython" package with "pip install dnspython" under Ubuntu 22.10 and made a following short script: #!/usr/bin/env python3 import dns.zone import dns.query zone = dns.zone.Zone("example.net") dns.query.inbound_xfr("10.0.0.1", zone) for (name, ttl, rdata) in zone.iterate_rdatas("SOA"): serial_nr = rdata...
I would recommend ignoring only the specific wrong line, not the whole module. dns.query.inbound_xfr("10.0.0.1", zone) # type: ignore[attr-defined] This will suppress attr-defined error message that is generated on that line. If you're going to take this approach, I'd also recommend running mypy with the --warn-unused...
4
5
74,400,966
2022-11-11
https://stackoverflow.com/questions/74400966/expand-wont-do-what-i-want-how-do-i-generate-a-custom-list-of-inputs-to-a-ru
I want to run a Snakemake workflow where the input is defined by a combination of different variables (e.g. pairs of samples, sample ID and Nanopore barcode,...): sample_1 = ["foo", "bar", "baz"] sample_2 = ["spam", "ham", "eggs"] I've got a rule using these: rule frobnicate: input: assembly = "{first_sample}_{second_...
Using expand with other combinatoric functions By default, expand uses the itertools function product. However, it's possible to specify another function for expand to use. To combine the first variable in the first with the first in the second and so on, one can tell expand to use zip: sample_1 = ["foo", "bar", "baz"...
4
4
74,412,482
2022-11-12
https://stackoverflow.com/questions/74412482/ibrk-tws-api-error-takes-4-positional-arguments-but-5-were-given
If I run a basic TWS example, I receive the error message . If I comment out the error() call back it runs fine. I've tried this on several examples and get the same result. Exception has occurred: TypeError error() takes 4 positional arguments but 5 were given File "/Users/jayurbain/Dropbox/twsapi/Algorithmic Trading...
The solution to the problem was to execute python setup install rather than using pip to install ibapi. Thanks for your answers.
5
-2
74,414,355
2022-11-12
https://stackoverflow.com/questions/74414355/equivalent-for-r-dplyrs-glimpse-function-in-python-for-panda-dataframes
I find the glimpse function very useful in R/dplyr. But as someone who is used to R and is working with Python now, I haven't found something as useful for Panda dataframes. In Python, I've tried things like .describe() and .info() and .head() but none of these give me the useful snapshot which R's glimpse() gives us. ...
Here is one way to do it: def glimpse(df): print(f"Rows: {df.shape[0]}") print(f"Columns: {df.shape[1]}") for col in df.columns: print(f"$ {col} <{df[col].dtype}> {df[col].head().values}") Then: import pandas as pd df = pd.DataFrame( {"column_one": ["A", "B", "C", "D"], "column_two": [1, 2, 3, 4]} ) glimpse(df) # Outp...
8
6
74,444,165
2022-11-15
https://stackoverflow.com/questions/74444165/multiple-objective-functions-with-binary-variables-google-or-tools
I have a set of U users and a set of S servers. I want to maximize the number of users allocated to a server while minimizing the number of servers used (this means that I have two objective functions). Each user has some requirements w and each server has a total capacity of C. The solver variables are the following: ...
there are usually 2 approaches: weighted sum: a * obj1 + b * obj2 lexicographic: optimize obj1, get optimal value, change objective to obj2, add constraint obj1 <= best_obj1_value (optional + slack). Then reoptimize. Bonus point when reusing the optimal solution with obj1 as a hint for the second solve.
4
6
74,449,223
2022-11-15
https://stackoverflow.com/questions/74449223/whats-the-diffrence-between-pandas-pd-to-pickle-and-pickle-module-pickle-dump
I would like to save python pandas DataFrame object as pickle. What's the diffrence in using pandas.to_pickle vs pickle.dumps? I've made some tests. Here's my test code : import pandas as pd import pickle df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'), index=['x', 'y']) # Save df.to_pickle('df1.pickle') with op...
After analyzing module code for pickle (python3.8) and pandas 1.5.0 here are my thoughts. Saving/dumping DataFrame to pickle Pickle code : Default using pickle protocol DEFAULT_PROTOCOL if not specified. DEFAULT_PROTOCOL(==4) is not the HIGHEST_PROTOCOL(==5). Pandas code : Default using pickle protocol HIGHEST_PROTO...
3
4
74,407,024
2022-11-11
https://stackoverflow.com/questions/74407024/how-to-optimize-the-code-and-reduce-memory-usage-python
The purpose is to reduce memory usage. Meaning that it should be optimized in a way that the hash is equal to the test hash. What I've tried so far: Adding __slots__ but it didn't make any changes. Change default dtype float64 to float32. Although it reduces the mem usage significantly, it brakes the test by changing ...
If you avoid pd.concat() and use the preferred way of augmenting dataframes: df["new_col_name"] = new_col_data this will reduce peak memory consumption significantly. In your code it is sufficient to fix the Transform class: class Transform: """adding a column of random data""" __slots__ = ['var'] def __init__(self, ...
4
3
74,449,864
2022-11-15
https://stackoverflow.com/questions/74449864/user-is-not-authenticated-in-django-it-shows-errors
I am creating a website so I finshed register page in login page, every details are correct but that is showing please verify your details I mean the else part also I put in a print statement after username and password same details are printing when I typed but not access login. views.py def sign_in(request): if reque...
authenticate() also requires request as an argument so it should be: user = authenticate(request,username=username,password=password) Your view for registering users should be like this: def register(request): if request.method == "POST": username=request.POST['username'] password=request.POST['password'] confirm_pass...
3
4
74,393,322
2022-11-10
https://stackoverflow.com/questions/74393322/tkinter-optionmenu-cannot-open-a-second-time-using-space
I am having some trouble working around what I can only assume is a bug in Tkinter. from tkinter import * def refocus(event, obj): obj.focus() root = Tk() options = ["Hello", "world", "How", "are", "you"] v1 = StringVar() v2 = StringVar() v3 = StringVar() o1 = OptionMenu(root, v1, *options) o1.configure(takefocus=1) o2...
Look at this: import tkinter as tk def open_option_menu(event): # Get the widget from the event that tkinter passed in obj = event.widget # Calculate the x/y position of the popup window x = obj.winfo_rootx() y = obj.winfo_rooty() + obj.winfo_height() # Show the popup window # obj["menu"] returns a `tk.Menu` object whi...
5
3
74,432,327
2022-11-14
https://stackoverflow.com/questions/74432327/free-memory-as-i-iterate-over-a-list
I have a hypothetical question regarding the memory usage of lists in python. I have a long list my_list that consumes multiple gigabytes if it is loaded into memory. I want to loop over that list and use each element only once during the iteration, meaning I could delete them from the list after looping over them. Whi...
Many of your assumptions here are incorrect. First biggie is the assumption that you can delete items as you loop over them with a for loop. You can't. You could with a while loop of the form: while my_list: item=my_list.pop(0) process(item) # Each my_list[0] element ref_count-- each loop... # If the ref_count==0, ite...
5
3
74,440,410
2022-11-15
https://stackoverflow.com/questions/74440410/sklearn-evaluate-accuracy-precision-recall-f1-show-same-result
I want to evaluate with accuracy, precision, recall, f1 like this code but it show same result. df = pd.read_csv(r'test.csv') X = df.iloc[:,:10] Y = df.iloc[:,10] X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2) clf = DecisionTreeClassifier() clf = clf.fit(X_train,y_train) predictions = clf.pred...
According to sklearn's documentation, the behavior is expected when using micro as average and when dealing with a multiclass setting: Note that if all labels are included, “micro”-averaging in a multiclass setting will produce precision, recall and F that are all identical to accuracy. Here is a nice blog article de...
4
6
74,442,230
2022-11-15
https://stackoverflow.com/questions/74442230/the-notion-of-block-in-python
The documentation states: A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. This seems to imply, contrary to what I had thought, that an indented piece of code, such as th...
This seems to imply, contrary to what I had thought, that an indented piece of code, such as the body of an if-statement or a for-loop is not a block. Indeed, at least in the technical context of the Python language reference, what we would normally call an "indented block" is not a "block". It's not unusual in techn...
3
6
74,439,252
2022-11-15
https://stackoverflow.com/questions/74439252/pandas-copying-values-of-a-certain-row-based-on-a-different-column
What I'm trying to achieve is that when a row in col2 has a 1, it will copy that 1 onto all the other values in col2 as long as the rows in col1 have the same name. As an example, if the dataframe looks like this col1 col2 xx 1 xx 0 xx 0 xx 0 yy 0 yy 0 yy 0 zz 0 zz 0 zz 1 The output would be col1 col2 xx 1 xx 1 xx 1 x...
Use groupby.transform('max'): df['col2'] = df.groupby('col1')['col2'].transform('max') Output: col1 col2 0 xx 1 1 xx 1 2 xx 1 3 xx 1 4 yy 0 5 yy 0 6 yy 0 7 zz 1 8 zz 1 9 zz 1
5
6
74,438,709
2022-11-14
https://stackoverflow.com/questions/74438709/how-is-secret-key-txt-more-secure-in-django-project
I apologize if this is a duplicate question but I can't find an answer online. In Django Checklist Docs I see the following to keep secret key secure. with open('/etc/secret_key.txt') as f: SECRET_KEY = f.read().strip() My project is deployed with AWS EBS. I've created a separate file called "secret_key.txt" which hol...
You usually add that file to the .gitignore, such that the file is not part of the (GitHub) repository. This means that you can add (other) settings in the project, and you load "sensitive" settings through environment variables, or files. This hackernoon post for example, discusses four ways to define sensitive variab...
4
9
74,435,728
2022-11-14
https://stackoverflow.com/questions/74435728/i-cant-run-geckodriver-python-selenium-winerror-216
I've got the win32 drivers from https://github.com/mozilla/geckodriver/releases and placed the exe under the python38 folder I'm running windows 11 OSError: [WinError 216] This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the softw...
You can use webdriver_manager to get rid of driver problems. You can use webdriver_manager for firefox as you can see in the link as follows for selenium 3 from selenium import webdriver from webdriver_manager.firefox import GeckoDriverManager driver = webdriver.Firefox(executable_path=GeckoDriverManager().install()) ...
5
6
74,409,966
2022-11-12
https://stackoverflow.com/questions/74409966/how-to-replace-setup-py-with-a-pyproject-toml-for-a-native-c-build-dependency
I came across this little project for creating a C-compiled version of the Black-Scholes function to be used in python. Although the example code seem to have been published in July this year, it seem that the use setup.py type of build has been deprecated beyond legacy builds. Any compilation fails, first complaining ...
After having wasted 2 days on trying to circumvent the required Visual Studio C++ Build tools requirements, the only unfortunate option that would work, was to submit to the >7GB download in order to get my 20 line C-function to compile and install nicely on Py3.10. (Follow this.) Using an external _custom_build.py Her...
7
9
74,432,427
2022-11-14
https://stackoverflow.com/questions/74432427/how-to-install-python-libraries-in-docker-file-on-ubuntu
I want to create a docker image (docker version: 20.10.20)that contains python libraires from a requirement.txt file that contains 50 libraries. Without facing root user permissions how can proceed. Here is the file: From ubuntu:latest RUN apt update RUN apt install python3 -y WORKDIR /Destop/DS # COPY requirement.txt ...
For me the only problem in your Dockerfile is in the line RUN apt install python -y. This is erroring with Package 'python' has no installation candidate. It is expected since python refers to version 2.x of Python wich is deprecated and no longer present in the default Ubuntu repositories. Changing your Dockerfile to ...
3
5
74,426,028
2022-11-14
https://stackoverflow.com/questions/74426028/pyplot-3d-scatter-plot-zlabel
Minimum working example: #Python import matplotlib.pyplot as plt x = [0, 1, 2, 3, 4, 5] y = [0, 1, 2, 3, 4, 5] z = [0, 1, 2, 3, 4, 5] fig = plt.figure() ax = plt.axes(projection="3d") ax.scatter(x, y, z, c='g', s=20) plt.xlabel("X data") plt.ylabel("Y data") #plt.zlabel("Z data") DOES NOT WORK ax.view_init(60,35) plt.s...
For 3D plots the labels need to be changed using the axes objects. Try something like this ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label')
3
4
74,425,460
2022-11-13
https://stackoverflow.com/questions/74425460/how-to-print-whole-number-without-zeros-after-decimal-point
I'm trying to print a whole number (such as 39 for example) in the following format: 39. It must not be a str type object like '39.' for example, but a number e. g. n = 39.0 should be printed like 39. n = 39.0 #magic stuff with output 39. I tried using :.nf methods (:.0f apparently -- didn't work), print(float(39.)) o...
From Format Specification Mini-Language (emphasis mine): The '#' option causes the “alternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float and complex types. For integers, when binary, octal, or hexadecimal output is us...
4
8
74,421,106
2022-11-13
https://stackoverflow.com/questions/74421106/why-does-this-specific-piece-of-code-using-random-random-run-slower-in-python-3
I'm just curious to hear other people's thoughts on why this specific piece of code might might run slower in Python 3.11 than in Python 3.10.6. Cross-posted from here. I'm new here - please kindly let me know if I'm doing something wrong. test.py script: import timeit from random import random def run(): for i in rang...
This looks like it's probably the PEP 659 optimizations not paying off for random.random. PEP 659 is an effort to JIT-optimize many common operations. (Not JIT compilation, but definitely JIT optimization.) It pays off for most Python code, but I think random.random isn't covered. random.random is a method (of a hidden...
3
7
74,372,527
2022-11-9
https://stackoverflow.com/questions/74372527/typeerror-cart-takes-no-arguments
This is views.py file from the cart section where I want to add product, remove product and show product details in the cart. Error is : Cart() takes no arguments. from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from ecommerce.models import Product ...
I could see one mistake it should be __init__() method not __int__ method. That's why Cart(request) gave that error as __init__() was not actually called.
5
5
74,417,696
2022-11-13
https://stackoverflow.com/questions/74417696/python-match-statement-with-enum
I'm trying to match "header" to one of the header types in my ENUM class. I've tried header to match Header.PROFILE_NAME, Header.PROFILE_NAME.name, Header.PROFILE_NAME.name. However none of these worked so far. Can't find a lot of information about it either. Hope someone can help me out on this one. Cheers in advance....
The match statement will work directly with enums, so convert your header into an enum first: for index, header in enumerate(profile): header = Header[header.upper()] # or whatever is needed to match the name match header: ...
6
7
74,418,107
2022-11-13
https://stackoverflow.com/questions/74418107/how-to-check-timestamps-and-day-period-then-drop-mismatch
I have data with timestamps. Users respond to questions and they also select day period (morning or evening). I want to drop rows where recorded timestamp and day period mismatch. So check, if timestamp is between 6am-12pm and discard if "daytime" is "evening", etc. df timestamps daytime 2020-04-10 11:40 Morning 2022-0...
Instead of dropping you can use .query() to filter. df["timestamps"] = pd.to_datetime(df["timestamps"]) df = df.query( "timestamps.dt.hour.between(6, 12, inclusive='both') & daytime.eq('Morning') | " "timestamps.dt.hour.between(18, 23, inclusive='both') & daytime.eq('Evening')" ).reset_index(drop=True) print(df) timest...
3
2
74,411,491
2022-11-12
https://stackoverflow.com/questions/74411491/python-equivalent-for-gcloud-auth-print-identity-token-command
The gcloud auth print-identity-token command prints an identity token for the specified account. $(gcloud auth print-identity-token \ --audiences=https://example.com \ --impersonate-service-account my-sa@my-project.iam.gserviceaccount.com \ --include-email) How do I do the same using Python?
Here a code sample (not so easy and well documented) import google.auth.transport.requests from google.auth.impersonated_credentials import IDTokenCredentials SCOPES = ['https://www.googleapis.com/auth/cloud-platform'] request = google.auth.transport.requests.Request() audience = 'my_audience' creds, _ = google.auth.de...
10
13
74,415,578
2022-11-12
https://stackoverflow.com/questions/74415578/openpyxl-or-pandas-which-is-better-at-reading-data-from-a-excel-file-and-return
Hello Stack OF Community, * Basically my goal is to extract values from an excel file, after reading through data from another column.* ** Thickness** of parcel, with values for example - [0.12, 0.12, 0.13, 0.14, 0.14, 0.15] (Heading: Thickness (mm)) Weight of parcel, with values for example - [4.000, 3.500, 2.500, 4.5...
Pandas actually uses openpyxl as well as well as some other engines inside. You can check engines field in the documentation. I think that reading and manipulations are easier with pandas, but if you need some advanced formatting, you will need to use openpyxl directly. (For basic cases pandas is enough). Here is a bas...
4
5
74,409,601
2022-11-12
https://stackoverflow.com/questions/74409601/why-is-visual-studio-code-not-showing-mypy-errors-when-i-have-my-package-install
I have a Python project which uses mypy for type checking. The root of my project contains a setup.py and the package folder rise, along with a virtual environment folder venv. Both my shells and VSCode are set to use this virtual environment. Most of the time, this setup works great: VSCode runs mypy every time I save...
I ended up installing the Mypy extension for Visual Studio Code and removing mypy from my linters configuration. The extension doesn't suffer from this bug (or misconfiguration, or whatever it is), and it runs faster to boot.
5
7
74,413,330
2022-11-12
https://stackoverflow.com/questions/74413330/is-it-possible-to-merge-plotly-traces-into-a-single-one
The following code presents a way to add two traces to a Plotly figure: import plotly.graph_objs as go fig = go.Figure() fig.add_trace(go.Scatter( x = [0, 1, 2, 3], y = [1, 2, 3, 4], mode = 'lines+markers', name = "Trace 0", )) fig.add_trace(go.Scatter( x = [5,6,7,8], y = [1, 2, 3, 4], mode = 'lines+markers', name = "T...
The other answer here is excellent, but I'll post an alternative solution for those interested. If for some reason you don't want to add another column to your dataframe (or maybe you're not using dataframes), you can specify the color of each trace and put your traces in the same legend group to ensure they toggle tog...
4
5
74,407,211
2022-11-11
https://stackoverflow.com/questions/74407211/check-dates-for-gap-of-more-than-one-day-and-group-them-if-continuous-in-spark
If I have table with dates in format MM/DD/YYYY like below. +---+-----------+----------+ | id| startdate| enddate| +---+-----------+----------+ | 1| 01/01/2022|01/31/2022| | 1| 02/01/2022|02/28/2022| | 1| 03/01/2022|03/31/2022| | 2| 01/01/2022|03/01/2022| | 2| 03/05/2022|03/31/2022| | 2| 04/01/2022|04/05/2022| +---+---...
This is a particular case of the sessionization problem (i.e. identify sessions in data based on some conditions). Here is a possible solution that uses windows. The logic behind the solution: Associate at each row the temporally previous enddate with the same id Calculate the difference in days between each startdate...
3
5
74,370,833
2022-11-9
https://stackoverflow.com/questions/74370833/how-to-add-new-site-language-in-django-admin
I work on a project where we want to have multilingual site. We start with two languages defined in settings.py LANGUAGES = ( ("en-us", _("United States")), ("cs", _("Czech Republic")), ) I am not the programmer doing the work but if I understood correctly all we need is to be able to add - for example - French langua...
The short answer is that you can't do that. The settings.py of a Django project is not designed, and not recommended to be modified by the web application.(It can introduce a security breach.) So I recommend to change LANGUAGES manually, or to enable all languages supported by Django by removing LANGUAGES key. Of cours...
4
7
74,382,683
2022-11-9
https://stackoverflow.com/questions/74382683/behavior-of-multiprocessing-pool-on-exception
Suppose I have a program that looks like this: jobs = [list_of_values_to_consume_and_act] with multiprocessing.Pool(8) as pool: results = pool.map(func, jobs) And whatever is done in func can raise an exception due to external circumstances, so I can't prevent an exception from happening. How will the pool behave on e...
No processes will be terminated at all. All calls to the target functions from within the pool's processes are wrapped in a try...except block. Incase an exception is caught, the process informs the appropriate handler thread in the main process which passes the exception forward so it can be re-rasied. Whether or not...
3
5
74,406,574
2022-11-11
https://stackoverflow.com/questions/74406574/why-is-python-dataclass-a-decorator-and-not-a-base-class
Why does Python implement dataclasses.dataclass as a class decorator and not as a base class? I think it would be at least clearer from the conceptual point of view to have it as a base class: the __init__ method seems to be the only thing a dataclass decorator adds to a class, and adding methods and attributes is what...
Dataclasses were introduced in PEP 557, which describes some of the design considerations for this feature, including rejected ideas. However, there is no mention of any rejected alternatives to using a decorator, such as using a base class instead. So it seems we cannot give a definitive answer for why a decorator was...
7
7
74,406,021
2022-11-11
https://stackoverflow.com/questions/74406021/import-json-lines-into-pandas
I want to import a JSON lines file into pandas. I tried to import it like a regular JSON file, but it did not work: js = pd.read_json (r'C:\Users\Name\Downloads\profilenotes.jsonl')
This medium article provides a fairly simple answer, which can be adapted to be even shorter. All you need to do is read each line then parse each line with json.loads(). Like this: import json import pandas as pd lines = [] with open(r'test.jsonl') as f: lines = f.read().splitlines() line_dicts = [json.loads(line) for...
6
6
74,405,574
2022-11-11
https://stackoverflow.com/questions/74405574/how-to-update-python-to-the-latest-version-on-archlinux
How to install the latest python version 3.11.0 on ArchLinux through pacman? ArchLinux wiki says current version is 3.10, although python 3.11 has been officially released. When running sudo pacman -Syyu p I'm welcomed with warning: python-3.10.8-3 is up to date. Am I doing something wrong?
Use AUR like "yay" to get the new python3.11. If you haven't installed yay on your system, setup yay by following these instructions Run this command after setting up yay in your system: yay -S python311
5
4
74,401,537
2022-11-11
https://stackoverflow.com/questions/74401537/pandas-groupby-two-columns-and-expand-the-third
I have a Pandas dataframe with the following structure: A B C a b 1 a b 2 a b 3 c d 7 c d 8 c d 5 c d 6 c d 3 e b 4 e b 3 e b 2 e b 1 And I will like to transform it into this: A B C1 C2 C3 C4 C5 a b 1 2 3 NAN NAN c d 7 8 5 6 3 e b 4 3 2 1 NAN In other words, something like groupby A and B and expand C into different...
Use GroupBy.cumcount and pandas.Series.add with 1, to start naming the new columns from 1 onwards, then pass this to DataFrame.pivot, and add DataFrame.add_prefix to rename the columns (C1, C2, C3, etc...). Finally use DataFrame.rename_axis to remove the indexes original name ('g') and transform the MultiIndex into col...
8
12
74,405,180
2022-11-11
https://stackoverflow.com/questions/74405180/why-cpython-exposes-pytuple-setitem-as-c-api-if-tuple-is-immutable-by-design
Tuple in python is immutable by design, so if we try to mutate a tuple object, python emits following TypeError which make sense. >>> a = (1, 2, 3) >>> a[0] = 12 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment So my question is, if tuple...
Similarly, there is a PyTuple_Resize function with the warning Because tuples are supposed to be immutable, this should only be used if there is only one reference to the object. Do not use this if the tuple may already be known to some other part of the code. The tuple will always grow or shrink at the end. Think of ...
12
11
74,403,900
2022-11-11
https://stackoverflow.com/questions/74403900/how-do-i-get-typer-to-accept-the-short-h-as-well-as-the-long-help-to-outp
Out of the box, Typer CLIs only recognize the long help option --help to display the help text. I would like to also accept the short option -h but I can't figure out how. I've searched the docs to no avail. Do I need to alias -h to --help and if so, how do I do that?
The key is to use context_settings={"help_option_names": ["-h", "--help"]}) As suggested by @jvx8ss in the comments, one needs to convert a typer.run app to one using @app.command() decorators. Here is a minimal working example: import typer app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]}) @a...
4
6
74,398,563
2022-11-11
https://stackoverflow.com/questions/74398563/how-to-use-polars-dataframes-with-scikit-learn
I'm unable to use polars dataframes with scikit-learn for ML training. Currently, I'm preprocessing all dataframes in polars and convert them to pandas for model training in order for it to work. Is there any method to directly use polars dataframes with the scikit-learn API (without converting to pandas first)?
You must call to_numpy when passing a DataFrame to sklearn. Though sometimes sklearn can work on polars Series it is still good type hygiene to transform to the type the host library expects. import polars as pl from sklearn.linear_model import LinearRegression data = pl.DataFrame( np.random.randn(100, 5) ) x = data.se...
12
10
74,400,353
2022-11-11
https://stackoverflow.com/questions/74400353/vscode-flake8-ignore
Flake8 was installed lately by one of the updates of vscode. I think it is time to comply to the "rules" of python to writer better and more readable code. Unfortunately I have some errors that I cannot fix in the code (no discussion about that, but a local module has to be loaded before some others). I want to ignore ...
seems like python.linting.flake8Args no longer works, I can get flake to work, but I get everything. My solution was to install the flake8 plugin: https://marketplace.visualstudio.com/items?itemName=ms-python.flake8 and use the flake8.args: "flake8.args": [ "--ignore=E24,E128,E201,E202,E225,E231,E252,E265,E302,E303,E40...
3
6
74,396,955
2022-11-11
https://stackoverflow.com/questions/74396955/how-to-type-hint-variable-that-is-initially-none-but-is-guaranteed-to-get-a-valu
I have a class variable as shown below: class MyClass: def __init__(self): self.value: MyOtherClass | None = None self.initialize_value() def initialize_value(self): self.value = MyOtherClass() def use_value(self): return self.value.used self.value is guaranteed to be initialized as an instance of MyOtherClass before ...
To avoid repetition, when such an attribute is used throughout the class in multiple methods, a common pattern for me is protecting it and defining a property that raises an error, if the attribute behind it is not set: class MyClass: def __init__(self): self._value: MyOtherClass | None = None self.initialize_value() @...
15
12
74,394,875
2022-11-10
https://stackoverflow.com/questions/74394875/mock-patch-in-pytest-fixture-doesnt-work-when-other-tests-have-run
Given the following code and tests: # some module from other.module import a_func # returns False by default def do_stuff(): return "banana" if a_func() else "pear" ############################# # tests in a different module @pytest.fixture def my_fixture(): with mock.patch("other.module.a_func", lambda: True): yield c...
You should do mock.patch("some.module.a_func") instead of mock.patch("other.module.a_func") from other.module import a_func means that a_func becomes part of the some.module, so patching the origin of function definition has no effect - instead, patching should be done where the function is used. Read Where to patch ...
10
12
74,397,741
2022-11-11
https://stackoverflow.com/questions/74397741/how-to-open-new-tab-with-command-line-in-file-explorer
I want to open a new folder in different tabs on the same window of Windows File Explorer in Windows 11, instead of opening a new window every time. I tried to use Start.exe C:\ Explorer.exe C: \ -W 0 Explorer.exe C: \ --windows 0 in terminal and Python. import os import sys gpus = sys.argv[1] path = os.path.realpath(...
I did some research on your problem and concluded that it is not allowed to open Tabs in the file explorer. In this link we can see that as of 11/09/2022 there is no response by MSFT https://techcommunity.microsoft.com/t5/windows-11/22h2-explorer-tabs-save-configuration/m-p/3672808
5
3
74,397,847
2022-11-11
https://stackoverflow.com/questions/74397847/how-to-randomly-sample-from-a-datafframe-while-preserving-the-distribution-in-py
I am using a Kaggle sample data. As shown bellow, 40% of the location is in CA and 47% of the category includes FOODS. What I am trying to achieve is to randomly select data from this data frame, while more or less preserve the same distribution for the values of the these two columns. Does python/Pandas have such a ca...
Your can select a fraction of each group with groupby.sample: # selecting 10% of each group df.groupby(['location', 'category']).sample(frac=0.1) But if your data is large and you select a decent number of rows, this should naturally maintain a representativity of the proportions: df.sample(n=1000) Example, let's pic...
4
3
74,393,947
2022-11-10
https://stackoverflow.com/questions/74393947/make-python-dataclass-iterable
I have a dataclass and I want to iterate over in in a loop to spit out each of the values. I'm able to write a very short __iter__() within it easy enough, but is that what I should be doing? I don't see anything in the documentation about an 'iterable' parameter or anything, but I just feel like there ought to be... H...
The simplest approach is probably to make a iteratively extract the fields following the guidance in the dataclasses.astuple function for creating a shallow copy, just omitting the call to tuple (to leave it a generator expression, which is a legal iterator for __iter__ to return: def __iter__(self): return (getattr(se...
14
20
74,393,442
2022-11-10
https://stackoverflow.com/questions/74393442/what-is-the-purpose-of-the-master-parameter-in-the-tkinter-variable-class-subc
I've been looking for some more detailed information regarding the Variable subclasses in tkinter, namely BooleanVar, DoubleVar, IntVar, and StringVar. I'm hoping someone with broader knowledge can point me in the right direction. Given the constructor: tkinter.Variable(master=None, value=None, name=None) I'm curious w...
When you create an instance of Tk, you are doing more than just creating a widget. For each instance, you are also creating an embedded Tcl interpreter. This tcl interpreter is where all of the widgets and variables and image objects exist. The objects within this interpreter are only available to that interpreter and ...
4
5
74,383,395
2022-11-10
https://stackoverflow.com/questions/74383395/property-sheets-of-openpyxlwriter-object-has-no-setter-using-pandas-and-open
This code used to get a xlsx file and write over it, but after updating from pandas 1.1.5 to 1.5.1 I got zipfile.badzipfile file is not a zip file Then I read here that after pandas 1.2.0 the pd.ExcelWriter(report_path, engine='openpyxl') creates a new file but as this is a completely empty file, openpyxl cannot load i...
TLDR Use .update to modify writer.sheets Rearrange the order of your script to get it working # run before initializing the ExcelWriter reader = pd.read_excel("Resultados.xlsx", engine="openpyxl") book = load_workbook("Resultados.xlsx") # use `with` to avoid other exceptions with pd.ExcelWriter("Resultados.xlsx", eng...
5
5
74,390,633
2022-11-10
https://stackoverflow.com/questions/74390633/explain-deprecationwarning-private-variables-such-as-cmd-call-set-will-be
Python interpreter version used in the code base I am working on has recently been updated from Python 3.7 to 3.9. A few new warnings similar to one in the title have started showing up when some of the tools written in Python are executed. I've searched the net extensively, read the What's New in 3.10 but haven't foun...
writing an attribute as so: _attr makes it a private attribute, and __attr makes it a protected attribute. This deprecation warning seems to indicate the attributes in question will be made not private and not protected in 3.10. TL;DR They won't have the underscore in 3.10, and they will be completely visible.
4
0
74,377,678
2022-11-9
https://stackoverflow.com/questions/74377678/class-attributes-dependent-on-other-class-attributes
I want to create a class attribute, that are dependent to another class attribute (and I tell class attribute, not instance attribute). When this class attribute is a string, as in this topic, the proposed solution class A: foo = "foo" bar = foo[::-1] print(A.bar) works fine. But when the class attribute is a list or ...
Python is trying to look up remove in the global scope, but it doesn't exist there. x, on the other hand, is looked up in the enclosing (class) scope. See the documentation: Resolution of names Class definition blocks and arguments to exec() and eval() are special in the context of name resolution. A class definition ...
5
6
74,378,923
2022-11-9
https://stackoverflow.com/questions/74378923/aligning-text-in-rows-of-pyplot-legend-at-multiple-points-without-using-monospa
I am trying to create a neat legend in Pyplot. So far I have this: fig = plt.figure() ax = plt.gca() marker_size = [20.0, 40.0, 60.0, 100.0, 150.0] marker_color = ['black', 'red', 'pink', 'white', 'yellow'] ranges = [0.0, 1.5, 20.0, 60.0, 500.0] marker_edge_thickness = 1.2 s = [(m ** 2) / 100.0 for m in marker_size] ...
You could replace the spaces by '\u2007', a space that is as wide as a digit. In most fonts, a space character is much narrower than a digit. Except for monospaced fonts, which don't look as nice, each letter has its own width. The character width can even be different depending on which letter goes before and after (E...
4
4
74,370,984
2022-11-9
https://stackoverflow.com/questions/74370984/is-tkwait-wait-variable-wait-window-wait-visibility-broken
I recently started to use tkwait casually and noticed that some functionality only works under special conditions. For example: import tkinter as tk def w(seconds): dummy = tk.Toplevel(root) dummy.title(seconds) dummy.after(seconds*1000, lambda x=dummy: x.destroy()) dummy.wait_window(dummy) print(seconds) root = tk.Tk(...
Basically, you need great care if you're using an inner event loop because: Conditions that would terminate the outer event loop aren't checked for until the inner event loop(s) are finished. It's really quite easy to end up recursively entering an inner event loop by accident. The recursive entry problem is usually ...
8
8
74,369,418
2022-11-9
https://stackoverflow.com/questions/74369418/dealing-with-cracks-in-the-unary-union-of-several-imprecise-polygons
I used shapely.ops.unary_union on a number of 6-sided shapely.geometry.Polygons, and obtained the following shape A: Note how there are two "cracks" in the upper part. These are not intended, and are presumably caused by some floating-point edge cases. If you construct another shape B that sits inside of A, and if A h...
You can fix this by buffering and un-buffering the shape. Here's an example of a polygon with a small crack: from shapely.geometry import Polygon bad_polygon = Polygon([[0, 0], [1, 0], [1, 0.4999], [0.5, 0.5], [1, 0.5001], [1, 1], [0, 1], [0, 0]]) To fix it, expand the shape slightly, and contract it the same amount,...
4
5
74,316,373
2022-11-4
https://stackoverflow.com/questions/74316373/what-is-the-point-for-asyncio-synchronization-primitives-not-to-be-thread-safe
It seems that several asyncio functions, like those showed here, for synchronization primitives are not thread safe... By being not thread safe, considering for example asyncio.Lock, I assume that this lock won't lock the global variable, when we're running multiple threads in our computer, so race conditions are probl...
For use-cases, look at what's Python asyncio.Lock() for? As for why it is not thread-safe. It is mostly performance. Asyncio is not made for multithreaded work like old servers used to do, the asyncio eventloop itself is not thread-safe and only runs coroutines in a single thread, hence a lock that is only running in a...
8
7
74,289,077
2022-11-2
https://stackoverflow.com/questions/74289077/attributeerror-multiprocessingdataloaderiter-object-has-no-attribute-next
I am trying to load the dataset using Torch Dataset and DataLoader, but I got the following error: AttributeError: '_MultiProcessingDataLoaderIter' object has no attribute 'next' the code I use is: class WineDataset(Dataset): def __init__(self): # Initialize data, download, etc. # read with numpy or pandas xy = np.loa...
I too faced the same issue, when i tried to call the next() method as follows dataiter = iter(dataloader) data = dataiter.next() You need to use the following instead and it works perfectly: dataiter = iter(dataloader) data = next(dataiter) Finally your code should look like follows: class WineDataset(Dataset): def _...
37
94
74,318,682
2022-11-4
https://stackoverflow.com/questions/74318682/how-to-submit-html-form-input-value-using-fastapi-and-jinja2-templates
I am facing the following issue while trying to pass a value from an HTML form <input> element to the form's action attribute and send it to the FastAPI server. This is how the Jinja2 (HTML) template is loaded: # Test TEMPLATES @app.get("/test",response_class=HTMLResponse) async def read_item(request: Request): return ...
Option 1 You could have the category name defined as Form parameter in the backend, and submit a POST request from the frontend using an HTML <form>, as described in Method 1 of this answer. app.py from fastapi import FastAPI, Form, Request from fastapi.responses import HTMLResponse from fastapi.templating import Jinja...
3
11
74,312,939
2022-11-4
https://stackoverflow.com/questions/74312939/can-you-make-a-regular-python-class-frozen
It's useful to be able to create frozen dataclasses. I'm wondering if there is a way to do something similar for regular python classes (ones with an __init__ function with complex logic possibly). It would be good to prevent modification after construction in some kind of elegant way, like frozen dataclasses.
yes. All attribute access in Python is highly customizable, and this is just a feature dataclasses make use of. The easiest way to control attribute setting is to create a custom __setattr__ method in your class - if you want to be able to create attributes during __init__ one of the ways is to have an specific paramet...
3
4
74,308,012
2022-11-3
https://stackoverflow.com/questions/74308012/type-hints-without-value-assignment-in-python
I was under the impression that typing module in Python is mostly for increasing code readability and for code documentation purposes. After playing around with it and reading about the module, I've managed to confuse myself with it. Code below works even though those two variables are not initialized (as you would nor...
It is fairly straightforward, when you consider the namespaces involved. This is hinted at by the fact that you get a NameError, when you actually try and do anything with test_var, such as passing it to a function (like print). It tells you that the name you used is not known to the interpreter. What does variable ass...
11
18
74,360,992
2022-11-8
https://stackoverflow.com/questions/74360992/how-to-cache-data-in-fastapi
How can I cache requests in FastAPI? For example, there are two functions and a PostgreSQL database: @app.get("/") def home(request: Request): return templates.TemplateResponse("index.html", {"request": request}) @app.post("/api/getData") async def getData(request: Request, databody = Body()): data = databody["data"] w...
You can try fastapi-cache: from fastapi import FastAPI from starlette.requests import Request from starlette.responses import Response from fastapi_cache import FastAPICache from fastapi_cache.backends.redis import RedisBackend from fastapi_cache.decorator import cache from redis import asyncio as aioredis app = FastAP...
6
7
74,323,364
2022-11-4
https://stackoverflow.com/questions/74323364/how-to-add-a-private-repository-using-poetry
Using Artifactory (https://cloud.google.com/artifact-registry) I intend to add a dependency with poetry (https://python-poetry.org/docs/repositories/). I can install with command: pip install --index-url https://us-central1-python.pkg.dev/<PROJECT_ID>/<SOME_LIB_REPO>/simple/ <PACKAGE_NAME> (auth using keyrings.google-a...
Your RepositoryError of 401 Client Error: Unauthorized for url: https://us-central1-python.pkg.dev/<PROJECT_ID>/<SOME_LIB_REPO>/simple/pytest/ clearly indicates that you lack authorization for the URL mentioned. So you will need to make sure you properly get and use the authorization, that is, you will have a user wi...
6
2
74,326,921
2022-11-5
https://stackoverflow.com/questions/74326921/graphql-schema-to-python-dataclasses-codegen
I have a GraphQL schema defined from server and I'd like to write a nice Python GraphQL client for it. I'm looking for a way to transform my GraphQL schema into python classes with type hints such that I'll be able to see all available queries, mutations, their fields(names & types) and return vals. I cannot write manu...
Thanks for all the answers, but after revisiting this issue I found out Ariadne is the best solution for my case. Generating async / sync clients based on GraphQL schema + queries, highly configurable. You are welcome to try them yourself: https://github.com/mirumee/ariadne-codegen
5
3
74,316,387
2022-11-4
https://stackoverflow.com/questions/74316387/how-to-use-blueprints-in-azure-functions-v2-for-python
In looking at the guide What do blueprints offer that just importing doesn't? Here are some points that are unclear: It says to have a file called http_blueprint.py in which you'd define some routes but it just looks like the regular http trigger but the decorator is a bp.route instead of an app.route. Are these also ...
Example of repo structure. project │ file001.py │ file002.py │ function_app.py │ README.md │ host.json │ local.settings.json file001.py: import azure.function as func import json bp01 = func.Blueprint() @bp01.route(route="route01") def method01(req:func.HttpRequest) -> func.HttpRequest: return func.HttpResponse ( json...
6
9
74,364,918
2022-11-8
https://stackoverflow.com/questions/74364918/how-to-pass-xfrozen-modules-off-to-python-to-disable-frozen-modules
Running a python script on VS outputs this error. How to pass -Xfrozen_modules=off to python to disable frozen modules? I was trying to update the python version from 3.6 to 3.11 and then started seeing this message.
If you are using VS Code you can add "pythonArgs": ["-Xfrozen_modules=off"] to your debug configuration in launch.json, like this: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=83038...
11
14
74,315,381
2022-11-4
https://stackoverflow.com/questions/74315381/docker-compose-environment-variable-is-not-set
Project tree /backend .env.dev docker-compose-dev.yml /project I have the following warning: docker-compose -f docker-compose-dev.yml up --build # i am in the /backend directory WARNING: The DB_USER variable is not set. Defaulting to a blank string. WARNING: The DB_PASSWORD variable is not set. Defaulting to a blank s...
If the complaint is coming from docker (compose) itself, try to: rename ./.env.dev to simply .env.dev; if not yet, rename .env.dev to .env (default) and remove the env_file entry from your compose. That will certainly work, then you can go back to investigate the issue with env_file ([1]). Update Now facing the same ...
11
8
74,365,266
2022-11-8
https://stackoverflow.com/questions/74365266/how-to-change-the-label-in-display-list-of-a-field-in-the-model-in-django-admin
I have a model with some fields with a verbose_name. This verbose name is suitable for the admin edit page, but definitively too long for the list page. How to set the label to be used in the list_display admin page?
You can create custom columns. For example, there is Person model below: # "models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=30) age = models.IntegerField() Now, you can create the custom columns "my_name" and "my_age" with my_name() and my_age() and can rename the...
5
3
74,351,267
2022-11-7
https://stackoverflow.com/questions/74351267/portable-way-to-write-python-3-shebang
Back when Python3 was there, I used to use: #!/usr/bin/env python3 But recently, especially with Ubuntu 22.04 or macOS, the python3 executable isn't always available in PATH, instead, I should use python to call python3. Is there any portable way to write Python3 shebang?
According to the Python docs, using #!/usr/bin/env python3 is still the recommended way -- but they admit that it does not always work: 2.4. Miscellaneous To easily use Python scripts on Unix, you need to make them executable, e.g. with chmod +x script and put an appropriate Shebang line at the top of the script. A go...
4
2
74,289,869
2022-11-2
https://stackoverflow.com/questions/74289869/how-to-unit-test-a-pure-asgi-middleware-in-python
I have an ASGI middleware that adds fields to the POST request body before it hits the route in my fastapi app. from starlette.types import ASGIApp, Message, Scope, Receive, Send class MyMiddleware: """ This middleware implements a raw ASGI middleware instead of a starlette.middleware.base.BaseHTTPMiddleware because th...
I've faced the similar problem recently, so I want to share my solution for fastapi and pytest. I had to implement per request logs for the fastapi app using middlewares. I've checked Starlette's test suite as Marcelo Trylesinski suggested and adapted the code to fit fastapi. Thank you for the recommendation, Marcelo! ...
5
4
74,319,151
2022-11-4
https://stackoverflow.com/questions/74319151/why-is-there-pip3-10-exe-in-python311-scripts
As you can see below, after I installed Python 3.11, I came to the realization that running pip3.10 freeze did not list me the packages I had in my Python 3.10.2 but those of my Python 3.11. This is explained by the fact that in Python311\Scripts I have both pip3.10.exe and pip3.11.exe. Is there a reason? When I want t...
This was a pip bug, I don't understand the details exactly but when pip tried to match to the correct Python version it was only accounting for single-digit version numbers, resulting in this weird behavior. Perhaps it is better explained in this thread on github. To summarize that thread (from user uranusjr): pip con...
4
4
74,350,734
2022-11-7
https://stackoverflow.com/questions/74350734/kedro-how-to-update-a-dataset-in-a-kedro-pipeline-given-that-a-dataset-cannot
In a Kedro project, I have a dataset in catalog.yml that I need to increment by adding a few lines each time I call my pipeline. #catalog.yml my_main_dataset: type: pandas.SQLTableDataSet credentials: postgrey_credentials save_args: if_exists: append table_name: my_dataset_name However I cannot just rely on append in ...
It may not be the best solution, but a workaround is for you to set two kedro datasets pointing to the same physical space. One for reading and the other for writing, but to the same file/table. Something like: #catalog.yml my_main_dataset_read: # same as my_main_dataset_write type: pandas.SQLTableDataSet credentials: ...
4
2
74,319,258
2022-11-4
https://stackoverflow.com/questions/74319258/split-list-of-dictionaries-in-separate-lists-based-primarily-on-list-size-but-se
I currently have a list of dictionaries that looks like that: total_list = [ {'email': 'usera@email.com', 'id': 1, 'country': 'UK'}, {'email': 'usera@email.com', 'id': 1, 'country': 'Germany'}, {'email': 'userb@email.com', 'id': 2, 'country': 'UK'} {'email': 'userc@email.com', 'id': 3, 'country': 'Italy'}, {'email': 'u...
This solution starts of by only working with the list of all emails. The emails are then grouped based on their frequency and the limit on group size. Later the remaining data, i.e. id and country, are joined back on the email groups. The first function create_groups works on the list of emails. It counts the number of...
4
3
74,344,614
2022-11-7
https://stackoverflow.com/questions/74344614/is-there-a-way-in-python-to-extract-only-the-core-text-without-boxes-footer-et
I am trying to extract only the core text from a "rich" pdf document, meaning that it has a lot of tables, graphs, boxes, footers etc. in which I am not interested in. I tried with some common python packages like PyPDF2, pdfplumber or pdfreader.The problem is that apparently they extract all the text present in the pd...
per D.L's comment, please add some reproducible code and, preferably, a pdf to work with. However, I think I can answer at least part of your question. jsvine's pdfplumber is an incredibly robust python pdf processing package. pdfplumber contains a bounding box functionality that lets you extract text from within (.wit...
3
4
74,362,585
2022-11-8
https://stackoverflow.com/questions/74362585/bioreactor-simulation-for-ethanol-production-using-gekko
I am trying to simulate a DAE system that solves a fed-batch bioreactor problem for ethanol production using GEKKO. This is done so I can later optimize it more easily to maximize Ethanol production. It was previously solved in MATLAB and produced the results as shown in the following figures: , , , , My problem now i...
Nice application! Here are some suggestions to improve the convergence. Remove the lower and upper bounds when simulating. This was causing the "no solution found" error. Vl = m.Var(value=1000, name='Vl') # lb=-0.0, ub=0.75*V Xt = m.Var(value=0.1, name='Xt') # lb=-0.0, ub=10 Xv = m.Var(value=0.1, name='Xv') # lb=-0.0...
4
3
74,308,059
2022-11-3
https://stackoverflow.com/questions/74308059/using-typeguard-decorator-typechecked-in-python-whilst-evading-circular-impor
Context To prevent circular imports in Python when using type-hints, one can use the following construct: # controllers.py from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from models import Book class BookController: def __init__(self, book: "Book") -> None: self.book = book Where...
Your problem is that by using the denamespacing import form (from x import y) the contents of an imported module can't be resolved lazily, so one side or the other will require a name before the other module has finished importing (and therefore before it has defined the name). The typical solution here is to use names...
5
6
74,290,259
2022-11-2
https://stackoverflow.com/questions/74290259/count-the-number-of-three-way-conversations-in-a-group-chat-dataset-using-pandas
I wanted to count the number of three way conversations that have occured in a dataset. A chat group_x can consist of multiple members. What is a three way conversation? 1st way - red_x sends a message in the group_x. 2nd way - green_x replies in the same group_x. 3rd way - red_x sends a reply in the same group_x. Th...
For me it's not clear how you define the "three way conversation". Within on group, if you have the input messages what option(s) do you consider as "three way conversation"? There are several options: Input : red_0, red_2, green_0, red_1, red_0, red_2, red_1 Option1: red_2, green_0, red_1 Option2: red_0, green_0, red_...
6
1
74,305,444
2022-11-3
https://stackoverflow.com/questions/74305444/error-while-trying-to-run-corr-in-python-with-pandas-module
While trying to run the corr() method in python using pandas module, I get the following error: FutureWarning: The default value of numeric_only in DataFrame.corr is deprecated. In a future version, it will default to False. Select only valid columns or specify the value of numeric_only to silence this warning. print(d...
The problem only lies in the one function corr() which is not deprecated but its numeric_only Argument in the function is. So, you can set it to false or true according to needs by df.corr(numeric_only = *[True/False]*). You can learn more at its documentation. p.s - I wrote so that it is more understandable and the fa...
9
11
74,360,037
2022-11-8
https://stackoverflow.com/questions/74360037/pytest-doctest-modules-executes-scripts
I have this MRE: . └── tests └── notest.py The notest.py just do a sys.exit(1): When I run pytest --doctest-modules I get this error: ERROR collecting tests/notest.py tests/notest.py:4: in <module> sys.exit(1) E SystemExit: 1 So the --doctest-modules would try to execute my script which is not a test. Is that normal ...
Is that normal behaviour? Yes. Passing --doctest-modules will activate a special doctest collector that is not restricted to globs specified by python_files (test_*.py and *_test.py by default). Instead, it will find and collect any python module that is not __init__.py or __main__.py. Afterwards, doctest will import...
3
5
74,359,505
2022-11-8
https://stackoverflow.com/questions/74359505/python-3-11-debugger-not-working-properly-anymore
So I have just installed python version 3.11 and changed my python interpreter in pycharm and the code runs properly now after I reinstalled the packages to my new venv. but when i debug my code I keep getting a long list of warnings and I have no idea how to fix it: ----------------------------------------------------...
Should be fixed in PyCharm 2022.3 (ticket https://youtrack.jetbrains.com/issue/PY-56939/CRITICAL-WARNING-error-debugging-Python-311-code). Early Access Preview version is already available https://www.jetbrains.com/pycharm/nextversion/
13
13
74,366,289
2022-11-8
https://stackoverflow.com/questions/74366289/how-to-add-drop-down-menu-to-swagger-ui-autodocs-based-on-basemodel-using-fastap
I have this following class: class Quiz(BaseModel): question: str subject: str choice: str = Query(choices=('eu', 'us', 'cn', 'ru')) I can render the form bases on this class like this @api.post("/postdata") def post_data(form_data: Quiz = Depends()): return form_data How can I display a drop down list for choice fie...
Option 1 Use literal values. Literal type is a new feature of the Python standard library as of Python 3.8 (prior to Python 3.8, it requires the typing-extensions package) and is supported by Pydantic. Example: from fastapi import FastAPI, Depends from pydantic import BaseModel from typing import Literal app = FastAPI(...
5
8
74,312,668
2022-11-4
https://stackoverflow.com/questions/74312668/does-column-slice-of-a-pandas-dataframe-with-columns-of-different-data-types-cre
I have some dataframes as follows: df = pd.DataFrame([[1,2.0],[3,4.0]], index = ['row1','row2'], columns = ['a','b']) df2 = df.iloc[:, :] df3 = df.iloc[:1, :] df4 = df.iloc[:, :1] Column a is int while column b is float. Question: are df2, df3, df4 view or copy test 1: print(df._is_view, df._is_copy) print(df2._is_vie...
You are setting values on a newly created sliced data frame. Don't do it. That's a kind of chained assignment, warned by the document. In your code, the df2 and df3 are views and df4 is a copy. It cannot be determined accurately from the undocumented API _is_view and _is_copy. And 'a copy of a slice' in the warning mea...
4
1
74,368,353
2022-11-8
https://stackoverflow.com/questions/74368353/how-to-handle-mypy-when-many-possible-types-but-expecting-a-specific-type
Say I have a generic function that can return a number of different types depending on what properties I select: def json_parser(json_data: Dict[str, Any], property_tree: List[str] ) -> Union[Dict[str, Any], List[str], str, None]: .... I then call this generic function with specific properties that I know will return ...
You've got two options, depending on how careful you want to be. First, typing.cast is a function that takes a type and a value and... magically makes the value have that type. At runtime it's defined as def cast(ty, value): return value but type-checkers are instructed to treat it as some magic black box. You could w...
4
4
74,365,554
2022-11-8
https://stackoverflow.com/questions/74365554/how-super-init-works-when-i-inherit-str-class
I am trying to inherit str class for fun. I provided two ways, 1) using super() and 2) using str class in the constructor as follows: class Str2(str): def __init__(self, value): super().__init__() # I did not use `value` here, but my code works! def ishello(self): if self == "Hello": return True else: False s = Str2("H...
str.__init__ does not do anything (similar to tuple.__init__, among other immutable classes). The actual initialization happens in __new__. Conceptually, this makes sense, since __new__ returns a new object, while __init__ can be run multiple times on an existing one. That means that whether you call super().__init__ o...
5
5
74,345,802
2022-11-7
https://stackoverflow.com/questions/74345802/getting-error-in-visual-code-studio-importerror-cannot-import-name-dummyopera
Getting error while running the airflow DAG code in visual studio code. Error ImportError: cannot import name 'DummyOperator' from 'airflow.operators' (c:\Users\10679196\AppData\Local\Programs\Python\Python38\lib\site-packages\airflow\operators\__init__.py) Import Statement from airflow import DAG from airflow.operato...
As per documentation the DummyOperator is deprecated and beginning with the version 2.4.0 is not supported any more. You should use from airflow.operators.empty import EmptyOperator BTW your old import seems also incorrect. For airflow < 2.4.0 this should work: from airflow.operators.dummy import DummyOperator
7
25
74,356,504
2022-11-8
https://stackoverflow.com/questions/74356504/installation-error-of-scikit-image-in-python-3-11-0
Getting errors when installing scikit-image with python-3.11.0. The package is simply installed via pip install scikit-image or python -m pip install -U scikit-image. The error messages showed that the problem occur on the wheel building process, and therefore hinder the scikit-image installation. How could I fix this ...
In my case, this problem was solved via installing a wheel file from: https://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-image In my case, I download the cp311 windows amd64 version. Then, install the .whl file to the virtual environment (env) D:\env>python -m pip install D:\Download\scikit_image-0.19.3-cp311-cp311-wi...
3
6
74,346,565
2022-11-7
https://stackoverflow.com/questions/74346565/fastapi-typeerror-issubclass-arg-1-must-be-a-class-with-modular-imports
When working with modular imports with FastAPI and SQLModel, I am getting the following error if I open /docs: TypeError: issubclass() arg 1 must be a class Python 3.10.6 pydantic 1.10.2 fastapi 0.85.2 sqlmodel 0.0.8 macOS 12.6 Here is a reproducible example. user.py from typing import List, TYPE_CHECKING, Optional...
TL;DR You need to call User.update_forward_refs(Item=Item) before the OpenAPI setup. Explanation So, this is actually quite a bit trickier and I am not quite sure yet, why this is not mentioned in the docs. Maybe I am missing something. Anyway... If you follow the traceback, you'll see that the error occurs because in...
13
12
74,318,512
2022-11-4
https://stackoverflow.com/questions/74318512/python-api-request-nested-dictionaries-to-dataframe-with-datetime-indexed-value
I run a query on python to get hourly price data from an API, using the get function: result = (requests.get(url_prices, headers=headers, params={'SpotKey':'1','Fields':'hours','FromDate':'2016-05-05','ToDate':'2016-12-05','Currency':'eur','SortType':'ascending'}).json()) where 'SpotKey' identifies the item I want to ...
You did not give examples of the dts, so I cannot verify. But in principle, trating the Date as timestamp and TimeSpan as as timedeltas should give you both the ability to ignore granularity changes and potentialy include additional "dts" parsing. def parse_time(x): if "dst" not in x: return x[:5]+":00" return f"{int(x...
5
4
74,344,904
2022-11-7
https://stackoverflow.com/questions/74344904/python-numpy-image-crop-one-side-fill-with-black-the-ther
I have a image with resolution 816x624, and would need to make a 640x640 image out of it. To do so, i'd have to crop the long side (centered), and fill up the short side with black (centered). the resulting image should be the center of the starting image, with a small black strip on top and bottom. How can this be don...
Given an imput image img, an expected height h and an expected width w: def resize_img(img, h, w): #cut the image cutted_img = img[ max(0, int(img.shape[0]/2-h/2)):min(img.shape[0], int(img.shape[0]/2+h/2)), max(0, int(img.shape[1]/2-w/2)):min(img.shape[1], int(img.shape[1]/2+w/2)), ] #pad the image padded_img = np.zer...
3
4
74,347,282
2022-11-7
https://stackoverflow.com/questions/74347282/count-nan-values-per-column-in-an-ndarray
Problem: I have a ndarray (2000,7) and I want to count the numbers of Nan's per column and save it in an ndarray Tried: number_nan_in_arr = np.count_nonzero(np.isnan(arr)) But this count the total number of nan's over all columns Solution: ?
You can add axis=0 to count null per column: number_nan_in_arr = np.count_nonzero(np.isnan(arr), axis=0) Example: import numpy as np a = np.array([[0, np.nan, 7, 0], [3, 0, 2, np.nan]]) np.count_nonzero(np.isnan(a), axis=0) Output: array([0, 1, 0, 1], dtype=int64)
3
2
74,313,762
2022-11-4
https://stackoverflow.com/questions/74313762/except-fails-on-unhashable-exceptions-documented-behaviour-or-a-bug
Consider the following code block: class MyException(Exception): __hash__ = None try: raise ExceptionGroup("Foo", [ MyException("Bar") ]) except* Exception: pass The except* should catch any number of exceptions of any kind, thrown together as an ExceptionGroup (or a single exception of any kind if thrown alone, come ...
This was reported at https://github.com/python/cpython/issues/99181 and we have a PR to fix it. Should be fixed in 3.11.1.
6
1
74,304,427
2022-11-3
https://stackoverflow.com/questions/74304427/setting-maximum-number-of-workers-in-dask-map-function
I have a Dask process that triggers 100 workers with a map function: worker_args = .... # array with 100 elements with worker parameters futures = client.map(function_in_worker, worker_args) worker_responses = client.gather(futures) I use docker where each worker is a container. I have configured docker to spawn 20 wo...
dask does not dynamically adjust worker resources depending on how many workers are idle. In the example you provided, once 20 workers are initiated, if only 5 workers are used, then they will not be allocated the resources from the remaining 15 workers that are idle. If that's acceptable (e.g. because the idle resourc...
5
3
74,322,978
2022-11-4
https://stackoverflow.com/questions/74322978/awaiting-a-future-versus-event-wait
In the UDP client example in the Python docs, they use loop.create_future() to create a new Future. The main program awaits this future until result is set on it, at which point the program cleans up resources and terminates. However, I have always used an asyncio.Event for this kind of thing. Is there any difference b...
They can be both used for synchronization, but a Future has a proper result and can raise exceptions. So, Event provides less features, but when the use case is only synchronization, it may express the intent better and be less error-prone. In fact, an Event is implemented as a list of futures.
5
3
74,332,390
2022-11-6
https://stackoverflow.com/questions/74332390/how-to-understand-snippet-of-regex
I am attempting to understand what this snippet of code does: passwd1=re.sub(r'^.*? --', ' -- ', line) password=passwd1[4:] I understand that the top line uses regex to remove the " -- ", and the bottom line I think removes something as well? I went back to this code after a while and need to improve it but to do that...
To break r'^.*? -- into pieces: r in front of a string in Python lets the interpreter know that it's a regex string. This lets you not have to do a bunch of confusing character escaping. The ^ tells the regex to match only from the beginning of the string. .*? tells the regex to match any number of characters up to......
4
4
74,326,894
2022-11-5
https://stackoverflow.com/questions/74326894/how-to-change-the-image-size-for-seaborn-objects
The solutions shown in How to change the figure size of a seaborn axes or figure level plot do not work for seaborn.objects. This question is about the new interface added in seaborn v0.12. Tried different ways to set the plotted image size but no one worked, below is the code, how to set the below image height and wid...
With Plot.layout: ( so.Plot(data=d, x="point_x", y="point_y") .add(so.Dot()) .layout(size=(w, h)) # in inches * (dpi / 100) .save("output.png", dpi=dpi) # e.g. dpi=100 .show() )
4
9