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
75,932,638
2023-4-4
https://stackoverflow.com/questions/75932638/finding-non-duplicate-numbers-and-duplicate-numbers-from-a-list
I'm new to coding and struggling a bit with this one. Can anyone show me how to write the pseudocode for a program that finds the non-duplicate numbers and duplicate numbers (as simply as possible.) thanks! ** input:** 56 75 1 46 100 97 75 46 46 Output: Non-duplicates: 56 1 100 97 Duplicates: 75 46 I tried : list = [5...
Use count() method: lst = [56, 75, 1, 46, 100, 97, 75, 46, 46] dupes = [] unique = [] for x in lst: if lst.count(x) == 1: unique.append(x) elif x not in dupes: dupes.append(x) print('Non-duplicates:', *unique, sep='\n',) print() print('Duplicates:', *dupes, sep='\n')
3
0
75,933,279
2023-4-4
https://stackoverflow.com/questions/75933279/how-to-improve-pytroch-model
Good evening, I have 4 classes with black and white images each class has 3000 images with a test of 600 images so how to improve this model and that's my full code: data_transform = transforms.Compose([ transforms.Grayscale(num_output_channels=1), transforms.Resize(size=(150, 150)), transforms.ToTensor(), transforms.N...
As @Niccolò Borgioli mentioned, your model is overfitting the training data, so a very simple change that will most likely improve your code is adding weight decay, that modifies the loss function to include a term proportional to the norm of the weights, it makes the weighs tend to zero and reduces overfitting by avoi...
3
1
75,933,354
2023-4-4
https://stackoverflow.com/questions/75933354/self-as-function-within-class-what-does-it-do
Sorry for the poor title but I'm unsure how better to describe the question. So I recently watched Andrej Kaparthy's build GPT video which is awesome and now trying to reconstruct the code myself I notices that he uses self() as a function and was curious why and what exactly it does. The code is here and I'm curious i...
Meh, this is pytorch. Remember that you can use the model like this: model(x) to do the model.forward(x). So inside of the model class self(x) will be the basically the same as doing self.forward(x).
4
2
75,932,613
2023-4-4
https://stackoverflow.com/questions/75932613/pydantic-problem-with-declared-types-vs-response-returned-type
I will show you some minimal example: from pydantic import BaseModel class Foo(BaseModel): value: PositiveInt | None = None def some_function(self) -> PositiveInt: return self.value In above example there is problem with type of the returned value of "some_function". The "self.value" is not "PositiveInt" - its "Option...
Using dataclasses from the default library, I would separate the __init__ parameter that could be None from the field which cannot be None. from dataclasses import dataclass, field @dataclass class Foo: value1: int = field(init=False) value2: int = field(init=False) v1: InitVar[int | None] = None v2: InitVar[int | None...
3
1
75,933,081
2023-4-4
https://stackoverflow.com/questions/75933081/where-is-the-giant-cpython-switch-case-statement-moved
Not sure if it's off topic but don't know any better place to ask. In cpython there was a very giant switch case statement for executing each opcode. This switch case previously was placed in the _PyEval_EvalFrameDefault function. Here is the link. The switch case statement starts here. This was a core part of cpython ...
It's in Python/generated_cases.c.h, which gets inserted into _PyEval_EvalFrameDefault with an #include "generated_cases.c.h". As you might guess from the name, generated_cases.c.h is generated code. You can see the code generator in Tools/cases_generator/generate_cases.py
5
6
75,922,697
2023-4-3
https://stackoverflow.com/questions/75922697/anyone-know-how-to-display-a-pandas-dataframe-in-databricks
Previously I had a pandas dataframe that I could display as a table in Databricks using: df.display() Pandas was updated to v2.0.0. today and I am now getting the following error when I run df.display(): AttributeError: 'DataFrame' object has no attribute 'iteritems' Anyone know how I can resolve this? I tried runnin...
As a workaround, downgrade to pandas v1.5 %pip install --upgrade pandas==1.5 The answers provided till now used to work prior to 3rd April 2023. As of April 4, with pandas 2.0.0, you are not able to convert a Pandas DataFrame to a Spark DataFrame using the command: spark.createDataFrame(df) Using the above command l...
3
2
75,926,636
2023-4-4
https://stackoverflow.com/questions/75926636/databricks-issue-while-creating-spark-data-frame-from-pandas
I have a pandas data frame which I want to convert into spark data frame. Usually, I use the below code to create spark data frame from pandas but all of sudden I started to get the below error, I am aware that pandas has removed iteritems() but my current pandas version is 2.0.0 and also I tried to install lesser vers...
It's related to the Databricks Runtime (DBR) version used - the Spark versions in up to DBR 12.2 rely on .iteritems function to construct a Spark DataFrame from Pandas DataFrame. This issue was fixed in the Spark 3.4 that is available as DBR 13.x. If you can't upgrade to DBR 13.x, then you need to downgrade the Pandas ...
28
39
75,921,577
2023-4-3
https://stackoverflow.com/questions/75921577/murmur3-hash-compatibility-between-go-and-python
We have two different libraries, one in Python and one in Go that need to compute murmur3 hashes identically. Unfortunately no matter how hard we try, we cannot get the libraries to produce the same result. It appears from this SO question about Java and Python that compatibility isn't necessarily straight forward. Rig...
That first Python result is almost right. >>> binascii.hexlify(base64.b64decode('jns74izOYMJwsdKjacIHHA==')) b'8e7b3be22cce60c270b1d2a369c2071c' In Go: x, y := murmur3.Sum128([]byte("chocolate-covered-espresso-beans")) fmt.Printf("%x %x\n", x, y) Results in: 70b1d2a369c2071c 8e7b3be22cce60c2 So the order of the two...
4
3
75,919,967
2023-4-3
https://stackoverflow.com/questions/75919967/how-to-benchmark-a-single-function-call-in-python
How to interactively (micro)benchmark a code expression in Python (i.e. the equivalent of @btime/@benchmark in Julia) ? I would like to benchmark interactively an expression (a function call), where the number of times this expression should be evaluated depends on its computational cost / variance.... I have tried tim...
You can also use the Timer class to enable de GC, as explained in the docs here: https://docs.python.org/3/library/timeit.html#timeit.Timer.timeit And instead of explicit import every variable/function that you want to use from main, you could pass globals() in the Timer arguments. In that way, all the globals variable...
3
3
75,920,424
2023-4-3
https://stackoverflow.com/questions/75920424/how-to-ignore-rev-in-pre-commit-config
Here is a .pre-commit-config.yaml from pre-commit. It will git clone the specified rev of git repo. How can I ignore the rev and always git clone the newest? repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.3.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace
you intentionally cannot from the docs pre-commit configuration aims to give a repeatable and fast experience and therefore intentionally doesn't provide facilities for "unpinned latest version" for hook repositories. Instead, pre-commit provides tools to make it easy to upgrade to the latest versions with pre-commit ...
5
12
75,919,378
2023-4-3
https://stackoverflow.com/questions/75919378/how-to-handle-circular-imports-in-sqlalchemy
I'm having an issue with circular imports in SQLAlchemy. I have two files foo.py and bar.py. foo.py defines a SQLAlchemy class Foo, and bar.py defines a class Bar. Both Foo and Bar are each other's foreign keys, so I map them to each other with Mapped["..."] to get type safety, however that means I need to import the a...
you can use TYPE_CHECKING. This constant is False at runtime, but True when mypy (and other type-checking tools) evaluate your code from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from .bar import Bar else: Bar = "Bar" # foo.py from sqlalchemy import Column, Integer, ForeignKey fro...
6
8
75,917,750
2023-4-3
https://stackoverflow.com/questions/75917750/very-slow-aggregate-on-pandas-2-0-dataframe-with-pyarrow-as-dtype-backend
Let's say I have the following dataframe: Code Price AA1 10 AA1 20 BB2 30 And I want to perform the following operation on it: df.groupby("code").aggregate({ "price": "sum" }) I have tried playing with the new pyarrow dtypes introduced in Pandas 2.0 and I created 3 copies, and for each copy I measured ...
https://github.com/pandas-dev/pandas/issues/52070 Looks like groupby for arrow isn't implemented yet - so there's likely a arrow -> numpy happening internally leading to a loss of performance.
5
11
75,913,380
2023-4-2
https://stackoverflow.com/questions/75913380/importerror-cannot-import-name-closed-from-websockets-connection
I installed rasa on a virtual environment on windows. But while I am trying to check either rasa is installed or not, it is showing an error that says- ImportError: cannot import name 'CLOSED' from 'websockets.connection' I have reinstalled rasa, and installed websockets. But still getting the error. Python version is ...
Try installing websockets version 10.0 like this: pip install websockets==10.0 It should help (it helped me)
6
20
75,907,222
2023-4-1
https://stackoverflow.com/questions/75907222/jupyterlab-extension-gives-a-function-not-found-error
I have issues with jupyter extensions on ArchLinux. In particular, I get the following error: [W 2023-04-01 18:34:36.504 ServerApp] A `_jupyter_server_extension_points` function was not found in jupyter_nbextensions_configurator. Instead, a `_jupyter_server_extension_paths` function was found and will be used for now. ...
This is not an error, but a warning aimed at developers of notebook extensions: jupyter_nbextensions_configurator and notebook_shim respectively, not at a user like you. You do not need to do anything. It's worth pointing out that the next version of Jupyter Notebook (v7) will not require jupyter_nbextensions_configura...
8
15
75,907,394
2023-4-1
https://stackoverflow.com/questions/75907394/what-is-the-difference-between-security-and-depends-in-fastapi
This is my code: from fastapi import FastAPI, Depends, Security from fastapi.security import HTTPBearer bearer = HTTPBearer() @app.get("/") async def root(q = Security(bearer)): return {'q': q} @app.get("/Depends") async def root(q = Depends(bearer)): return {'q': q,} Both routes give precisely the same result and act...
TL;DR Use Security for security related dependencies as it is thought as a convenience for the devs. Use Depends when more general dependencies are needed. Nevertheless, you may use these two interchangeably (for security related requirements). Original answer The Security class is a more specialized version of Depends...
4
3
75,902,589
2023-3-31
https://stackoverflow.com/questions/75902589/change-the-shape-of-legend-markers-with-geopandas-geodataframe-plot
I like the convenience of the following syntax to make maps: import geopandas world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) world.plot(column='continent',legend=True,legend_kwds = {'loc':'lower left'}) However, I am looking for a way to change the shape of markers that this produces. ...
Using geopandas makes it difficult to find a way to edit the legend's properties or get hold of the legend object. Here is a way to go. First, get the axis from the plot statement: ax = world.plot( ... ) the axis provides access to all the plot components and many functions to manipulate your plot, including the legen...
3
4
75,909,463
2023-4-1
https://stackoverflow.com/questions/75909463/how-to-use-pd-melt-to-unpivot-a-dataframe-where-columns-share-a-prefix
I'm trying to unpivot my data using pd.melt but no success so far. Each row is a business, and the data contains information about the business and multiple reviews. I want my data to have every review as a row. My first 150 columns are in groups of 15, each group column name shares the same pattern reviews/n/ for 0 < ...
You can use pandas.wide_to_long() to do what you want. However, you will need to rename your columns from the pattern reviews/N/COL to reviews/COL/N (or something similar) first, as wide_to_long() can only unpivot based on prefixes, whereas in your column names, you have a prefix and a suffix. You could do this manuall...
4
6
75,908,794
2023-4-1
https://stackoverflow.com/questions/75908794/split-a-csv-file-into-multiple-files-based-on-a-pattern
I have a csv file with the following structure: time,magnitude 0,13517 292.5669,370 620.8469,528 0,377 832.3269,50187 5633.9419,3088 20795.0950,2922 21395.6879,2498 21768.2139,647 21881.2049,194 0,3566 292.5669,370 504.1510,712 1639.4800,287 46709.1749,365 46803.4400,500 I'd like to split this csv file into separate c...
With pandas, you can use groupby and boolean indexing : #pip install pandas import pandas as pd df = pd.read_csv("input_file.csv", sep=",") # <- change the sep if needed for n, g in df.groupby(df["time"].eq(0).cumsum()): g.to_csv(f"file_{n}.csv", index=False, sep=",") Output : time magnitude # <- file_1.csv 0.0000 13...
3
4
75,908,169
2023-4-1
https://stackoverflow.com/questions/75908169/generating-a-column-showing-the-number-of-distinct-values-between-consecutive-da
I have a pandas dataframe with the following format: UserId Date BookId 1 2022-07-15 10 1 2022-07-16 11 1 2022-07-16 12 1 2022-07-17 12 From this table, what I want to obtain is the number of new BookId on each consecutive day for each user. For example, based on the table above, the user read two new...
Using duplicated and a pivot_table: (df.assign(count=~df['BookId'].duplicated()) .pivot_table(index='UserId', columns='Date', values='count', aggfunc='sum') .astype(int).reset_index().rename_axis(columns=None) ) Considering only consecutive days for the duplicates: s = df.groupby(pd.to_datetime(df['Date']))['BookId']....
3
1
75,907,862
2023-4-1
https://stackoverflow.com/questions/75907862/pyside6-wsl2-importerror-libegl-so-1
I'm using isolated with poetry/venv Python: 3.11.2 with Ubuntu WSL2 22.04 python app.py Gives me the following error: Traceback (most recent call last): File "/home/lara/projects/qtapp/app.py", line 4, in <module> from PySide6.QtGui import QGuiApplication ImportError: libEGL.so.1: cannot open shared object file: No su...
You can search packages.ubuntu.com to figure out which package provides a certain file. In this case it's libegl1. Install it in WSL with: apt install libegl1
4
8
75,907,155
2023-4-1
https://stackoverflow.com/questions/75907155/is-asyncio-affected-by-the-gil
On this page I read this: Coroutines in the asyncio module are not limited by the Global Interpreter Lock or GIL. But how is this possible if both the asyncio event loop and the threading threads are running in a single Python process with GIL? As far as I understand, the impact of the GIL on asyncio will not be as s...
There are really two kinds of answers to this, depending on whether you take the GIL as the concrete implementation or the conceptual limitation. The answer is No'ish for the former, and Yes'ish for the latter. No, asyncio concurrency is not bound to the GIL. The GIL exists to synchronise thread concurrency: When more...
14
21
75,907,397
2023-4-1
https://stackoverflow.com/questions/75907397/create-a-single-column-from-a-pandas-data-frame-with-n-columns
I have a data frame with 3 columns: A, B and C as below: A: 1 2 3 B: 10 20 30 C: 100 200 300 I need to save the values only in a csv file in "one" row like this ( no need to save the column name) 1 2 3 10 20 30 100 200 300 I tried to create a new data frame with only one coumn using pandas, and transpose it, then write...
You can use unstack, to_frame and T: (df.unstack().to_frame().T .to_csv('out.csv', header=None, index=None, sep=' ') ) Or, with help of numpy's ravel: (pd.DataFrame([df.to_numpy().ravel('F')]) .to_csv('out.csv', header=None, index=None, sep=' ') ) Output file: 1 2 3 10 20 30 100 200 300
4
2
75,905,429
2023-4-1
https://stackoverflow.com/questions/75905429/django-insert-data-into-child-table-once-the-parent-record-is-created
I am using Django REST Framework and facing a problem during inserting data into the child table. There are 2 models named Card and ContactName that have the following fields. The Card has a relation with ContactName via a foreign key field name card. models.py: class Card(models.Model): image = models.ImageField(uploa...
Basically you can pass this data to your serializer by Including extra context and by overriding the create method as you are doing in your code: views.py class CardViewSet(viewsets.ModelViewSet): parser_classes = (MultiPartParser, FormParser) queryset = Card.objects.all() serializer_class = CardSerializer def create(s...
4
1
75,904,780
2023-4-1
https://stackoverflow.com/questions/75904780/takes-long-time-while-building-image-on-python-wit-messaage-building-wheel-for
i have problem while building docker image on python : below execution process takes long time around 20 minutes: Building wheel for pandas (pyproject.toml): still running... Building wheel for pandas (pyproject.toml): still running... Building wheel for pandas (pyproject.toml): still running... Building wheel for pand...
There is no building wheel for Pandas==1.4.3 and Python==3.11 so the fallback is to download the source archive (pandas-1.4.3.tar.gz) and build it from scratch. You have 2 options: Downgrade your python version from 3.11 to 3.10 in Dockerfile: FROM python:3.10.10-buster Upgrade the pandas version from 1.4.3 to 1.5....
6
9
75,901,770
2023-3-31
https://stackoverflow.com/questions/75901770/how-do-i-check-the-version-of-python-a-module-supports
I was wondering if there is a generic way to find out if your version of python is supported by a specific module? For example, let us say that I have python 3.11 installed on my computer and I want to install the modules biopython and lru-dict. Going to their respective pypi entries biopython shows this in their Proje...
No, there is no generic way. If the library has tests you can run them and check, but it might give you false positives as well as false negatives :shrug: The lru-dict has this fragment in their setup.py, which is one of the places you can check for supported versions: 'Programming Language :: C', 'Programming Languag...
4
2
75,896,790
2023-3-31
https://stackoverflow.com/questions/75896790/how-to-drop-duplicate-from-a-pandas-dataframe-with-some-complex-conditions
I am trying to drop duplicates, but based on some conditions. My dataframe looks like this: idx a b c d e f 1 1 ss1 0 25 A B 2 3 ss7 0 25 A B 3 5 ss5 0 12 C D 4 11 im3 0 12 C D 5 5 ss8 0 50 C K 6 9 im8 0 5 F G 7 8 ix6 0 5 F G Rows are considered duplicates if the values of columns d, e and f together match other recor...
Sort by b key first (everything starts by 'ss' is moved to the end) then drop duplicates from ['d', 'e', 'f'] (keep the last): out = (df.sort_values('b', key=lambda x: x.str.startswith('ss')) .drop_duplicates(['d', 'e', 'f'], keep='last').sort_index()) # OR out = (df.sort_values('b', key=lambda x: x.str.startswith('ss'...
3
3
75,891,371
2023-3-30
https://stackoverflow.com/questions/75891371/keep-only-the-value-in-the-last-non-nan-column-set-all-other-values-to-nan-fas
I want to convert df into df_target, by keeping only the value in the last non-nan column (for each row individually). The other value should be set to nan. The following code already achieves what I want, but is very slow for large DataFrames. Is there any solution that is faster? import pandas as pd data = { 'A': [1,...
Do: df.where(df.notnull().iloc[:,::-1].cumsum(axis=1).le(1), pd.NA) The idea is to count (cumsum) the non-NA (notnull) from right to left (.iloc[:,::-1]) on each row (axis=1), then mask everything with >=2 NA as NA Output: A B C 0 1 <NA> <NA> 1 2 <NA> <NA> 2 <NA> <NA> 3 3 <NA> <NA> 4 4 <NA> 5 <NA>
3
3
75,890,154
2023-3-30
https://stackoverflow.com/questions/75890154/unable-to-stream-api-response-in-flask-application-on-google-cloud-application
I'm developing a little testing website using the OpenAI API. I'm trying to stream GPT's response, just like how it's done on https://chat.openai.com/chat. This works just fine when running my Flask application on a local development server, but when I deploy this app to Google Cloud, the response is given in one go, i...
From your app.yaml, it means you're deploying to Google App Engine (GAE) Standard Environment. GAE doesn't support streaming - see doc where it says App Engine does not support streaming responses where data is sent in incremental chunks to the client while a request is being processed. All data from your code is coll...
4
4
75,889,507
2023-3-30
https://stackoverflow.com/questions/75889507/filter-and-merge-a-dataframe-in-python-using-pandas
I have a dataframe and I need to filter out who is the owner of which books so we can send them notifications. I am having trouble merging the data in the format I need. Existing dataframe Book Owner The Alchemist marry To Kill a Mockingbird john Lord of the Flies abel Catcher in the Ry marry Alabama ju...
You need to split, explode, groupby.agg: (df.assign(Owner=lambda d: d['Owner'].str.split(';')) .explode('Owner') .groupby('Owner', as_index=False, sort=False).agg(', '.join) ) NB. if you need the plural form in the column headers, add .add_suffix('s') or .rename(columns={'Book': 'Books', 'Owner': 'Owners'}). Output: ...
3
2
75,886,674
2023-3-30
https://stackoverflow.com/questions/75886674/how-to-compute-sentence-level-perplexity-from-hugging-face-language-models
I have a large collection of documents each consisting of ~ 10 sentences. For each document, I wish to find the sentence that maximises perplexity, or equivalently the loss from a fine-tuned causal LM. I have decided to use Hugging Face and the distilgpt2 model for this purpose. I have 2 problems when trying to do in a...
If the goal is to compute perplexity and then select the sentences, there's a better way to do the perplexity computation without messing around with tokens/models. Install https://huggingface.co/spaces/evaluate-metric/perplexity: pip install -U evaluate Then: perplexity = evaluate.load("perplexity", module_type="metr...
8
15
75,886,126
2023-3-30
https://stackoverflow.com/questions/75886126/how-to-filtering-pandas-dataframe-by-multiple-columns
I would like to get values from column n where values in subset of other columns is True. Example, the data frame: t, f = True, False data = [ [t, f, f, '1'], [f, f, f, '2'], [f, t, f, '3'], [f, f, t, '4'] ] df = pd.DataFrame(data, columns=list("abcn")) df as table a b c n 0 True False False 1 1 False False False 2 2...
Use any to aggregate the booleans for your boolean indexing: fcols = ("a", "b") out = df[df[[*fcols]].eq(t).any(axis=1)]#.dropna(axis=0, how='all') # dropna not needed Output: a b c n 0 True False False 1 2 False True False 3 Intermediate indexing Series: df[[*fcols]].eq(t).any(axis=1) 0 True 1 False 2 True 3 False ...
3
3
75,883,361
2023-3-30
https://stackoverflow.com/questions/75883361/python-how-to-access-dataclass-properties-in-list-of-dataclasses
Using python 3.10.4 Hi all, I'm putting together a script where I'm reading a yaml file with k8s cluster info, and I'd like to treat the loaded yaml as dataclasses so I can reference them with . properties. Example yaml: account: 12345 clusters: - name: cluster_1 endpoint: https://cluster_2 certificate: abcdef - name: ...
The dataclasses module doesn't provide built-in support for this use case, i.e. loading YAML data to a nested class model. In such a scenario, I would turn to a ser/de library such as dataclass-wizard, which provides OOTB support for (de)serializing YAML data, via the PyYAML library. Disclaimer: I am the creator and m...
3
2
75,879,765
2023-3-29
https://stackoverflow.com/questions/75879765/this-account-is-not-available-unable-to-switch-user-in-python-alpine-docker-con
I have a simple Dockerfile FROM python:3.10-alpine # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set arguments ARG USERNAME=jpg ARG USER_DIR=/home/$USERNAME ARG WORK_DIR=$USER_DIR/app # Creating a non-root user RUN adduser -S $USERNAME # Switching the user USER $USERNAME # Create a ...
You're getting the This account is not available message because running adduser -S explicitly sets the shell for the account to /sbin/nologin (because you've asked for a system account with -S, the assumption is you don't expect interactive logins for this user). You can explicitly set the shell for the named user: / ...
3
5
75,881,502
2023-3-29
https://stackoverflow.com/questions/75881502/how-can-i-reverse-direction-of-plotlys-colorbar-so-that-small-values-at-top-an
I'm currently using the colorbar on plotly to indicate the depths at which underwater SONAR receivers have been placed. Currently, the colorbar looks like this: However, I think it would make more sense if the bigger values, which indicate greater depth, should be at the bottom and the smaller numbers, which indicate ...
You can reverse the colorscale, then hardcode the tickvals by passing tickvals = [1, 1.1, ... 3.4], and make the ticktext the opposite: ticktext = ['3.4', '3.3', ... '1']. This will also require you to manually add the text " log(meters, 10)" to the topmost tick. I am not sure why, but there's this strange behavior whe...
5
2
75,881,339
2023-3-29
https://stackoverflow.com/questions/75881339/aggregate-2-subsets-of-a-dataframe-keep-original-index-use-the-first-subset
I have a dataset as such: df0 = (pd.DataFrame({'year_minor_renovation': ['2023', '2025', np.nan, '2026'], 'year_intermediate_renovation': [np.nan, '2025', '2027', '2030'], 'year_major_renovation': ['2030', np.nan, np.nan, np.nan], 'costs_minor_renovation': [1000, 3000, np.nan, 2000], 'costs_intermediate_renovation': [n...
You can use pd.wide_to_long: out = (pd.wide_to_long(df0.reset_index(), stubnames=['year', 'costs'], i='index', j='var', sep='_', suffix='.*') .dropna().astype({'year': int}) .pivot_table(index='index', columns='year', values='costs', aggfunc='sum') .rename_axis(index=None, columns=None)) out = out.reindex(columns=range...
4
4
75,874,050
2023-3-29
https://stackoverflow.com/questions/75874050/check-whether-boolean-column-contains-only-true-values
Working in Databricks, I've got a dataframe which looks like this: columns = ["a", "b", "c"] data = [(True, True, True), (True, True, True), (True, False, True)] df = spark.createDataFrame(data).toDF(*columns) df.display() I'd like to select only those columns of the dataframe in which not all values are True. In pan...
Here is one approach which follows a similar operational model to that of pandas def is_all(c): return (F.sum(F.col(c).astype('int')) == F.count(c)).alias(c) # create a boolean mask, # for e.g in pandas this would similar to df.all(axis=0) mask = df.agg(*[is_all(c) for c in columns]).collect()[0] # Use the boolean mask...
4
1
75,847,922
2023-3-26
https://stackoverflow.com/questions/75847922/how-to-do-if-and-else-in-polars-group-by-context
Update: The vectorization rules have since been formalized. The query runs as expected without warning. For a dataframe, the goal is to have the mean of a column - a group_by another column - b given the first value of a in the group is not null, if it is, just return null. The sample dataframe df = pl.DataFrame({"a":...
You can use: pl.col("a").is_null().first() instead of: pl.col("a").first().is_null() If we look at both approaches: df.group_by("b", maintain_order=True).agg( pl.col("a"), pl.col("a").is_not_null().alias("yes"), pl.col("a").first().is_not_null().alias("no"), ) shape: (2, 4) ┌─────┬───────────┬────────────────────┬...
4
4
75,818,269
2023-3-23
https://stackoverflow.com/questions/75818269/polars-fill-nulls-with-the-only-valid-value-within-each-group
Each group only has one valid or not_null value in a random row. How do you fill each group with that value? import polars as pl data = { 'group': ['1', '1', '1', '2', '2', '2', '3', '3', '3'], 'col1': [1, None, None, None, 3, None, None, None, 5], 'col2': ['a', None, None, None, 'b', None, None, None, 'c'], 'col3': [F...
The immediate way to do exactly what you asked is (and it looks the most like your pandas approach): df.with_columns(pl.exclude('group').forward_fill().backward_fill().over('group')) using pl.all() instead of pl.exclude('group') also works but it'll save some theoretical time by not making it look through the group co...
7
7
75,808,628
2023-3-22
https://stackoverflow.com/questions/75808628/python-polars-group-by-and-indexing-for-time-series-data
I have been developing some codes in pandas, yet I found the executions in pandas are a bit too slow. I then stumbled upon polars, which claims to be blazingly fast and much faster than pandas. I have thus been trying to transfer my existing codes to polars. I am currently working on some stock data, where I have to fi...
Polars has dedicated .rolling_* expressions, e.g. .rolling_min() df.with_columns(roll = pl.col("Price").rolling_min(3)) shape: (7, 3) ┌────────────┬───────┬──────┐ │ Date ┆ Price ┆ roll │ │ --- ┆ --- ┆ --- │ │ date ┆ i64 ┆ i64 │ ╞════════════╪═══════╪══════╡ │ 2023-01-01 ┆ 1 ┆ null │ │ 2023-01-02 ┆ 2 ┆ null │ │ 2023-0...
3
2
75,850,086
2023-3-26
https://stackoverflow.com/questions/75850086/tensorflow-results-are-not-reproducible-despite-using-tf-random-set-seed
According to a tutorial on Tensorflow I am following, the following code is supposed to give reproducible results, so one can check if the exercise is done correctly. Tensorflow version is 2.11.0. import tensorflow as tf import numpy as np class MyDenseLayer(tf.keras.layers.Layer): def __init__(self, n_output_nodes): s...
You see this behaviour because after TF 2.7, Keras switched to tf.random.uniform for the tf.keras.initializers.xxx, and glorot_uniform is used in self.add_weight by default. Long story short, the best thing you can do is to set seeds using tf.keras.utils.set_random_seed() or use any version below 2.7.0 and set it using...
3
5
75,867,644
2023-3-28
https://stackoverflow.com/questions/75867644/how-to-return-pydantic-object-with-a-specific-http-response-code-in-fastapi
I have an endpoint which returns a Pydantic object. However, I would like a response code other than 200 in some cases (for example if my service in not healthy). How can I achieve that with FastAPI? class ServiceHealth(BaseModel): http_ok: bool = True database_ok: bool = False def is_everything_ok(self) -> bool: retur...
You can return a Response Directly. For example, you can use JSONResponse and set the status manually: @router.get("/health") async def health() -> ServiceHealth: response = ServiceHealth() if response.is_everything_ok(): return JSONResponse(content=response.dict(), status_code=200) return JSONResponse(content=response...
3
1
75,848,964
2023-3-26
https://stackoverflow.com/questions/75848964/create-a-type-of-pair-tensor-from-cartesian-product-of-1d-array-with-itself
I have an array of strings, like arr = np.array(['A', 'B', 'B', 'B', 'C', 'C', 'C', 'C']) I want to create a torch tensor matrix with the type of pairs that will be created by cartesian product. So, the result would be a 8x8 tensor where: if the row == 'A' and column is col == 'B', then the value in a matrix is for e...
Combine meshgrid and fancy indexing Comments on the published solution There are two flaws in the approach published in the original post. First, the square root of the product of two unequal numbers can be an integer. For example, the root of 1 * 4 is two which is an integer number. Therefore, zeros will be inserted a...
4
1
75,842,787
2023-3-25
https://stackoverflow.com/questions/75842787/issues-with-saving-a-transparent-gif-using-pillow
I am using Python to create a program that can automatically make Pokemon gifs for me by using Sprite sheets from a Sprite repository. It combines animation, along with its shadow to create a sprite sheet that is then cut up into frames. The frames are assembled into GIFs which are then shown in the program, inside can...
In summary, the issue was that PIL struggles when creating gifs with frames that have transparency. The answer to my issue is the top voted answer here. Specifically the code chunk, which I will copy here: # This code adapted from https://github.com/python-pillow/Pillow/issues/4644 to resolve an issue # described in ht...
4
0
75,832,256
2023-3-24
https://stackoverflow.com/questions/75832256/how-to-get-output-from-fiona-instead-of-fiona-model-object
I'm following the examples in the docs but using Virginia's parcel shp file. Warning: it's about 1GB zipped and 1.8GB unzipped. I have very simply fiava = fiona.open("VirginiaParcel.shp/VirginiaParcel.shp", layer='VirginiaParcel') from which I can do fiava.schema to get # {'properties': {'FIPS': 'str:8', # 'LOCALITY':...
You can use fiona.model.to_dict() from fiona.model import to_dict d = to_dict(fiava[0]) if you want to serialize the data as json without calling to_dict() on each object, you can use the fiona.model.ObjectEncoder: import json from fiona.model import ObjectEncoder j = json.dumps(fiava, cls=ObjectEncoder)
4
2
75,832,713
2023-3-24
https://stackoverflow.com/questions/75832713/stable-baselines-3-support-for-farama-gymnasium
I am building an environment in the maintained fork of gym: Gymnasium by Farama. In my gym environment, I state that the action_space = gym.spaces.Discrete(5) and the observation_space = gym.spaces.MultiBinary(25). Running the environment with the agent-environment loop suggested on the Gym Basic Usage website runs wit...
I was a bit confused by the other answer here as I was sure I'd seen gymnasium in the Stable Baselines 3 docs somewhere. Sure enough, it's even in the most basic "getting started" example: https://stable-baselines3.readthedocs.io/en/master/guide/quickstart.html. However, I just tried running exactly this code and recei...
3
4
75,834,708
2023-3-24
https://stackoverflow.com/questions/75834708/filling-contours-but-leaving-contained-regions-unfilled
I have this python code that supposedly fills the contours of an image, but leaves the holes contained in it unfilled. This is what I want: But this is what I get: I've tried specifying the contour hierarchies for filling with cv2, but I can't get the result I want. This is what I've tried: import numpy as np import...
The issue is that cv2.drawContours fills the entire inner part of a closed contour, regardless if there is an inner contour. Instead of filling the contours without a parent with white, we may start with white contour, and fill the contours without a child with black. Assuming we know that the inner part should be bla...
3
2
75,853,863
2023-3-27
https://stackoverflow.com/questions/75853863/install-pytorch-version-1-0-0-using-pip-or-cuda-in-2023
I want to install the pytoch version 1.0.0, but i couldn't able to do that I tried pip install torch===1.0.0 -f https://download.pytorch.org/whl/torch_stable.html its not wotking I'm getting a error Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/ Looking in links: htt...
It seems like your Python3 version is newer (>3.7) than what the version of torch you're trying to install supports. Available versions of torch start from 1.7.1. Consider using an older version of Python3 (<=3.7). To do this, I recommend installing conda or miniconda from here. Then, run: conda create -n myenv python=...
5
4
75,853,973
2023-3-27
https://stackoverflow.com/questions/75853973/azure-app-service-app-not-in-root-directory
I have a mono repo with more than one application in it. The application I'm trying to deploy is in the directory rest_api. The deploy as seen in github actions is successful, but start-up fails. This is my start-up command gunicorn -w 1 -k uvicorn.workers.UvicornWorker main:app This is what the github actions file loo...
I found out that the problem was requirements were not in rest_api/requirements.txt but in rest_api/requirements/requirements.txt.
5
0
75,867,972
2023-3-28
https://stackoverflow.com/questions/75867972/pandas-irregular-time-series-data-compare-row-to-next-8-hours-of-rows
Right now I am using pandas to analyze call center data. The data is structured as followed: call_time = pd.to_datetime([ '2020-01-01 01:00:00', '2020-01-01 09:00:00', '2020-01-01 01:00:00', '2020-01-01 03:00:00', '2020-01-01 04:00:00', '2020-01-01 06:00:00', '2020-01-01 01:00:00', '2020-01-01 10:00:00', ]) df = pd.Da...
You can solve this with rolling windows: was_answered = df.groupby("phone_number", group_keys=True)["was_answered"] # When the call has never been answered in the previous 8 # hours, it's a return call. Since we use closed="left", if # it's the first call in 8 hours, the window is empty, its # sum is NaN and hence not ...
3
1
75,836,953
2023-3-24
https://stackoverflow.com/questions/75836953/how-to-resolve-typeerror-dispatch-model-got-an-unexpected-keyword-argument-o
After running the following code: import torch from accelerate import infer_auto_device_map, init_empty_weights from transformers import AutoConfig, AutoModelForCausalLM config = AutoConfig.from_pretrained("facebook/opt-13b") with init_empty_weights(): model = AutoModelForCausalLM.from_config(config) device_map = infer...
please try updating your accelerate package, for example pip install accelerate==0.18.0
4
2
75,851,849
2023-3-27
https://stackoverflow.com/questions/75851849/mouve-mouse-human-like-with-python-selenium-like-pptr-ghost-cursor
I try this code: Human-like mouse movements via Selenium but trying to figure out how to integrate it in a real life scraper to follow with my mouse with different DOM elements: #!/usr/bin/python # https://stackoverflow.com/questions/39422453/human-like-mouse-movements-via-selenium import os from time import sleep from...
Using pyautogui+Selenium ChromeDriver https://youtu.be/zZfPST2QS-g I think there's a better way, using Bezier curves as I do here and Selenium ActionsChains like your github links suggest, overriding class to do something like driver.move_to_element() and driver.random_mouse(), but this is working well for simple requi...
3
2
75,862,378
2023-3-28
https://stackoverflow.com/questions/75862378/plot-difference-between-two-plotly-hexbin-maps
I've seen posts relating to plotting the difference between two hexbin maps in matplotlib. I couldn't find anything executing the same process but for Plotly hexbin map box plots. If I have two separate hexbin subplots (t, y), is it possible to produce a single plot that subtracts the difference between t and y? import...
Since plotly determines the counts within each hexbin when creating the figure, you'll need to access the count data inside both fig2 and fig3. Here is the array as it's stored inside fig2.data[0]['z']: array([15., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 5., 0., 0., 0., 0...
3
3
75,864,807
2023-3-28
https://stackoverflow.com/questions/75864807/mypy-complaining-about-no-any-return-rule-being-violated-for-obvious-boolean-e
The following code throws a mypy error: from typing import Dict, Any def asd(x: Dict[str, Any]) -> bool: return x['a'] == 1 asd({"x": 2}) IMO it doesn't matter what is passed as a dict. x['a'] == 1 should always be a boolean. But mypy complains with: test.py:4: error: Returning Any from function declared to return "bo...
The __eq__ method, one of Python's rich comparison methods, does not always return True or False, it can also return NotImplemented (or other values). This is used, for example, in the case where the first type cannot compare itself with the second, so a.__eq__(b) returns NotImplemented. In that case, it then tries b._...
5
5
75,818,230
2023-3-23
https://stackoverflow.com/questions/75818230/what-is-the-best-practice-to-apply-cross-validation-using-timeseriessplit-over
Let's say I have dataset within the following pandas dataframe format with a non-standard timestamp column without datetime format as follows: +--------+-----+ |TS_24hrs|count| +--------+-----+ |0 |157 | |1 |334 | |2 |176 | |3 |86 | |4 |89 | ... ... |270 |192 | |271 |196 | |270 |251 | |273 |138 | +--------+-----+ 274 r...
Considering the argues in the comments and assist of @igrinis and found a possible solution addressed in Edit1/post2, I came up with the following implementation to: meet the declared forecasting strategy: ... training RF regressor to train-set (first 200 days\observations) and fit model over test-set (last 74 days\...
4
0
75,813,474
2023-3-22
https://stackoverflow.com/questions/75813474/im-trying-to-scrape-a-bing-dict-page-with-beautifulsoup-however-response-cont
I'm trying to scrape a Bing dict page https://cn.bing.com/dict/search?q=avengers Here is the code import requests from bs4 import BeautifulSoup url = "https://cn.bing.com/dict/search?q=avengers" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029....
A small modification to Arthur Chukhrai's answer works, by loading https://cn.bing.com/dict and then writing the text in the search box: from selenium import webdriver from selenium.webdriver.common.by import By from bs4 import BeautifulSoup import time url = "https://cn.bing.com/dict/" # Start a new Selenium web drive...
5
3
75,861,726
2023-3-28
https://stackoverflow.com/questions/75861726/multiple-callbacks-to-filter-data-dash-plotly
I'm hoping to include multiple callbacks or combine them to filter data. These functions will be used to visualise graphs. The first callback returns point data if it's within a designated region. It is assigned to a dropdown bar called area-dropdown. The dropdown bar and callback function returns smaller subsets from ...
I combined your callback functions update_dataset, date_chart and scatter_chart into a single callback. This function processes the dropdown selection, both checklists, and the radioitem components and outputs the updated scatter mapbox and bar charts. import geopandas as gpd import plotly.express as px import dash fro...
3
2
75,848,129
2023-3-26
https://stackoverflow.com/questions/75848129/how-to-apply-rate-limit-based-on-method-parameter
I'm using the python module ratelimit to throttle a function, which calls a rest api, I need to apply throttle based on the method of the requests, e.g. for PUT/POST/DELETE 1 per 10s, for GET 5 per 1s, how can I achieve this without breaking the function into two? from ratelimit import limits, sleep_and_retry @sleep_an...
You don't have to re-invent the wheel by creating your own rate limiter when ratelimit already works well. To apply different rate limits based on the method argument passed in, make a decorator that creates two ratelimit.limits-decorated functions from the given function--one decorated with arguments needed by the GET...
4
8
75,821,466
2023-3-23
https://stackoverflow.com/questions/75821466/python-render-svg-image-with-the-python-only-modules
The question is simple, but I have googled a lot of methods, and there no such solution as: import svg-render-library figure = svg-render-library.open('test.svg') figure.render() Is there any simple methods to display an SVG image using only python libraries? I am asking about rendering the SVG image without any conve...
Currently, there is no method to render natively cross-platform with just the standard library (ie. some python distributions for OSX do not include tkinter by default). Ergo, there is no good way to do this. AFAIK, there are no other ways to do this maintaining your described API without writing your own code or reach...
7
1
75,820,558
2023-3-23
https://stackoverflow.com/questions/75820558/how-to-create-a-table-with-buttons-element-in-a-column-with-pynecone
The table's last column (action) contains pc.button, that can get data in the row that the button residing in, and then send that data to a State variable. Some thing like this: name age job action John 20 Developer Update May 23 Designer Update I have tried pc.list like this: return pc.center( pc.list([ ...
https://youtube.com/shorts/u-TUSQ9DkCw <-- Example here I write the following full example for what you want. The simple answer is to use table_container. But we need to care about some detail. from pcconfig import config import pynecone as pc class Member(pc.Model, table=True): ename:str # The attribute cannot be call...
3
3
75,839,825
2023-3-25
https://stackoverflow.com/questions/75839825/how-to-prevent-transformer-generate-function-to-produce-certain-words
I have the following code: from transformers import T5Tokenizer, T5ForConditionalGeneration tokenizer = T5Tokenizer.from_pretrained("t5-small") model = T5ForConditionalGeneration.from_pretrained("t5-small") input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids sequence_ids ...
after looking at the docs found out there is a bad_words_ids parameter that you can pass in the generate() given a bad word list you can create the id list using tokenizer(bad_words, add_special_tokens=False).input_ids input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids ...
3
5
75,845,842
2023-3-26
https://stackoverflow.com/questions/75845842/is-the-default-trainer-class-in-huggingface-transformers-using-pytorch-or-tens
Question According to the official documentation, the Trainer class "provides an API for feature-complete training in PyTorch for most standard use cases". However, when I try to actually use Trainer in practice, I get the following error message that seems to suggest that TensorFlow is currently being used under the h...
It depends on how the model is trained and how you load the model. Most popular models on transformers supports both PyTorch and Tensorflow (and sometimes also JAX). from transformers import AutoTokenizer, AutoModelForSeq2SeqLM from transformers import TFAutoModelForSeq2SeqLM model_name = "google/flan-t5-large" model =...
4
5
75,866,093
2023-3-28
https://stackoverflow.com/questions/75866093/how-does-huggingfaces-zero-shot-classification-work-in-production-webapp-do-i
I have already used huggingface's zero-shot classification: I used "facebook/bart-large-mnli" model as reported here (https://huggingface.co/tasks/zero-shot-classification). The accuracy is quite good for my task. My question is about productionizing the code: In particular I would like to create a Gradio (or streamli...
Q: How does zero-shot classification work? Do I need train/tune the model to use in production? Options: (i) train the "facebook/bart-large-mnli" model first, secondly save the model in a pickle file, and then predict a new (unseen) sentence using the pickle file? or (ii) can I simply import the "facebook/bart-large-m...
4
9
75,870,293
2023-3-28
https://stackoverflow.com/questions/75870293/tkinter-share-single-frame-accross-multiple-tabs-or-dynamically-reparent
I have tkinter.Notebook that contains multiple tabs. I have tkinter.Frame "run box" with set of controls, that I want share across several tabs. Specifically Test info and Test list should have it. Currently I duplicate entire "run box" into each tab that needs it. And it works somewhat fine, but feels excessive and n...
A widget can only be in one place at a time. There is no way to share a frame among multiple notebook tabs without removing it from one tab and adding it to another when the active tab changes. If that's what you want to do, you can create the "runbox" once, and then add a container to each tab to act as a placeholder....
3
2
75,871,610
2023-3-28
https://stackoverflow.com/questions/75871610/spawning-a-new-process-with-an-asyncio-loop-from-within-the-asyncio-loop-running
I'm a little confused about the interaction between multiprocessing and asyncio. My goal is to be able to spawn async processes from other async processes. Here is a small example: import asyncio from multiprocessing import Process async def sleep_n(n): await asyncio.sleep(n) def async_sleep(n): # This does not work # ...
I think I've pinned it down. Its an issue with how multiprocessing works on Linux vs Windows/MacOS From the docs: Contexts and start methods Depending on the platform, multiprocessing supports three ways to start a process. These start methods are spawn The parent process starts a fresh Python interpreter process. Th...
4
2
75,867,636
2023-3-28
https://stackoverflow.com/questions/75867636/how-to-get-value-of-jaxlib-xla-extension-arrayimpl
Using type(z1[0]) I get jaxlib.xla_extension.ArrayImpl. Printing z1[0] I get Array(0.71530414, dtype=float32). How can I get the actual number 0.71530414? I tried z1[0][0] because z1[0] is a kind of array with a single value, but it gives me an error: IndexError: Too many indices for array: 1 non-None/Ellipsis indices ...
You can use float(x[0]) to convert x[0] to a Python float: In [1]: import jax.numpy as jnp In [2]: x = jnp.array([0.71530414]) In [3]: x Out[3]: Array([0.71530414], dtype=float32) In [4]: x[0] Out[4]: Array(0.71530414, dtype=float32) In [5]: float(x[0]) Out[5]: 0.7153041362762451 If you're interested in converting the...
4
6
75,869,481
2023-3-28
https://stackoverflow.com/questions/75869481/remove-stripes-vertical-streaks-in-remote-sensing-images
I have a remote sensing photo that has bright non continuous vertical streaks or stripes as in the pic below, my question is there a way to remove them using python and opencv or any other ip library? ,
You could just do a 7x1 median filter on the image: Input: After 7x1 median filter:
4
2
75,870,150
2023-3-28
https://stackoverflow.com/questions/75870150/convert-pandas-dataframe-to-nested-dictionary-where-key-value-pairs-are-columns
I have a pandas dataframe with 3 columns. Say it looks like this: test_df = pd.DataFrame({ 'key1': [1, 1, 1, 1, 2, 2, 2], 'key2': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], 'value': ['a-mapped', 'b-mapped', 'c-mapped', 'd-mapped', 'e-mapped', 'f-mapped', 'g-mapped'] }) > test_df key1 key2 value 0 1 a a-mapped 1 1 b b-mapped...
Try: out = test_df.groupby("key1").apply(lambda x: dict(zip(x["key2"], x["value"]))).to_dict() print(out) Prints: { 1: {"a": "a-mapped", "b": "b-mapped", "c": "c-mapped", "d": "d-mapped"}, 2: {"e": "e-mapped", "f": "f-mapped", "g": "g-mapped"}, }
3
3
75,856,310
2023-3-27
https://stackoverflow.com/questions/75856310/grouping-dataframe-by-similar-non-matching-values
If I have a pandas dataframe with the following columns: id, num, amount. I want to group the dataframe such that all rows in each group have the same id and amount and where each row's value of num has a value that is not more than 10 larger or smaller the next row's value of num. For the same id, if one row to the ne...
The logic is not fully clear, but assuming you want to start a new group when there is a gap of more than 10: close = (df.sort_values(by=['amount', 'num']) .groupby('amount') ['num'].diff().abs().gt(10).cumsum() ) for _, g in df.groupby(['amount', close]): print(g, end='\n\n') Output: id amount num 0 aaa-aaa 130 12 3...
3
4
75,858,529
2023-3-27
https://stackoverflow.com/questions/75858529/polars-rolling-count-with-temporal-window
I'm trying to write a method for a features pipeline that returns a polars expression. The method should take a column name as a string and an integer number of days. I want to perform a rolling count on that column using a window equal to the number of days. There doesn't seem to be a rolling_count expression, so I at...
As per the suggestion from @jqurious, by using .clip I was able to achieve the desired outcome without acting on the DataFrame. def temporal_rolling_count(col: str, days: int) -> pl.Expr: return ( pl.col(col).clip(1,1) .rolling_sum(window_size=f"{days}d", by="date_time") .over(col) .fill_null(0) ) EDIT I managed to pe...
3
1
75,864,073
2023-3-28
https://stackoverflow.com/questions/75864073/use-of-unstructuredpdfloader-unstructured-package-not-found-please-install-it-w
I just have a newly created Environment in Anaconda (conda 22.9.0 and Python 3.10.10). Then I proceed to install langchain (pip install langchain if I try conda install langchain it does not work). According to the quickstart guide I have to install one model provider so I install openai (pip install openai). Then I en...
Run this pip install unstructured or this pip install "unstructured[local-inference]"
12
8
75,862,628
2023-3-28
https://stackoverflow.com/questions/75862628/how-to-put-serials-in-a-data-frame-by-group
There is a data frame with a model and an item as a column below df = pd.DataFrame({'model':['A','A','A','A','A','A','A','B','B','B','B','B','B','B'], 'item':['aa','ab','ab','ab','ac','ad','ad','ba','ba','ba','bb','bb','bb','bc']}) I want to add a serial column to this data frame, but there are some rules The serial...
You want pd.factorize on item within each model group (groupby). The reset part is just a modulo away: df['serial'] = df.groupby(['model'])['item'].transform(lambda x: pd.factorize(x)[0]) % 3 Output: model item serial 0 A aa 0 1 A ab 1 2 A ab 1 3 A ab 1 4 A ac 2 5 A ad 0 6 A ad 0 7 B ba 0 8 B ba 0 9 B ba 0 10 B bb 1 ...
4
4
75,854,700
2023-3-27
https://stackoverflow.com/questions/75854700/how-to-fine-tune-a-huggingface-seq2seq-model-with-a-dataset-from-the-hub
I want to train the "flax-community/t5-large-wikisplit" model with the "dxiao/requirements-ner-id" dataset. (Just for some experiments) I think my general procedure is not correct, but I don't know how to go further. My Code: Load tokenizer and model: from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoM...
TL;DR Take some time to go through https://huggingface.co/course/ or read the https://www.oreilly.com/library/view/natural-language-processing/9781098136789/ After that, you would have answered most of the questions you're having. Show me the code: Scroll down the bottom of the answer =) What is a datasets.Dataset and...
5
12
75,860,763
2023-3-27
https://stackoverflow.com/questions/75860763/how-can-i-use-startswith-without-specifying-a-certain-string-is-there-any-alter
I would like to apply vocal_start to so many different variables and i can't handle them all and i wouldn't always repeat startswith. So I don't want to write variable1.startswith(("a", "e", "i", "o", "u")), but i would like to apply startswith(("a", "e", "i", " o", "u")) directly to all variables without specifying va...
You can get your desired form to work if you don't mind writing really obscure code. Write a class whose __eq__ does what you want and then use an instance of that class for your compare. >>> class Startswith: ... def __eq__(self, rhs): ... return rhs.startswith(('a', 'e', 'i', 'o', 'u')) ... >>> startswith = Startswit...
3
3
75,824,045
2023-3-23
https://stackoverflow.com/questions/75824045/tensorflow-m2-pro-failure
When I run the following test script for tensorflow import tensorflow as tf cifar = tf.keras.datasets.cifar100 (x_train, y_train), (x_test, y_test) = cifar.load_data() model = tf.keras.applications.ResNet50( include_top=True, weights=None, input_shape=(32, 32, 3), classes=100,) loss_fn = tf.keras.losses.SparseCategoric...
While unclear from the official Apple documentation, it looks like the tensorflow-macos version should match the tensorflow-metal plugin version from the "Releases" section. Since you are using tensorflow-macos==2.9, you should use tensorflow-metal==0.5.0 and not tensorflow-metal==0.6.0. I was able to reproduce and sol...
3
3
75,858,336
2023-3-27
https://stackoverflow.com/questions/75858336/is-there-a-better-way-to-define-multiple-boolean-variables
I have multiple Boolean variables in my code and now they are defined like this: self.paused, self.show_difficulty, self.resizable, self.high_score_saved, \ self.show_high_scores, self.show_game_modes = \ False, False, True, False, False, False And I thought of refactoring the code like this to improve readability. ui...
To group values like this, I'd recommend using a dataclass over a dictionary. This means you can still have named attributes rather than needing to do string lookups. This will allow auto-completes and static analyzers to work with your code. from dataclasses import dataclass @dataclass class UIOptions: paused: bool = ...
3
6
75,854,837
2023-3-27
https://stackoverflow.com/questions/75854837/seaborn-cumulative-sum-and-hue
I have the following dataframe in pandas: data = { 'idx': [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10], 'hue_val': ["A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","C","C","C","C","C","C","C","C","C","C",], 'value': np.random.rand(30), } df = pd.DataFrame(data) Now I...
Given OPs dataframe import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt data = { 'idx': [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10], 'hue_val': ["A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","C","C","C","C","C","C","C","C","...
3
2
75,830,063
2023-3-24
https://stackoverflow.com/questions/75830063/how-to-optimize-and-speed-up-this-matrices-multiplication-in-python
According to the gradient equation, matrices multiplication is given by where both @ and * are needed. Here is the code if readers are interested: # parameters beta = 0.98 alpha = 0.03 delta = 0.1 T = 1000 loop = 1 dif = 1 tol = 1e-8 kss = ((1 / beta - (1 - delta)) / alpha)**(1 / (alpha - 1)) k = np.linspace(0.5 * kss...
Here is some improvements: beta * Q2 is computed twice, J can be used instead the second time. J * c is also computed multiple time while it can be done once. The same for I - J. B @ (J * c) @ E and B @ (J * c @ E) are mathematically equivalent, but the later is faster in your case and can also be computed once. CPyth...
5
5
75,847,828
2023-3-26
https://stackoverflow.com/questions/75847828/the-fastest-way-to-get-all-permutations-of-a-range-without-having-consecutive-ne
I want to get all permutations of any range with length n, starting from 0 and ending on n (range(n)) that don't have consecutive numbers. Example: [0,1,2,3,4] There the permutations should look like for example [0,2,4,1,3] or [3,1,4,2,0] My current approach just gets all existing permutations and just skips these ones...
The following recursive function does the trick. It constructs only the wanted permutations. It accepts a dst argument indicating the minimum distance that must be exceeded by the next addition taken from set rem to the end of list beg. # comp_perm: complete the permutation # beg: beginning of sequence # rem: set of re...
3
2
75,845,280
2023-3-26
https://stackoverflow.com/questions/75845280/constraining-equation-that-includes-multiple-variables-at-a-boundary-using-gekko
I have a system of differential equations that I'm trying to perform some optimal control on, using Gekko. In particular, I have a point-mass orbiting a planet and would simply like to raise its orbit using modelled thrusters as control inputs. In order to set the final radial position and velocity at the new raised or...
Only variables can be directly fixed in gekko. Below are three options. I recommend trying Option 2 first and then use Option 3 if the solver can't find a solution. Option 1: Define Equations With terminal complex expressions, use a final parameter that is non-zero only at the final time point with an equation definiti...
3
1
75,842,117
2023-3-25
https://stackoverflow.com/questions/75842117/pydantic-apply-validator-on-all-fields-of-specific-type
In my project, all pydantic models inherit from a custom "base model" called GeneralModel. This enables to configure the same behavior for the entire project in one place. Let's assume the following implementation: from pydantic import BaseModel class GeneralModel(BaseModel): class Config: use_enum_values = True exclud...
Quote from the Pydantic validators documentation: a single validator can also be called on all fields by passing the special value '*' and: you can also add any subset of the following arguments to the signature (the names must match): [...] field: the field being validated. Type of object is pydantic.fields.ModelF...
3
2
75,840,780
2023-3-25
https://stackoverflow.com/questions/75840780/convert-singular-values-into-lists-when-parsing-pydantic-fields
I have an application that needs to parse some configuration. These structures often contain fields that can be either a string, or an array of strings, e.g. in YAML: fruit: apple vegetable: - tomato - cucumber However, internally I'd like to have fruit=['apple'] and vegetable=['tomato', 'cucumber'] for uniformity. I'...
Suggested approach Writing custom field validator is indeed the way to go IMHO. As a general rule, it is a good idea to define the model in terms of the schema you want at the end of the parsing process, not in terms of what you might get. We can apply a few tricks to reduce code repetition to a minimum. Firstly, we ca...
4
2
75,841,115
2023-3-25
https://stackoverflow.com/questions/75841115/issue-with-implementing-inverse-fft-for-polynoms
I am studying the FFT algorithm for fast polynomial multiplication. We went over the algorithm and I decided to try and implement it in Python. from typing import List import numpy as np def fft(p: List[int]) -> List[int]: n = len(p) if n == 1: return p unity_root = np.exp(2j * np.pi / n) p_even = p[::2] p_odd = p[1::2...
The problem is that, in ifft, you're dividing the root of unity by n. You need to divide the final result instead.
3
2
75,837,715
2023-3-24
https://stackoverflow.com/questions/75837715/how-to-format-labels-in-scientific-notation-for-bar-label
I am plotting data in a seaborn barplot. I want to label something from my pandas dataframe into the bar. I have gotten the labeling part figured out (see code to replicate below), but I still want to convert it to scientific notation. import pandas as pd d = {'name': ['experiment1','experiment2'], 'reads': [15000,1200...
As already stated, labels= supersedes fmt=, so they may not be used together. p.containers[0] → <BarContainer object of 2 artists>, which are the properties describing the bars. If using the default height (vertical bars), or width (horizontal bars), then use the fmt='%.3E' If using custom labels, the formatting must...
3
3
75,834,257
2023-3-24
https://stackoverflow.com/questions/75834257/how-to-fix-attributeerror-web3-object-has-no-attribute-tochecksumaddress
I'm trying to use 1inch oracle methods from here. This is python wrapper around 1inch apis. I want to know token price from some oracle so i'm using oracle method "get_rate_to_ETH". But in a result I have this exception: Traceback (most recent call last): File "D:\projects\1inchArb\1inch_api.py", line 20, in <module> p...
Update to latests version оf 1inch.py - 1.9, released 20 March 2023 and also web3 to use version 6.0.0. 1inch.py is using web3 as dependency. web3 removed CamelCase naming in latest version 6.0.0 1inch.py released new version to change their code and migrate to using web3, version 6.0.0.
3
2
75,827,502
2023-3-23
https://stackoverflow.com/questions/75827502/how-to-get-pydantic-model-types
Consider the following model: from pydantic import BaseModel class Cirle(BaseModel): radius: int pi = 3.14 If I run the following code, I can see the fields of this model: print(Circle.__fields__) # Output: { 'radius': ModelField(name='radius', type=int, required=True), 'pi': ModelField(name='pi', type=float, required...
You can use the type_ variable of the pydantic fields. The variable is masked with an underscore to prevent collision with the Python internal type keyword. from pydantic import BaseModel class Cirle(BaseModel): radius: int pi = 3.14 for key, value in Cirle.__fields__.items(): print(key, value.type_) # Output: # radius...
8
6
75,826,424
2023-3-23
https://stackoverflow.com/questions/75826424/python-how-do-i-get-a-new-value-every-instance-in-a-np-where
I have a data set with a column filled with 1s and 0s as such: column 1: 1 1 1 1 0 0 0 1 1 0 1 1 and I am currently using np.where() to create a new column that segments the data from column 1. The issue is, whenever it comes across a new segments of 1s I want the values in column 2 to increase by 1. n = 1 df['column2...
Cheeky one-liner: df["column2"] = df['column1'].diff().ne(0).cumsum().add(1).floordiv(2).where(df['column1'].astype(bool), other=0) df: column1 column2 0 1 1 1 1 1 2 1 1 3 1 1 4 0 0 5 0 0 6 0 0 7 1 2 8 1 2 9 0 0 10 1 3 11 1 3
4
3
75,824,594
2023-3-23
https://stackoverflow.com/questions/75824594/python-poetry-install-fails-on-typed-ast-1-5-4-how-to-overcome-the-obstacle-a
I tried to install the package using pip: pip wheel --use-pep517 "typed-ast (==1.5.4)" but it falls in the same place. What's the general approach when you walk into such kind of problems? I've found this thread, which seemed to be helpful, but it wasn't (.venv) ➜ src git:(develop) ✗ poetry install Installing dependen...
Do you install python3.11-dev? sudo apt install -y python3.11-dev or packages for compiling sudo apt install -y build-essential libssl-dev libffi-dev python3.11-dev
6
6
75,825,190
2023-3-23
https://stackoverflow.com/questions/75825190/how-to-put-iconbitmap-on-a-customtkinter-toplevel
This is the code example: class ToplevelWindow(customtkinter.CTkToplevel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.geometry("400x300") self.title("New Window") self.resizable(False, False) self.iconbitmap('icon.ico') self.after(100, self.lift) class App(customtkinter.CTk): def __init...
This is a bug of customtkinter. If you look into the source code of CTkToplevel, there is below code inside __init__(): class CTkToplevel(tkinter.Toplevel, ...): def __init__(self, ...): ... try: # Set Windows titlebar icon if sys.platform.startswith("win"): customtkinter_directory = os.path.dirname(os.path.dirname(os....
3
6
75,816,824
2023-3-22
https://stackoverflow.com/questions/75816824/implement-seek-in-read-only-gzip-stream
I have an app that seeks within a .gz file-like object. Python's gzip.GzipFile supports this, but very inefficiently – when the GzipFile object is asked to seek back, it will rewind to the beginning of the stream (seek(0)) and then read and decompress everything up to the desired offset. Needless to say this absolutely...
You could try a library called indexed_gzip, which builds on top of the zlib's zran.c utility. Essentially, this library keeps a series of checkpoints throughout the file, and when a request for a specific byte offset arrives, it starts from the nearest checkpoint. (indexed_gzip calls this an "index seek point.") Examp...
5
4
75,823,656
2023-3-23
https://stackoverflow.com/questions/75823656/create-dictionary-with-pairs-from-column-from-pandas-dataframe-using-regex
I have the following dataframe import pandas as pd df = pd.DataFrame({'Original': [92,93,94,95,100,101,102], 'Sub_90': [99,98,99,100,102,101,np.nan], 'Sub_80': [99,98,99,100,102,np.nan,np.nan], 'Gen_90': [99,98,99,100,102,101,101], 'Gen_80': [99,98,99,100,102,101,100]}) I would like to create the following dictionary ...
You can do: gen_cols = df.filter(like='Gen_').columns sub_cols = df.filter(like='Sub_').columns d = dict(zip(sorted(sub_cols), sorted(gen_cols))) d.update({g : 'Original' for g in gen_cols}) print(d) {'Sub_80': 'Gen_80', 'Sub_90': 'Gen_90', 'Gen_90': 'Original', 'Gen_80': 'Original'}
3
3
75,823,000
2023-3-23
https://stackoverflow.com/questions/75823000/modules-getattr-is-called-twice
PEP-562 introduced __getattr__ for modules. While testing I noticed this magic method is called twice when called in this form: from X import Y. file_b.py: def __getattr__(name): print("__getattr__ called:", name) file_a.py: from file_b import foo, bar output: __getattr__ called: __path__ __getattr__ called: foo __ge...
Because your __getattr__ returns None for __path__ instead of raising an AttributeError, the import machinery thinks your file_b is a package. None isn't actually a valid __path__, but all __import__ checks here is hasattr(module, '__path__'). It doesn't check the value: elif hasattr(module, '__path__'): return _handle...
3
7
75,823,194
2023-3-23
https://stackoverflow.com/questions/75823194/create-column-in-dataframe-for-each-row-in-other-dataframe-and-compute-values
I have a DataFrame called player: player_df = pd.DataFrame(np.random.rand(10,3), columns=['x','y','more_cols']) _____________________________________________________________________________ player_df: x y more_cols 0 0.352673 0.479360 0.638508 1 0.764669 0.326961 0.778483 2 0.805774 0.911662 0.316030 3 0.114446 0.18514...
If your distance function is vectorized, you can do: import numpy as np def distance(x1, y1, x2, y2): return np.sqrt((x2-x1)**2+(y2-y1)**2) tmp = checkpoints_df.set_index('checkpoint_name') for c in checkpoints_df.index: player_df[c] = distance(player_df['x'], player_df['y'], tmp.loc[c, 'x'], tmp.loc[c, 'y']) Or, full...
3
2
75,821,532
2023-3-23
https://stackoverflow.com/questions/75821532/shapely-runtimewarning-invalid-value-encountered-in-intersection
Got this warning when trying to calculate the intersection between two geometry objects. >>> shapely.intersection(LineString([(0, 0), (1, 1)], LineString([(2.5, 2.5), (3, 3)])) .../lib/python3.9/site-packages/shapely/set_operations.py:133: RuntimeWarning: invalid value encountered in intersection return lib.intersectio...
I think the warning occurs when there is no intersection at all between the two geometries, so what I did is to check if there is an intersection first with intersects() and only then calculate the intersection between them. You can then handle the case where no intersection occurs according to your application. def ge...
3
6
75,815,288
2023-3-22
https://stackoverflow.com/questions/75815288/slice-a-multidimensional-pytorch-tensor-based-on-values-in-other-tensors
I have 4 PyTorch tensors: data of shape (l, m, n) a of shape (k,) and datatype long b of shape (k,) and datatype long c of shape (k,) and datatype long I want to slice the tensor data such that it picks the element addressed by a in 0th dimension. In the 1st and 2nd dimensions, I want to pick a patch of values based ...
I would first expand the indices and then add shifts to the repeated indices. Note that the shift for the row and column should be reversed. For example, import torch data = torch.arange(200).reshape((2, 10, 10)) a = torch.Tensor([1, 0, 1, 1, 0]).long() b = torch.Tensor([5, 6, 3, 4, 7]).long() c = torch.Tensor([4, 3, 7...
3
2
75,740,652
2023-3-15
https://stackoverflow.com/questions/75740652/fastapi-streamingresponse-not-streaming-with-generator-function
I have a relatively simple FastAPI app that accepts a query and streams back the response from ChatGPT's API. ChatGPT is streaming back the result and I can see this being printed to console as it comes in. What's not working is the StreamingResponse back via FastAPI. The response gets sent all together instead. I'm re...
First, it wouldn't be good practice to use a POST request for requesting data from the server. Using a GET request instead would be more suitable, in your case. In addition to that, you shouldn't be sending credentials, such as auth_key as part of the URL (i.e., using the query string), but you should rather use Header...
37
76
75,748,777
2023-3-15
https://stackoverflow.com/questions/75748777/does-polars-preserve-row-order-in-a-left-join
Consider the following polars dataframes: >>> left = pl.DataFrame(pl.Series('a', [1,5,3,2])) >>> left shape: (4, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ 5 │ │ 3 │ │ 2 │ └─────┘ >>> right = pl.DataFrame([pl.Series('a', [0,1,2,3]), pl.Series('b', [4,5,6,7])]) >>> right shape: (4, 2) ┌─────┬─────┐ │ a ┆ b │ │ ---...
Update (November 2024): Polars has decided to no longer guarantee preserving row order in left joins in the future. More background on this decision can be found in this GitHub issue. The bottom line: this guarantee may be expensive. A new maintain_order parameter will be added in the future which allows users to contr...
5
2
75,793,219
2023-3-20
https://stackoverflow.com/questions/75793219/polars-replace-time-zone-function-throws-error-of-non-existent-in-time-zone
here's our test data to work with: import polars as pl import pandas as pd from datetime import date, time, datetime df = pl.DataFrame( pl.datetime_range( start=date(2022, 1, 3), end=date(2022, 9, 30), interval="5m", time_unit="ns", time_zone="UTC", eager=True ).alias("UTC") ) I specifically need replace_time_zone to ...
You cannot replace the timezone in a UTC time series with a timezone that has DST transitions - you'll end up with non-existing and/or missing datetimes. The error could be a bit more informative, but I do not think this is specific to polars. Here's an illustration. "America/New_York" had a DST transition on Mar 13. 2...
3
2
75,791,765
2023-3-20
https://stackoverflow.com/questions/75791765/how-to-download-videos-that-require-age-verification-with-pytube
I download and clip some youtube videos with pytube but some videos are not downloading and asking for age verification. How can I solve this? Thanks for your advice
For pytube 15.0.0 I had the AgeRestrictedError in streams contents even using the use_oauth option. I fixed the problem only replacing ANDROID_MUSIC with ANDROID as "client" at line 223 of innertube.py: def __init__(self, client='ANDROID_MUSIC', use_oauth=False, allow_cache=True): def __init__(self, client='ANDROID', u...
20
36
75,804,599
2023-3-21
https://stackoverflow.com/questions/75804599/openai-api-how-do-i-count-tokens-before-i-send-an-api-request
OpenAI's text models have a context length, e.g.: Curie has a context length of 2049 tokens. They provide max_tokens and stop parameters to control the length of the generated sequence. Therefore the generation stops either when stop token is obtained, or max_tokens is reached. The issue is: when generating a text, I d...
How do I count tokens before(!) I send an API request? As stated in the official OpenAI article: To further explore tokenization, you can use our interactive Tokenizer tool, which allows you to calculate the number of tokens and see how text is broken into tokens. Alternatively, if you'd like to tokenize text programm...
86
114
75,799,955
2023-3-21
https://stackoverflow.com/questions/75799955/how-to-do-inference-with-yolov5-and-onnx
I've trained a YOLOv5 model and it works well on new images with yolo detect.py I've exported the model to ONNX and now i'm trying to load the ONNX model and do inference on a new image. My code works but I don't get the correct bounding boxes. I need to get the area of the bounding boxes etc. so I can't just use detec...
I decided to give up and use this code : import cv2 import torch from PIL import Image # Model model = torch.hub.load(path_to_yolo_library, 'custom', path=onnx_path, source='local') img = Image.open(image_path) # PIL image img = img.resize((640,640)) # Inference results = model(img, size=640) # includes NMS # Results r...
4
0