QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
75,522,656
6,239,971
Python - Pandas DataFrame manipulation
<p>I've got a DataFrame called <code>product</code> with a list of orders, products, and quantities for each product. Here's a screenshot:</p> <p><a href="https://i.sstatic.net/P9Ofp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/P9Ofp.png" alt="enter image description here" /></a></p> <p>I need to make...
<python><pandas><dataframe><data-manipulation>
2023-02-21 15:36:00
2
454
Davide
75,522,641
3,069,498
Python: how is `None` evaluated in logical expressions, in relation to other boolean values?
<p>In Python 3...</p> <ul> <li>Sample 1:</li> </ul> <pre><code>s: str = None b: bool = True b = (s != None) and (s != &quot;some-not-allowed-value&quot;) print (b) </code></pre> <p>Displays <code>False</code> (<em>as it seems intuitive</em>)</p> <hr /> <ul> <li>Sample 2:</li> </ul> <pre><code>s: str = None b: bool = Tr...
<python><logical-operators><nonetype>
2023-02-21 15:34:24
1
832
Serban
75,522,460
7,425,726
insert record to fill missing time window
<p>I have a dataset with consecutive time periods corresponding with activities (drive, rest, charge etc). But there is no record for the night so the data is not continuous. I would like to add an extra record to fill this gap such that the start time of each record is always equal to the end time of the previous reco...
<python><pandas>
2023-02-21 15:20:21
2
1,734
pieterbons
75,522,458
11,971,785
Mixin using @extend_schema (drf_spectacular) using instance serializer
<p>I want to set the responses for @extend_schema dynamically. The Mixin is inherited by different Subclasses, their response can vary depending on their Serializer. Therefore I would like to have the responses be set dynamically. Is that possible?</p> <pre><code>class Mixin: @extend_schema( request=None, ...
<python><django-rest-framework><drf-spectacular>
2023-02-21 15:20:10
0
9,265
Andreas
75,522,454
1,864,294
Drop rows from the end on condition
<p>For a series</p> <pre><code>s = pd.Series([1, 0, 1, 0, 2, 0, 0, 0]) </code></pre> <p>I would like to remove all rows with consecutive zeros at the end:</p> <pre><code>pd.Series([1, 0, 1, 0, 2]) </code></pre> <p>My current solution</p> <pre><code>s.loc[s != s.shift()] </code></pre> <p>does not remove the last zero ro...
<python><pandas>
2023-02-21 15:19:46
4
20,605
Michael Dorner
75,522,432
1,700,890
Append list in dictionary through dictionary comprehension
<p>Here is my example:</p> <pre><code>sample_dict = {'foo':[1], 'bar': [2]} {el: sample_dict[el].append(3) for el in sample_dict.keys()} </code></pre> <p>it generates:</p> <pre><code>{'foo': None, 'bar': None} </code></pre> <p>while I am expecting this:</p> <pre><code>{'foo': [1,3], 'bar': [2,3]} </code></pre> <p>What ...
<python><append><dictionary-comprehension>
2023-02-21 15:17:25
1
7,802
user1700890
75,522,400
558,619
if type(X) == type(Y) boolean triggering as false when it's the same type
<p>I have a small bit of code in a class (<code>Delta_Viewer</code>) that looks like this:</p> <pre><code>class Delta_Viewer(): def __init__(self, df): self.df : pd.Dataframe = df self._columns = trade_types # init method, properties, etc up here def __sub__(self, other): ...
<python>
2023-02-21 15:15:00
0
3,541
keynesiancross
75,522,319
4,916,174
SignalR with Python websockets return 503
<p>I have created simplest Hub in ASP.NET Core and pushed it into Azure containing below piece of code:</p> <pre><code>public class TestHub: Hub { } app.UseEndpoints(endpoints =&gt; { endpoints.MapControllers(); endpoints.MapHub&lt;TestHub&gt;(&quot;/testHub&quot;); }); </code></pre> <p>To validate hub is workin...
<python><websocket><signalr>
2023-02-21 15:07:13
0
3,442
miechooy
75,522,265
1,673,492
Typehints on autospecced mock does not match original
<p>I would like an autospecced mock to give me the same typehints as i get from my original function, but I cannot make it work. Below is a minimal example of what I am trying to do</p> <pre><code>from __future__ import annotations import typing from unittest.mock import create_autospec import pandas as pd def func...
<python><python-unittest><python-typing>
2023-02-21 15:02:30
0
331
ano
75,522,220
6,077,239
Got ValueError: exog is not 1d or 2d when fitting OLS with a corner case
<p>The following code causes an Exception to be raised.</p> <pre><code>&gt;&gt;&gt; import statsmodels.api as sm &gt;&gt;&gt; sm.OLS(np.array([np.nan]), sm.add_constant(np.array([[1]]), has_constant=&quot;add&quot;), missing=&quot;drop&quot;).fit().params ValueError: exog is not 1d or 2d </code></pre> <p>Is there any...
<python><statsmodels>
2023-02-21 14:58:26
0
1,153
lebesgue
75,522,116
3,491,031
Weisfeiler-Lehman Networkx function for different k-levels
<p>I am trying to use the Weisfeiler-Lehman (WL) algorithm implemented in networkx library to check if two graphs are isomorphic.</p> <p>My graphs are the following:</p> <pre class="lang-python prettyprint-override"><code>import networkx as nx g1 = nx.Graph() g1.add_edges_from([(1, 2), (1, 4), (2, 4), (2, 5), (3, 5), (...
<python><networkx><graph-theory><isomorphism>
2023-02-21 14:48:26
1
574
jAdex
75,522,008
1,666,623
SSL Error in Python Requests run from Github's Actions
<p>I am trying to periodically download data in Python from parliamentary website <a href="https://www.psp.cz/" rel="nofollow noreferrer">https://www.psp.cz/</a> using Github's Actions. (For example this data file: <a href="https://www.psp.cz/eknih/cdrom/opendata/poslanci.zip" rel="nofollow noreferrer">https://www.psp....
<python><ssl><python-requests><ssl-certificate><github-actions>
2023-02-21 14:39:53
0
1,419
Michal Skop
75,521,871
16,844,801
VScode Jupyter Notebook crash in cell
<p>I get this error when I run sklearn to train on a very large dataset. If the dataset is small, it works, but if it is above a threshold, the kernel crashes.</p> <p>Error:</p> <pre><code>info 16:24:11.630: Process Execution: &gt; ~/miniconda3/envs/auto-sklearn/bin/python -m pip list &gt; ~/miniconda3/envs/auto-sklear...
<python><python-3.x><visual-studio-code><scikit-learn><jupyter-notebook>
2023-02-21 14:28:27
2
434
Baraa Zaid
75,521,662
15,915,737
Upsert Pandas Dataframe into Snowflake Table
<p>I'm upserting data in snowflake table by creating a Temp Table (from my dataframe) and then merging it to my Table. But is there a more efficient way of achieving it ? Like merging directly the dataframe on snowflake table without a temp Table ?</p> <p>Because I will do it on several tables having a few thousant row...
<python><dataframe><snowflake-cloud-data-platform><upsert>
2023-02-21 14:11:00
1
418
user15915737
75,521,643
5,651,960
How to scrape multiple tables form HTML file in python?
<p>OBJECTIVE: Trying to scrape the contents of multiples HTML files and put into a csv file.</p> <p>Looking for the unbolded items to be column headers and for the bolded information to fit into a row inside a csv file.</p> <p>So far, I've been able to effectively get tables 1 and 2 (there are 5 total).</p> <p>Believe ...
<python><html><dataframe><web-scraping><beautifulsoup>
2023-02-21 14:09:21
1
949
RageAgainstheMachine
75,521,556
5,398,197
Python socketIO callback is lost: `Unknown callback received, ignoring.`
<p>I have a Flask-SocketIO server that connects with a number of python-socketIO clients. I want to know which clients are online. To get to know this, I am sending a <code>ping</code> event from the server with a callback function to process the response.</p> <p>The structure of the server code is as follows:</p> <pre...
<python><azure-web-app-service><flask-socketio><python-socketio>
2023-02-21 14:02:25
1
328
Bart
75,521,500
1,616,785
Better way to identify chunks where data is available in zarr
<p>I have a zarr store of weather data with 1 hr time interval for the year 2022. So 8760 chunks. But there are data only for random days. How do i check which are the hours in 0 to 8760, the data is available? Also the store is defined with <code>&quot;fill_value&quot;: &quot;NaN&quot;,</code></p> <p>I am iterating o...
<python><python-xarray><zarr>
2023-02-21 13:58:11
1
1,401
sjd
75,521,488
3,265,791
Docker and tensorflow - image size explodes with tensorflow
<p>I am trying to add tensorflow to my conda enviroment by adding the following depenencies to my .yml enviroment file</p> <pre><code>name: py310 channels: - conda-forge dependencies: - python=3.10 - pandas </code></pre> <h3>Additional tensorflow dependencies</h3> <pre><code> - pip - cudatoolkit=11.2 - cud...
<python><docker><tensorflow><pip><conda>
2023-02-21 13:57:13
0
639
MMCM_
75,521,428
3,265,791
Docker and conda - how does "clean --all -y" work?
<p>I am bit confused by the conda command <code>conda clean --all -y</code> inside a docker script. Generally, the idea is to shrink the final docker image. <code>conda clean --all -y</code> should help to delete downloaded tarballs, and indeed, the docker log shows:</p> <pre><code>Will remove 430 (853.4 MB) tarball(s)...
<python><docker><conda>
2023-02-21 13:51:31
1
639
MMCM_
75,521,330
6,213,883
Why does Python seem to behave differently between a call with pytest and a "manual" call?
<h2>Context</h2> <p>I want to test the behavior of a singleton class when used in multiprocessing environment because it has been brought to my attention that it does not work properly. It seems the same object is being used in two different processes.</p> <h2>Minimal example</h2> <ul> <li>Python 3.8.3</li> <li>Windows...
<python><pytest><python-3.8>
2023-02-21 13:42:48
1
3,040
Itération 122442
75,521,238
1,436,812
Matplotlib figure as SVG with Shiny for Python
<p>The axis labels and titles in the figure in the app below appears unsharp to me. I assume it's because the figure is rendered as PNG, so I assume that rendering it as SVG will fix the issue. However, I'm not sure how to do that. Any pointers?</p> <pre><code>from shiny import * import matplotlib.pyplot as plt app_ui...
<python><py-shiny>
2023-02-21 13:33:57
1
641
Stefan Hansen
75,520,939
8,681,882
Optimised way to format an 2D float array to a list of list of dictionaries
<p>I'm making a web app using fastapi</p> <p>I have an endpoint named <code>/distances</code></p> <p>which is outputting an array of float <code>distances</code>, from a string input <code>word</code></p> <p>And then formatting it to a list of dictionnaries to be readable as a json API</p> <pre><code>@app.get(&quot;/di...
<python><arrays><fastapi>
2023-02-21 13:06:48
0
337
Noa Be
75,520,831
7,677,894
Is LabelEncoder ordered in sklearn?
<p><code>LabelEncoder</code> is used to generate labels for pytorch projects. Codes like:</p> <pre><code>from sklearn.preprocessing import LabelEncoder label_encoder = LabelEncoder() label_encoder.fit(annotation['instance_ids']) annotation['labels'] = list(map(int,label_encoder.transform(annotation['instance_ids'])))...
<python><scikit-learn>
2023-02-21 12:55:58
1
983
Ink
75,520,797
1,697,288
SQLAlchemy MSSQL bulk upSert
<p>I've been trying various methods to bulk upSert an Azure SQL (MSSQL) database using SQLAlchemy 2.0, the source table is fairly large 2M records and I need to bulk upSert 100,000 records (most of which won't be there).</p> <p><strong>NOTE</strong> This will run as an Azure function so if there is a better way I'm ope...
<python><sql-server><sqlalchemy><azure-functions><azure-sql-database>
2023-02-21 12:52:04
1
463
trevrobwhite
75,520,480
4,576,519
Append model checkpoints to existing file in PyTorch
<p>In PyTorch, it is possible to save model checkpoints as follows:</p> <pre class="lang-py prettyprint-override"><code>import torch # Create a model model = torch.nn.Sequential( torch.nn.Linear(1, 50), torch.nn.Tanh(), torch.nn.Linear(50, 1) ) # ... some training here # Save checkpoint torch.save(network...
<python><file><pytorch><save><checkpointing>
2023-02-21 12:23:16
1
6,829
Thomas Wagenaar
75,520,180
6,108,107
calculate zscores using groupby and highlighting using style
<p>I want to highlight possible outliers in a dataframe based on zscore grouped by location. I have used <a href="https://stackoverflow.com/questions/70003657/highlight-outliers-using-zscore-in-pandas">this answer</a> to identify and score values but I can't seem to implement the .groupby correctly. For example <code>...
<python><pandas>
2023-02-21 11:54:21
1
578
flashliquid
75,520,141
19,130,803
file write with cancel using python
<p>I am writing data to a new file. I am reading data from flask request(uploading a file) but during writing I am providing option to cancel the writing, for that I have used process and event, and passing required arguments.</p> <p><strong>Read file</strong></p> <pre><code>file = request.files.get(&quot;file&quot;) ...
<python>
2023-02-21 11:51:11
1
962
winter
75,520,116
13,314,132
How do I use TextClassifier to load a previously generated model?
<p>I have used <code>arcgis</code> <code>learn.text</code> to import <code>TextClassifier</code> in order for creating a Machine learning module. Now I want to use the same model in <code>Streamlit</code>for creating an interface for re-use and displaying the predictions.</p> <p>Code for streamlit-app:</p> <pre><code>i...
<python><arcgis><text-classification><streamlit>
2023-02-21 11:49:12
1
655
Daremitsu
75,519,932
2,160,256
Azure Function Python Model 2 in Docker container
<p>I am failing to get a minimal working example running with the following setup:</p> <ul> <li>azure function in docker container</li> <li>python as language, specifically the <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python?tabs=asgi%2Capplication-level&amp;pivots=python-mod...
<python><azure><azure-functions>
2023-02-21 11:33:24
1
860
Marti Nito
75,519,912
16,169,533
Flask (Working outside of application context) with RabiitMQ
<p>I'm trying to build a consumer on a flask app and when i trying to get a data from another app (Django) to create it on flask database i got this error.</p> <pre><code>RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed the current applicati...
<python><flask>
2023-02-21 11:32:07
1
424
Yussef Raouf Abdelmisih
75,519,754
8,176,763
object str cannot be used in await expression in psycopg3
<p>I have a function that copies a csv file to a database. I'm trying to do that asynchronously:</p> <pre><code>import psycopg from config import config from pathlib import WindowsPath from psycopg import sql import asyncio async def main(): conn = await psycopg.AsyncConnection.connect(f'postgresql://{config.USER_...
<python><asynchronous><python-asyncio><psycopg2><psycopg3>
2023-02-21 11:18:29
1
2,459
moth
75,519,704
16,981,638
how to remove list brackets from the web scraped data
<p>i'm trying to scrape some data from a website but the final result have the output data in lists, so how can i extract the data without those list brackets.</p> <p><a href="https://i.sstatic.net/Mod2q.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Mod2q.png" alt="enter image description here" /></a><...
<python><web-scraping><beautifulsoup>
2023-02-21 11:13:48
2
303
Mahmoud Badr
75,519,693
15,481,917
Django: get model's fields name
<p>I am trying to create a table in react that uses as table information from a django backend.</p> <p>I would like to fetch the table's columns from the API, so I tried updating the model:</p> <pre><code>class Activity(models.Model): aid = models.AutoField(primary_key=True) uid = models.ForeignKey(USER_MODEL, ...
<python><django>
2023-02-21 11:13:12
2
584
Orl13
75,519,552
4,684,861
How to convert Pyspark Dataframe to Pandas on Spark Dataframe?
<p>I have intermediate pyspark dataframe which I want to convert to Pandas on Spark Dataframe (not just toPandas()). I have gone through the official docs and found out <code>pandas_api()</code> does the job for me. But when I try use it says, <code>AttributeError: 'DataFrame' object has no attribute 'pandas_api'</code...
<python><apache-spark><pyspark><databricks>
2023-02-21 10:59:19
1
11,241
Mohamed Thasin ah
75,519,501
12,752,172
How to pass checkbox data into main window function in customtkinter in python?
<p>I'm creating a python app with the &quot;customtkinter&quot;. I need to open another window when the user clicks on a button and on that window there are 2 options to select and submit. After clicking on submit button need to close that window and pass the selected value into the main window and display them on the ...
<python><tkinter><customtkinter>
2023-02-21 10:54:43
1
469
Sidath
75,519,060
773,718
Unable to save binary images data from a numpy array to a video file using openCV Python
<p>I'm reading a binary video file that has 54 frames of depth image data that was taken by the Kinect sensor.</p> <p>I'm able to read the data frame by frame and show it by following the code below:</p> <pre><code># Load the depth map data from the binary file with open(dataset_path + filename, &quot;rb&quot;) as f: ...
<python><numpy><opencv><dataset>
2023-02-21 10:18:38
1
4,682
MSaudi
75,518,754
188,331
Train Tokenizer with HuggingFace dataset
<p>I'm trying to train the Tokenizer with HuggingFace <a href="https://huggingface.co/datasets/wiki_split" rel="nofollow noreferrer">wiki_split datasets</a>. According to the Tokenizers' <a href="https://github.com/huggingface/tokenizers" rel="nofollow noreferrer">documentation at GitHub</a>, I can train the Tokenizer ...
<python><huggingface-tokenizers>
2023-02-21 09:50:42
1
54,395
Raptor
75,518,559
12,860,141
How Do I unnest following structure of json into interpretable table using python?
<p>I have dataframe <code> df</code> which has column called <code> test_col</code> which contains json structures as shown below. As you can see lineItemPromotions object has nested jsons in it which can have 0-10 numbers of items in it. By unnesting, it should create new rows for each ID under lineItemPromotions. H...
<python><json><pandas>
2023-02-21 09:31:28
2
493
dan
75,518,463
8,099,689
What does "symbolically traceable" mean for a function?
<p>Specifically, I am referring to Python and PyTorch, but I guess the term has a meaning more general than Python/PyTorch.</p> <p>The PyTorch <a href="https://pytorch.org/docs/stable/generated/torch._assert.html" rel="nofollow noreferrer">docs</a> state for the function <code>torch._assert</code>:</p> <blockquote> <p>...
<python><pytorch><assert>
2023-02-21 09:22:43
1
366
joba2ca
75,518,435
6,111,772
pysimplegui: why does a working layout fail in a Column / Frame?
<p>A working layout looses part of the information when used in a 'Column' or 'Frame'. Minimized source:</p> <pre><code>import PySimpleGUI as sg lo = [ [sg.T(&quot;Line 1&quot;)], [sg.T(&quot;Aa&quot;),sg.T(&quot;Bb&quot;)], [ [sg.T(&quot;1 &quot;),sg.T(&quot;2&quot;)], # (*) ...
<python><pysimplegui><col>
2023-02-21 09:20:47
2
441
peets
75,518,353
11,449
Python logging output doesn't show unless I call another logger first
<p>I have some behaviour I can't explain wrt the Python logging library, and none of the docs nor tutorials I've read match with what I'm seeing (well they probably do, I guess I'm just missing some crucial detail somewhere). Consider first what does work as expected:</p> <pre><code>import logging logger = logging.get...
<python><logging><python-logging>
2023-02-21 09:12:46
1
19,644
Roel
75,518,345
3,909,896
Catching exit codes from submodules in python
<p>I have a function that allows me to run <code>az cli</code> commands from within python. However, whenever I get a non-zero exit code, the entire process is being shut down, including my python job. This happens for instance when I try to look up a user that does not exist.</p> <p>I tried to wrap the function call w...
<python><azure><azure-cli>
2023-02-21 09:12:02
1
3,013
Cribber
75,518,324
6,343,313
Parallelising a select query in Python's sqlite does not seem to improve performance
<p>After reading <a href="https://stackoverflow.com/questions/24298023">this</a> post, I have been trying to compare parallelization with non parallelization in sqlite. I am using Python's sqlite3 library to create a database containing a table called randNums which contains a two columns, an id and a val. The val is a...
<python><sqlite><parallel-processing>
2023-02-21 09:09:42
2
1,580
Mathew
75,518,264
6,734,243
how to add extra space before closing tag in bs4 prettify?
<p>I'm using bs4 to parse html output in my test suit and compare them with existing html files. prettify and prettier behaviour seems different in how they manage closing tags.</p> <p>Using the following inputs:</p> <pre class="lang-py prettyprint-override"><code>from bs4 import BeautifulSoup, formatter fmt = formatt...
<python><beautifulsoup>
2023-02-21 09:04:18
1
2,670
Pierrick Rambaud
75,518,142
8,176,763
openpyxl returns function instead of value evaluation
<p>I am reading from a file like this in <code>openpyxl</code>:</p> <pre><code>import openpyxl from pathlib import WindowsPath p = WindowsPath(r'.\data\product_version.xlsx') if p.exists(): wb = openpyxl.load_workbook(p) ws = wb.active for row in ws.iter_rows(values_only=True): print(row) </code>...
<python><openpyxl>
2023-02-21 08:52:12
0
2,459
moth
75,518,069
258,483
How to make several libraries under same parent path in Python
<p>Suppose I have <code>library1</code></p> <pre><code>. └── mycompany/ ├── __init__.py └── library1/ ├── __init__.py ├── file1.py └── file2.py </code></pre> <p>And <code>library2</code>:</p> <pre><code>. └── mycompany/ ├── __init__.py └── library2/ ├── __init__.py ...
<python><python-packaging>
2023-02-21 08:44:45
0
51,780
Dims
75,518,012
14,427,209
How to check if there are digits in a string, and speel them in Python?
<p>I am quite new to this programming world. I am wondering if we can check if we can spell out an integer from a string that was given in the input. For example, I am using the below to take an input and convert it to lowercase.</p> <pre><code>request = input('You: ').lower().strip() </code></pre> <p>What I want now i...
<python><python-3.x><string><function><integer>
2023-02-21 08:38:19
1
317
TECH FREEKS
75,517,967
13,803,549
Delete select menu after interaction Discord.py
<p>I have several buttons that each bring up a different select menu. I have been trying to figure out a way to delete a select menu after a selection is made so when the user clicks on the next buttons it stays clean with only the current menu showing.</p> <p>I tried attaching a &quot;submit&quot; button to the menu's...
<python><discord><discord.py>
2023-02-21 08:34:09
1
526
Ryan Thomas
75,517,910
9,644,712
Invalid projection when opening geopandas
<p>I need to do some spatial operations in geopandas. I created the new conda environment and installed geopandas <code>conda install --channel conda-forge geopandas</code>. When I run the following simple code:</p> <pre><code>import geopandas as gpd from shapely.geometry import Point gdf = gpd.GeoDataFrame([Point(1,1...
<python><geopandas><pyproj>
2023-02-21 08:27:19
1
453
Avto Abashishvili
75,517,843
13,088,678
median in each subgroup
<p>I have a csv file having city name and price. Need to find the median of price for each group of city.</p> <p>Input: from a csv file</p> <pre><code>London, 10 London, 25 London, 30 Brasov, 50 Brasov, 60 </code></pre> <p>Expected:</p> <pre><code>London, 25 Brasov, 55 </code></pre> <p>Solution using Pandas:</p> <pre><...
<python><python-3.x>
2023-02-21 08:20:04
1
407
Matthew
75,517,671
1,221,704
HTTP ERROR 500 when running Azure functions
<p>I am trying to run my python application as Azure functions. It runs perfectly fine when I use the default/original code.</p> <p>However, I am having problems when I add a new class. When I run the new code locally, it runs correctly (through &quot;Run and &quot;Debug&quot; as well as http://localhost:7071/api/myapp...
<python><azure><azure-functions><serverless>
2023-02-21 08:00:08
1
311
Groot
75,517,667
6,751,456
djano support nested or flat values for a single field using single serializer
<p>I have a <code>DateRangeSerializer</code> serializer that validates a payload.</p> <pre><code>import rest_framework.serializers as serializer from django.conf import settings class ValueNestedSerializer(serializer.Serializer): lower = serializer.DateTimeField(input_formats=settings.DATETIME_INPUT_FORMATS, requ...
<python><json><django><django-serializer>
2023-02-21 07:59:34
1
4,161
Azima
75,517,520
20,102,061
'pyrcc5' is not recognized as an internal or external command, operable program or batch file
<p>I am working from my laptop here in school, I've moved files from my PC at home to my laptop and when I try to run things I get this error:</p> <pre><code>'pyrcc5' is not recognized as an internal or external command, </code></pre> <p>operable program or batch file.</p> <p>Code: <a href="https://i.sstatic.net/ToSj9....
<python><pyqt5>
2023-02-21 07:41:39
1
402
David
75,517,410
3,520,404
Extract text based on annots from PDF using Python and PyPDF2
<p>I am trying to read the below PDF programmatically using Python to extract useful information.</p> <p><a href="https://i.sstatic.net/JLe5e.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JLe5e.png" alt="enter image description here" /></a></p> <p>Here, the &quot;attachments&quot; are basically links t...
<python><pdf><pypdf>
2023-02-21 07:29:55
1
14,416
saran3h
75,517,337
100,265
What is * in return function in python?
<p>What is * in return (last line of code)?</p> <pre><code>def func_list(): arr=[x for x in range(1,6,2)] arr1=arr arr1.append(10) return *arr, print(func_list()) </code></pre> <p>after run this code, return value is:</p> <blockquote> <p>(1, 3, 5, 10)</p> </blockquote>
<python><return>
2023-02-21 07:20:37
2
1,495
mSafdel
75,517,264
3,520,404
Check if two sentences contain any matching word using Python
<p>I'm trying to simply check whether two sentences have any similar words.</p> <p>Here's an example:</p> <pre><code>string_one = &quot;Author: James Oliver&quot; string_two = &quot;James Oliver has written this beautiful article which says....&quot; </code></pre> <p>In this case, these two sentences match the criteria...
<python><pypdf>
2023-02-21 07:12:56
2
14,416
saran3h
75,517,239
13,049,379
scipy.spatial.transform.Rotation giving apparantly wrong results
<p>For the below code,</p> <pre><code>from scipy.spatial.transform import Rotation for theta in [0,10,80,90,100,135,170,180,185,300]: r = Rotation.from_euler('zxy', [theta,theta,theta], degrees=True) print(f&quot;for theta = {theta} we get {r.as_euler('zxy', degrees=True)}&quot;) </code></pre> <p>the output is:...
<python><rotation>
2023-02-21 07:09:51
1
1,433
Mohit Lamba
75,517,186
8,176,763
python relative import fix
<p>I have a folder structure like this:</p> <pre><code>backend/ stage/ stage.py config.py </code></pre> <p>I am trying to import <code>config.py</code> into <code>stage.py</code> script with a relative import:</p> <pre><code>from ..backend import config </code></pre> <p>The directory which i run from the she...
<python>
2023-02-21 07:03:05
3
2,459
moth
75,517,089
813,970
python pandas - group by two columns and find average
<p>I have a dataframe like this</p> <pre><code>TxnId TxnDate TxnCount 233 2023-02-01 2 533 2023-02-01 1 433 2023-02-01 4 233 2023-02-02 3 533 2023-02-02 5 233 2023-02-03 3 533 2023-02-03 5 433 2023-02-03 2 </code></pre...
<python><pandas>
2023-02-21 06:49:12
2
628
KurinchiMalar
75,516,954
3,853,711
How do I access multiple python/shelve database at the same time?
<p>I'm building a simple program that concurrently save data to different shelve database with multithreading but error occurs when 2 threads invoke <code>shelve.open()</code> (for different files):</p> <pre><code>import threading import shelve import time def parallel_shelve(idx): print(&quot;thread {}: start&qu...
<python><python-3.x><shelve>
2023-02-21 06:29:07
2
5,555
Rahn
75,516,824
663,413
How to calculate percentages using Pandas groupby
<p>I have 3 users s1 who has 10 dollars, s2 10,20 dollars, and s3 20,20,30 dollars. I want to calculate percentage of users who had 10, 20 and 30 dollars. Is my interpretation correct here?</p> <p>input</p> <pre><code>import pandas as pd df1 = (pd.DataFrame({'users': ['s1', 's2', 's2', 's3', 's3', 's3'], ...
<python><pandas>
2023-02-21 06:08:50
2
831
ferrelwill
75,516,759
1,539,757
How we can import a python file stored in memory using memfs
<p>I have config.py file</p> <pre><code>def main(): dataToReturn = { &quot;url&quot;:&quot;testurl&quot; } </code></pre> <p>I have a python file myfile.py</p> <pre><code>from context import config def main(): testfunResp = config.main() logger.log(&quot;log in apistack&quot;) ...
<python><python-2.7>
2023-02-21 05:58:27
0
2,936
pbhle
75,516,608
1,857,373
KeyError on column appears only in when I assign column value, all other cells can use column except this assigned cell
<p><strong>Problem</strong></p> <p>Odd, when I run this in Jupyter Notebook new cells it works, but inside my full Jupyter Notebook I never drop the column but the data frame somehow has this column missing, hence error below. The only logic between # SETUP and # ASSIGN is code that processes missing values. When I ste...
<python><python-3.x><pandas><dataframe><jupyter-notebook>
2023-02-21 05:30:10
0
449
Data Science Analytics Manager
75,516,576
6,077,239
How to return multiple stats as multiple columns in Polars grouby context?
<p>The task at hand is to do multiple linear regression over multiple columns in groupby context and return respective beta coefficients and their associated t-values in separate columns.</p> <p>Below is an illustration of an attempt to do such using statsmodels.</p> <pre class="lang-py prettyprint-override"><code>impo...
<python><python-polars>
2023-02-21 05:26:14
2
1,153
lebesgue
75,516,448
2,998,077
Python Pandas GroupBy to calculate differences in months
<p>A data frame below and I want to calculate the intervals of months under the names.</p> <p>Lines so far:</p> <pre><code>import pandas as pd from io import StringIO import numpy as np csvfile = StringIO( &quot;&quot;&quot;Name Year - Month Score Mike 2022-11 31 Mike 2022-11 136 Lilly 2022-11 23 Lilly 20...
<python><pandas><dataframe>
2023-02-21 04:59:49
1
9,496
Mark K
75,516,194
2,739,700
Azure blob shared key creation 403 error getting
<p>I wanted to create Azure blob container using python code using shared key Authorization,</p> <p>I am getting below error:</p> <pre><code>b'\xef\xbb\xbf&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;&lt;Error&gt;&lt;Code&gt;AuthenticationFailed&lt;/Code&gt;&lt;Message&gt;Server failed to authenticat...
<python><python-3.x><azure><rest><azure-blob-storage>
2023-02-21 04:03:03
2
404
GoneCase123
75,516,086
2,458,922
Difference between sklearn.neural_network and simple Deep Learning by Keras with Sequential and Dese Nodes?
<p>Given , sklearn.neural_network and simple Deep Learning by Keras with Sequential and Dese Nodes, are the <strong>mathematically same</strong> just two API's with computation optimization? Yes Keras has a Tensor Support and could also liverage GPU and Complex models like CNN and RNN are permissible.</p> <p>However,...
<python><tensorflow><keras><deep-learning><neural-network>
2023-02-21 03:38:47
1
1,731
user2458922
75,515,931
3,136,710
Comparing an empty string against a vowel in a condition statement returning True
<p>The code simply subtracts 1 from <code>syllables</code> if consecutive vowels are encountered. However, when we iterate in the inner for loop for the second word <code>arms</code>, the variable <code>prev</code> is an empty string again, which should make <code>if (char in vowels) and (prev in vowels):</code> False,...
<python>
2023-02-21 03:00:04
0
652
Spellbinder2050
75,515,846
41,634
Best way to load a mmap dictionary in Python without deserializing
<p>Context:</p> <p>I've got Python processes running on the same container and I want to be able to share a read-only key-value object between them.</p> <p>I'm aware I could use something like Redis to share that info, but I'm looking for optimal solution in regards to latency as well as memory usage.</p> <p>My idea wa...
<python><mmap><rocksdb><data-serialization>
2023-02-21 02:39:54
2
2,035
Damien
75,515,809
21,169,587
Changing delimiters for DOCUMENT_TEXT_DETECTION in Google's Cloud Vision API
<p>I'm trying out Google's Cloud Vision API for text detection and have noticed the detection is using symbols such as <code>:</code>, <code>-</code> and <code>/</code> as breakpoints. I do not want them to be breakpoints in the scanned text as they make parsing the results for information more difficult. Looking throu...
<python><python-3.x><google-cloud-vision>
2023-02-21 02:34:07
0
867
Shorn
75,515,629
1,380,626
How to build the bias_act_plugin extension for stylegan3
<p>I am trying to run the code in <a href="https://github.com/NVlabs/stylegan3" rel="nofollow noreferrer">stylegan3</a>, and I am getting the error</p> <pre><code>RuntimeError: Error building extension 'bias_act_plugin' </code></pre> <p>I looked online for some ideas and <a href="https://github.com/NVlabs/stylegan3/iss...
<python><pytorch><ninja><stylegan>
2023-02-21 01:47:41
0
6,302
odbhut.shei.chhele
75,515,593
4,119,822
Calling Cython Functions from Numba njited function where numpy ndarrays are involved
<p>I am trying to do the following...</p> <pre class="lang-py prettyprint-override"><code># my_cython.pyx cpdef api double cyf(double x, double[:] xarr, double[:] yarr) nogil: # Do stuff return result </code></pre> <pre class="lang-py prettyprint-override"><code># my_cython.pxd cpdef api double cyf(double x, do...
<python><numpy><cython><numpy-ndarray><numba>
2023-02-21 01:34:40
0
329
Oniow
75,515,493
3,380,902
Pandas - look up key and map dictionary to a column
<p>I am trying to <code>.map</code> a dictionary to a pandas DataFrame. One of the columns in pandas DataFrame is the key in dict. Here's a reproducible example,</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'id': [0, 1, 2], 'nm': ['pn1','pn2','pn3], 'v...
<python><pandas><dictionary>
2023-02-21 01:07:54
2
2,022
kms
75,515,479
143,397
Why would a large TCP transfer randomly stall until data is sent in the opposite direction?
<p>I have two programs I'm writing that communicate with a simple ad-hoc protocol over TCP. They work together to transfer large (1-64 MB) binary files from the server to the client.</p> <p>There's an issue with data transmission stalling that causes a socket timeout on the receive side. I'd like to better understand w...
<python><sockets><tcp><network-programming><boost-asio>
2023-02-21 01:05:01
1
13,932
davidA
75,515,433
5,141,652
python tkinter move items from one frame to another
<p>I have 2 lists of items available items and active items, I am initially adding the items into the available list from a dictionary. I would like to activate items and move them from the available list into the active list when the associated activate button is pressed (this should also remove the item from the avai...
<python><python-3.x><tkinter>
2023-02-21 00:53:35
1
1,037
Chris
75,515,426
18,108,767
How to extract surfaces from an 3d array (volume)
<p>I create a 3d array like this:</p> <pre><code>arr = np.zeros((100, 100)) for i in range(5): for j in range(5): arr[i*20:(i+1)*20, j*20:(j+1)*20] = i+1 arr = np.tile(arr[np.newaxis,:,:], (100,1,1)) arr = np.transpose(arr, (0, 2, 1)) </code></pre> <p>The resulting shape will be <code>(100,100,100)</code>. ...
<python><numpy><numpy-ndarray>
2023-02-21 00:51:37
1
351
John
75,515,229
1,839,674
tf.data.Dataset.from_generator long to initialize
<p>I have a generator that I am trying to put into a tf.data.dataset.</p> <pre><code>def static_syn_batch_generator( total_size: int, batch_size: int, start_random_seed:int=0, fg_seeds_ss:SampleSet=None, bg_seeds_ss:SampleSet=None, target_level:str=&quot;Isotope&quot;): static_syn = StaticSynt...
<python><tensorflow><tf.data.dataset><tf.dataset>
2023-02-20 23:54:31
0
620
lr100
75,515,139
1,368,342
Extract stdout from long-running process
<p><em>Disclaimer: I have seen many similar questions, but either they do not use <code>asyncio</code>, or they don't seem to do exactly what I do.</em></p> <p>I am trying to get the output of a long-running command (it's actually a server that logs out to stdout) with the following:</p> <pre class="lang-py prettyprint...
<python><subprocess><python-asyncio>
2023-02-20 23:33:58
1
8,143
JonasVautherin
75,515,109
2,813,606
ImportError: cannot import name 'NDArray' from 'numpy.typing' (Prophet)
<p>I have not had as much trouble trying to install any other package in my Python experience than I have with Prophet.</p> <p>Here is a snippet of my code:</p> <pre><code>#Import libraries import pandas as pd from prophet import Prophet #Load data test = pd.read_csv('https://raw.githubusercontent.com/facebook/prophet...
<python><numpy><facebook-prophet>
2023-02-20 23:28:06
1
921
user2813606
75,514,999
13,676,262
How to call a function in a cog from a view using Nextcord?
<p>I have a Cog and a view in nextcord. I'm trying to call the function <code>magic_function</code> from my view, but I've found no way of achieving it. Do you know how is it possible ? Here is a simplification of the situation :</p> <pre class="lang-py prettyprint-override"><code>class MyView(nextcord.ui.View): de...
<python><discord><nextcord>
2023-02-20 23:07:46
1
340
Deden
75,514,895
1,497,385
Creating a cheap "overlay" Python virtual environment on top of current one without re-installing packages
<p>Problem:</p> <p>My program is getting a list of (<code>requirements_123.txt</code>, <code>program_123.py</code>) pairs (actually a list of script lines like <code>pip install a==1 b==2 c==3 &amp;&amp; program_123.py</code>).</p> <p><strong>My program needs to run each program in an isolated virtual environment based...
<python><pip><virtualenv><python-venv><virtual-environment>
2023-02-20 22:51:45
1
6,866
Ark-kun
75,514,846
1,930,248
pip says version 40.8.0 of setuptools does not satisfy requirement of setuptools>=40.8.0
<p>I am seriously stumped with this one and can't find any questions that match.</p> <p>If I run <code>pip3 show setuptools</code> or <code>pip2 list</code>, both say that <code>setuptools 40.8.0</code> is installed, but when I try to install a module locally, from a local source code directory, I get the error that sa...
<python><pip>
2023-02-20 22:42:51
2
917
RayInNoIL
75,514,819
371,334
How can we redact dynamic strings in Datadog traces?
<p>If we do <code>raise RuntimeError(password)</code> in an endpoint handler, the password will show up in the Datadog trace. How can we tell Datadog that certain variables should be redacted?</p>
<python><datadog>
2023-02-20 22:38:35
1
1,070
Andrew
75,514,736
2,595,859
Machine Learning associate solutions with issues
<p>I'm new with ML. I have basically a set of solutions, articles with title and steps, for common app issues in our departament. I want to use ML to scan those solutions and train a model that based on user inputs like &quot;In My pc microsoft word is not starting&quot;. I'm still not sure if solution would be model t...
<python><tensorflow><machine-learning><dataset>
2023-02-20 22:26:45
1
471
UserMan
75,514,722
523,612
Why do I get "TypeError: open() missing required argument 'flags' (pos 2)" or "TypeError: an integer is required (got type str)" when opening a file?
<p><strong>If your question was closed as a duplicate of this, it is because</strong> you have code along the lines of:</p> <pre><code>from os import * with open('example.txt', mode='r') as f: print('successfully opened example.txt') </code></pre> <p>This causes an error message that says <code>TypeError: open() m...
<python><file-io><python-os><shadowing>
2023-02-20 22:24:56
1
61,352
Karl Knechtel
75,514,549
8,127,672
Python inject a class based on a value passed to a function
<p>Let's say I have two classes which have methods accepting arguments as below:</p> <pre><code>class Foo: def __m1(*scenario): print(&quot;Foo.m1()&quot;) for s in scenario: print(s) class Bar: def __m1(*scenario): print(&quot;Bar.m1()&quot;,scenario) </code></pre> <p>Now...
<python><python-3.x>
2023-02-20 22:00:53
4
534
JavaMan
75,514,538
371,334
How to have different sample rates for different endpoints with Datadog
<p>Datadog can be configured to have different sample rates for different services via the <code>DD_TRACE_SAMPLING_RULES</code> environment variable. But how could we have different sample rates for different endpoints within a service?</p>
<python><datadog>
2023-02-20 21:59:48
1
1,070
Andrew
75,514,243
854,183
UnicodeEncodeError error when I redirect the output of a Python script into file
<p>I am writing a Python script to gather statistics on a directory that contains a very large number of files. The script itself works correctly by printing text into the terminal. I get no error. However, when I redirect the output stream into file in bash, I get the error below:</p> <pre><code>python file_paths_proc...
<python><bash><unicode>
2023-02-20 21:20:42
1
2,613
quantum231
75,514,168
3,593,246
Identify a unique tag using BeautifulSoup
<p>BeautifulSoup treats two tags as identical if they both contain the exact same content, even when the two tags are <em>not</em> the same DOM node.</p> <p>Example:</p> <pre><code>from bs4 import BeautifulSoup x = '&lt;div class=&quot;a&quot;&gt;&lt;span&gt;hello&lt;/span&gt;&lt;/div&gt;&lt;div class=&quot;b&quot;&gt;...
<python><beautifulsoup>
2023-02-20 21:09:58
1
362
jayp
75,513,921
9,841,408
How do I manually set the max value for the Y axis in my pandas boxplot?
<p>I'm looking at <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.boxplot.html" rel="nofollow noreferrer">this</a> official Pandas documentation, which says I can specify an &quot;object of class matplotlib.axes.Axes&quot; when creating my boxplot.</p> <p>How do I format this boxplot axis object ...
<python><pandas><matplotlib><boxplot><axes>
2023-02-20 20:38:45
2
399
Catlover
75,513,875
11,229,812
Python -How to compare columns from two dataframe and create 3rd with new values?
<p>I have two dataframes that contains names. What I am need to do is to check which of the names in second dataframe are not present in the first dataframe. For this example</p> <pre><code>list1 = ['Mark','Sofi','Joh','Leo','Jason'] df1 = pd.DataFrame(list1, columns =['Names']) </code></pre> <p>and</p> <pre><code>list...
<python><python-3.x><pandas>
2023-02-20 20:32:44
3
767
Slavisha84
75,513,842
1,750,821
Python SQLite math functions (no such function: SQRT)
<p>With Python 3.11 I try to use math function (sqrt) with SQLite SQL query. Let's say:</p> <pre><code>import sqlite3 as sq import pandas as pd con = sq.connect('database.db') query = &quot;SELECT SQRT(value) FROM table;&quot; pd.read_sql_query(query, con, index_col=None) </code></pre> <p>It throws &quot;no such functi...
<python><sqlite>
2023-02-20 20:27:48
1
366
d3m0n
75,513,793
10,731,523
Python Tensorflow - how does GradientTape operate and why can it give None as a result?
<p><strong>Abstract</strong><br /> I am trying to create a neural network with custom training. In my attempts I ended up with a<br /> <code>ValueError: No gradients provided for any variable</code> error. While trying to figure it out, I've found out that the problem appears because GradientTape sees no connection bet...
<python><tensorflow><machine-learning><neural-network><gradienttape>
2023-02-20 20:20:56
0
1,435
Rabter
75,513,683
1,088,259
How auto consume to new topics?
<p>I consume data from kafka and all works perfect. But one problem - when i'm creating new topic - my script doesn't know about this. How auto refresh list of subscribed topics? I think pattern can help me, but it was mistake.</p> <pre><code>from kafka import KafkaConsumer import json consumer = KafkaConsumer( ...
<python><apache-kafka>
2023-02-20 20:05:28
1
355
user1088259
75,513,619
8,818,287
is redudant to use `__all__` and `import specific_module`?
<h3>Background</h3> <p>Reading the answers for <a href="https://stackoverflow.com/questions/44834/what-does-all-mean-in-python">this question</a>, and looking at the Pandas and Django repository.</p> <p>If <code>__all__</code> is defined then when you <code>import *</code> from your package, only the names defined in <...
<python><pandas><syntax>
2023-02-20 19:55:41
1
789
asa
75,513,612
12,435,792
How to add empty columns to a dataframe?
<p>I have a dataframe with 38 columns. I want to add 19 more blank columns at the end of it.</p> <p>I've tried this:</p> <pre><code>df.insert([39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57], ['Quality Control - Dupe Ticketing/Dupe Invoicing', 'Error Type', 'Passe...
<python><pandas><dataframe>
2023-02-20 19:55:16
3
331
Soumya Pandey
75,513,518
1,497,139
How are fully qualified names for slots defined in LinkML?
<p>linkML's slot concept will allow to share slot names between classes as IMHO is typical for the ontological approach to modeling. In most of my <a href="https://wiki.bitplan.com/index.php/SiDIF" rel="nofollow noreferrer">SiDIF</a> based models i am using object oriented approaches where there are separate properties...
<python><linkml>
2023-02-20 19:43:51
1
15,707
Wolfgang Fahl
75,513,420
11,170,350
Average consective nth row in numpy
<p>I have a 3D numpy array.</p> <pre><code>x=np.random.randint(low=0,high=10,size=(100,64,1000)) </code></pre> <p>I want to average every 4th row, for example first 4, then 4-8, 8-12 and so on. I tried the following way</p> <pre><code>x =np.split(x,len(x)/4) np.mean(np.stack(x),1) </code></pre> <p>I am bit confused if ...
<python><numpy>
2023-02-20 19:29:20
2
2,979
Talha Anwar
75,513,149
11,173,364
How to save the output of a jupyter notebook cell (a pandas dataframe) as a high resolution picture?
<p>For normal plots I can set the <code>dpi</code> argument to generate a high resolution picture.</p> <p>But for outputs of a cell such as in this picture, which is a output by displaying a pandas dataframe, how can I save it as a high resolution picture?</p> <p><a href="https://i.sstatic.net/wxK7G.png" rel="nofollow ...
<python><jupyter-notebook>
2023-02-20 18:52:50
1
769
user900476
75,513,103
14,167,364
tkinter mainloop() not ending the script once it completes
<p>For some reason the <code>mainloop()</code> is not ending. The final <code>print</code> statement never gets triggered but everything else does. Any idea what is causing this or how to resolve it? It happens even without the threading.</p> <pre><code>import time from tkinter.filedialog import askdirectory from tkint...
<python><tkinter><python-multithreading><mainloop>
2023-02-20 18:48:06
2
580
Justin Oberle