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,797,128
10,259,099
Python3 module 'cups' has no attribute 'Connection'
<p>I try to convert python2 to python3 and there is code not working on `cups.Connection()``</p> <pre><code>import cups conn = cups.Connection() </code></pre> <p>And its produce stacktree</p> <pre><code>Traceback (most recent call last): File &quot;/Users/sagara/Downloads/Printing Script/mnd_75 (latest).py&quot;, lin...
<python><cups><pycups>
2023-03-21 03:37:46
0
341
Rofie Sagara
75,797,103
2,998,077
Pandas new column from counts of column contents
<p>A simple data frame that I want to add a column, to tell how many Teams that the Project has, according to a name dictionary.</p> <p><a href="https://i.sstatic.net/Ctp4u.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Ctp4u.png" alt="enter image description here" /></a></p> <p>The way I came up with s...
<python><pandas><dataframe>
2023-03-21 03:28:59
1
9,496
Mark K
75,797,073
6,248,559
Pandas data masking where the conditions come from other variables
<p>I have a dataframe and two lists as below:</p> <pre><code>seller1 = [5, 4, 3] seller2 = [4, 2, 1] df = {'customer': [1, 1, 1, 2, 2, 2], 'time': [1,2,3,1,2,3], 'location': [3,4,2,4,3,3], 'demand':[10,12,15,20,8,16], 'price':[3,4,4,5,2,1]} df = pd.DataFrame(df) </code></pre> <p>Which results in the following table:<...
<python><pandas><dataframe><data-masking>
2023-03-21 03:22:34
2
301
A Doe
75,796,987
6,676,101
How do we check whether a class has overridden a particulair method inherrited from `object`?
<p>I was thinking about writing a class decorator which would check whether a particular method inherited from <code>object</code> had been overridden or not.</p> <pre class="lang-python prettyprint-override"><code>import io def check_str_method(kls:type) -&gt; type: with io.StringIO() as strm: if &quot;__...
<python><python-3.x><decorator><python-decorators>
2023-03-21 03:00:44
1
4,700
Toothpick Anemone
75,796,965
6,676,101
How do we write a decorator which forces a class to inherit from some other class?
<p>Normally, we have one class inherit from another as follows:</p> <pre class="lang-python prettyprint-override"><code>class ChildClass(ParentClass): &quot;&quot;&quot; ChildClass is a subclass of ParentClass ParentClass is a superclass of ChildClass &quot;&quot;&quot; pass </code></pre> <...
<python><python-3.x><decorator><python-decorators>
2023-03-21 02:56:25
1
4,700
Toothpick Anemone
75,796,905
15,724,084
python tkinter getting text value from selected radiobutton
<p>I have a radiobuttons, for user to select. On each selection it gives to Entry widget some text. Now, I want to get the text value from the radiobutton which is <code>selected</code>. As I remember checkboxes have true or false values, but I used radio buttons on my project. screen<a href="https://i.sstatic.net/vPnF...
<python><tkinter><radio-button>
2023-03-21 02:40:55
1
741
xlmaster
75,796,866
850,781
How do I select a subset of a DataFrame based on a condition on one level of a MultiIndex
<p>Similar to <a href="https://stackoverflow.com/q/75796107/850781">How do I select a subset of a DataFrame based on one level of a MultiIndex</a>, let</p> <pre><code>df = pd.DataFrame({&quot;v&quot;:range(12)}, index=pd.MultiIndex.from_frame( pd.DataFrame({&quot;name&quot;:4*[&q...
<python><pandas><dataframe><multi-index>
2023-03-21 02:29:59
1
60,468
sds
75,796,835
10,259,099
Migrate python2 to 3 IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
<p>So I try to migrate legacy python2 script to python3 but i got error on the some code</p> <pre><code>print ('resizing images') for x in range(0, len(img)): imgResized.append(cv2.resize(img[x], (301 * len(img), 301))) print ('resizing done') source = interlace(imgResized, 301 * len(img), 301 * len(img)) cv2_im =...
<python><numpy><opencv>
2023-03-21 02:23:40
1
341
Rofie Sagara
75,796,716
13,176,896
InvalidRequestError when make order in pybit
<p>I want to test some codes for placing short-open orders using pybit. My code is as follows.</p> <pre><code>from pybit import * session = usdt_perpetual.HTTP(endpoint = &quot;https://api-testnet.bybit.com&quot;, api_key = 'yyyyy', api_secret = 'xxxxxx') sym...
<python><bybit><python-bybit><pybit>
2023-03-21 01:47:50
1
2,642
Gilseung Ahn
75,796,673
19,425,874
Receiving print error while using ReportLab to print PDFs in Python
<p>This is a difficult issue to diagnose, because I am unsure how to even get the full details. I've been testing for hours and there is no clear pattern. Every few times I run my script, I receive this printer error (image below):</p> <p><a href="https://i.sstatic.net/9YO2a.png" rel="nofollow noreferrer"><img src="h...
<python><pdf-generation><pywin32><reportlab>
2023-03-21 01:31:31
0
393
Anthony Madle
75,796,615
1,857,373
TypeError: get_params() missing 1 required positional argument: 'self' on RandomSearchCV
<p><strong>Problem</strong></p> <p>Running a KNeighborsClassifier with OneVsRestClassifier. Already have several other classifiers working perfect with OneVsRestClassifier, but when I try the pattern of code that worked for other RandomSearchCV for classifer, this once hits a snat on Error Type.</p> <p>I have parameter...
<python><scikit-learn>
2023-03-21 01:19:27
0
449
Data Science Analytics Manager
75,796,520
4,441,239
Unable to generate service tokens - Permission denied on resource
<p>I am trying to follow documentation mentioned here in Google documentation: <a href="https://cloud.google.com/run/docs/authenticating/service-to-service#acquire-token" rel="nofollow noreferrer">https://cloud.google.com/run/docs/authenticating/service-to-service#acquire-token</a></p> <p>I have tried both programmatic...
<python><google-cloud-platform><google-cloud-iam>
2023-03-21 00:55:12
2
949
Moni
75,796,507
14,173,197
How to run multiple batches in parallel with multiprocessing in python?
<p>I have a large dataset (approx 38,000 records) that I need to train. So I am trying to break down the loop into batches. As each batch is independent, I want to run batches in parallel for faster execution. How can I do that using multiprocessing? Below is my code:</p> <pre><code> if __name__ == '__main__': # Cr...
<python><pandas><multiprocessing>
2023-03-21 00:53:25
1
323
sherin_a27
75,796,504
11,198,671
Plotting an ellipse with eigenvectors using matplotlib and numpy
<p>I ran into a deadlock with the following code, and I hope you can help me out. It seems like a deadlock situation because I need to understand the math in order to write the code, but I also need the code to understand the math. I have spent half a day trying to figure out what's wrong, but with no success. It could...
<python><numpy><matplotlib><math><ellipse>
2023-03-21 00:52:30
1
345
jupiter_jazz
75,796,489
11,370,582
Assign url to wsgi gunicorn server
<p>This may seem like a stupid question but I'm very new to web development so please bear with me.</p> <p>I have created a dash web app that I am deploying with a wsgi server, and I can't for the life of me find any information on how to actually assign a url to the ip address.</p> <p>For example, if I follow this tut...
<python><flask><url><web-applications><plotly-dash>
2023-03-21 00:48:29
1
904
John Conor
75,796,382
850,781
How do I select a subset of a DataFrame based on a condition on a column
<p>Similar to <a href="https://stackoverflow.com/q/75796107/850781">How do I select a subset of a DataFrame based on one level of a MultiIndex</a>, let</p> <pre><code>df = pd.DataFrame({&quot;v&quot;:[x*x for x in range(12)]}, index=pd.MultiIndex.from_product([[&quot;a&quot;,&quot;b&quot;,&quot;c&quo...
<python><pandas><dataframe><multi-index>
2023-03-21 00:19:33
1
60,468
sds
75,796,355
6,665,586
Error when testing private methods in Pytest
<p>I have a private method in a module, for example</p> <p>wallets.py</p> <pre><code>def __foo(): return 0 </code></pre> <p>When I try to test this method with this code</p> <p>test_wallets.py</p> <pre><code>from unittest import TestCase from db.services import wallets class GetTokenQuantity(TestCase): def tes...
<python><pytest><python-unittest>
2023-03-21 00:11:52
1
1,011
Henrique Andrade
75,796,307
17,090,926
How do you use conditionals with Polars LazyFrames
<p>i tried to use lazyframes, but it seems there are a lot of limitations.</p> <p>for example, i have a list comprehension which runs a function on an expression x</p> <pre><code>final = [ df.select( threshold_rank(λ=lambda_df.select(series + '_lambda').item(), x=pl.col(series)) ...
<python><dataframe><python-polars>
2023-03-20 23:58:42
1
415
rnd om
75,796,164
12,787,236
How to add main function to pylint missing-function-docstring (C0116) as an exception?
<p>How can I avoid pylint to mark missing docstring in the <code>main</code> function, without removing any others from the default, like the <code>__init__</code> method?</p> <p><a href="https://i.sstatic.net/fiJ8t.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fiJ8t.png" alt="enter image description h...
<python><configuration><pylint><linter>
2023-03-20 23:24:09
1
1,948
Henrique Branco
75,796,107
850,781
How do I select a subset of a DataFrame based on one level of a MultiIndex
<p>Let</p> <pre><code>df = pd.DataFrame({&quot;v&quot;:range(12)}, index=pd.MultiIndex.from_product([[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;],[1,2,3,4]])) </code></pre> <p>and suppose I want to select only rows with the first level being <code>a</code> or <code>c</code>:</p> <pre><code> v a 1 0 2 1 3 ...
<python><pandas><dataframe><multi-index>
2023-03-20 23:11:22
1
60,468
sds
75,795,933
4,937,644
How do I extract text into a CSV file from multiple text files using Python?
<p>I have a folder full of subfolders with text (.txt) files that look like this:</p> <pre><code>some random information here ignore it author: Lisa Smith Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sit amet leo quis risus viverra varius pretium sed nunc. Nullam vitae tempor nisl. Quisque viverra ...
<python><csv>
2023-03-20 22:38:38
1
661
hy9fesh
75,795,728
6,817,610
pySpark - join on nullable column, conditional join
<p>I have a pyspark code that joins two DFs on 3 columns:</p> <pre><code>final_df = spark_company_df .join( spark_geo_df, (spark_company_df.column1 == spark_geo_df.column1) &amp; (spark_company_df.column2 == spark_geo_df.column2) &amp; (spark_company_df.column3 == spark_geo_df.column3), &quot;left_...
<python><sql><apache-spark><pyspark><apache-spark-sql>
2023-03-20 22:03:13
1
953
Anton Kim
75,795,588
4,103,997
How to create new column that can combine adjacent but broken up "on" values into groups using pandas
<p>I have a dataframe with a column of 1s (corresponding to an &quot;ON&quot; signal) and 0s (corresponding to an &quot;off&quot; signal).</p> <p>My data has some noise in it, such that the first &quot;ON&quot; signal has some 0s in the middle which makes it appear broken up. The same happens with the other &quot;ON&qu...
<python><pandas><dataframe>
2023-03-20 21:41:27
2
488
Ciaran
75,795,474
12,139,954
Why did the bart-large-cnn summarization model giving funny output with different length settings?
<p>I have a piece of text of 4226 characters (316 words + special characters)</p> <p>I am trying different combinations of min_length and max_length to get summary</p> <pre><code>print(summarizer(INPUT, max_length = 1000, min_length=500, do_sample=False)) </code></pre> <p>With the code:</p> <p>The code is</p> <pre><cod...
<python><nlp><huggingface-transformers><summarization><large-language-model>
2023-03-20 21:26:38
1
381
Ani
75,795,327
5,942,100
Tricky remove, replace and transform transformation using Pandas
<p>I wish to remove the first row, and then push the value in the second row as a column header, replacing the original value.</p> <p><strong>Data</strong></p> <pre><code> Unnamed: 0_Date val1 val2 0 1 state 2 AA1 63 65 3 AA2 0 0 </code></pre> <p><stron...
<python><pandas><numpy>
2023-03-20 21:08:55
1
4,428
Lynn
75,795,302
11,572,712
Error in the creation of a class instance
<p>I have created the class <code>Animal</code>:</p> <pre class="lang-py prettyprint-override"><code>class Animal: def __int__(self, height, weight): self.height = height self.weight = weight </code></pre> <p>Then I want to create the instance <code>animal_1</code> of class <code>Animal</code> like ...
<python><class><error-handling>
2023-03-20 21:05:47
1
1,508
Tobitor
75,795,170
11,294,747
How to design Codeforces interactive grader?
<p>I came across one interactive problem in Codeforces. I want to know how the grader or interactor (as per Codeforces' terms) might be designed.</p> <p>Let's say I want to create a grader for this problem: <a href="https://codeforces.com/gym/101021/problem/1" rel="noreferrer">1. Guess the Number</a>.</p> <p>My solutio...
<python>
2023-03-20 20:50:46
1
383
sgalpha01
75,794,919
3,197,684
How to segment and transcribe an audio from a video into timestamped segments?
<p>I want to segment a video transcript into chapters based on the content of each line of speech. The transcript would be used to generate a series of start and end timestamps for each chapter. This is similar to how YouTube now &quot;auto-chapters&quot; videos.</p> <p>Example .srt transcript:</p> <pre><code>... 70 0...
<python><machine-learning><nlp><openai-api><automatic-speech-recognition>
2023-03-20 20:14:46
1
741
nonsequiter
75,794,830
5,805,610
I want to connect to an api and extract the data
<p>I'm doing my own python analytics project on compiling and analysing data from this open-data source:</p> <p>(<a href="https://data.gov.ie/dataset?q=homeless&amp;api=true&amp;sort=score+desc%2C+metadata_created+desc&amp;theme=Housing" rel="nofollow noreferrer">https://data.gov.ie/dataset?q=homeless&amp;api=true&amp;...
<python><pandas><data-analysis>
2023-03-20 20:03:59
1
334
Nabeel
75,794,492
21,286,804
mypy does not recognize a method of a class
<pre><code>from abc import ABC, abstractmethod from typing import List class AirConditioner: &quot;&quot;&quot;Class that represents an air conditioner&quot;&quot;&quot; def __init__(self, identify: str, state: bool, temperature: int): self.identify = identify self._state = state self...
<python><python-3.x><mypy><command-pattern>
2023-03-20 19:24:33
2
427
Magaren
75,794,429
518,004
-bash: python: command not found on mac
<p>I've tried a number of approaches:</p> <pre><code>brew install python ==&gt; Downloading https://formulae.brew.sh/api/formula.jws.json ######################################################################## 100.0% ==&gt; Downloading https://formulae.brew.sh/api/cask.jws.json ########################################...
<python><macos>
2023-03-20 19:17:36
1
8,739
Will
75,794,357
18,086,775
Unable to save excel workbook on mac using xlwings
<p>I'm running the same Xlwings code with jupyter notebook on both MAC and Windows to save a new Excel workbook in a folder.</p> <pre><code>import xlwings as xw import os wb = xw.Book() wb.save(os.path.join(os.getcwd(),r'pro/fi/g.xlsx')) wb.close() </code></pre> <p>It runs on Windows fine but gives the following error...
<python><xlwings>
2023-03-20 19:09:08
1
379
M J
75,793,858
2,991,243
Regular expression in python is not returning the desired result
<p>Suppose that I have a string consisting of different sentences. I expect to remove the part that begins with <code>It was formerly known as </code> until the end of this sentence. I want to stop cleaning until it reaches <code>. Withey Limited</code>. If it is not the case, it ends cleaning until <code>. It</code>.<...
<python><regex>
2023-03-20 18:08:59
1
3,823
Eghbal
75,793,853
10,620,003
np.concatenate(np.stack the different arrays with a general solution
<p>I have 6 array with same size. I have a general function and based on a value I should consider 2, 3, 5, 6 array of these and concate them with the following way. Could you please help me with a general solution for this? Here I only provide a simple example and in my real data, I should build different array and I ...
<python><numpy>
2023-03-20 18:08:08
1
730
Sadcow
75,793,794
4,802,259
adding __getitem__ accessor to Python class method
<p>I'm attempting to add an item getter (<code>__getitem__</code>, to provide the <code>[]</code> syntax) to a class method so that I can use some unique-ish syntax to provide types to functions outside the normal parentheses, like the following. The syntax on the last line (of this first snippet) is really the goal fo...
<python><python-decorators><python-typing>
2023-03-20 18:03:00
4
2,864
David Culbreth
75,793,683
6,039,697
Algorithm to render a binary tree datastructure
<p>I have some data organized as a binary tree where each node has exactly 0 or 2 children.</p> <p>I'm looking for an algorithm that allows me to render this tree to an image (PNG preferred).</p> <p>I want to render the nodes as a box which contains some multiline text representing the data represented by the node.</p>...
<python><binary-tree><render>
2023-03-20 17:53:04
1
1,184
Michael Pacheco
75,793,632
20,051,041
How to convert a string list to (object) list in Pandas?
<p>I have the dictionary below in which the values are string type:</p> <pre><code>data = {'object_1':&quot;['abc']&quot;, 'object_2':&quot;['def']&quot;, &quot;object_3&quot;: &quot;['xyz']&quot;, &quot;object_4&quot;: &quot;['abc']&quot;} </code></pre> <p>I want to convert the values of the dictionary from a string t...
<python><pandas><string>
2023-03-20 17:47:39
3
580
Mr.Slow
75,793,592
13,981,285
Control bitrate of video generated using opencv VideoWriter
<p>I am generating a video from a set of images using <code>cv2.VideoWriter(filename,fourcc,fps,size)</code></p> <p>I want to use a particular bitrate for my output videos to reduce the file sizes. I am trying to mimic a ffmpeg command which generated videos with smaller sizes. One prominent difference I noticed is the...
<python><linux><opencv><ffmpeg><h.264>
2023-03-20 17:43:53
0
402
darthV
75,793,590
8,968,801
Django Rest Framework: Remove Appended "[]" from List Parameter
<p>I have a django rest framework application set up with two packages: One's called djangorestframework-camel-case (to &quot;camelizes&quot; the parameters in the API docs) and the other is drf-spectacular (to automatically generate Swagger docs for my API).</p> <p>The camel case package also has the effect that it ca...
<python><django><django-rest-framework>
2023-03-20 17:43:41
0
823
Eddysanoli
75,793,546
1,241,786
Regex to include curly brackets in some strings
<p>I have a spreadsheet that contains a &quot;find&quot; column and a &quot;replace&quot; column. Note that some strings are a subset of other strings.</p> <pre><code>Find Replace {Example1} {50M00_Dewirer_South\Example1} {Example1\Alarm} {50M00_Dewirer_South\Example1\Alarm} {Exam...
<python><regex>
2023-03-20 17:39:46
1
728
kubiej21
75,793,541
16,853,253
Google Cloud Console shows Client is unauthorized to retrieve access tokens using this method in python
<p>I saw so many question relating to this GCP issue, none of it helped. I have created service account and added to &quot;Manage Domain-wide delegation&quot; with scopes. But I still get this error <code>Client is unauthorized to retrieve access tokens using this method or client not authorized for any of the scopes r...
<python><google-cloud-platform><google-workspace>
2023-03-20 17:38:38
1
387
Sins97
75,793,446
14,890,683
Python - Plotly - make_subplots - Title Overlap / Move Subplot Titles
<p>How do I adjust the subplot titles so that they don't overlap with the x-axis?</p> <p><a href="https://i.sstatic.net/n2lNf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/n2lNf.png" alt="Plotly Image" /></a></p> <p>Here is the code for reference:</p> <pre class="lang-py prettyprint-override"><code>imp...
<python><plotly>
2023-03-20 17:25:21
1
345
Oliver
75,793,406
14,409,562
when concatenating two data frames an extra row is added
<p>I am trying to concatenate two panda dataframes but unfortunately it's not working this is the following code:</p> <pre><code> train_df =pd.concat([x_train,y_train],axis =1 ) print(train_df) </code></pre> <p>y_train and x_train are of the same length and have the correct size and row indexes, I just wish to concten...
<python><arrays><pandas>
2023-03-20 17:21:18
1
412
a_confused_student
75,793,236
1,422,096
Roll and pad in Numpy
<p>Is there a built-in Numpy function to shift (roll + pad) an 1D array?</p> <p>Something like this:</p> <pre><code>import numpy as np def roll_pad(a, t): b = np.roll(a, t) if t &gt;= 0: b[:t] = 0 else: b[t:] = 0 return b z = np.array([1, 2, 3, 4, 5, 6]) print(z) print(roll_pad(z, 2))...
<python><numpy><zero-padding>
2023-03-20 17:04:01
1
47,388
Basj
75,793,219
4,436,572
Polars replace_time_zone function throws error of "non-existent in time zone"
<p>here's our test data to work with:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl import pandas as pd from datetime import date, time, datetime df = pl.DataFrame( pl.datetime_range( start=date(2022, 1, 3), end=date(2022, 9, 30), interval=&quot;5m&quot;, t...
<python><datetime><timezone><python-polars>
2023-03-20 17:01:52
2
1,288
stucash
75,793,123
6,679,011
Twilio credential issues
<p>This is my case. I need to fetch SMS data through Twilio. This is what I have: Account SID 'ACxxxxxxxxx' For security reason, they could not give me the token for the Account SID, but setup a API Sid and its token API SID 'SKxxxxxxxxxxxxx' Token 'XXXXXXXXXXXXXXXXX'</p> <p>I already figured out how to access the data...
<python><twilio-api>
2023-03-20 16:51:21
1
469
Yang L
75,793,089
1,773,592
How do I seek using python in GCP Pubsub?
<p>I am trying to use the Google Python pubsub client to seek to now in a subscription:</p> <pre><code>seek_request_dict = { &quot;subscription&quot;:subscription, &quot;time&quot;:current_time } request = pubsub_v1.types.SeekRequest(seek_request_dict) </code></pre> <p>this gives the error:<...
<python><google-cloud-platform><google-cloud-pubsub>
2023-03-20 16:48:48
0
3,391
schoon
75,793,069
12,548,458
Can conda channels include multiple channels?
<p>I'm reading the <a href="https://conda.io/projects/conda/en/latest/user-guide/concepts/channels.html" rel="nofollow noreferrer">documentation on Conda channels</a>, and the documentation appears to state that:</p> <ul> <li>By default, Conda uses the <code>defaults</code> channel. This can be verified locally:</li> <...
<python><anaconda><conda>
2023-03-20 16:47:11
1
3,289
dlq
75,793,013
864,245
Combining Dumper class with string representer to get exact required YAML output
<p>I'm using PyYAML 6.0 with Python 3.9.</p> <p>In order, I am trying to...</p> <ol> <li>Create a YAML list</li> <li>Embed this list as a multi-line string in another YAML object</li> <li>Replace this YAML object in an existing document</li> <li>Write the document back, in a format that will pass YAML 1.2 linting</li> ...
<python><yaml><pyyaml>
2023-03-20 16:41:43
1
1,316
turbonerd
75,793,007
416,734
What is the benefit of using complex numbers to store graph coordinates?
<p>I am looking at a <a href="https://github.com/hughcoleman/advent-of-code/blob/main/2022/12.py" rel="nofollow noreferrer">solution</a> to an <a href="https://adventofcode.com/2022/day/12" rel="nofollow noreferrer">Advent of Code puzzle</a> that stores coordinates as complex numbers:</p> <pre><code> heightmap = { ...
<python><graph-theory><complex-numbers>
2023-03-20 16:41:22
1
831
outis
75,792,946
4,504,711
Fast implementations in Python to compute the mean of products
<p>I have a list of float elements <code>x=[0.1, 2, 0.5, ...]</code> with length <code>l=len(x)</code>. I am looking for fast/vectorized implementations to compute mean of the products between all two pairs from <code>x</code>:</p> <pre><code>S=0.0 for x1 in x: for x2 in x: S+=x1*x2/(l*l) </code></pre> <p>T...
<python><numpy><covariance>
2023-03-20 16:34:18
2
2,842
Botond
75,792,901
8,913,983
Calculate the carry over from rows based on criteria in pandas
<p>I have a <code>df</code> like this :</p> <pre><code>date time value 2021-08 0.0 22.50 2021-08 5.0 6600.00 2021-09 0.0 1057.62 2021-09 1.0 646.35 2021-09 2.0 311.76 2021-09 3.0 3982.50 2021-09 4.0 900.00 2021-09 7.0 546.00 2021-09 9.0 1...
<python><pandas><datetime>
2023-03-20 16:28:55
2
4,870
Jonas Palačionis
75,792,678
11,304,830
Count words in a sentence controlling for negations
<p>I am trying to count the number of times some words occur in a sentence while controlling for negations. In the example below, I write a very basic code where I count the number of times &quot;w&quot; appear in &quot;txt&quot;. Yet, I fail to control for negations like &quot;don't&quot; and/or &quot;not&quot;.</p> <...
<python><nlp>
2023-03-20 16:08:43
1
1,623
Rollo99
75,792,660
10,673,107
Solve TSP without crossing through the object
<p>I have a grid of points which are forming a cube. The cube looks like this:</p> <p><a href="https://i.sstatic.net/ioKsT.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ioKsT.png" alt="enter image description here" /></a></p> <p>Now I want to create a path through all the points, so I had the following...
<python>
2023-03-20 16:07:11
2
994
A. Vreeswijk
75,792,623
4,939,167
How to setup and teardown with multiple files and test cases in pytest
<p>I am new to pytest. I have 10 test files which has multiple tests defined in each test file like below</p> <pre><code>test_repo - features -step_defs - stress_tests -file1 (10 test cases) -file2 (3 test cases) - functional_tests - file2 (2 test cases) - file3 (20 t...
<python><pytest><pytest-bdd>
2023-03-20 16:03:43
1
352
Ashu123
75,792,476
8,713,442
Find mode in panda Dataframe
<p>Find mode among all values in c1_ind and c2_ind . I don't want to mode along each column.</p> <pre><code>import pandas as pd import numpy as np from scipy.stats import mode list =[{&quot;col1&quot;:123,&quot;C1_IND &quot;:&quot;Rev&quot;,&quot;C2_IND&quot;:&quot;Hold&quot;}, {&quot;col1&quot;:456,&quot;C1_IND...
<python><pandas><dataframe><numpy>
2023-03-20 15:49:44
1
464
pbh
75,792,259
11,770,390
Prevent sharing of environmental variables windows <-> wsl subsystem
<p>I'm using an SDK on both windows and in wsl ubuntu. The SDK provide some functionality through a python script that collects environment information (env variables) and locates certain resources based on it. Now I'm getting this error:</p> <pre><code> File &quot;/home/myuser/dev/esp-idf/tools/idf_tools.py&quot;, li...
<python><terminal><environment-variables><esp-idf>
2023-03-20 15:32:04
1
5,344
glades
75,792,213
12,961,237
Convert Docx numbered list to Python and keep indexes
<p>I have a bunch of documents in <code>docx</code> format containing numbered lists like:</p> <pre><code>1) Foo 2) Bar </code></pre> <p>and also nested lists like:</p> <pre><code>I. Heading a) Sub paragraph II. ... </code></pre> <p>I'm currently working with <code>docx2python</code> which at least gives <em>some</...
<python><docx>
2023-03-20 15:28:12
1
1,192
Sven
75,792,173
11,968,226
Python DeepL API glossary not working for translation
<p>I am using the <a href="https://www.deepl.com/de/docs-api/translate-text/translate-text/" rel="nofollow noreferrer">DeepL API</a> to translate text and I also want to include a <code>glossary</code> for translating.</p> <p>Creating the glossary worked fine, I can see all the correct entries but translating with the ...
<python><glossary><deepl>
2023-03-20 15:23:58
1
2,404
Chris
75,792,127
19,980,284
Convert pandas column values based on groupings of values
<p>I have a pandas columns with values <code>1.0</code>, <code>2.0</code>, <code>3.0</code>, <code>4.0</code>, and <code>5.0</code> like below:</p> <pre><code>0 5.0 1 2.0 2 3.0 3 3.0 4 5.0 ... 1039 5.0 1040 1.0 1041 2.0 1042 4.0 1043 1.0 </code></pre> <p>I want rows ...
<python><pandas><dataframe><numpy>
2023-03-20 15:19:50
1
671
hulio_entredas
75,792,022
412,252
How do I get typing working in python mixins?
<ul> <li>I have a mixin that will always be used with a specific type of class i.e. a subclass of <code>widgets.Input</code></li> <li>I want to override a few methods using the mixin, and I'm referencing attributes that exist on <code>widgets.Input</code> in my custom methods</li> </ul> <p>How do I tell the python type...
<python><django><mypy><python-typing>
2023-03-20 15:08:57
1
4,674
demux
75,792,014
19,980,284
Is it possible to combine levels of categorical variables in a statsmodels logit model?
<p>Let's say I'm regressing on hair color, and I have two independent variables: income and gender.</p> <p>Let's say income is a pandas column with <code>1</code>, <code>2</code>, and <code>3</code> representing these different income levels:</p> <pre><code>0-49,999 : 1 50,000-99,999: 2 100,000-199,999: 3 </code></pre>...
<python><logistic-regression><statsmodels>
2023-03-20 15:08:38
0
671
hulio_entredas
75,791,918
112,976
Headers with FastAPI
<p>I created an endpoint which requires the User Agent as described in the documentation: <a href="https://fastapi.tiangolo.com/tutorial/header-params/#__tabbed_2_1" rel="nofollow noreferrer">https://fastapi.tiangolo.com/tutorial/header-params/#__tabbed_2_1</a></p> <p>However, the Swagger documentation generated displa...
<python><swagger><fastapi>
2023-03-20 14:59:47
1
22,768
poiuytrez
75,791,765
18,363,860
how to download videos that require age verification with pytube?
<p>I download and clip some youtube videos with pytube but some videos are not downloading and asking for age verification. How can I solve this? Thanks for your advice</p>
<python><dataset><pytube>
2023-03-20 14:47:32
7
353
byhite
75,791,727
2,697,895
How can I escape from a GPIO.wait_for_edge?
<p>I have this code:</p> <pre><code>while True: try: Stat1 = GPIO.input(WPIN) time.sleep(WARNST) Stat2 = GPIO.input(WPIN) if Stat1 == Stat2: SendWarnStat(Stat2) Event = None while Event != WPIN: Event = GPIO.wait_for_edge(WPIN, GPIO.BOTH) except: break </code></pre> <p>Is there a way to ...
<python>
2023-03-20 14:43:46
2
3,182
Marus Gradinaru
75,791,698
774,133
Cannot cast array data from dtype('O') in np.bincount
<p>Unfortunately I cannot share the data I am now using, so this question will not contain an MWE.</p> <p>I have this code:</p> <pre class="lang-py prettyprint-override"><code>def baseline(labels): # dummy classifier returning the most common label in labels print(labels.shape) print(type(labels)) print...
<python><numpy>
2023-03-20 14:41:20
1
3,234
Antonio Sesto
75,791,594
764,365
plot failing to update for multiple Pandas hist calls on mac when run one at a time
<p>Here's some sample code. Surprisingly this bug seems to require running the last line separately from the rest.</p> <pre><code>import pandas as pd import numpy as np n = np.nan a = [1,2,3,4,5,1,2,3,4,5.0,n,n,n,n,n,n] b = [1,1,1,2,2,2,3,3,3,4.0,6,7,8,n,n,n] d = {'a':a,'b':b} df = pd.DataFrame(d) df.b.hist() #Wait fo...
<python><pandas>
2023-03-20 14:32:09
1
3,304
Jimbo
75,791,352
5,687,779
How to type annotate a parent property/parameter in python without causing a circular dependency?
<p>Assuming I have two <code>.py</code> files</p> <pre><code>==== car.py ==== from .wheel import Wheel class Car(): def __init__(self) -&gt; None: self._wheel = Wheel(self, &quot;large&quot;) ==== wheel.py ==== from .car import Car class Wheel(): def __init__(self, parent: Car, desc: str) -&gt; None: ...
<python><python-3.x><python-typing>
2023-03-20 14:12:40
0
573
Shai Ben-Dor
75,791,316
2,955,541
Find Indices Where NumPy Int Array Value Matches Its Index Position
<p>I have a long array of integers and I'd like to find all of the array indices where the array value matches the index position. Here is the solution that I came up with:</p> <pre><code>import numpy as np def find_index_value_match(a): return a == np.arange(len(a)) a = np.array([0,1,4,4,4,0,7,9,2,3]) find_inde...
<python><numpy>
2023-03-20 14:09:19
0
6,989
slaw
75,791,277
12,871,587
How to deal with slightly different columns when scanning multiple csv files?
<p>I have a folder containing thousands of csv files which I'd like to scan with PL lazy frame.</p> <p>Scanning in fact works just fine, but when I try to fetch or collect the df, I get &quot;ShapeError: unable to append to a dataframe of width 63 with a dataframe of width 67&quot;.</p> <p>This means that there are som...
<python><dataframe><csv><python-polars>
2023-03-20 14:06:40
1
713
miroslaavi
75,791,141
1,422,096
Numpy range as a constant
<p>Let's say we have</p> <pre><code>import numpy as np z = np.array([1, 2, 3, 4, 5, 6]) </code></pre> <p>In some cases, I'd like to define a &quot;numpy range&quot; as a global constant, i.e. instead of doing</p> <pre><code>print(z[2:4]) </code></pre> <p>with hard-coded values 2 and 4 everywhere in my code, I'd prefer ...
<python><numpy>
2023-03-20 13:54:54
2
47,388
Basj
75,791,034
21,305,238
Use another class' methods without decorators and inheritance
<p>I have a class, which have several methods of its own, not shown here for simplicity:</p> <pre class="lang-py prettyprint-override"><code>class Foo: def __init__(self, arg: str): self.bar = arg </code></pre> <p>Let's say, aside from its own methods, I want <code>Foo</code>'s instances to use <code>str</code>'s...
<python><oop><magic-methods><getattr>
2023-03-20 13:44:20
2
12,143
InSync
75,791,023
1,496,362
How to load TimeSeriesData from non-continuous csv files
<p>I need to load a all csv files in a folder to train a time series model (PyTorch Lightening).</p> <p>The issue is that while the rows within a file are continuous (t, t+1, etc.), there is a break between files.</p> <p>How do I correctly deal with this? Do I pad them with seq_len?</p> <p>This is how I currently load ...
<python><pytorch><pytorch-lightning><dataloader><pytorch-dataloader>
2023-03-20 13:43:12
0
5,417
dorien
75,791,020
12,257,924
Why doesn't PyTorch Lightning module save logged val loss? ModelCheckpoint error
<p>I'm running an LSTM-based model training on Kaggle. I use Pytorch Lightning and wandb logger for that.</p> <p>That's my model's class:</p> <pre><code>class Model(pl.LightningModule): def __init__( self, input_size: int, hidden_size: int, bidirectional: bool = False, lstm_l...
<python><machine-learning><deep-learning><pytorch><pytorch-lightning>
2023-03-20 13:43:02
2
639
Karol
75,790,860
651,871
How to return the average value using fastapi & pydantic
<p>I am new to fasts-api and python as I am a mobile developer.</p> <p>At the moment I managed to get this response from my API (please look at <code>averageLevel</code> which is an array at the moment):</p> <pre><code>[ { &quot;user_id&quot;: 139, &quot;event_date&quot;: &quot;2023-03-20T12:18:17&quot;, ...
<python><sqlalchemy><fastapi><pydantic>
2023-03-20 13:27:33
1
6,314
Mat
75,790,838
5,896,319
How to add a new field to the default user model in Django?
<p>I want to add a new field to default Django user. I created a AbstractUser inherited model and added to the settings.py but I getting this error:</p> <blockquote> <p>ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'fdaconfig.customuser', but app 'fdaconfig' doesn't provide model 'cust...
<python><django>
2023-03-20 13:25:17
0
680
edche
75,790,507
3,613,158
Correct way to use a local Django project in a new computer (VS Code)
<p>I created my first local Python/Django project a few months ago using Visual Studio Code. It worked perfectly.</p> <p>Now I'm trying to use it on a new computer. I've tried just saving the VS workspace and then loading it on the new computer, but it gives me the following error:</p> <pre><code>ModuleNotFoundError: N...
<python><django><visual-studio-code>
2023-03-20 12:53:13
1
691
migueltic
75,790,452
14,640,406
Mux KLV STANAG data into MPEG-TS stream in Python
<p>I have some MPEGTS video streams and i need to mux KLV metadata into these. KLV data may e in a .pcap format or any another binary format. Any ideas about how can i perform this using some Python library?</p>
<python><mpeg2-ts><klvdata><stanag>
2023-03-20 12:47:13
0
309
carraro
75,790,418
9,879,869
Pandas: make new column and return list of values from other column
<p>Suppose I have two columns</p> <pre><code>d = {'a_lower': [1, 2], 'a_upper': [3, 4]} df = pd.DataFrame(data=d) a_lower a_upper 0 1 3 1 2 4 </code></pre> <p>I want to have 3rd column that returns a list from the values of the two columns</p> <pre><code> a_lower a_upper a...
<python><pandas>
2023-03-20 12:44:17
2
1,572
Nikko
75,790,393
3,232,194
fastapi, pymongo not querying lookup and returns empty on response
<p>I have a simply query, find the user in user collection from group collection. It is returning empty.</p> <p>Problem 1: &quot;user&quot; is empty.</p> <p>Problem 2: Response is completely empty <code>[]</code> in postman.</p> <pre><code>query = group.collection.aggregate([ { '$match': {&quot;usersId: {&...
<python><pymongo><fastapi>
2023-03-20 12:41:52
0
1,475
hammies
75,790,133
12,297,666
Error in Sklearn MinMaxScaler Normalization
<p>Check the code:</p> <pre><code>import numpy as np from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split x = np.array([[-1, 4, 2], [-0.5, 8, 9], [3, 2, 3]]) y = np.array([1, 2, 3]) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=2) ...
<python><scikit-learn><normalization>
2023-03-20 12:13:36
1
679
Murilo
75,789,990
10,982,203
Packaging Python module with source C/C++ files and compile on install
<p>I have a C library which I have ported to Python3. The Python module loads C code from the shared library.</p> <p>However, instead of building shared library for for each platform, I plan to package the C/C++ code which can be compiled at the user end when installing the module.</p> <p>I am using setuptools and I tr...
<python><c++><python-3.x>
2023-03-20 11:58:17
0
471
Ketu
75,789,933
11,452,928
Jax fitting MLP gives different result than Tensorflow
<p>I need to build a MLP in Jax, but I get slightly different (and in my opinion inaccurate) result from Jax respect to a MLP created in Tensorflow.</p> <p>In both cases I created a dataset where the y are linear function of X plus a standard gaussian error, the dataset is the same in both cases.</p> <p>I initialized t...
<python><tensorflow><machine-learning><jax><mlp>
2023-03-20 11:52:33
0
753
fabianod
75,789,732
2,636,044
Specify keys for pydantic nested model
<p>I have a structure similar to this in JSON</p> <pre><code>{ 'name': 'My Company', 'region': { 'us': { 'person': { 'name': 'John' } }, 'mx': { 'person': { 'name': 'Juan' } } } } </code></pre> <p>I'm trying to model it as pydantic classes</p> <pre><code>cla...
<python><pydantic>
2023-03-20 11:29:11
1
1,339
Onilol
75,789,651
12,769,783
Type hint generic function with arguments of passed function
<p>I would like to write type hints that allow type checkers to recognize if a wrong argument is passed to a function I call &quot;<code>meta</code>&quot; in the example code below:</p> <p>I have got the following functions:</p> <ul> <li>a function <code>meta</code> that takes a function and arguments for that function...
<python><python-typing>
2023-03-20 11:21:28
1
1,596
mutableVoid
75,789,602
14,045,537
Pandas nested groupby and sum unique values based on another column
<p>I have a pandas dataframe</p> <pre><code>import pandas as pd import numpy as np data = pd.DataFrame({&quot;ID1&quot;: [&quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;b&quot;, &quot;b&quot;, &quot;b&quot;, &quot;c&quot;, &quot;c&quot;, &quot;c&quot;], &quot;ID2&quot;: [&quot;k&quot;, &quot;k...
<python><pandas><dataframe><group-by>
2023-03-20 11:15:06
2
3,025
Ailurophile
75,789,548
18,013,020
CORS error in flask even after using flask-cors
<p>I start learning some <code>back-end</code> development with <code>Flask</code> but when I try to make a route that returns json data but it throws <code>CORS ERROR</code>, for tunneling I use <code>ngrok</code></p> <p>main.py</p> <pre><code>from flask import Flask, jsonify from flask_cors import CORS app = Flask(_...
<javascript><python><flask><cors><flask-cors>
2023-03-20 11:09:49
1
346
Mustafa
75,789,537
4,537,160
Python, make attribute accessible to other attributes of a class
<p>I have a Python class (MainClass), having 3 attributes:</p> <ul> <li>a data_history dict, which is updated at runtime (the program is analyzing a video stream, so data_history gets updated basically at each frame);</li> <li>2 other objects (data_analyzer_00, data_analyzer_01), each having a use_data_history() method...
<python><class><attributes>
2023-03-20 11:08:14
1
1,630
Carlo
75,789,398
361,023
How to use pyfakefs, pytest to test a function using `multiprocessing.Queue` via a `Manager`?
<p>I am trying to test a code that uses <code>multiprocessing.Queue</code>. I tried using the <code>additional_skip_names</code>, calling <code>multiprocessing.freeze_support()</code> and <code>multiprocessing.set_start_method('forkserver')</code>, but nothing seems to work.</p> <p>Here is a minimal example:</p> <pre c...
<python><python-3.x><multiprocessing><pytest><pyfakefs>
2023-03-20 10:53:49
0
96,298
Jorge E. Cardona
75,789,222
12,436,050
Extracting multiple fields from a JSON in python
<p>I have the following JSON object:</p> <pre class="lang-js prettyprint-override"><code>{ 'organisations': { 'total-items': '41477', 'organisation': [ { 'mappings': None, 'active-request': 'false', 'identifiers': { 'identifier': { 'code': 'ORG-100023310', ...
<python><json>
2023-03-20 10:34:27
4
1,495
rshar
75,789,043
7,720,535
Vectorize applying function on a Pandas DataFrame
<p>I have a Pandas DataFrame with two columns, <code>val</code> and <code>target</code>.</p> <pre><code>import random import numpy as np import pandas as pd df = pd.DataFrame({'val': np.random.uniform(-1., 1., 1000), 'target': random.choices([True, False], k=1000)}) </code></pre> <p>Target column...
<python><pandas>
2023-03-20 10:17:52
2
485
Esi
75,788,847
4,502,950
Stack and explode columns in pandas
<p>I have a dataframe to which I want to apply explode and stack at the same time. Explode the 'Attendees' column and assign the correct values to courses. For example, for Course 1 'intro to' the number of attendees was 24 but for Course 2 'advanced' the number of attendees was 46. In addition to that, I want all the ...
<python><pandas>
2023-03-20 09:57:55
2
693
hyeri
75,788,779
16,971,617
Finding the median of a segment using numpy
<p>I would like to find out the median of each segment within an image. The first step is to do segmentation. I use the skimage.segmentation as <a href="https://scikit-image.org/docs/stable/api/skimage.segmentation.html#examples-using-skimage-segmentation-felzenszwalb" rel="nofollow noreferrer">follows</a>.</p> <p>Yet ...
<python><numpy><image-segmentation><scikit-image>
2023-03-20 09:51:24
2
539
user16971617
75,788,685
1,988,046
Low latency image streaming between Win11 and WSL2
<p>I need to stream images from a C# application running on Windows 11 to a python module running on WSL2 (Ubuntu 20.04).</p> <p>Please note that I'm not a networking expert - I do computer vision.</p> <p>I've tried using WebSockets and am passing a 640x480 image to python and receiving a short string in response. Unfo...
<python><c#><windows-subsystem-for-linux><shared-memory>
2023-03-20 09:45:01
0
513
mike1952
75,788,659
12,863,331
Modify a pandas dataframe so that two or more cells will be merged and centered when opened in Excel
<p>I've seen some solutions but couldn't apply them after trying many times.<br /> The code I used is based on the <a href="https://xlsxwriter.readthedocs.io/example_merge1.html" rel="nofollow noreferrer">documentation</a>.<br /> In the following example the intention is to merge cells with the value 1:</p> <pre><code>...
<python><excel><pandas><xlsxwriter>
2023-03-20 09:42:30
2
304
random
75,788,557
19,580,067
Extract the Group Email Address from the recipients of outlook email using win32
<p>I'm trying to extract the all email info from outlook such as email body, sender address and the recipients addresses.</p> <p>The extraction of the sender and body works fine but unable to get the recipents email addresses as the recipients list contains group emails which results none while extracting the address w...
<python><outlook><pywin32><win32com><office-automation>
2023-03-20 09:31:57
2
359
Pravin
75,788,523
2,964,170
How to get last word from string in python
<p>I have string trying to get last word from string like this AUTHORITY[&quot;EPSG&quot;,&quot;6737&quot;]</p> <pre><code>a = 'PROJCS[&quot;Korea&quot;,GEOGCS[&quot;K 2000&quot;,DATUM[&quot;Geocentric_datum&quot;, SPHEROID[&quot;GRS 1980&quot;,6378137,298.257222101,AUTHORITY[&quot;EPSG&quot;,&quot;7019&quot;]], AUTHOR...
<python><python-3.x><string>
2023-03-20 09:28:22
3
425
Vas
75,788,472
1,887,381
How to detect the inner radius and outer radius of this circle in python?
<p>i want to detect the radius of two circles in <code>mask</code> image, but <code>cv2.HoughCircles</code> can not detect these two circles.</p> <p>what should i do? thanks in advance.</p> <p><a href="https://i.sstatic.net/VwO5k.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VwO5k.jpg" alt="enter image...
<python><opencv><computer-vision><hough-transform>
2023-03-20 09:22:56
0
2,661
12343954
75,788,424
10,829,044
pandas combine specific excel sheets into one
<p>I have an excel sheet named <code>output.xlsx</code> with multiple sheets in it.</p> <p>Example, the sheets within it are named as <code>P1</code>,<code>P2</code>,<code>P3</code>,<code>P4</code></p> <p>I would like to do the below</p> <p>a) Combine sheet <code>P1</code> and sheet <code>P2</code> into one single shee...
<python><excel><pandas><dataframe><group-by>
2023-03-20 09:17:42
1
7,793
The Great
75,788,354
5,084,737
Unable to use EcsTaskRole inside task to get s3 buckets
<p>I have an ECS Fargate task running, having a task role with following policy:</p> <pre><code>{ &quot;Version&quot;: &quot;2012-10-17&quot;, &quot;Statement&quot;: [ { &quot;Action&quot;: [ &quot;ecs:*&quot;, &quot;ec2:*&quot;, &quot;elasticl...
<python><amazon-web-services><boto3>
2023-03-20 09:10:12
0
1,117
Sadan A.