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
69,923,305
2021-11-11
https://stackoverflow.com/questions/69923305/is-python-available-for-windows-on-arm
I know that Python is available for Mac and Linux on ARM because I have Python installed via Homebrew on Mac and it's ARM and I have Python installed via apt on Ubuntu and it's ARM. However, I can't find any download links for Python for Windows on ARM. The Windows download link on the Python website contain amd64 so i...
It will be supported starting with Python 3.11: https://bugs.python.org/issue33125 I'll probably make the ARM64 packages available through the Windows Store for 3.11's prereleases, and possibly as a side-loadable MSIX from python.org. The same ticket also mentions an unofficial build for testing purposes: https://www...
6
5
69,920,761
2021-11-10
https://stackoverflow.com/questions/69920761/how-to-hide-internal-modules-in-a-packages-namespace
My Python package, tinted, finally works. However, when I run dir(tinted), the core.py and sequences.py files exist in the package! I want only the function tint to be included in the package. Current output of dir(tinted): ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '...
Let's say you have your Python package in a folder named tinted. You have a function named tint defined in module core.py inside that folder. But you want to expose that function at the top level of the package's namespace. Which is good practice for important functions, they should be at the top level. Then in __init_...
5
2
69,918,148
2021-11-10
https://stackoverflow.com/questions/69918148/deprecationwarning-executable-path-has-been-deprecated-please-pass-in-a-servic
I started a selenium tutorial today and have run into this error when trying to run the code. I've tried other methods but ultimately get the same error. I'm on MacOS using VSC. My Code: from selenium import webdriver PATH = '/Users/blutch/Documents/Chrom Web Driver\chromedriver.exe' driver = webdriver.Chrome(PATH) dri...
This error message... DeprecationWarning: executable_path has been deprecated, please pass in a Service object ...implies that the key executable_path will be deprecated in the upcoming releases. This change is inline with the Selenium 4.0 Beta 1 changelog which mentions: Deprecate all but Options and Service argumen...
11
32
69,916,200
2021-11-10
https://stackoverflow.com/questions/69916200/get-column-as-pl-series-not-as-pl-dataframe-in-polars
I'm trying to get the column of a Dataframe as Series. df['a'] returns allways a pl.Dataframe. Right now I'm doing it this way pl.Series('GID_1',df['GID_1'].to_numpy().flatten().tolist()) I don't think that's the best way to do it. Does anyone have an idea?
I don't really understand. This snippet runs, so it returns a pl.Series. df = pl.DataFrame({ "A": [1, 2, 3], "B": [1, 2, 3] }) assert isinstance(df["A"], pl.Series)
5
8
69,914,867
2021-11-10
https://stackoverflow.com/questions/69914867/filling-up-shuffle-buffer-this-may-take-a-while
I have a dataset that includes video frames partially 1000 real videos and 1000 deep fake videos. each video after preprocessing phase converted to the 300 frames in other worlds I have a dataset with 300000 images with Real(0) label and 300000 images with Fake(1) label. I want to train MesoNet with this data. I used c...
Note that this is not an error, but a log message: https://github.com/tensorflow/tensorflow/blob/42b5da6659a75bfac77fa81e7242ddb5be1a576a/tensorflow/core/kernels/data/shuffle_dataset_op.cc#L138 It seems you may be choosing too large a dataset if it's taking too long: https://github.com/tensorflow/tensorflow/issues/3064...
6
3
69,912,744
2021-11-10
https://stackoverflow.com/questions/69912744/periodically-restart-python-multiprocessing-pool
I have a Python multiprocessing pool doing a very long job that even after a thorough debugging is not robust enough not to fail every 24 hours or so, because it depends on many third-party, non-Python tools with complex interactions. Also, the underlying machine has certain problems that I cannot control. Note that by...
The problem with your current code is that it iterates the multiprocessed results directly, and that call will block. Fortunately there's an easy solution: use apply_async exactly as suggested in the docs. But because of how you describe the use-case here and the failure, I've adapted it somewhat. Firstly, a mock task:...
5
3
69,909,234
2021-11-10
https://stackoverflow.com/questions/69909234/pandas-select-columns-based-on-row-values
I have a very large pandas.Dataframe and want to create a new Dataframe by selecting all columns where one row has a specific value. A B C D E Region Nord Süd West Nord Nord value 2.3 1.2 4.2 0.5 1.3 value2 20 400 30 123 200 Now i want to create a new DataFrame with all columns where the row "Region" has the value "N...
Use first DataFrame.loc for select all rows (:) by mask compred selected row Region by another loc: df = df.loc[:, df.loc['Region'] == 'Nord'] print (df) A D E Region Nord Nord Nord value 2.3 0.5 1.3 value2 20 123 200 Better is crated MultiIndex by first row with original columns, then is possible select by DataFrame....
6
7
69,906,944
2021-11-10
https://stackoverflow.com/questions/69906944/approaches-to-changing-language-at-runtime-with-python-gettext
I have read lots of posts about using Python gettext, but none of them addressed the issue of changing languages at runtime. Using gettext, strings are translated by the function _() which is added globally to builtins. The definition of _ is language-specific and will change during execution when the language setting ...
The only plausible, general approach is to rewrite all relevant code to not only use _ to request translation but to never cache the result. That’s not a fun idea and it’s not a new idea—you already list Refactoring and Deferred translation that rely on the cooperation of the gettext clients—but it is the “best way […]...
5
3
69,822,702
2021-11-3
https://stackoverflow.com/questions/69822702/poetry-was-not-installed-with-the-recommended-installer-cannot-update-automatic
How to I upgrade to the latest version? Specification: Windows 10, Visual Studio Code, Ubuntu Bash. Current Version: me@PF2DCSXD:/mnt/c/Users/user/Documents/GitHub/workers-python/workers/composite_key/compositekey/tests$ python3 --version Python 3.8.10 Attempt to update | poetry self update: me@PF2DCSXD:/mnt/c/User...
The error message suggests you've probably installed poetry with pip, which does not support automatic poetry updates. You should uninstall the poetry version currently installed, and reinstall it using the recommended method, which uses a custom installation script. On osx/linux, you'll just have to run curl -sSL http...
9
10
69,875,125
2021-11-7
https://stackoverflow.com/questions/69875125/find-element-by-commands-are-deprecated-in-selenium
When starting the function def run(driver_path): driver = webdriver.Chrome(executable_path=driver_path) driver.get('https://tproger.ru/quiz/real-programmer/') button = driver.find_element_by_class_name("quiz_button") button.click() run(driver_path) I'm getting errors like these: <ipython-input-27-c5a7960e105f>:6: Depr...
This error message: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead implies that the find_element_by_* commands are deprecated in the latest Selenium Python libraries. As AutomatedTester mentions: This DeprecationWarning was the reflection of the changes made with respe...
92
205
69,844,072
2021-11-4
https://stackoverflow.com/questions/69844072/why-isnt-python-newtype-compatible-with-isinstance-and-type
This doesn't seem to work: from typing import NewType MyStr = NewType("MyStr", str) x = MyStr("Hello World") isinstance(x, MyStr) I don't even get False, but TypeError: isinstance() arg 2 must be a type or tuple of types because MyStr is a function and isinstance wants one or more type. Even assert type(x) == MyStr or...
The purpose of NewType is purely for static type checking, but for dynamic purposes it produces the wrapped type. It does not make a new type at all, it returns a callable that the static type checker can see, that's all. When you do: x = MyStr("Hello World") it doesn't produce a new instance of MyStr, it returns "Hel...
8
1
69,848,969
2021-11-5
https://stackoverflow.com/questions/69848969/how-to-build-numpy-from-source-linked-to-apple-accelerate-framework
It is my understanding that NumPy dropped support for using the Accelerate BLAS and LAPACK at version 1.20.0. According to the release notes for NumPy 1.21.1, these bugs have been resolved and building NumPy from source using the Accelerate framework on MacOS >= 11.3 is now possible again: https://numpy.org/doc/stable/...
I actually attempted this earlier today and these are the steps I used: In the site.cfg file, put [accelerate] libraries = Accelerate, vecLib Build with NPY_LAPACK_ORDER=accelerate python3 setup.py build Install with python3 setup.py install Afterwards, np.show_config() returned the following blas_mkl_info: NOT ...
7
4
69,906,416
2021-11-9
https://stackoverflow.com/questions/69906416/forecast-future-values-with-lstm-in-python
This code predicts the values of a specified stock up to the current date but not a date beyond the training dataset. This code is from an earlier question I had asked and so my understanding of it is rather low. I assume the solution would be a simple variable change to add the extra time but I am unaware as to which ...
You could train your model to predict a future sequence (e.g. the next 30 days) instead of predicting the next value (the next day) as it is currently the case. In order to do that, you need to define the outputs as y[t: t + H] (instead of y[t] as in the current code) where y is the time series and H is the length of t...
8
22
69,890,200
2021-11-8
https://stackoverflow.com/questions/69890200/how-to-configure-os-specific-dependencies-in-a-pyproject-toml-file-maturin
I have a rust and python project that I am building using Maturin(https://github.com/PyO3/maturin). It says that it requires a pyproject.toml file for the python dependencies. I have a dependency of uvloop, which is not supported on windows and arm devices. I have added the code that conditionally imports these package...
The syntax for environment markers is specified in PEP 508 – Dependency specification for Python Software Packages. I will show below how to exclude uvloop as a dependency on Windows platform with a marker for platform.system() which returns: "Linux" on Linux "Darwin" on macOS "Windows" on Windows Using pyproject.tom...
10
18
69,828,508
2021-11-3
https://stackoverflow.com/questions/69828508/warning-ignoring-xdg-session-type-wayland-on-gnome-use-qt-qpa-platform-wayland
I try to use library cv2 for changing picture. In mode debug I found out that problem in function cv2.namedWindow: def run(self): name_of_window = 'Test_version' image_cv2 = cv2.imread('external_data/probe.jpg') cv2.namedWindow(name_of_window, cv2.WINDOW_NORMAL) cv2.imshow(name_of_window, image_cv2) cv2.waitKey(0) cv2....
I reverted back to Xorg from wayland and its working, no more warnings Here are the steps: Disabled Wayland by uncommenting WaylandEnable=false in the /etc/gdm3/custom.conf Add QT_QPA_PLATFORM=xcb in /etc/environment Check whether you are on Wayland or Xorg using: echo $XDG_SESSION_TYPE
24
17
69,872,686
2021-11-7
https://stackoverflow.com/questions/69872686/how-to-upload-file-from-python-flask-web-app-to-supabase-storage
I want to be able to upload a file from Flask to Supabase Storage, but it only has documentation for the javascript api link to docs. Also, I can't find any examples or any open source project that does that. Here it is my function to upload: def upload_file(self): if 'file' not in request.files: flash('No file part') ...
from storage3 import create_client url = "https://<your_supabase_id>.supabase.co/storage/v1" key = "<your api key>" headers = {"apiKey": key, "Authorization": f"Bearer {key}"} storage_client = create_client(url, headers, is_async=False) def upload_file(self): if 'file' not in request.files: flash('No file part') return...
5
1
69,870,135
2021-11-7
https://stackoverflow.com/questions/69870135/attributeerror-module-backend-interagg-has-no-attribute-figurecanvas
I am using verision 3.6.0 of matplotlib and version 2.6.3 of networkx and for some reason my code is giving me AttributeError: module 'backend_interagg' has no attribute 'FigureCanvas' as an error. Code: import networkx as nx import matplotlib.pyplot as plt import numpy as np import matplotlib G = nx.DiGraph() nodes =...
This is a fairly common issue with many causes (edited) tldr matplotlib can't find a backend that supports canvas drawing This usually happens on OSX (where tkinter might not be linked due to how OSX does applications) or linux (where tkinter might not be installed because it comes separately and not by default) try se...
5
13
69,869,534
2021-11-7
https://stackoverflow.com/questions/69869534/files-and-folders-in-google-colab
I just started using Google colab for my projects and I tried to create and parse text files. But I don't quite understand how the file directory works here. Below are my questions: On the left navigation pane (in the picture) that show the list of folders and files. Are they in my drive, if they are, where they are l...
The google colab folders are temporary and they will disappear after 8 hours I think. You need to save them to your mounted google drive location. The content folder is part of colab and will be deleted. You need to mount google drive to your Colab session. from google.colab import drive drive.mount('/content/gdrive') ...
5
11
69,834,335
2021-11-4
https://stackoverflow.com/questions/69834335/loading-yolo-invalid-index-to-scalar-variable
Getting an error for IndexError: invalid index to scalar variable on the yolo_layers line. network = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights') layers = network.getLayerNames() yolo_layers = [layers[i[0] - 1] for i in network.getUnconnectedOutLayers()] This code won't work on my Jupyter notebook but wi...
It's may caused by the different versions of cv2. The version of cv2 module with CUDA support will give you a 2-D array when calling network.getUnconnectedOutLayers(). However, the version without CUDA support will give a 1-D array. You may try to take the brackets out which closing the index 0.
9
14
69,874,192
2021-11-7
https://stackoverflow.com/questions/69874192/combined-aggregate-based-on-valid-values
I have a df with this structure: id a1_l1 a2_l1 a3_l1 a1_l2 a2_l2 a3_l2 1 1 5 3 1 2 3 2 1 5 3 1 2 3 3 2 5 3 5 5 3 4 5 5 3 5 5 3 5 5 5 2 6 5 5 2 7 5 5 2 8 2 5 2 9 3 5 1 10 3 5 1 I want to summarize in a table such that I get: l1 l2 a1 0.4 0.5 a2 1 0.5 a3 0 0 In which what I'm doing is counting how may times 5 was pre...
You can reshape to have a dataframe with MultiIndex, then perform a simple division of the (sum of the truthy values equal to 5) by not na. Finally, unstack: df2 = df.set_index('id') df2.columns = df2.columns.str.split('_', expand = True) df2 = (df2.eq(5).sum()/df2.notna().sum()).unstack() output: l1 l2 a1 0.4 0.5 a2...
7
4
69,842,280
2021-11-4
https://stackoverflow.com/questions/69842280/if-condition-with-a-dataframe
I want if the conditions are true if df[df["tg"] > 10 and df[df["tg"] < 32 then multiply by five otherwise divide by two. However, I get the following error ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). d = {'year': [2001, 2001, 2001, 2001, 2001, 2001, 2...
You can use where: df['score'] = (df['tg']*5).where(df['tg'].between(10, 32), df['tg']/5)
10
5
69,884,878
2021-11-8
https://stackoverflow.com/questions/69884878/replacing-imp-with-importlib-maintaining-old-behavior
I inherited some code that I need to rework since it is using deprecated imp module instead of importlib To test the functionality I have created a simple test script: # test.py def main(): print("main()") if __name__ == "__main__": print("__main__") main() When I run that with the old code (below as a minimal example...
Eventually I solved it like below based on https://github.com/epfl-scitas/spack/blob/a60ae07083a5744607064221a0cd48204a54394e/lib/spack/llnl/util/lang.py#L598-L625: if sys.version_info[0] == 3: if sys.version_info[1] >= 5: import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_path) mod...
6
1
69,837,716
2021-11-4
https://stackoverflow.com/questions/69837716/error-could-not-find-a-version-that-satisfies-the-requirement-busio-from-versi
When Running Installation, pip install busio Getting ERROR, ERROR: Could not find a version that satisfies the requirement busio (from versions: none) ERROR: No matching distribution found for busio Python version is 3.7.3.
There is a module called "busio" (GitHub) by Adafruit which they describe as providing “hardware-driven interfaces for I2C, SPI, UART”. This can be installed via Adafruit’s Blinka package: pip3 install adafruit-blinka
4
4
69,830,902
2021-11-3
https://stackoverflow.com/questions/69830902/poetry-installation-with-windows-wsl-not-working-ignoring-home
I have a WSL instance, Ubuntu 20.04 and I have created another Ubuntu 18.04 WSL instance. I installed Poetry on the 20.04 without issues. I am trying to install Poetry on the Ubuntu 18.04 instance, using the curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python3 - command. At th...
That was because bash didn't knew where to look for the bin so it found only the Windows executable (PATH is shared between wsl and windows) to solve it you needed to add the following to your ~/.bashrc (preferably on top) export PATH="$HOME/.poetry/bin:$PATH" With the new installer (poetry 1.1.7 onward) the Bin path ...
5
13
69,864,793
2021-11-6
https://stackoverflow.com/questions/69864793/efficient-summation-in-python
I am trying to efficiently compute a summation of a summation in Python: WolframAlpha is able to compute it too a high n value: sum of sum. I have two approaches: a for loop method and an np.sum method. I thought the np.sum approach would be faster. However, they are the same until a large n, after which the np.sum ha...
(fastest methods, 3 and 4, are at the end) In a fast NumPy method you need to specify dtype=np.object so that NumPy does not convert Python int to its own dtypes (np.int64 or others). It will now give you correct results (checked it up to N=100000). # method #2 start=time.time() w=np.arange(0, n+1, dtype=np.object) res...
32
21
69,875,694
2021-11-7
https://stackoverflow.com/questions/69875694/pip-failed-to-build-package-cytoolz
I'm trying to install eth-brownie using 'pipx install eth-brownie' but I get an error saying pip failed to build package: cytoolz Some possibly relevant errors from pip install: build\lib.win-amd64-3.10\cytoolz\functoolz.cp310-win_amd64.pyd : fatal error LNK1120: 1 unresolved externals error: command 'C:\\Program Files...
Managed to get it working with python 3.10.1 on Win10 x64 installing cython and cytoolz first: python -m pip install --user cython python -m pip install --user cytoolz python -m pip install --user eth-brownie https://github.com/eth-brownie/brownie/issues/1315
8
9
69,894,628
2021-11-9
https://stackoverflow.com/questions/69894628/scipy-stats-bootstrap-not-importing-python
I have tried pip install scipy and everything appears fine, going through the path I opened the files and couldn't find any mention of the bootstrap library despite it being on their website: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bootstrap.html After looking on Github https://github.com/scipy...
I had this issue and solved it by re-installing the scipy package with pip install -U scipy in order to upgrade to version 1.7
4
6
69,818,376
2021-11-3
https://stackoverflow.com/questions/69818376/localhost5000-unavailable-in-macos-v12-monterey
I cannot access a web server on localhost port 5000 on macOS v12 (Monterey) (Flask or any other). E.g., use the built-in HTTP server, I cannot get onto port 5000: python3 -m http.server 5000 ... (stack trace) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 466, in server_bin...
macOS Monterey introduced AirPlay Receiver running on port 5000. This prevents your web server from serving on port 5000. Receiver already has the port. You can either: turn off AirPlay Receiver, or; run the server on a different port (normally best). Turn off AirPlay Receiver Go to System Preferences → Sharing → Unt...
55
154
69,860,233
2021-11-5
https://stackoverflow.com/questions/69860233/cant-install-python-package-on-alpine-docker-anymore
I have a problem that started very recently. The Docker Alpine Python library is not installable any more: apk update && apk upgrade && apk add python fetch https://dl-cdn.alpinelinux.org/alpine/v3.14/main/x86_64/APKINDEX.tar.gz fetch https://dl-cdn.alpinelinux.org/alpine/v3.14/community/x86_64/APKINDEX.tar.gz v3.14.2...
You are trying to use the python (alias) library instead of python3. Try to use apk update && apk upgrade && apk add python3 instead.
20
26
69,876,843
2021-11-7
https://stackoverflow.com/questions/69876843/importerror-cannot-import-name-dcc-from-partially-initialized-module-dash
I'm very new to python/dash/plotly and I keep getting the same error: ImportError: cannot import name 'dcc' from partially initialized module 'dash' (most likely due to a circular import) Does anyone know how to fix this? I've imported the following: from dash import dcc from dash import html from dash.dependencies i...
"most likely due to a circular import": this is probably due to your file being named as a dash or as a module name. But I got the error message ImportError: cannot import name 'dcc' from 'dash' For me reinstalling dash fixed the issue. pip3 uninstall dash pip3 install dash
4
11
69,888,603
2021-11-8
https://stackoverflow.com/questions/69888603/how-to-find-peaks-of-fft-graph-using-python
I am using Python to perform a Fast Fourier Transform on some data. I then need to extract the locations of the peaks in the transform in the form of the x-values. Right now I am using Scipy's fft tool to perform the transform, which seems to be working. However, when i use Scipy's find_peaks I only get the y-values, n...
There seem to be two points of confusion here: What find_peaks is returning. How to interpret complex values that the FFT is returning. I will answer them separately. Point #1 find_peaks returns the indices in "a" that correspond to peaks, so I believe they ARE values you seek, however you must plot them differently....
6
7
69,830,431
2021-11-3
https://stackoverflow.com/questions/69830431/how-to-use-python3-10-on-ubuntu
I have installed Python 3.10 from deadsnakes on my Ubuntu 20.04 machine. How to use it? python3 --version returns Python 3.8.10 and python3.10 -m venv venv returns error (I've installed python3-venv as well).
python3.10 --version will work. python3-venv is for 3.8, so install python3.10-venv. For reference: deadsnakes packages for 3.10 for Focal.
9
6
69,888,695
2021-11-8
https://stackoverflow.com/questions/69888695/how-to-alias-generic-types-for-decorators
Consider the example of a typed decorator bound to certain classes. import unittest from typing import * T = TypeVar("T", bound=unittest.TestCase) def decorate(func: Callable[[T], None]) -> Callable[[T], None]: def decorated_function(self: T) -> None: return func(self) return decorated_function Now I even have a gener...
As in many cases, when Callable is too limited use a Protocol instead: class TD(Protocol): """Type of any callable `(T -> None) -> (T -> None)` for all `T`""" def __call__(self, __original: Callable[[T], None]) -> Callable[[T], None]: ... TD is not a generic type and thus does not need "filling in" a type variable. It...
11
3
69,853,699
2021-11-5
https://stackoverflow.com/questions/69853699/finding-weekly-combinations-of-items-bought-together-using-pandas-groupby
I have a df: date category subcategory order_id product_id branch 2021-05-04 A aa 10 5 web 2021-06-04 A dd 10 2 web 2021-05-06 B aa 18 3 shop 2021-07-06 A aa 50 10 web 2021-07-06 C cc 10 15 web 2021-07-05 A ff 101 30 shop 2021-10-04 D aa 100 15 shop I am trying to answer a question which items categories and subcatego...
This is what you need: import pandas as pd import numpy as np from datetime import timedelta from datetime import datetime as dt # df=pd.read_excel('demo.xlsx') df['date']=pd.to_datetime(df['date']) df['date']=df['date'].dt.strftime('%Y-%m-%d') df['date']=pd.to_datetime(df['date']) df['year_week'] = df['date'].dt.strft...
9
5
69,883,423
2021-11-8
https://stackoverflow.com/questions/69883423/google-business-profile-api-readmask
After the deprecation of my discovery url, I had to make some change on my code and now I get this error. googleapiclient.errors.HttpError: <HttpError 400 when requesting https://mybusinessbusinessinformation.googleapis.com/v1/accounts/{*accountid*}/locations?filter=locationKey.placeId%3{*placeid*}&readMask=paths%3A+%...
You have not set the readMask correctly. I have done a similar task in Java and Google returns the results. readMask is a String type, and what I am going to provide you in the following line includes all fields. You can omit anyone which does not serve you. I am also writing the request code in Java, maybe it can help...
4
7
69,852,812
2021-11-5
https://stackoverflow.com/questions/69852812/how-to-add-a-percentage-computation-in-pandas-result
I have the following working code. I need to add a percentage column to monitor changes. I dont know much on how to do it in pandas. I need ideas on what part needs to be modified. import pandas as pd dl = [] with open('sampledata.txt') as f: for line in f: parts = line.split() # Cleaning data here.. Conversions to int...
You can add the following lines just after your code: The function compute_percentage() is using the list variable dl. def compute_percentage(row): vl = [float(parts[1]) for parts in dl if parts[0] == row['col1']] i = round(100. * (vl[-1]-vl[0])/vl[0] if vl[0] != 0 else 0, 2) if float(int(i)) == i: i = int(i) return st...
7
1
69,849,870
2021-11-5
https://stackoverflow.com/questions/69849870/typeerror-load-missing-1-required-positional-argument-loader
I am trying to run this github repo found at this link: https://github.com/HowieMa/DeepSORT_YOLOv5_Pytorch After installing the requirements via pip install -r requirements.txt. I am running this in a python 3.8 virtual environment, on a dji manifold 2g which runs on an Nvidia jetson tx2. The following is the terminal ...
Try this: yaml.load(fo.read(), Loader=yaml.FullLoader) It seems that pyyaml>=5.1 requires a Loader argument.
4
17
69,906,075
2021-11-9
https://stackoverflow.com/questions/69906075/is-it-possible-to-maintain-type-information-when-unpacking-object-attributes
Imagine I have an object which is an instance of a class such as the following: @dataclass class Foo: bar: int baz: str I'm using dataclasses for convenience, but in the context of this question, there is no requirement that the class be a dataclass. Normally, if I want to unpack the attributes of such an object, I mu...
As juanpa.arrivillaga has pointed out, the assignment statements docs indicate that, in the case that the left hand side of an assignment statement is a comma separated list of one or more targets, The object must be an iterable with the same number of items as there are targets in the target list, and the items are a...
7
1
69,906,411
2021-11-9
https://stackoverflow.com/questions/69906411/create-a-new-column-in-a-pandas-dataframe-from-existing-column-names
I want to deconstruct a pandas DataFrame, using column headers as a new data-column and create a list with all combinations of the row index and columns. Easier to show than explain: index_col = ["store1", "store2", "store3"] cols = ["January", "February", "March"] values = [[2,3,4],[5,6,7],[8,9,10]] df = pd.DataFrame(...
df.unstack().swaplevel().reset_index().values.tolist() #OR df.reset_index().melt(id_vars="index").values.tolist() # [['store1', 'January', 2], # ['store2', 'January', 5], # ['store3', 'January', 8], # ['store1', 'February', 3], # ['store2', 'February', 6], # ['store3', 'February', 9], # ['store1', 'March', 4], # ['stor...
11
10
69,903,636
2021-11-9
https://stackoverflow.com/questions/69903636/how-can-i-load-a-model-in-pytorch-without-having-to-remember-the-parameters-used
I am training a model in pytorch for which I have made a class like so: from torch import nn class myNN(nn.Module): def __init__(self, dense1=128, dense2=64, dense3=32, ...): self.MLP = nn.Sequential( nn.Linear(dense1, dense2), nn.ReLU(), nn.Linear(dense2, dense3), nn.ReLU(), nn.Linear(dense3, 1) ) ... In order to sav...
Indeed serializing the whole Python is quite a drastic move. Instead, you can always add user-defined items in the saved file: you can save the model's state along with its class parameters. Something like this would work: First save your arguments in the instance such that we can serialize them when saving the model:...
5
13
69,904,141
2021-11-9
https://stackoverflow.com/questions/69904141/change-marker-style-by-a-dataframe-column-categorical-in-seaborn-stripplot
I was looking to visualise a categorical variable as marker style in seaborn stripplot, but it does not seem to be possible easily. Is there an easy way to do this. For example, I'm trying to run this code tips = sns.load_dataset("tips") sns.stripplot(x="day", y="total_bill", hue="time", style="sex", jitter=True, data=...
sns.relplot is a figure-level function which relies on the axes-level function sns.scatterplot. sns.scatterplot has a parameter x_jitter which unfortunately currently has no effect (seaborn 0.11.2). You can mimic the functionality by grasping the positions of the points, add some random jitter and assigning these posit...
4
5
69,900,954
2021-11-9
https://stackoverflow.com/questions/69900954/when-creating-a-seaborn-heatmap-could-not-convert-string-to-float-valueerror
Hi everyone I have the following dataframe and I want to create heatmap from it with the following code. plt.figure(figsize=(10,10)) g = sns.heatmap( top_5_stations_hourly_total_traffic_by_time, square=True, cbar_kws={'fraction' : 0.01}, cmap='OrRd', linewidth=1 ) g.set_xticklabels(top_5_stations_hourly_total_traffic_...
pivot your data before calling heatmap: df_heatmap = df.pivot("STATION", "TIME", "HOURLY_TOTAL_TRAFFIC") >>> sns.heatmap(df_heatmap)
5
3
69,840,389
2021-11-4
https://stackoverflow.com/questions/69840389/what-functions-or-modules-require-contiguous-input
As I understand, you need to call tensor.contiguous() explicitly whenever some function or module needs a contiguous tensor. Otherwise you get exceptions like: RuntimeError: invalid argument 1: input is not contiguous at .../src/torch/lib/TH/generic/THTensor.c:231 (E.g. via.) What functions or modules require contiguo...
After additional digging under the hood through source_code, it seems that view is the only function that explicitly causes an exception when a non-contiguous input is passed. One would expect any operation using Tensor Views to have the potential of failing with non-contiguous input. In reality, it seems to be the cas...
6
3
69,898,774
2021-11-9
https://stackoverflow.com/questions/69898774/how-to-update-multiple-objects-in-django
I'd like to update more than one objects at same time, when the register date achieve more than 6 days: The Idea is update all issue_status from 'On Going' to 'Pending' for each objects Is it necessary iterate it? Below is my current code and error: models.py class MaintenanceIssue(models.Model): issue_status = models....
at: on_going_issues = MaintenanceIssue.objects.get(issue_status='On Going') if on_going_issues.pending_issue > 6: on_going_issues.issue_status = 'Pending' on_going_issues.save() should filter by the field and then loop through each on_going_issues = MaintenanceIssue.objects.filter(issue_status='On Going') for one in o...
4
0
69,898,015
2021-11-9
https://stackoverflow.com/questions/69898015/unexpected-type-warning-raised-with-list-in-pycharm
Right to the point, here below is the sample code which will raise error in PyCharm: list1 = [0] * 5 list1[0] = '' list2 = [0 for n in range(5)] list2[0] = '' PyCharm then return an error on both line 2 and line 4 as below: Unexpected type(s):(int, str)Possible type(s):(SupportsIndex, int)(slice, Iterable[int]) Runni...
In your case PyCharm sees you first line and thinks that the type of list is List[int]. I mean it is a list of integers. You may tell that you list is not int-typed and can accept any value this way: from typing import Any, List list1: List[Any] = [0] * 5 list1[0] = '' I used typing module just to explain the idea. He...
5
7
69,897,460
2021-11-9
https://stackoverflow.com/questions/69897460/how-to-make-matplotlib-markers-colorblind-friendly-in-a-simple-way
Currently I'm using command plt.errorbar(X,Y,yerr=myYerr, fmt="o", alpha=0.5,capsize=4) and I get default marker colours: But what should I do to force matplotlib to be more colorblind-friendly?
According to this [1] you can use the predefined colorblind style. It should be as simple as: import matplotlib.pyplot as plt plt.style.use('tableau-colorblind10') [1] https://matplotlib.org/stable/users/prev_whats_new/whats_new_2.2.html#new-style-colorblind-friendly-color-cycle Check out the last image from this link...
6
9
69,879,246
2021-11-8
https://stackoverflow.com/questions/69879246/no-module-named-wtforms-compat
While we are trying to execute with python 3.6.8 version getting below module error from wtforms.compat import string_types, text_type ModuleNotFoundError: No module named 'wtforms.compat' when i tried installing or upgrading wtforms still it shows the same error Can any one pls suggest
Noticed this error today while running our Airflow 1.10.12 builds: from wtforms.compat import text_type ModuleNotFoundError: No module named 'wtforms.compat' Apparently, the issue has to do with the latest version of wtforms released yesterday (3.0.0). We managed to get around it by pinning it to the previous version:...
20
35
69,879,919
2021-11-8
https://stackoverflow.com/questions/69879919/how-to-add-stretch-for-qgridlayout-in-pyqt5
I created widgets in a grid-layout. The widgets are stretching based on the window. Is it possible to avoid the stretching and align them as shown in picture below? I created a code to achieve this, but I feel it is not a straightforward solution. If there are any better solutions to achieve this, please share them. Gr...
The QGridLaout class doesn't have any simple convenience methods like QBoxLayout.addStretch() to do this. But the same effect can be achieved by adding some empty, stretchable rows/columns, like this: GL.setRowStretch(GL.rowCount(), 1) GL.setColumnStretch(GL.columnCount(), 1)
4
8
69,886,443
2021-11-8
https://stackoverflow.com/questions/69886443/error-in-python-using-wikipedia-module-wikipedia-exceptions-pageerror-page-id
newbie in Python here when I run this simple code (to load Harry Potter page and simply print it) it returns me Error with the wrong name I wanted to search (harry plotter) can anyone tell me how to fix? thank you! import wikipedia page = wikipedia.page("Harry Potter") print(page.summary) Error message: Traceback (mos...
This appears to be a strange result of auto_suggest being set by default. If you do wikipedia.page("Harry Potter", auto_suggest=False) It works fine. Otherwise it autocompletes potter to plotter, hence the error.
6
13
69,875,734
2021-11-7
https://stackoverflow.com/questions/69875734/how-to-hide-dataframe-index-on-streamlit
I want to use some pandas style resources and I want to hide table indexes on streamlit. I tryed this: import streamlit as st import pandas as pd table1 = pd.DataFrame({'N':[10, 20, 30], 'mean':[4.1, 5.6, 6.3]}) st.dataframe(table1.style.hide_index().format(subset=['mean'], decimal=',', precision=2).bar(subset=['mean']...
Documentation for st.dataframe shows "Styler support is experimental!" and maybe this is the problem. But I can get table without index if I use .to_html() and st.write() import streamlit as st import pandas as pd df = pd.DataFrame({'N':[10, 20, 30], 'mean':[4.1, 5.6, 6.3]}) styler = df.style.hide_index().format(subset...
9
5
69,882,397
2021-11-8
https://stackoverflow.com/questions/69882397/check-if-string-is-in-another-column-pandas
Below is my DF df= pd.DataFrame({'col1': ['[7]', '[30]', '[0]', '[7]'], 'col2': ['[0%, 7%]', '[30%]', '[30%, 7%]', '[7%]']}) col1 col2 [7] [0%, 7%] [30] [30%] [0] [30%, 7%] [7] [7%] The aim is to check if col1 value is contained in col2 below is what I've tried df['test'] = df.apply(lambda x: str(x.col1) in str(x.col2...
You can also replace the square brackets with word boundaries \b and use re.search like in import re #... df.apply(lambda x: bool(re.search(x['col1'].replace("[",r"\b").replace("]",r"\b"), x['col2'])), axis=1) # => 0 True # 1 True # 2 False # 3 True # dtype: bool This will work because \b7\b will find a match in [0%, ...
6
2
69,868,258
2021-11-6
https://stackoverflow.com/questions/69868258/how-to-pass-pandas-dataframe-to-airflow-tasks
I'm learning how to use airflow to build machine learning pipeline. But didn't find a way to pass pandas dataframe generated from 1 task into another task... It seems that need to convert the data to JSON format or save the data in database within each task? Finally, I had to put everything in 1 task... Is there anyway...
Although it is used in many ETL tasks, Airflow is not the right choice for that kind of operations, it is intended for workflow not dataflow. But there are many ways to do that without passing the whole dataframe between tasks. You can pass information about the data using xcom.push and xcom.pull: a. Save the outcome o...
11
17
69,880,739
2021-11-8
https://stackoverflow.com/questions/69880739/numpy-concatenate-behaviour-how-to-concatenate-example-correctly
I have following multi-dimensional array: windows = array([[[[[[0., 0.], [1., 0.]], [[0., 0.], [1., 0.]], [[0., 0.], [1., 0.]]], [[[0., 1.], [0., 0.]], [[0., 1.], [0., 0.]], [[1., 0.], [0., 0.]]], [[[1., 0.], [0., 0.]], [[0., 1.], [0., 0.]], [[0., 1.], [0., 0.]]]]]]) print(windows.shape) (1, 1, 3, 3, 2, 2) # (n, d, a, ...
IIUC, you want to merge dimensions 2+4 and 3+5, an easy way would be to swapaxes 4 and 5 (or -3 and -2), and reshape to (1,1,6,6): windows.swapaxes(-2,-3).reshape(1,1,6,6) output: array([[[[0., 0., 0., 0., 0., 0.], [1., 0., 1., 0., 1., 0.], [0., 1., 0., 1., 1., 0.], [0., 0., 0., 0., 0., 0.], [1., 0., 0., 1., 0., 1.], ...
5
2
69,854,335
2021-11-5
https://stackoverflow.com/questions/69854335/optimize-the-calculation-of-horizontal-and-vertical-adjacency-using-numpy
I have following cells: cells = np.array([[1, 1, 1], [1, 1, 0], [1, 0, 0], [1, 0, 1], [1, 0, 0], [1, 1, 1]]) and I want to calculate horizontal and vertical adjacencies to come to this result: # horizontal adjacency array([[3, 2, 1], [2, 1, 0], [1, 0, 0], [1, 0, 1], [1, 0, 0], [3, 2, 1]]) # vertical adjacency array([[...
I had a really quick attempt at this with Numba but have not checked it too thoroughly though the results seem about right: #!/usr/bin/env python3 # https://stackoverflow.com/q/69854335/2836621 # magick -size 1920x1080 xc:black -fill white -draw "circle 960,540 960,1040" -fill black -draw "circle 960,540 960,800" a.png...
6
4
69,879,845
2021-11-8
https://stackoverflow.com/questions/69879845/how-to-plot-my-pandas-dataframe-in-matplotlib
I have the following code: import matplotlib.pyplot as plt import numpy as np import pandas as pd data = pd.read_csv("Ari_atlag.txt", sep = '\t', header = 0) #Num_array = pd.DataFrame(data).to_numpy() print(data.head()) data.plot() #data.columns = ['Date', 'Number_of_test', 'Avarage_of_ARI'] #print(Num_array) plt.show(...
Use x='Date' as parameter of plot: df.plot(x='Date') plt.show()
5
4
69,876,148
2021-11-7
https://stackoverflow.com/questions/69876148/is-there-an-efficient-way-to-compare-two-dataframes-of-different-sizes
I found this post, but it's not quite my scenario. Is there an efficient way of comparing two data frames The reason I want to compare two dataframes is that I am looking for changes that may have occured. (Think "audit"). The two frames have exactly the same column layout, just that one may have more or less rows than...
Use compare after merge your 2 dataframes on ID and Period: out = pd.merge(df1, df2, on=['ID', 'Period'], how='outer', suffixes=('_df1', '_df2')).set_index(['ID', 'Period']) out.columns = pd.MultiIndex.from_tuples(out.columns.str.split('_').map(tuple)) \ .swaplevel() out = out['df1'].compare(out['df2']) Output: >>> ou...
4
7
69,876,305
2021-11-7
https://stackoverflow.com/questions/69876305/pytorch-automatically-determine-the-input-shape-of-linear-layer-after-conv1d
I want to build a model with several Conv1d layers followed by several Linear layers. Conv1d layers will work for data of any given length, the problem comes at the first Linear layer, because the data length is unknown at initialization time. Every time the length of the input data changes, the output size of Conv1d l...
You can use the builtin nn.LazyLinear which will find the in_features on the first inference and initialize the appropriate number of weights accordingly: linear = nn.LazyLinear(out_features)
6
11
69,875,073
2021-11-7
https://stackoverflow.com/questions/69875073/confusion-matrix-valueerror-classification-metrics-cant-handle-a-mix-of-binary
I'm currently trying to make a confusion matrix for my neural network model, but keep getting this error: ValueError: Classification metrics can't handle a mix of binary and continuous targets. I have a peptide dataset that I'm using with 100 positive and 100 negative examples, and the labels are 1s and 0s. I've conve...
The model outputs the predicted probabilities, you need to transform them back to class labels before calculating the classification metrics, see below. import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout from sklearn.datasets impo...
4
8
69,871,651
2021-11-7
https://stackoverflow.com/questions/69871651/yt-dlp-rate-limit-not-throttiling-speed-in-python-script
I have implemented yt-dlp as part of my Python script, it works well, but I am unable to get the rate-limit feature to work. If you run the same command from the CLI the rate is limited correctly, is anyone able to tell me the correct syntax? I have tried several combinations such as rate-limit, limit-rate 0.5m, 500k, ...
Looking at the source code you'll find that the option you're looking for is called ratelimit. Its value should be a float: ydl_opts = { 'ratelimit': 500000 } with yt_dlp.YoutubeDL(params=ydl_opts) as ydl: ydl.download([link])
5
2
69,873,513
2021-11-7
https://stackoverflow.com/questions/69873513/using-set-params-function-for-linearregression
I recently started working on Machine Learning with Linear Regression. I have used a LinearRegression (lr) to predict some values. Indeed, my predictions were bad, and I was asked to change the hyperparameters to obtain better results. I used the following command to obtain the hyperparameters: lr.get_params().keys() l...
The correct syntax is set_params(**params) where params is a dictionary containing the estimator's parameters, see the scikit-learn documentation. from sklearn.linear_model import LinearRegression reg = LinearRegression() reg.get_params() # {'copy_X': True, # 'fit_intercept': True, # 'n_jobs': None, # 'normalize': Fals...
5
3
69,866,838
2021-11-6
https://stackoverflow.com/questions/69866838/modulenotfounderror-no-module-named-mxnet
I have been looking for the solution for this error for a whole morning. I created an separate environment for python 3.6 and I still got this error. I am using anacondas. So i am so frustrated. ModuleNotFoundError: No module named 'mxnet' from gluonts.model.deepar import DeepAREstimator from gluonts.trainer import Tr...
Conda is more usable when we want to install something that is not written in python. It is not the case in Mxnet. I would suggest using pip install for libraries in python. You may take a look at this link to better understand how to use conda environments. What is the difference between pip and conda? Also here's the...
4
2
69,866,469
2021-11-6
https://stackoverflow.com/questions/69866469/subtract-two-xarrays-while-keeping-all-dimensions
this might be the most basic question out there but I just could not find a solution. I have two different xarrays containing wind data. Both xarrays have the dimensions (time: 60, plev: 19, lat: 90). I now need to take the difference between the two xarrays over all dimensions to find the anomaly between the two scena...
The quick answer is that you're doing it right, but your dimensions are not aligned. xarray IS designed to subtract entire arrays, but the coordinate labels must be aligned exactly. You likely have a disagreement between elements of your plev coordinate, which you can check with xr.align: xr.align(wind1_array, wind2_ar...
5
10
69,858,906
2021-11-5
https://stackoverflow.com/questions/69858906/select-priority-item-from-list
Say I have a descending ordered list in terms of preference: person_choice = ['amy', 'bob', 'chad', 'dan', 'emily'] meaning, amy is preferred to bob, who is preferred to chad and so on. And I have a couple more lists like these (with names appearing in no particular order and list length): group1 = ['joyce', 'amy', 'e...
Using max with a custom key: person_choice = ['amy', 'bob', 'chad', 'dan', 'emily'] group1 = ['joyce', 'amy', 'emily', 'karen', 'rebecca'] group2 = ['chad', 'kyle', 'michael', 'neo', 'bob'] def choice(group): return max(group, key=lambda name: -person_choice.index(name) if name in person_choice else float('-inf')) prin...
4
5
69,856,889
2021-11-5
https://stackoverflow.com/questions/69856889/why-is-the-class-variable-not-updating-for-all-its-instances
I'm learning about classes and don't understand this: class MyClass: var = 1 one = MyClass() two = MyClass() print(one.var, two.var) # out: 1 1 one.var = 2 print(one.var, two.var) # out: 2 1 I thought that class variables are accessible by all instances, why is the Class variable not updating for all its instances?
It doesn't change for all of them because doing this: one.var = 2, creates a new instance variable with the same name as the class variable, but only for the instance one. After that, one will first find its instance variable and return that, while two will only find the class variable and return that. To change the cl...
5
4
69,843,204
2021-11-4
https://stackoverflow.com/questions/69843204/how-to-type-a-variable-in-fastapi-swaggerui-with-hyphen-in-its-name
If I send a request to this API: from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Response(BaseModel): var_name: str @app.put("/", response_model=Response) def simple_server(a: str): response = Response(var_name=a) return response I get a response which this json file {"var_name1": "a"}...
Modify your pydantic object slightly: from pydantic import BaseModel, Field class Response(BaseModel): var_name: str = Field(alias="var-name") class Config: allow_population_by_field_name = True The allow_population_by_field_name option is needed to allow creating object with field name, without it you could instantia...
5
11
69,849,956
2021-11-5
https://stackoverflow.com/questions/69849956/python-how-to-process-complex-nested-dictionaries-efficiently
I have a complex nested dictionary structured like this: example = { ('rem', 125): { ('emo', 35): { ('mon', 133): { ('ony', 33): 0 }, ('mor', 62): { ('ore', 23): 0 }, ('mot', 35): { ('ote', 22): 0 }, ('mos', 29): { ('ose', 29): 0 } }, ('emi', 32): { ('min', 109): { ('ine', 69): 0 }, ('mit', 58): { ('ite', 64): 0, ('ity...
I was able to get about 25 % faster by combining the three processes. def merge(obj, /): result = {} for key, val in sorted(obj.items()): if isinstance(val, dict): val = merge(val) if not val: continue if len(val) == 1: k1, val = next(iter(val.items())) key = (key[0] + k1[0][2:], key[1]) result[key] = val return result...
5
4
69,848,807
2021-11-5
https://stackoverflow.com/questions/69848807/how-do-i-find-the-row-of-a-string-index
I have a dataframe where the indexes are not numbers but strings (specifically, name of countries) and they are all unique. Given the name of a country, how do I find its row number (the 'number' value of the index)? I tried df[df.index == 'country_name'].index but this doesn't work.
We can use Index.get_indexer: df.index.get_indexer(['Peru']) [3] Or we can build a RangeIndex based on the size of the DataFrame then subset that instead: pd.RangeIndex(len(df))[df.index == 'Peru'] Int64Index([3], dtype='int64') Since we're only looking for a single label and the indexes are "all unique" we can also...
8
9
69,846,902
2021-11-4
https://stackoverflow.com/questions/69846902/how-to-plot-stacked-100-bar-plot-with-seaborn-for-categorical-data
I have a dataset that looks like this (assume this has 4 categories in Clicked, the head(10) only showed 2 categories): Rank Clicked 0 2.0 Cat4 1 2.0 Cat4 2 2.0 Cat4 3 1.0 Cat1 4 1.0 Cat4 5 2.0 Cat4 6 2.0 Cat4 7 3.0 Cat4 8 5.0 Cat4 9 5.0 Cat4 This is a code that returns this plot: eee = (df.groupby(['Rank','Clicked']...
Seaborn doesn't support stacked barplot, so you need to plot the cumsum: # calculate the distribution of `Clicked` per `Rank` distribution = pd.crosstab(df.Rank, df.Clicked, normalize='index') # plot the cumsum, with reverse hue order sns.barplot(data=distribution.cumsum(axis=1).stack().reset_index(name='Dist'), x='Ran...
10
7
69,840,223
2021-11-4
https://stackoverflow.com/questions/69840223/way-to-pass-arguments-to-fastapi-app-via-command-line
I'm using python 3.8.0 for my FastAPI app. It uses the .env file located on the root of a project directory. I am using the dotenv package, and the location of the .env file is hardcoded within the app. Here is my unit file [Unit] Description=Gunicorn instance for my_app After=network.target [Service] User=nginx Group=...
You can set the path from which systemd will read the environment for your process exactly in unit file configuration. The setting is called EnvironmnetFile=. Just set the option to the path for .env.prod in one unit file and for the path to .env.test for another.
5
3
69,833,454
2021-11-4
https://stackoverflow.com/questions/69833454/using-lambda-to-get-image-from-s3-returns-a-white-box-in-python
I'm trying to get my image from S3 bucket and return it. Here's the code: import base64 import boto3 import json import random s3 = boto3.client('s3') def lambda_handler(event, context): number = random.randint(0,1) if number == 1: response = s3.get_object( Bucket='bucket-name', Key='image.png', ) image = response['Bod...
Here it is how I do this: Your lambda with corrected body: import base64 import boto3 import json import random s3 = boto3.client('s3') def lambda_handler(event, context): response = s3.get_object( Bucket='bucket-name', Key='image.png', ) image = response['Body'].read() return { 'headers': { "Content-Type": "image/png"...
6
3
69,827,390
2021-11-3
https://stackoverflow.com/questions/69827390/pandas-column-multiindex-into-row-multiindex
I have a pandas dataframe df = pd.DataFrame([[i+10*j for i in range(6)] for j in range(5)], index=[f"item{i}" for i in range(5)]) df.columns = pd.MultiIndex.from_product((["abc", "xyz"], ["one", "two", "three"])) abc xyz one two three one two three item0 0 1 2 3 4 5 item1 10 11 12 13 14 15 item2 20 21 22 23 24 25 ite...
Here you go: df.stack(level=0)
4
4
69,824,126
2021-11-3
https://stackoverflow.com/questions/69824126/mypy-invalid-index-type-str-for-unionstr-dictstr-str-expected-type-u
Why am I getting the error? I have added the type properly, right? Invalid index type "str" for "Union[str, Dict[str, str]]"; expected type "Union[int, slice]" Code from typing import List, Dict, Union d = {"1": 1, "2": 2} listsOfDicts: List[Dict[str, Union[str, Dict[str, str]]]] = [ {"a": "1", "b": {"c": "1"}}, {"a":...
Mypy expects dictionaries to have the same type. Using Union models a subtype relation, but since Dict type is invariant, the key-value pair must match exactly as defined in the type annotation—which is the type Union[str, Dict[str, str]], so the subtypes in the Union wouldn't get matched (neither str, Dict[str, str] a...
5
7
69,822,726
2021-11-3
https://stackoverflow.com/questions/69822726/use-of-r-carriage-return-in-python-regex
I'm trying to use regex to match every character between a string and a \r character : text = 'Some text\rText to find !\r other text\r' I want to match 'Text to find !'. I already tried : re.search(r'Some text\r(.*)\r', text).group(1) But it gives me : 'Text to find !\r other text' It's surprising because it works p...
.* is greedy in nature so it is matching longest match available in: r'Some text\r(.*)\r Hence giving you: re.findall(r'Some text\r(.*)\r', 'Some text\rText to find !\r other text\r') ['Text to find !\r other text'] However if you change to non-greedy then it gives expected result as in: re.findall(r'Some text\r(.*?)...
4
4
69,822,360
2021-11-3
https://stackoverflow.com/questions/69822360/separate-fastapi-documentation-into-sections
Currently the OpenAPI documentation looks like this: Is it possible to separate it into multiple sections? For example, 2 sections, one being the "books" section that contains the methods from "/api/bookcollection/books/" endpoints and the other containing the endpoints with "/api/bookcollection/authors/". I have cons...
The OpenAPI allows the use of tags to group endpoints. FastAPI also supports this feature. The documentation section can be found here. Example: from fastapi import FastAPI tags_metadata = [ { "name": "users", "description": "Operations with users. The **login** logic is also here.", }, { "name": "items", "description"...
4
9
69,819,337
2021-11-3
https://stackoverflow.com/questions/69819337/how-keep-a-value-in-a-dataframe-using-the-values-of-another-dataframe-as-indexes
I have the following two DataFrames: import pandas as pd df = pd.DataFrame([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], index = [0, 0.25, 0.50, 0.75, 1], columns = [0, 0.25, 0.50, 0.75, 1]) df_cross = pd.DataFrame([[0.0, 0.25], [0.0, 0.75], [0.5, 1]], columns = ['indexes_to_kee...
Let us try crosstab on df_cross, then use where to mask the values s = pd.crosstab(*df_cross.values.T) df.where(s == 1) 0.00 0.25 0.50 0.75 1.00 0.00 NaN 0.0 NaN 0.0 NaN 0.25 NaN NaN NaN NaN NaN 0.50 NaN NaN NaN NaN 0.0 0.75 NaN NaN NaN NaN NaN 1.00 NaN NaN NaN NaN NaN PS: pd.crosstab(*df_cross.values.T) is just a ...
5
5
69,782,818
2021-10-30
https://stackoverflow.com/questions/69782818/turn-a-tf-data-dataset-to-a-jax-numpy-iterator
I am interested about training a neural network using JAX. I had a look on tf.data.Dataset, but it provides exclusively tf tensors. I looked for a way to change the dataset into JAX numpy array and I found a lot of implementations that use Dataset.as_numpy_generator() to turn the tf tensors to numpy arrays. However I w...
Both tensorflow and JAX have the ability to convert arrays to dlpack tensors without copying memory, so one way you can create a JAX array from a tensorflow array without copying the underlying data buffer is to do it via dlpack: import numpy as np import tensorflow as tf import jax.dlpack tf_arr = tf.random.uniform((1...
5
6
69,802,491
2021-11-1
https://stackoverflow.com/questions/69802491/create-recursive-dataclass-with-self-referential-type-hints
I want to write a dataclass definition in Python, but can't refer to that same class inside the declaration. Mainly what I want to achieve is the typing of this nested structure, as illustrated below: @dataclass class Category: title: str children: [Category] # I can't refer to a "Category" tree = Category(title='titl...
Option #1 You can wrap class name in a string in order to forward-declare the annotation: from dataclasses import dataclass @dataclass class Category: title: str children: list['Category'] Note: The ability to use list[type] for type hinting in Python was introduced in Python 3.9 as part of PEP 585. For Python version...
30
37
69,752,434
2021-10-28
https://stackoverflow.com/questions/69752434/how-can-i-represent-stdin-and-stderr-with-pathlib-path
I love the pathlib.Path api and use it a lot for quick cli tools. Especially with typer. I have a few tightly related questions: In UNIX cli commands - is the de facto standard for stdin. Is that the same under Windows? Is there a clean, cross-platform way to have a pathlib.Path object (or actually the {POSIX,Windows}...
There is no cross-platform pseudo file name for standard input and standard output. In POSIX, it's /dev/stdin for standard input and /dev/stdout for standard output, although many CLI tools would accept - in the command line arguments as a shorthand for standard input or standard output. In Windows, it's CONIN$ for sta...
7
1
69,810,895
2021-11-2
https://stackoverflow.com/questions/69810895/pandas-ignores-dropna-false-with-categorical-columns-in-groupby
I want to include NA values when using groupby() which does not happen by default. I think the option dropna=False make it happen. But when the column is of type Categorical the option has no effect. I assume the best would say there is a well thought design decision behind that. Or maybe it is related to this pandas b...
This is a bug. It has been fixed and will be released in pandas 2.0. The simplest workaround is to temporarily undo the categories thing: orig = df['2019'].cat.categories.dtype if np.issubdtype(orig, np.integer) or orig == 'bool': orig = 'Int64' # Allow NA values. res = df.astype({'2019': orig}).groupby('2019', dropna=...
8
4
69,786,885
2021-10-31
https://stackoverflow.com/questions/69786885/after-conda-update-python-kernel-crashes-when-matplotlib-is-used
I have create this simple env with conda: conda create -n test python=3.8.5 pandas scipy numpy matplotlib seaborn jupyterlab The following code in jupyter lab crashes the kernel : import matplotlib.pyplot as plt plt.subplot() I don't face the problem on Linux. The problem is when I try on Windows 10. There are no err...
Update 2021-11-06 The default pkgs/main channel for conda has reverted to using freetype 2.10.4 for Windows, per main / packages / freetype. If you are still experiencing the issue, use conda list freetype to check the version: freetype != 2.11.0 If it is 2.11.0, then change the version, per the solution, or conda up...
46
75
69,796,919
2021-11-1
https://stackoverflow.com/questions/69796919/how-to-generate-python-typing-information-for-a-library-that-supports-sync-and-a
I have a problem with both typing and type-hints in Python. I prepared an (executable) example that showcases the problem that I am facing for a library that should expose both, a synchronous and asynchronous interface. It is obviously a simplified example, cutting out the noise and focussing on the issue at hand: impo...
This can be solved using Paramspec introduced in PEP-612 Here is the modified decorator from your example : from typing import ParamSpec, TypeVar from collections.abc import Awaitable, Callable P = ParamSpec("P") R = TypeVar("R") def to_async(func: Callable[P, R]) -> Callable[P, Awaitable[R]]: ... This will capture ne...
5
4
69,748,975
2021-10-28
https://stackoverflow.com/questions/69748975/virtual-environments-architecture-made-by-pipenv-become-intel-chip-on-apple-mac
I'm struggling with using python on mac m1, and I found that there's an issue on pipenv for making virtual environment with correct architecture. As you can see on the above picture, when I open the terminal with aram64 architecture and make virtual environment using pipenv, the architecture becomes i386. I'm not sure...
I had this exact problem, and @Beel's comment gave me the clue that I needed to solve it. In my case, pipenv was referencing a version of python that was built for x86_64. Specifically: $ which pipenv /opt/anaconda3/bin/pipenv $ file /opt/anaconda3/bin/python /opt/anaconda3/bin/python: Mach-O 64-bit executable x86_64 ...
6
3
69,808,514
2021-11-2
https://stackoverflow.com/questions/69808514/how-to-fix-jupyter-extension-activation-failed-when-opening-python-files
I installed python lately on my macos system and when I try to open a python file I see this error popup about Jupyter extension :
Just ran into this today (I'm on MacOS for my work computer). In my case, upgrading to the pre-release version of the Jupyter extension (v2022.5.1001281006) solved it right away. If you're not an experienced programmer/software engineer, as is the case for me, I suggest trying to upgrade (or roll back) either VS code o...
7
2
69,783,897
2021-10-31
https://stackoverflow.com/questions/69783897/compute-class-weight-function-issue-in-sklearn-library-when-used-in-keras-cl
The classifier script I wrote is working fine and recently added weight balancing to the fitting. Since I added the weight estimate function using 'sklearn' library I get the following error : compute_class_weight() takes 1 positional argument but 3 were given This error does not make sense per documentation. The scri...
After spending a lot of time, this is how I fixed it. I still don't know why but when the code is modified as follows, it works fine. I got the idea after seeing this solution for a similar but slightly different issue. class_weights = compute_class_weight( class_weight = "balanced", classes = np.unique(train_classes),...
35
92
69,785,084
2021-10-31
https://stackoverflow.com/questions/69785084/running-cells-with-python-3-10-requires-ipykernel-installed
I just installed Python 3.10 on my laptop (Ubuntu 20.04). Running a Jupyter Notebook inside of VS Code works with Python 3.9 but not with Python 3.10. I get the error message: Running cells with 'Python 3.10.0 64 bit' requires ipykernel installed or requires an update. Update February 2022 Jalil Nourmohammadi Khiarak ...
I would like to add a comment for that: Your solution is correct but it didn't work for me when I have used it on my new Linux. I did the following job to solve the problem. Probably people after using the following comment: python3.10 -m pip install ipykernel Will get error for 'distutils.util'. So you should install...
17
16
69,809,832
2021-11-2
https://stackoverflow.com/questions/69809832/ipykernel-jupyter-notebook-labs-cannot-import-name-filefind-from-traitlets
I installed Jupyter notebook and labs on and EC2 instance and for some reason I get the following error: ImportError: cannot import name 'filefind' from 'traitlets.utils' (/usr/lib/python3/dist-packages/traitlets/utils/init.py) Jupyter opens fine in the browser but I can't seem to be able to work in an python noteboo...
I disencourage the solution of op. Downloading and overwriting python libraries is not the way of keeping your system stable and clean! What I found out is that while installing Jupyter notebook it had found four significant errors which resulted from python3 packages that were not installed correctly within that insta...
9
19
69,810,210
2021-11-2
https://stackoverflow.com/questions/69810210/mediapipe-solutionfacedetection
I want to use mediapipe facedetection module to crop face Images from original images and videos, to build a dataset for emotion recognition. is there a way of getting the bounding boxes from mediapipe faceDetection solution? cap = cv2.VideoCapture(0) with mp_face_detection.FaceDetection( model_selection=0, min_detecti...
In order to figure out format you can follow two ways: Check protobuf files in medipipe Check out for what "Detection" is: https://github.com/google/mediapipe/blob/master/mediapipe/framework/formats/detection.proto We need location_data. It should have format field, which should be BOUNDING_BOX, or RELATIVE_BOUNDING_...
5
4
69,776,492
2021-10-30
https://stackoverflow.com/questions/69776492/indexerror-tuple-index-out-of-range-when-i-try-to-create-an-executable-from-a-p
I have been trying out an open-sourced personal AI assistant script. The script works fine but I want to create an executable so that I can gift the executable to one of my friends. However, when I try to create the executable using the auto-py-to-exe, it states the below error: Running auto-py-to-exe v2.10.1 Building ...
This is a Python 3.10 issue. To fix it: You have to go to the folder "Python310\Lib" and edit the file 'dis.py'. In the 'dis.py' file you have to find this "def _unpack_opargs" and inside the else statement write a new line with this: "extended_arg = 0", then save the file. I did something like that: else: arg = None e...
24
40
69,800,500
2021-11-1
https://stackoverflow.com/questions/69800500/how-to-calculate-correlation-coefficients-using-sklearn-cca-module
I need to measure similarity between feature vectors using CCA module. I saw sklearn has a good CCA module available: https://scikit-learn.org/stable/modules/generated/sklearn.cross_decomposition.CCA.html In different papers I reviewed, I saw that the way to measure similarity using CCA is to calculate the mean of the ...
In reference to the notebook you provided which is a supporting artefact to and implements ideas from the following two papers "SVCCA: Singular Vector Canonical Correlation Analysis for Deep Learning Dynamics and Interpretability". Neural Information Processing Systems (NeurIPS) 2017 "Insights on Representational Simi...
7
10
69,805,091
2021-11-2
https://stackoverflow.com/questions/69805091/how-to-create-an-interactive-brain-shaped-graph
I'm working on a visualization project in networkx and plotly. Is there a way to create a 3D graph that resembles how a human brain looks like in networkx and then to visualize it with plotly (so it will be interactive)? The idea is to have the nodes on the outside (or only show the nodes if it's easier) and to color ...
Based on the clarified requirements, I took a new approach: Download accurate brain mesh data from BrainNet Viewer github repo; Plot a random graph with 3D-coordinates using Kamada-Kuwai cost function in three dimensions centered in a sphere containing the brain mesh; Radially expand the node positions away from the c...
7
2
69,752,055
2021-10-28
https://stackoverflow.com/questions/69752055/valueerror-none-values-not-supported-code-working-properly-on-cpu-gpu-but-not
I am trying to train a seq2seq model for language translation, and I am copy-pasting code from this Kaggle Notebook on Google Colab. The code is working fine with CPU and GPU, but it is giving me errors while training on a TPU. This same question has been already asked here. Here is my code: strategy = tf.distribute.e...
As stated in the referenced answer in the link you provided, tensorflow.data API works better with TPUs. In order to adapt it in your case, try to use return instead of yield in generate_batch function: def generate_batch(X = X_train, y = y_train, batch_size = 128): ... return encoder_input_data, decoder_input_data, de...
5
1
69,755,906
2021-10-28
https://stackoverflow.com/questions/69755906/how-to-obtain-smooth-histogram-after-scaling-image
I am trying to linearly scale an image so the whole greyscale range is used. This is to improve the lighting of the shot. When plotting the histogram however I don't know how to get the scaled histogram so that its smoother so it's a curve as aspired to discrete bins. Any tips or points would be much appreciated. impor...
I think what you have in mind is a spline curve that passes through your points. Here is how to do it: import cv2 as cv import numpy as np import matplotlib.pyplot as plt from scipy import interpolate img = cv.imread(r'3NKTJ.jpg', cv.IMREAD_GRAYSCALE) img_s = img/255 img_s = img_s / np.max(img_s) img_s = img_s*255 hist...
6
3
69,798,145
2021-11-1
https://stackoverflow.com/questions/69798145/circleci-started-11-1-2021-can-t-find-python-executable-python-you-can-set
As of this morning, CircleCI is failing for me with this strange build error: Can't find Python executable "python", you can set the PYTHON env variable I noticed it on a new commit. of course, thinking it was my new commit I forced pushed my last known passing commit onto main branch. In particular, this seems to hav...
Try using a next-generation Ruby image. In your case, change circleci/ruby:2.7.4-node-browsers to cimg/ruby:2.7.4-browsers. You can find the full list of images here.
6
2
69,817,464
2021-11-2
https://stackoverflow.com/questions/69817464/pyyaml-error-could-not-determine-a-constructor-for-the-tag-vault
I am trying to read a YAML file that has the tag !vault in it. I get the error: could not determine a constructor for the tag '!vault' Upon reading a couple of blogs, I understood that I need to specify some constructors to resolve this issue, but I'm not clear on how to do it. import yaml from yaml.loader import Saf...
Either use the from_yaml utility function: from ansible.parsing.utils.yaml import from_yaml # inventory_info = yaml.safe_load(stream) # Change this inventory_info = from_yaml(stream) # to this Or add the constructor to yaml.SafeLoader: from ansible.parsing.yaml.objects import AnsibleVaultEncryptedUnicode def construct...
7
4
69,776,414
2021-10-30
https://stackoverflow.com/questions/69776414/pytzusagewarning-the-zone-attribute-is-specific-to-pytzs-interface-please-mig
I am writing a simple function that sends messages based on a schedule using AsyncIOScheduler. scheduler = AsyncIOScheduler() scheduler.add_job(job, "cron", day_of_week="mon-fri", hour = "16") scheduler.start() It seems to work, but I always get the following message: PytzUsageWarning: The zone attribute is specific t...
To set a PIP495 compatible timezone in APScheduler, set a parameter when instantiating the scheduler: scheduler = AsyncIOScheduler(timezone="Europe/Berlin") scheduler.add_job(job, "cron", day_of_week="mon-fri", hour = "16") scheduler.start() With flask-APScheduler (version 1.12.2), add the timezone to the configuratio...
15
22
69,742,016
2021-10-27
https://stackoverflow.com/questions/69742016/multiple-strategies-for-same-function-parameter-in-python-hypothesis
I am writing a simple test code in Python using the Hypothesis package. It there a way to use multiple strategies for the same function parameter? As an example, use integers() and floats() to test my values parameter without writing two separate test functions? from hypothesis import given from hypothesis.strategies i...
In general if you need your values to be one of several things (like ints or floats in your example) then we can combine strategies for separate things into one with | operator (which operates similar to one for sets -- a union operator and works by invoking __or__ magic method): from hypothesis import given from hypot...
5
5
69,812,523
2021-11-2
https://stackoverflow.com/questions/69812523/how-to-specify-requirements-in-python-packages-metadata
Core metadata specification documents the metadata field Requires-External which seems to be for specifying system (non-python) dependencies. How do you actually specify this field though? This is what I've tried: . ├── mypackage │ └── __init__.py └── setup.py Contents of setup.py from setuptools import setup setup( n...
So what is the syntax to pass Requires-External to setuptools/distutils? There is none by default, as neither distutils nor setuptools support the field. Also, requires_external keyword arg is not supported as well - it is silently ignored, just as any other unknown keyword arg. To add local support for requires_exte...
6
0
69,786,993
2021-10-31
https://stackoverflow.com/questions/69786993/tuning-xgboost-hyperparameters-with-randomizedsearchcv
I''m trying to use XGBoost for a particular dataset that contains around 500,000 observations and 10 features. I'm trying to do some hyperparameter tuning with RandomizedSeachCV, and the performance of the model with the best parameters is worse than the one of the model with the default parameters. Model with default ...
As stated in the XGBoost Docs Parameter tuning is a dark art in machine learning, the optimal parameters of a model can depend on many scenarios. You asked for suggestions for your specific scenario, so here are some of mine. Drop the dimensions booster from your hyperparameter search space. You probably want to go ...
11
21
69,785,596
2021-10-31
https://stackoverflow.com/questions/69785596/sklearn-manifold-tsne-typeerror-ufunc-multiply-did-not-contain-a-loop-with-si
I have run the sklearn.manifold.TSNE example code from the sklearn documentation, but I got the error described in the questions' title. I have already tried updating my sklearn version to the latest one (by !pip install -U scikit-learn) (scikit-learn=1.0.1). However, the problem is still there. Does anyone know how to...
Delete learning_rate='auto' solved my problem. Thanks @FlaviaGiammarino comment!!
27
38
69,736,380
2021-10-27
https://stackoverflow.com/questions/69736380/using-nested-asyncio-gather-inside-another-asyncio-gather
I have a class with various methods. I have a method in that class something like : class MyClass: async def master_method(self): tasks = [self.sub_method() for _ in range(10)] results = await asyncio.gather(*tasks) async def sub_method(self): subtasks = [self.my_task() for _ in range(10)] results = await asyncio.gath...
TLDR: Using gather instead of returning tasks simplifies usage and makes code easier to maintain. While gather has some overhead, it is negligible for any practical application. Why gather? The point of gather to accumulate child tasks before exiting a coroutine is to delay the completion of the coroutine until its ch...
10
9