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,416,640
282,918
Python3: is there an elegant way to check nested attributes?
<p>for now I use this:</p> <pre><code>print(theObject.nestedObjectOne.NestedObjectTwo.NestedObjectThree if theObject and theObject.NestedOBjectOne and theObject.NestedObjectOne.NestedObjectTwo else &quot;n/a&quot;) </code></pre> <p>In order to support a case where <code>NestedObjectOne</code> is None.</p> <p>Is there a...
<python><python-3.x>
2023-02-10 22:17:49
1
5,534
JasonGenX
75,416,580
9,773,920
Save dataframe to same excel workbook but different sheets
<p>I want to loop through my data and save every component based data in separate sheet in the same excel workbook in S3 bucket.</p> <p>Dataframe df looks as below:</p> <p><a href="https://i.sstatic.net/zWPyg.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zWPyg.png" alt="enter image description here" />...
<python><pandas><amazon-web-services><dataframe><aws-lambda>
2023-02-10 22:07:59
2
1,619
Rick
75,416,497
19,369,393
How to expand a filtering mask to cover more pixels of the area of interest in OpenCV?
<p>Take a look at <a href="https://i.sstatic.net/ELRl7.jpg" rel="nofollow noreferrer">this</a> image. I want to turn this card blue.</p> <p>I use Python and OpenCV to perform image processing.</p> <p><strong>Here's how I do it now:</strong></p> <pre><code>import cv2 import numpy as np # Load the image image = cv2.imre...
<python><opencv><image-processing><mathematical-morphology>
2023-02-10 21:58:19
1
365
g00dds
75,416,208
10,620,003
modify the dataframe based on ids and time (put all times series data for each id beside each others)
<p>I have a dataframe which has 3 columns. id, date and val. The ids are different. I want to put all of the ids besides eachothers. For example, the first rows consist only one id with different dates and then the second distinct ids and etc. Here is a simple example;</p> <pre><code>import pandas as pd df['id'] = [10,...
<python><dataframe>
2023-02-10 21:19:22
0
730
Sadcow
75,416,188
998,070
Get Evenly Spaced Points from a Curved Shape
<p>How may I take a shape that was created with more points at its curves and subdivide it so that the points are distributed more equally along the curve? In my research I thought that <code>numpy</code>'s <a href="https://numpy.org/doc/stable/reference/generated/numpy.interp.html" rel="nofollow noreferrer">interp</a>...
<python><numpy><matplotlib><scipy><curve>
2023-02-10 21:17:28
3
424
Dr. Pontchartrain
75,416,108
9,388,056
Polars YYYY week into a date
<p>Does anyone know how to parse YYYY Week into a date column in Polars?<br /> I have tried this code but it throws an error.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl pl.DataFrame({ &quot;week&quot;: [201901, 201902, 201903, 201942, 201943, 201944] }).with_columns(pl.col(&quot;week&q...
<python><date><python-polars>
2023-02-10 21:05:32
2
620
Frank
75,416,041
5,212,614
Trying to plot data using networkx, and getting error about mapping nodes
<p>This is my first attempt at using networkx. Here is my sample code.</p> <pre><code>import pandas as pd import numpy as np data = [{'Circuit_Number': 1,'Description':'Stadium', 'Duration':10, 'Device_County':'Westchester', 'Picklist':1000, 'Postlist':50000}, {'Circuit_Number': 2, 'Description':'Stadium', 'Du...
<python><python-3.x><dataframe><networkx>
2023-02-10 20:57:03
0
20,492
ASH
75,415,993
4,655,673
How to parse a date-time string with extra characters like (+0) in Python?
<p>I am parsing log files which contain a timestamp with some extra text at the end.</p> <pre><code>2023-02-10 08:16:15.123456(+0) </code></pre> <p>I am not sure what the (+0) means, but the values change randomly. (+12), (+123), (+1234) are all possible values.</p> <p>I can get the entire string except the what is in ...
<python><datetime>
2023-02-10 20:51:05
0
847
MichaelE
75,415,991
7,934,786
how to split the items of a space-separated list into the columns in pandas
<p>I have a dataframe with multiple columns and the content of one of the columns looks like a list:</p> <pre><code>df = pd.DataFrame({'Emojis':['[1 2 3 4]', '[4 5 6]']}) </code></pre> <p>What I want to do to split the contents of these &quot;lists&quot; into the columns and since the sizes of the lists are not the sam...
<python><pandas><dataframe>
2023-02-10 20:50:52
2
2,170
sariii
75,415,671
7,800,760
Python: return type hint of arbitrary depth dictionary
<p>I am using a defaultdict collection to easily build an arbitrary depth python dictionary as follows:</p> <pre><code>from collections import defaultdict from datetime import datetime def recursive_dict() -&gt; defaultdict: &quot;&quot;&quot;enable arbitrary depth dictionary declaration&quot;&quot;&quot; ret...
<python><dictionary><mypy>
2023-02-10 20:05:44
1
1,231
Robert Alexander
75,415,643
14,141,126
Return specific values from nested Elastic Object
<p>I have to preface this with the fact that I'm working with Elasticsearch module, which returns <code>elastic_transport.ObjectApiResponse</code>. My problem is that I need to select specific keys from this json/dictionary looking log. The indices come from different sources, and thus contain different key/value pairs...
<python><elasticsearch>
2023-02-10 20:02:08
0
959
Robin Sage
75,415,616
238,074
AWS Boto3 sts get_caller_identity - catching exceptions if credentials are invalid
<p>With a Python app, using Boto3 v1.26.59 (and botocore of same version) about the first thing done is to try to get the username of the user. We have Identity Center (SSO) users. With aged credentials (token), two exceptions are thrown and I don't seem to be able to catch them. Here is a snippet:</p> <pre class="lang...
<python><amazon-web-services><single-sign-on><boto><botocore>
2023-02-10 19:58:49
1
2,922
Kevin Buchs
75,415,472
19,854,658
How to visualize EM steps in GMM model?
<p>I would like to visualize the EM steps taken in a GMM model but don't know how I would go about doing that.</p> <p>I've generated some synthetic data and fitted a model:</p> <pre><code>a = np.random.normal(loc=[2,2,2], scale=1.0, size=(100,3)) b = np.random.normal(loc=[5,5,5], scale=1.0, size=(100,3)) c = np.random....
<python><pandas><machine-learning><visualization><gmm>
2023-02-10 19:41:45
1
379
Jean-Paul Azzopardi
75,415,440
5,924,264
__init__() takes from 1 to 2 positional arguments but 4 were given after refactorizing class to be under base class
<p>I have a class that currently looks something like this:</p> <pre><code>import attr @attr.s class my_class(object): var1 = attr.ib(default=5) var2 = attr.ib(default=5) var3 = attr.ib(default=5) @classmethod def func(cls): cls(1, 2, 3) my_class.func() </code></pre> <p>I need to create an abstract base...
<python><inheritance><attr><python-attrs>
2023-02-10 19:37:37
1
2,502
roulette01
75,415,350
1,413,826
Fiducial detection - hamming distance alternative
<p>I have a custom fiducial marker that is an X shape. It's all black and on a white background. I am able to use thresholding and contours to identify potential fiducial candidates, which I then perspective warp and downsize to 10x10 pixels and compare to a &quot;fixed&quot; or template fiducial. My current comparison...
<python><computer-vision><object-detection><hamming-distance><fiducial-markers>
2023-02-10 19:28:53
0
2,648
steve
75,415,211
2,382,483
Buffered FIFO queue for streaming bytes in python?
<p>I am doing a lot of processing and generating of csv and json files in python, to which I'm new-ish. Here's a typical example of what I have done so far:</p> <pre><code># return a db cursor that streaming rows of data row_iter = await get_row_iterator() # get a pointer to a google cloud storage object to store the ...
<python><node.js>
2023-02-10 19:10:32
0
3,557
Rob Allsopp
75,415,208
17,160,160
Extract longest block of continuous non-null values from each row in Pandas data frame
<p>Suppose I have a Pandas data frame structured similarly to the following:</p> <pre><code>data = { 'A' : [5.0, np.nan, 1.0], 'B' : [7.0, np.nan, np.nan], 'C' : [9.0, 2.0, 6.0], 'D' : [np.nan, 4.0, 9.0], 'E' : [np.nan, 6.0, np.nan], 'F' : [np.nan, np.nan, np.nan], 'G' : [np.nan, np.nan, 8.0...
<python><pandas>
2023-02-10 19:10:21
3
609
r0bt
75,415,048
17,274,113
Python lidar package dealing with NoData values
<p>I am attempting to use the python <code>lidar</code> package function <code>lidar.ExtractSinks()</code>. I have a raster dataset that looks like the following.</p> <p><a href="https://i.sstatic.net/4Txla.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4Txla.png" alt="enter image description here" /></...
<python><lidar><no-data>
2023-02-10 18:49:58
0
429
Max Duso
75,415,039
12,244,355
Python: Issue with reassigning columns to DataFrame
<p>I have a DataFrame with multiple columns. I am trying to normalize all the columns except for one, <code>price</code>.</p> <p>I found a code that works perfectly on a sample DataFrame I created, but when I use it on the original DataFrame I have, it gives an error <code>ValueError: Columns must be same length as key...
<python><pandas><dataframe><normalize><reassign>
2023-02-10 18:49:16
1
785
MathMan 99
75,415,020
12,394,134
plotly error: ValueError: The data property of a figure may only be assigned a list or tuple that contains a permutation of a subset of itself
<p>I am simulating some data and trying to plot various samples of it using <code>plotly</code> and <code>ipythonwidgets</code>. I created dropdowns to let people choose the sample size and the number of samples that they want to collect from a population distribution generated with this:</p> <pre><code>from random imp...
<python><plotly><python-interactive>
2023-02-10 18:47:27
1
326
Damon C. Roberts
75,414,955
12,890,458
How to view runtime warnings in PyCharm when running tests using pytest?
<p>When running tests in PyCharm 2022.3.2 (Professional Edition) using pytest (6.2.4) and Python 3.9 I get the following result in the PyCharm console window:</p> <blockquote> <p>D:\cenv\python.exe &quot;D:/Program Files (x86)/JetBrains/PyCharm 2022.3.2/plugins/python/helpers/pycharm/_jb_pytest_runner.py&quot; --path D...
<python><pycharm><pytest><warnings>
2023-02-10 18:39:22
2
460
Frank Tap
75,414,867
14,366,102
How to properly encode a file in Polish in Python?
<p>I want to open the inflation data from the Polish Statistics Office.</p> <p>The code below:</p> <pre><code>import pandas as pd inflation_data_url = 'https://stat.gov.pl/download/gfx/portalinformacyjny/pl/defaultstronaopisowa/4741/1/1/miesieczne_wskazniki_cen_towarow_i_uslug_konsumpcyjnych_od_1982_roku.csv' pd = pd.r...
<python><pandas>
2023-02-10 18:30:18
1
811
Aleister Crowley
75,414,808
18,756,733
How to combine two HTML files into one in Python
<p>I created two plotly charts and saved them as HTML files separately. Is there a way to combine them into one HTML file? For example I can do this with PDF files using the following code:</p> <pre><code>from PyPDF2 import PdfFileMerger, PdfFileReader merger = PdfFileMerger() merger.append(PdfFileReader(open(filename...
<python><charts><merge>
2023-02-10 18:24:51
1
426
beridzeg45
75,414,637
6,672,237
Altair + panel: chart dynamic dropdown filter doesn't work
<p>I almost have it, but the filter selection only works when executing the cell in jupyter. It doesn't get updated when the dropdown selector is used. I have three parts:</p> <ol> <li>A scatterplot that has to have a filter/dropdown menu bound to a list of values from a <code>df</code>'s column <code>Island</code>.</l...
<python><panel><altair>
2023-02-10 18:02:09
1
562
kuatroka
75,414,598
17,696,880
Check if a string matches any of the lines of a txt file, and if it doesn't match any then add it to that txt file
<pre class="lang-py prettyprint-override"><code>import os if (os.path.isfile('data_file.txt')): data_memory_file_path = 'data_file.txt' else: open('data_file.txt', &quot;w&quot;).close() data_memory_file_path = 'data_file.txt' #Example input list with info in sublists reordered_input_info_lists = [ [...
<python><python-3.x><string><file><writefile>
2023-02-10 17:57:45
1
875
Matt095
75,414,564
7,519,434
Inherit template without using super()
<p>I have the following <code>base.html</code></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;link rel = &quot;stylesheet&quot; href = &quot;{{ url_for('static'...
<python><jinja2>
2023-02-10 17:53:35
1
3,989
Henry
75,414,525
935,376
Python: looping faster using inbuilt functions
<p>I took a python test where I had to code a function to solve the problem below. It passed some test cases but failed runtime for some others because it took a long time. The function feels bloated. How to make the function faster?</p> <p>Here is the problem:</p> <p>A truck fleet dispatcher is trying to determine wh...
<python><python-3.x>
2023-02-10 17:50:58
0
2,064
Zenvega
75,414,333
3,281,427
How to override the autocomplete view for a specific model field in the Django admin?
<p>I need to override the way a Select2 widget of a particular <code>ForeignKey</code> is behaving in the Django (4.1) admin.</p> <p>Namely, I am trying to increase the number of objects returned by the AJAX requests and defined by <code>paginate_by</code> in <a href="https://github.com/django/django/blob/main/django/c...
<python><django><jquery-select2>
2023-02-10 17:29:12
1
1,694
Buddyshot
75,414,227
14,895,107
WARNING:absl:Found untraced functions such as _jit_compiled_convolution_op while saving in tensorflow
<p>i just trained a cnn with 99% accuracy on the mnist dataset. my model is working fine and giving accurate results. but when i converted my <code>h5</code> model to a <code>tflite</code> model, im getting only one result at every time. ie : <a href="https://i.sstatic.net/AD93n.png" rel="nofollow noreferrer"><img src=...
<python><tensorflow><conv-neural-network><tensorflow2.0><tensorflow-lite>
2023-02-10 17:16:57
0
903
Abhimanyu Sharma
75,414,218
5,446,815
Rotate pie chart in interactive window without replotting
<p>I am drawing a pie chart out of provided data, and this can potentially get out of hand as the length of the labels can be pretty long, and there can be a lot of them overlapping each other. Because of this, it is crucial to find a good startangle parameter to my pie chart drawing.</p> <p>Conceptually, I want to use...
<python><matplotlib>
2023-02-10 17:16:13
0
652
Matrefeytontias
75,414,174
11,710,304
Testing if strip in column was successful with polars
<p>I have developed a function to strip a dataset using polars. Now I want to check with a test if the strip was successful. For this I want to use the following logic. But this code is in python. How can I solve this using polars?</p> <pre><code>def test_strip(): df = pd.DataFrame({ 'ID': [1, 1, 1, 1, 1], ...
<python><python-polars>
2023-02-10 17:12:01
1
437
Horseman
75,414,167
7,376,511
Dynamically generate mypy-compliant property setters
<p>I am trying to declare a base class with certain attributes for which the (very expensive) calculation differs depending on the subclass, but that accepts injecting the value if previously calculated</p> <pre><code>class Test: _value1: int | None = None _value2: str | None = None _value3: list | None = N...
<python><mypy><setter>
2023-02-10 17:11:31
2
797
Some Guy
75,413,996
10,010,688
Python encode spaces in url only and not other special characters
<p>I know this question has been asked many times but I can't seem to find the variation that I'm looking for specifically.</p> <p>I have a url, lets say its:</p> <pre><code>https://somethingA/somethingB/somethingC/some spaces here </code></pre> <p>I want to convert it to:</p> <pre><code>https://somethingA/somethingB/s...
<python>
2023-02-10 16:54:33
1
3,858
Mark
75,413,774
5,722,359
X Error of failed request: BadAlloc (insufficient resources for operation) while running tkinter
<p>I encountered the following error message while running a python script that I am working on. It occurred while tkinter was loading ~1800 thumbnail images, each being 200x200 pixels large, into individual <code>ttk.Checkkbuttons</code>. It did not finish this process and the program crashed with this error message.<...
<python><tkinter><tk-toolkit>
2023-02-10 16:34:40
0
8,499
Sun Bear
75,413,603
11,622,712
How to retrieve the text removed by regex sub?
<p>I have a regex expression in Python that is expected to remove all occurences of the word &quot;NOTE.&quot; and the following sentence. How can I do it correctly and also return all sentences being removed that way?</p> <pre><code>import re text = &quot;NOTE. This is the subsequent sentence to be removed. The weathe...
<python><regex>
2023-02-10 16:17:30
3
2,998
Fluxy
75,413,514
10,872,199
Django channels. How to select consumer when sending through channel layer?
<p>In my application, I got two consumers with same handler names:</p> <pre class="lang-py prettyprint-override"><code>class GeneralConsumer(AuthenticatedOnlyAsyncConsumer): async def new_message(self, data): ... async def message_update(self, data): ... async def message_delete(self, data...
<python><django><websocket><django-channels>
2023-02-10 16:09:52
0
896
PythonNewbie
75,413,389
7,162,827
CDK scope-error when executing external jobs
<p>I've created a setup that works to generate state machines, however for some reason it does not work for the two specific <code>Task</code>s <code>GlueStartJobRun</code> and <code>StepFunctionsStartExecution</code>. Here is part of my current setup:</p> <pre><code>. ├── app.py ├── cloudformation │ ├── stepfunction...
<python><scope><aws-cdk><aws-step-functions>
2023-02-10 15:56:34
1
567
armara
75,413,249
15,176,150
What does `amd64` mean in Python .whl files?
<p>I'm trying to download some Python <code>.whl</code> files, but I'm not sure what version I should be downloading.</p> <p>I have a windows machine with an Intel chip, but all the versions I see use <code>amd64</code>, does that mean the versions are for AMD chips only?</p>
<python><x86-64><intel><python-wheel><amd-processor>
2023-02-10 15:44:11
1
1,146
Connor
75,413,155
19,425,874
How to scrape multiple tags in single iteration?
<p>I have a script below that works perfectly - it visits each HREF tag on a list of URLs, then returns the associated p tag information. It pushes the info directly to a Google Sheet.</p> <p>I noticed, the player &quot;position&quot; isn't included, because it is an H2 tag not a p... I started to redo the entire scri...
<python><web-scraping><beautifulsoup><python-requests>
2023-02-10 15:36:38
1
393
Anthony Madle
75,413,037
12,255,379
Installing NumPy to a virtual environment on raspberry pi for python 3.7
<p>I'm trying to install NumPy for python 3.7 on my raspberry pi as a part of installing OpenCV. Originally when running</p> <pre class="lang-bash prettyprint-override"><code>sudo pip3.7 install opencv-python mediapipe Flask==2.0.3 </code></pre> <p>and then got error on building wheels for NumPy. I sequentially tried t...
<python><numpy><raspberry-pi>
2023-02-10 15:26:07
0
769
Nikolai Savulkin
75,413,010
5,181,219
Within a Python context manager, prevent people from running PySpark queries
<p>I would like to create a Python context manager that you would use in this way:</p> <pre class="lang-py prettyprint-override"><code>with ContextManager() as cm: ... </code></pre> <p>and I would like to make it so within the context manager, any attempt of the user to interact with PySpark should return an excep...
<python><pyspark><dynamic><contextmanager>
2023-02-10 15:24:00
0
1,092
Ted
75,412,980
11,391,711
how MultiStepLR works in PyTorch
<p>I'm new to <code>PyTorch</code> and am working on a toy example to understand how weight decay works in learning rate passed into the optimizer. When I use <a href="https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.MultiStepLR.html" rel="nofollow noreferrer"><code>MultiStepLR </code></a>, I was exp...
<python><machine-learning><pytorch><learning-rate>
2023-02-10 15:21:44
1
488
whitepanda
75,412,875
15,803,668
PyQt5 SplashScreen for loading custom modules before opening Main Window
<p>I have a <code>pyqt5</code> application. In the program you can open various other windows from the MainWindow. The different windows are stored in a separate module and are imported into the main file, which represents the MainWindow. Furthermore I use several custom widgets, which are also stored in a separate mod...
<python><pyqt5>
2023-02-10 15:10:59
0
453
Mazze
75,412,546
3,951,933
How to get state of the streaming source in GStreamer-Python?
<p>I'm trying to analyze and take actions depending on the current state of the streaming source in gstreamer. I have a basic script to create pipeline elements, linking them and eventually see the live IP camera stream on my screen. However, most of the IP cameras seems to stop streaming the video at some point. The c...
<python><ffmpeg><camera><gstreamer><rtsp>
2023-02-10 14:38:59
1
447
doruk.sonmez
75,412,446
457,123
foreachBatch not getting executed in Spark stream write
<p>I seems like the run_command function is not run in the below code. What is wrong?</p> <pre><code>df.writeStream \ .foreachBatch(run_command) \ .format(&quot;delta&quot;) \ .outputMode(&quot;append&quot;) \ .option(&quot;checkpointLocation&quot;, &quot;/tmp/delta/events/_checkpoints/&quot;) \ .pa...
<python><apache-spark><stream><databricks>
2023-02-10 14:28:10
0
4,959
Mathias Rönnlund
75,412,207
18,168,625
Github Actions don't reuse cache
<p>I have a pretty simple step for CI on Github Actions, which is supposed to cache Python dependencies, so it would save a lot of computing time.</p> <pre><code> some-step: name: 'Test step' runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - run: pipx install poetry - name: Set ...
<python><continuous-integration><github-actions><python-poetry>
2023-02-10 14:03:34
2
580
Aleks Kuznetsov
75,412,114
9,707,473
How to slice a numpy array using index arrays with different shapes?
<p>Let's say that we have the following 2d numpy array:</p> <pre><code>arr = np.array([[1,1,0,1,1], [0,0,0,1,0], [1,0,0,0,0], [0,0,1,0,0], [0,1,0,0,0]]) </code></pre> <p>and the following indices for rows and columns:</p> <pre><code>rows = np.array([0,2,4]...
<python><arrays><python-3.x><numpy>
2023-02-10 13:56:15
2
512
lezaf
75,412,082
11,167,163
How to add header & scrollbar to a tkinter table?
<p>I have the following code which is working, but I don't understand how to add a scroll bar to the table, and how to shows header at the top of each column.</p> <p>Also I would like to display gridlines, but I struggle to do it.</p> <p>Any help would be appreciated !</p> <pre><code>import tkinter as tk class Example...
<python><tkinter>
2023-02-10 13:53:43
1
4,464
TourEiffel
75,411,837
2,444,023
How to make a TTF or OTF from SVG or BMP
<p>I am working on a pixel font which I am able to create with <code>Pillow</code>. <code>Pillow</code> can export <code>*.bmp</code> files. I would like to get from <code>*.bmp</code> to <code>*.ttf</code> or <code>*.otf</code>. In my current example I have a letter <code>a</code> (unicode <code>0061</code>) and lette...
<python><svg><fonts><bitmap><truetype>
2023-02-10 13:34:39
0
2,838
Alex
75,411,807
11,197,301
pandas fill a dataframe according to column and row value operations
<p>Let's say that I have this dataframe:</p> <pre><code>,,,,,, ,,2.0,,,, ,2.0,,2.23606797749979,,, ,,2.23606797749979,,,2.0, ,,,,,2.23606797749979, ,,,2.0,2.23606797749979,, ,,,,,, </code></pre> <p><a href="https://i.sstatic.net/iaFYL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iaFYL.png" alt="enter ...
<python><pandas><dataframe><select><indexing>
2023-02-10 13:31:17
1
623
diedro
75,411,652
7,376,511
Assign function to variable and get variable name from inside said function
<pre><code>def my_function(): ... my_variable = my_function my_variable() </code></pre> <p>In this case, is there a way to get <code>my_variable</code> as string from inside <code>my_function</code>?</p>
<python>
2023-02-10 13:16:02
1
797
Some Guy
75,411,547
10,714,156
Convert `DataFrame.groupby()` into dictionary (and then reverse it)
<p>Say I have the following <code>DataFrame()</code> where I have repeated observations per individual (column <code>id_ind</code>). Hence, first two rows belong the first individual, the third and fourth rows belong to the second individual, and so forth...</p> <pre><code>import pandas as pd X = pd.DataFrame.from_dic...
<python><pandas><list><dataframe><dictionary>
2023-02-10 13:06:29
1
1,966
Álvaro A. Gutiérrez-Vargas
75,411,504
12,149,587
Gather items that cause all() to return false
<p>This question is about what one can/cannot do with <code>all()</code> function.</p> <p>I would like to identify all elements which fail the condition set in <code>all()</code> function.</p> <p>In the example below <code>all()</code> will return <code>False</code> since not all elements are of type <code>int</code>. ...
<python><list><iterator><boolean>
2023-02-10 13:01:46
2
3,525
0buz
75,411,474
16,981,638
how to match data from a linked pages together by web scraping
<p>i'm trying to scrap some data from a web site and i have an issue in matching the data from every subpage to the data of the main page</p> <p>for Expample: the main page have a country name &quot;<strong>Alabama Trucking Companies</strong>&quot; and when i enter to it link, i'll found some cities(Abbeville, Adamsvil...
<python><python-3.x><pandas><web-scraping>
2023-02-10 12:59:16
1
303
Mahmoud Badr
75,411,455
2,635,863
concatenate/merge multiple dataframes - pandas
<p>I have multiple data frames that I would like to concatenate. Some of these do not have certain columns so should be filled with NA.</p> <pre><code>df1_1 = pd.DataFrame({'id':[1,1,2,2,3,3], 'age':[22,22,55,55,53,53], 'group':1,'y':[1,2,3,4,5,6]}) df1_2 = pd.DataFrame({'id':[1,1,2,2,3,3], 'age':[22,22,55,55,53,53], '...
<python><pandas>
2023-02-10 12:57:07
1
10,765
HappyPy
75,411,340
16,883,182
Unexpected behavior in the "scrap" module of Pygame when attempting to copy/paste Unicode text
<p>I'm currently working on a GUI toolkit in Pygame, and so far it's looking pretty good. I'm currently working on a text-box widget, and it is nearly done. But I would like to implement copy/paste support. I scrolled through the Pygame docs and found there is a module, <code>pygame.scrap</code>, which is for this purp...
<python><unicode><utf-8><character-encoding>
2023-02-10 12:46:39
0
315
I Like Python
75,411,269
1,362,485
FileNotFound when trying to pickle TensorFlow object in GPU
<p>I'm running the code below, and it works perfectly if TensorFlow is installed <em>without</em> GPU. But if installed <em>with</em> GPU, I get a FileNotFound error when I try to load the object.</p> <p>I tried also with joblib and pickle directly, and I always get the same error.</p> <p>Any help will be greatly appre...
<python><tensorflow><keras><pickle><dill>
2023-02-10 12:39:46
4
1,207
ps0604
75,411,254
5,432,214
Minimal reproducible example of a django project using appengine task queue (dev_appserver.py)
<p>I am trying to create a django project which uses AppEngine's task queue, and would like to test it locally before deploying (using gcloud<code>s </code>dev_appserver.py`).</p> <p>I can't seem to find resources that help in local development, and the closest thing was a Medium article that helps setting up django wi...
<python><django><google-app-engine><google-cloud-platform><dev-appserver>
2023-02-10 12:38:37
1
1,310
HitLuca
75,411,162
3,421,383
Not able to get undetected-chromedriver.exe download file
<p>Not able to get <code>undetected-chromedriver.exe</code> download file</p> <p>I am using <code>undetected-chromedriver</code> in Python. I have installed <code>undetected-chromedriver</code> using <code>pip install undetected-chromedriver</code></p> <p>Below is my code</p> <pre><code>import undetected_chromedriver a...
<python><google-chrome><selenium-chromedriver><undetected-chromedriver>
2023-02-10 12:30:49
1
814
simond
75,411,149
11,183,333
Create a partial pdf from bytes in python
<p>I have a pdf file somewhere. This pdf is being send to the destination in equal amount of bytes (apart from the last chunk).</p> <p>Let's say this pdf file is being read in like this in python:</p> <pre><code>with open(filename, 'rb') as file: chunk = file.read(3000) while chunk: #the sen...
<python><pdf><stream><pypdf>
2023-02-10 12:30:11
1
324
Patrick Visi
75,410,827
12,014,637
How does masking work in Tensorflow Keras
<p>I have difficulty understanding how exactly masking works in Tensorflow/Keras. On the Keras website (<a href="https://www.tensorflow.org/guide/keras/masking_and_padding" rel="nofollow noreferrer">https://www.tensorflow.org/guide/keras/masking_and_padding</a>) they simply say that the neural network layers skip/ignor...
<python><tensorflow><keras>
2023-02-10 11:58:51
2
618
Amin Shn
75,410,778
12,671,057
Sort by price and remove prices
<p>I have a shopping list:</p> <pre><code>items = [ ['Aspirin', 'Walgreens', 6.00], ['book lamp', 'Amazon', 2.87], ['popsicles', 'Walmart', 5.64], ['hair brush', 'Amazon', 6.58], ['Listerine', 'Walmart', 3.95], ['gift bag', 'Target', 1.50] ] </code></pre> <p>I want to sort the items from cheapes...
<python><sorting>
2023-02-10 11:54:15
7
27,959
Kelly Bundy
75,410,769
5,594,712
Time response of a double sided frequency response
<p>I am trying to learn more about fourier transforms and inverse fourier transform. For the example below, I am unable to understand the time response signal.</p> <p>Here is what I am doing,</p> <p><strong>Step 1:</strong> I am starting in this case from the frequency domain with this signal:</p> <p><a href="https://i...
<python><scipy><signal-processing><fft>
2023-02-10 11:53:28
1
1,244
Adam Merckx
75,410,767
2,664,205
convert a string containing a valid file path into a list of path components
<p>Is there a function in python that takes as input variables with paths (a character containing a valid path) e.g.</p> <pre><code>[&quot;/Users/xyz/Dropbox/figures/foo.txt&quot;,&quot;/Users/xyz/Dropbox/figures/folder/&quot;] </code></pre> <p>and converts them into a character vector of path components (e.g. directo...
<python><path>
2023-02-10 11:53:20
1
1,064
witek
75,410,747
11,748,924
Audio to Spectrogram Image
<p>I expect I can convert an audio file or waveform to the spectrogram image where:</p> <ol> <li>X-axis represent time (horizontal axis), where goes to the right meaning to the ending duration of audio.</li> <li>Y-axis represent frequency (vertical axis), where goes to the up meaning to the maximum of frequency from au...
<python><image><audio><spectrogram>
2023-02-10 11:51:29
1
1,252
Muhammad Ikhwan Perwira
75,410,653
7,295,599
PyUSB: communication with OWON Oscilloscope (2)
<p>After quite some hassle <a href="https://stackoverflow.com/q/59105167/7295599">talking to an OWON oscilloscope</a>, there are new problems during the installation on another PC.</p> <p>The USB driver seems to be installed, at least that's what Windows10 makes me believe.</p> <p><a href="https://i.sstatic.net/tTcjB.p...
<python><windows><usb><libusb><pyusb>
2023-02-10 11:41:47
0
27,030
theozh
75,410,631
1,934,903
pytest mocker.patch.object's return_value uses different mock than the one I passed it
<p>I'm using pytest to patch the os.makedirs method for a test. In a particular test I wanted to add a side effect of an exception.</p> <p>So I import the <code>os</code> object that I've imported in my script under test, patch it, and then set the side effect in my test:</p> <pre class="lang-py prettyprint-override"><...
<python><unit-testing><mocking><pytest><python-unittest>
2023-02-10 11:40:01
1
21,108
Chris Schmitz
75,410,533
726,730
PyQt5 QTreeWidget disable on cell select style
<p><strong>File: preview_example.py</strong></p> <pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Users\chris\My Projects\papinhio-player\ui/menu-1/playlists/preview/preview_example.ui' # # Created by: PyQt5 UI code generator 5.15.7 # # WA...
<python><pyqt5><qtreewidget>
2023-02-10 11:30:40
1
2,427
Chris P
75,410,443
13,506,329
Check if the column value of a row is equal to values in current or other columns for other rows of the same dataframe
<p>I have a <code>dataframe</code> of the following</p> <pre><code> | a| b_1 | b_2 |b_3 |c_1 | c_2 | c_3 | |--|-----------|-----------|-----|-----------|-----------|-----| |e1|3295.000000|-775.000000|604.5|3575.000000|-626.000000|604.5| |e2|3615.000000|-731.000000|604.5|1 |0 ...
<python><python-3.x><pandas><dataframe>
2023-02-10 11:22:08
1
388
Lihka_nonem
75,410,431
4,875,766
Polars: create column from sampling function
<p>I am looking to make a new column on a polars data frame.</p> <p>Suppose I have 2 Lazy Dataframes, <code>df_1</code> and <code>df_2</code> of different sizes. I want to sample, for each record of <code>df_2</code>, a column of <code>df_1</code>. In pandas:</p> <pre class="lang-py prettyprint-override"><code>import n...
<python><python-polars>
2023-02-10 11:21:12
2
331
TobyStack
75,410,355
10,051,099
How to find "os" module file path in Python3.11 without importing it?
<p>I can get the path of 'os.py' like this:</p> <pre class="lang-py prettyprint-override"><code>import os os.__file__ </code></pre> <p>But how can I get it without importing it? I found <a href="https://stackoverflow.com/questions/4693608/find-path-of-module-without-importing-in-python">this relevant question</a>, but ...
<python><python-3.11>
2023-02-10 11:13:30
1
3,695
tamuhey
75,410,317
15,913,281
Duplicating and Transforming Data in Dataframe
<p>I have a dataframe of football results. It is laid out in date order with a row for each game. Each row contains the name of the home team and away team in different columns along with the result.</p> <p>I want to create a new dataframe that contains a series of all the games played by each team (home and away) in a...
<python><pandas>
2023-02-10 11:09:59
1
471
Robsmith
75,410,264
1,728,544
PySide6: column of checkboxes for a boolean variable in a data table
<p>I am trying to create a table in PySide6 to show data from a database. One of the variables in my database is a boolean variable, and I would like that to show in the table as an editable checkbox, which I can simply click on to switch between True and False values.</p> <p>This, I would have thought, should be a rea...
<python><qt><pyside6>
2023-02-10 11:06:20
0
423
Adam Jacobs
75,410,261
6,930,340
How to check if occurrences of identical consecutive numbers is below a threshold in pandas series
<p>I need to check if the occurrences of identical consecutive numbers is below a certain threshold, e.g. maximal two same consecutive numbers.</p> <pre><code>pd.Series(data=[-1, -1, 2, -2, 2, -2, 1, 1]) # True pd.Series(data=[-1, -1, -1, 2, 2, -2, 1, 1]) # False </code></pre> <p>Further checks:<br /> Only the number...
<python><pandas><list>
2023-02-10 11:06:12
1
5,167
Andi
75,410,243
7,376,511
del self followed by super() call raises RuntimeError
<p>I was playing around with inheritance today, and I came across this exception:</p> <pre><code>class A: def __init__(self): del self super().__init__(**locals()) A() # RuntimeError: super(): arg[0] deleted </code></pre> <p>Why does this happen? If I replace the line with <code>super().__init__(**{}...
<python><inheritance><garbage-collection>
2023-02-10 11:04:52
0
797
Some Guy
75,410,127
7,415,134
Connecting redis to docker
<p>I have a docker image and i want to connect to the redis database locally.</p> <pre><code>redis = redis.Redis( host='localhost', port = 6379, charset=&quot;utf-8&quot;, decode_responses=True) </code></pre> <p>what i typed in to the terminal</p> <pre><code>sudo docker build -t scraper . sudo docker ru...
<python><docker><redis><localhost>
2023-02-10 10:54:58
0
379
Sid
75,410,037
15,093,600
Different python package requirements for 32 and 64 bit
<p><strong>Problem</strong></p> <p>My code depends on two packages <code>A</code> and <code>B</code>.</p> <p>Recently I found an issue with the packages compatibility: maintainers of package <code>A</code> stopped releasing whl packages for 32 bit Python, while maintainers of package <code>B</code> removed some functio...
<python><pip><setuptools>
2023-02-10 10:46:47
1
460
Maxim Ivanov
75,409,843
7,483,211
How to programatically collect a list of all stack traces during function call, not just when exception happens?
<p>In order to debug how a complicated library executes a function call, e.g. <code>pd.Series(np.NaN)|pd.Series(&quot;True&quot;)</code> I would like to generate a list of all states of the stack during the execution of that function. So for every line of Python code executed (even inside functions and functions called...
<python><debugging><trace><stack-trace><sys>
2023-02-10 10:30:50
1
10,272
Cornelius Roemer
75,409,689
11,491,600
Azure Cognitive Search:
<p>I have recently upgraded my Azure Cognitive Search instance so it has semantic search.</p> <p>However, when I add query_type=semantic, in the client search I get the following stacktrace...</p> <pre><code>Traceback (most recent call last): File &quot;call_semantic_search.py&quot;, line 34, in &lt;module&gt; c,...
<python><azure>
2023-02-10 10:16:10
2
465
Bob
75,409,645
8,170,368
How to reshape matrices using index instead of shape inputs?
<p>Given an array of shape (8, 3, 4, 4), reshape them into an arbitrary new shape (8, 4, 4, 3) by inputting the new indices compared to the old positions (0, 2, 3, 1).</p>
<python><numpy><matrix>
2023-02-10 10:12:36
2
388
mariogarcc
75,409,518
5,722,359
How to change the colour of a ttk.Checkbutton when it is !disabled and selected?
<p>How to change the colour of the indicator of <code>ttk.Checkbutton</code> when it is <code>!disabled</code> and <code>selected</code>? The following picture shows it is blueish in colour.</p> <p><a href="https://i.sstatic.net/HM5hJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HM5hJ.png" alt="sample...
<python><tkinter><tk-toolkit><ttk>
2023-02-10 10:01:50
1
8,499
Sun Bear
75,409,463
10,035,626
Python does not note every new chrome access log when retrieving target urls from redirect urls
<p>I'm applying the code of <a href="https://stackoverflow.com/a/70869691/10035626">Shahin Shirazi</a> to retrieve the target url of a redirect link using Python. I'm applying this code to multiple redirect links. However, when I run this code, in some cases Python writes the target url of the previous redirect link ag...
<python><google-chrome><http><url><http-redirect>
2023-02-10 09:57:51
0
561
Scijens
75,409,168
10,613,037
Ignore elements where the condition cannot be met with .mask()
<p>I have the following series'</p> <pre class="lang-py prettyprint-override"><code>s = pd.Series([0,1,'random',2,3,4]) s2 = pd.Series([5,6,7,8,9,10]) </code></pre> <p>How can I use <code>s.mask</code> to return a series where every even number in <code>s</code> is replaced by <code>s2</code>, and elements in s that...
<python><pandas>
2023-02-10 09:31:25
1
320
meg hidey
75,409,082
5,368,122
SQLAlchemy unable to execute query python
<p>I have to conencto an Azure SQL database using Managed Identity. The connection is successful. The code I am using is:</p> <pre><code>self.logging.info(&quot;Connecting to database - connection string: {conn_str}&quot;.format(conn_str=self.conn_str)) credential = ManagedIdentityCredential(client_id = 'xxxxxxxxxxxxx'...
<python><azure><sqlalchemy><odbc><pyodbc>
2023-02-10 09:22:09
1
844
Obiii
75,408,945
55,408
How to specify index content/entries in Markdown?
<p>Based on the <a href="https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-index" rel="nofollow noreferrer">Sphinx documentation</a>, to specify various index entries (<code>single</code> entry, for example) in reStructuredText, like this:</p> <pre><code>.. index:: single: executi...
<python><markdown><python-sphinx><restructuredtext><myst>
2023-02-10 09:07:06
1
19,094
Igor Brejc
75,408,909
12,814,680
Extracting values from non empty nested lists, randomly
<p>I have the following list of objects from which I would like to extract random values.</p> <pre><code>l = [ {'A':[],'B':['b1','b2'],'C':[],'D':['d1','d2','d3'],'E':['e1']}, {'A':['a4','a5','a6'],'B':['b6'],'C':['c4','c5','c6'],'D':[],'E':['e4','e5','e6']}, {'A':['a7'],'B':['b7','b8'],'C':['c7','c8','c9']...
<python>
2023-02-10 09:02:46
2
499
JK2018
75,408,889
4,875,428
Learning rate for lightgbm with boosting_type = "rf"
<p>In the documentation i could not find anything on if/how the learning_rate parameter is used with random forest as boosting type in the python lightgbm implementation: <a href="https://lightgbm.readthedocs.io/en/latest/Parameters.html" rel="nofollow noreferrer">https://lightgbm.readthedocs.io/en/latest/Parameters.ht...
<python><random-forest><lightgbm>
2023-02-10 09:01:25
1
361
skeletor
75,408,638
7,848,740
Django Python MQTT Subscribe onMessage got executed two times
<p>I've my Mosquitto MQTT broker and I've created a simple Django APP that subscribes to the topic <code>$SYS/broker/uptime</code> like below</p> <pre><code>from django.apps import AppConfig from threading import Thread import paho.mqtt.client as mqtt class MqttClient(Thread): def __init__(self, broker, port, tim...
<python><django><visual-studio-code><mqtt><mosquitto>
2023-02-10 08:34:44
1
1,679
NicoCaldo
75,408,504
9,198,074
Selenium unable to click button
<p>there is a button in <a href="https://mokivezi.lt/leidiniai" rel="nofollow noreferrer">https://mokivezi.lt/leidiniai</a> called &quot;<strong>Open</strong>&quot; you can see it under catalog image.</p> <p>It's element is: <code>&lt;button data-href=&quot;open&quot; aria-label=&quot;Open UAB &amp;quot;Makveža&amp;quo...
<python><selenium><selenium-webdriver><web-scraping>
2023-02-10 08:19:57
2
1,059
Gedas Miksenas
75,408,317
10,419,999
AWS bulk indexing using gives 'illegal_argument_exception', 'explicit index in bulk is not allowed')
<p>While I am trying to bulk index on AWS Opensearch Service (ElasticSearch V 10.1) using opensearch-py, I am getting below error</p> <pre><code>RequestError: RequestError(400, 'illegal_argument_exception', 'explicit index in bulk is not allowed') </code></pre> <pre><code>from opensearchpy.helpers import bulk bulk(clie...
<python><elasticsearch><opensearch><amazon-opensearch>
2023-02-10 07:58:57
1
4,912
Shijith
75,408,055
16,853,253
Unable to create database when running flask app
<p>I'm new to flask and I got stuck into one thing. So I have <code>run.py</code> file inside it</p> <pre><code>from market import app from market.models import db if __name__ == &quot;__main__&quot;: with app.app_context(): db.create_all() app.run(debug=True) </code></pre> <p>so when I call <cod...
<python><flask><flask-sqlalchemy>
2023-02-10 07:27:01
3
387
Sins97
75,407,809
6,457,407
Knowing when you've read everything off a multiprocessing Queue
<p>I have some code that farms out work to tasks. The tasks put their results on a queue, and the main thread reads these results from the queue and deals with them.</p> <pre><code>from multiprocessing import Process, Queue, Pool, Manager import uuid def handle_task(arg, queue, end_marker): ... add some number o...
<python><python-3.x><multiprocessing><queue>
2023-02-10 06:54:41
1
11,605
Frank Yellin
75,407,687
3,380,902
dealing with pip install dependency conflicts
<p>I have ~300 python packages that I am trying to install from a shell script that is configured to run when an instance is created. The script fails due to dependency conflicts.</p> <pre><code>ERROR: Cannot install ipykernel==6.16.2, jupyter-client==7.3.4, nbclassic==0.4.5, nbclient==0.7.0, nest-asyncio==1.5.6, noteb...
<python><pip>
2023-02-10 06:39:03
1
2,022
kms
75,407,672
8,547,986
split top three rows of pandas into three separate columns
<p>I have a pandas dataframe:</p> <pre><code> clientid date generatedTime feature featurePercentage 0 12345 2022-11-18 00:00:00 2022-11-23 08:58:09 timely_log 1.0 1 12345 2022-11-19 00:00:00 2022-11-24 08:55:46 red 0.822815 2 12345 2022-11-19 00:00:00 2022-11-24 08:55:46 timely_log 0.177185 </c...
<python><pandas>
2023-02-10 06:36:56
2
1,923
monte
75,407,605
4,470,126
Pyspark - Converting a stringtype nested json to columns in dataframe
<p>I am working on processing a CDC data recieved via kafka tables, and load them into databricks delta tables. I am able to get it working all, except for a nested JSON string which is not getting loaded when using from_json, spark.read.json.</p> <p>When I try to fetch schema of the json from level 1, using &quot;spa...
<python><json><pyspark><databricks>
2023-02-10 06:25:56
1
3,213
Yuva
75,407,467
8,481,155
Apache Beam exit pipeline on condition Python SDK
<p>I have an Apache Beam pipeline which reads from a BigQuery table and does a few processing. The dataflow job would be triggered by a Cloud Function. My requirement is to check a date column in the BigQuery which it reads at the first step and stop the pipeline from proceeding to the next stages if the date is same a...
<python><python-3.x><google-cloud-dataflow><apache-beam>
2023-02-10 06:04:11
1
701
Ashok KS
75,407,432
14,847,960
How would I add concatenate items to a master dataframe that I receive from a requests.get()
<p>I have an api call that is returning the date and adjusted close prices for given tickers in a for loop.</p> <p>There are 1100 unique tickers x 252 days, and I want to create a dataframe that's 1100x252 with the index as date.</p> <p>The problem is that I can only query the api one ticker at a time, and it returns b...
<python><pandas><python-requests>
2023-02-10 05:58:02
1
324
jd_h2003
75,407,365
2,588,860
Iterating over pyspark df becomes slower every iteration
<p>If I have a spark DF, it is my understanding that the DF is not really materialized until it is persisted or something similar, and that it is theoretically &quot;just an explain plan&quot; until said thing happens. For example, if I have <code>df</code> and remove some rows from it, until the DF needs to be materia...
<python><pyspark>
2023-02-10 05:42:39
0
2,159
rodrigocf
75,407,351
13,115,571
How to use environment variable in odoo custom modules
<p>I installed odoo in ubuntu 20.04 and I set up environment variables in <code>/etc/environment</code>. But odoo is owned by odoo user. So, when I try to call in odoo custom module using <code>os.environ.get()</code>, I don't get anything. So, how can I solve that?</p>
<python><environment-variables><odoo><ubuntu-20.04>
2023-02-10 05:40:23
2
430
Neural
75,407,200
4,348,400
Does PriorityQueue call sorted every time get is called?
<p>The docs for <a href="https://docs.python.org/3/library/queue.html#queue.PriorityQueue" rel="nofollow noreferrer"><code>queue.PriorityQueue</code></a> say:</p> <blockquote> <p>The lowest valued entries are retrieved first (the lowest valued entry is the one returned by <code>sorted(list(entries))[0]</code>).</p> </b...
<python><performance><sorting><priority-queue>
2023-02-10 05:11:31
1
1,394
Galen