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
โŒ€
76,068,654
594,319
Python generic protocol: TypeVar is "Unknown" (Pylance) or "Any" (Mypy)
<p>For a generic class or protocol, why is the result of <code>f()</code> stored in <code>fout</code> here &quot;Unknown&quot; (Pylance v2023.4.30) or &quot;Any&quot; (mypy v1.2.0) rather than &quot;T@MyProto&quot;? This is mostly academic, as the goal for <code>fout</code> to be a valid input to <code>g()</code>, whic...
<python><mypy><python-typing><pyright>
2023-04-20 22:26:48
0
2,347
moon prism power
76,068,615
4,885,544
Python Mailchimp Transactional payload not being recognized by mailchimp template
<p>I am using the <code>MailchimpTransactional</code> package to send an email with a dynamic body, and mailchimp is rendering the subject, from, to and other field correctly. However; the variables in the actual body of the template are not being populated in the mailchimp email. Below is my payload I am sending. Noth...
<python><django><mailchimp>
2023-04-20 22:17:51
1
486
sclem72
76,068,612
2,687,317
python time plotting, not working with data with microseconds
<p>I have a dataset with 589 datetime strings and 589 points. The time seq has msec accuracy. e.g. -</p> <pre><code>['2022-10-07 12:05:39.866', '2022-10-07 12:05:40.914', '2022-10-07 12:05:41.963', '2022-10-07 12:05:43.012', '2022-10-07 12:05:44.060', '2022-10-07 12:05:45.109', '2022-10-07 12:05:46...
<python><matplotlib><astropy>
2023-04-20 22:16:25
0
533
earnric
76,068,519
16,363,897
Expanding average per group ignoring previous n rows
<p>This if a follow-up question to <a href="https://stackoverflow.com/questions/76065644/pandas-expanding-average-per-group-without-changing-the-order-of-the-rows/76066078">this one</a>.</p> <p>I have the following dataframe:</p> <pre><code> a b week 8 10 9 9 3 8 9 5 5 9 7 2 10 ...
<python><pandas><dataframe>
2023-04-20 21:54:03
1
842
younggotti
76,068,347
807,797
Pythonic way to assign global administrator roles for Azure Active Directory
<p><strong>What specifically needs to be changed in the Python 3 code below in order to successfully assign the Global Administrator role for an Azure Active Directory Tenant to a given service principal?</strong></p> <p>We tried to adjust the code from <a href="https://stackoverflow.com/questions/66752779/azure-cli-eq...
<python><azure><azure-active-directory><azure-cli><azure-rbac>
2023-04-20 21:16:18
1
9,239
CodeMed
76,068,150
1,394,353
How to use inspect.signature to check that a function needs one and only one parameter?
<p>I want to validate (at runtime, this is not a typing question), that a function passed as an argument takes only 1 positional variable (basically that function will be called with a string as input and returns a truthy).</p> <p>Naively, this is what I had:</p> <pre><code>def check(v_in : Callable): &quot;&quot;&...
<python><signature><introspection>
2023-04-20 20:43:55
2
12,224
JL Peyret
76,068,146
7,910,725
Python: Replace lower case to upper, and vice versa, simultaneously via ReGex lib
<p>I open this question although a duplicate of it exists in C# lang. (without the relevant resolution needed).</p> <p>Im trying to replace all the lower case characters in a given string, with upper case chars, and vice versa. This should be done simultaneously with the least time complexity (because of use in high vo...
<python><regex>
2023-04-20 20:43:00
3
355
Mabadai
76,068,055
7,498,328
Parsing a list with double backslashes in Python3 and converting to a dict object?
<p>I have a peculiar list in Python as:</p> <pre><code>peculiar_list=['&quot;{\\n \\&quot;persons\\&quot;: \\&quot;person 1\\&quot;,\\n \\&quot;score\\&quot;: \\&quot;Very Good\\&quot;,\\n \\&quot;comment\\&quot;: \\&quot;This result was found to be very good for the the user\'s interest.\\&quot;,\\n \\&quot;level\...
<python><python-3.x><dictionary>
2023-04-20 20:30:30
1
2,618
user321627
76,068,044
3,277,396
Using subprocess.Popen messing Ubuntu terminal output
<p>Using subprocess.Popen messing Ubuntu terminal output</p> <pre><code>import subprocess import time subprocess.Popen(&quot;sudo ./agt_internal&quot;, shell=True, cwd=&quot;/home/boblittle/AGT/&quot;) time.sleep(10) for i in range(10): print('Good Morning America') </code></pre> <p>The terminal output is messed ...
<python><ubuntu><subprocess>
2023-04-20 20:29:18
2
496
SHR
76,068,016
10,620,003
Rename the columns of the dataframe based based on another number
<p>I have a dataframe and I want to change the columns of that with a specifc way. I want to change the 0-27 of the columns to d0, d1, d2, ...d27. And the 28-56 to d10-d127, and the third 28 of the columns (56-84) to (d20-d227) and etc. Can you please help me with that.</p> <p>I already did that with another dataframe ...
<python><dataframe>
2023-04-20 20:25:17
1
730
Sadcow
76,068,002
13,722,601
How to replace a character in a multiline string with a variable
<p>I have a multiline string containing the ascii art of a playing card:</p> <pre><code>clubs_ascii = &quot;&quot;&quot; _____ |V . | | /.\ | |(_._)| | | | |____V| &quot;&quot;&quot; </code></pre> <p>I try to replace the letter &quot;V...
<python><string>
2023-04-20 20:23:29
1
433
some_user_3
76,067,991
7,498,328
How to parse a list in Python that might have whitespace and returning JSONDecodeError: Extra data: line 1 column 6 (char 5) errors?
<p>I have the following list in Python3</p> <pre><code>mylist=['&quot;{ &quot;score&quot;: &quot;Really Good&quot;, &quot;text&quot;: &quot;This is a text accompanying the score, level, and more.&quot;, &quot;level&quot;: &quot;high level&quot;}&quot;', '&quot;{ &quot;score&quot;: &quot;Not So Good&quot;, &quot;t...
<python><python-3.x>
2023-04-20 20:21:11
1
2,618
user321627
76,067,982
11,171,435
No pendingTickersEvents being emitted after subscribing to IBKR streaming market data through reqMktData,
<p>Fairly new to ib_insync. Requesting streaming market data but the ticker events aren't being emitted even after 2-3 minutes, no error gets thrown or anything, just nothing happens. Below is the code snippet attached.</p> <pre><code>def _on_connected_event(): print(f&quot;Connected to IB!&quot;) def _on_pend...
<python><algorithmic-trading><interactive-brokers><tws><ib-insync>
2023-04-20 20:19:42
1
351
Mubbashir Ali
76,067,675
8,340,881
Iterate through each rows in pandas dataframe and get value from a different dataframe
<p>I have 3 pandas dataframe, df, df_a, df_b as below</p> <pre><code>df = pd.DataFrame(data={'table': [&quot;a&quot;, &quot;a&quot;, &quot;b&quot;], 'seq': [&quot;xx&quot;, &quot;xy&quot;, &quot;z&quot;]}) df_a = pd.DataFrame(data={'a_id': [1, 2, 3], 'col1': [&quot;fg&quot;, &quot;rt&quot;, &quot;zh&quot;]}) df_b = pd....
<python><pandas>
2023-04-20 19:37:04
2
1,255
Shanoo
76,067,656
7,505,256
Mypy - Incompatible types in assignment when assigning different values in alternative branches
<p>I am wondering why I am getting <code>Incompatible types in assignment</code> here?</p> <pre class="lang-py prettyprint-override"><code>from typing import cast import pyvisa from pyvisa.constants import InterfaceType from pyvisa.resources import GPIBInstrument, TCPIPInstrument class Instrument: resource_manag...
<python><python-typing><mypy>
2023-04-20 19:34:23
2
316
Prokie
76,067,541
15,452,168
response 404 on using requests for scraping postal data
<p>for education purposes I want to scrap the population of Germany per pin code. This information is available at <a href="https://postal-codes.cybo.com/germany/" rel="nofollow noreferrer">https://postal-codes.cybo.com/germany/</a></p> <p>I tried to run web scraping tools such as requests and some others which I found...
<python><web-scraping><beautifulsoup><python-requests>
2023-04-20 19:16:34
1
570
sdave
76,067,520
3,380,902
Must be list or null Exception when attempting to pandas json_normalize
<p>I have a pandas dataframe containing <code>json</code> data that I am attempting to normalize using pandas <code>json_normalize</code>.</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'id': [0, 1], 'j': [{'type': 's', 'loc': {'s': {'value': '0.0', 'text': 'xxx'}, 'ps': {...
<python><json><pandas><json-normalize>
2023-04-20 19:13:05
1
2,022
kms
76,067,245
1,876,739
Add Values of Pandas Series with MultiIndex to Values of A Single Level Index Series
<p>Given a pandas <code>Series</code> with simple index</p> <pre><code>import pandas as pd simple_index_series = pd.Series([1,2,3], index=['a', 'b', 'c']) a 1 b 2 c 3 </code></pre> <p>And a Series with a MultiIndex</p> <pre><code>multi_index_series = pd.Series( 0, index = pd.MultiIndex.from_product([['fo...
<python><pandas>
2023-04-20 18:33:22
1
17,975
Ramรณn J Romero y Vigil
76,067,216
1,942,868
FIle upload from browser to S3 which has block public access
<p>I want to upload the file to <code>S3</code> from browser accessing the web application running on <code>Fargate</code></p> <p>However, this <code>S3</code> must have <code>block public access=ON</code>.</p> <p>So, It is impossible to upload directly from browser.</p> <p>Then, I have some alternative ideas,</p> <ul>...
<python><amazon-web-services><amazon-s3><aws-lambda><aws-fargate>
2023-04-20 18:28:49
2
12,599
whitebear
76,067,104
1,492,337
Using Vicuna + langchain + llama_index for creating a self hosted LLM model
<p>I want to create a self hosted LLM model that will be able to have a context of my own custom data (Slack conversations for that matter).</p> <p>I've heard Vicuna is a great alternative to ChatGPT and so I made the below code:</p> <pre><code>from llama_index import SimpleDirectoryReader, LangchainEmbedding, GPTListI...
<python><machine-learning><pytorch><chatgpt-api><langchain>
2023-04-20 18:14:37
2
433
Ben
76,067,002
1,795,245
Create new dataframe by applying 2D mask on another DataFrame with the same shape
<p>Is there a fast and easy way to create a new data frame based on a masked dataframe and a dataframe with values:</p> <pre><code>df_1 = pd.DataFrame(data = [[False, True],[True, False],[False, True], [False, False]] ) 0 1 0 False True 1 True False 2 False True 3 False False df_2 = pd.D...
<python><pandas><dataframe>
2023-04-20 17:59:36
4
649
Jonas
76,066,919
3,623,603
What is a best practice for handling paths in Python modules?
<p>I have the following folder structure in Linux:</p> <pre><code>Model | |-----Shared_Modules (contains shared.py, a module full of shared functions) | |-----Segment_Sales (contains main.py, run the model from this file) | -----------data (contains data.csv) </code></pre> <p>main.py in the <cod...
<python><pandas><module><path><sys>
2023-04-20 17:47:21
0
510
Vaslo
76,066,812
11,546,773
How to combine columns in polars horizontally?
<p>I'm trying to combine multiple columns into 1 column with python Polars. However I don't seem to find an (elegant) way to combine columns into a list.</p> <p>I only need to combine column b - e into 1 column. Column a needs to stay exactly as it is now. I've tried using <code>map_elements</code> to achieve this. Des...
<python><dataframe><python-polars>
2023-04-20 17:32:36
1
388
Sam
76,066,749
19,130,803
Postgres truncate command SQL: passing dynamic table name
<p>I am working on a Python web project using a <code>postgres</code> database as backend with the <code>psycopg2</code> package.</p> <p>Earlier, I was trying <code>static</code> query for <code>truncate</code> command for demo purpose, after it works, I tried to make it <code>dynamic</code>, thereby passing <code>tab...
<python><postgresql>
2023-04-20 17:23:44
2
962
winter
76,066,634
1,044,117
capturing/replaying requests with python gives a different result than a browser
<p>I'm trying to interact with the form at <a href="https://referti.policlinicodiliegro.it/servizi/#/portalereferto/ritiro" rel="nofollow noreferrer">https://referti.policlinicodiliegro.it/servizi/#/portalereferto/ritiro</a> via command-line / python.</p> <p>I captured a request/response via Chrome Developer Tools netw...
<python><python-requests>
2023-04-20 17:05:27
1
19,047
fferri
76,066,597
10,146,283
Splitting polygon by line using intersection returns original polygon in Shapely
<p>I reduced my problem to some MWE so that it can be reproduced. I'm using Shapely 2.0 I want to split a polygon P in 2 parts by a line L.</p> <p><code>POLYGON ((292718.0381447676 6638193.414029885, 292694.50537013356 6637994.803334004, 292718.0381447676 6638193.414029885, 292718.9708331647 6638193.303518486, 292722.0...
<python><shapely>
2023-04-20 17:00:06
1
626
Beinje
76,066,562
3,517,025
How to visualize nodes in horizontal cluster with invisible edges (Python diagrams)
<p>I'm trying to make a horizontal cluster containing two nodes (here visualized as users) in Python module <a href="https://diagrams.mingrammer.com/" rel="nofollow noreferrer">diagrams</a> which uses Graphviz for rendering.</p> <p>But the only way to achieve this is by adding edges between the nodes.</p> <h3>Horizonta...
<python><graphviz><diagram>
2023-04-20 16:56:02
1
5,409
Joey Baruch
76,066,499
11,510,977
Error in Converting PyTorch Model to ONNX format
<p>I want to convert <code>https://github.com/TencentARC/GFPGAN</code> to ONNX format to use in Android App. After going through the procedure, it shows error (AttributeError: 'dict' object has no attribute 'modules').</p> <p>Following is my code in Colab:</p> <pre><code>!pip install onnx !pip install torch torchvisio...
<python><pytorch><onnx><tflite>
2023-04-20 16:46:41
1
373
Hammad Ali Shah
76,066,446
13,723,501
Gtk thread blocking function execution?
<p>I have the following python code:</p> <pre class="lang-py prettyprint-override"><code>import threading from fpysensor import fp import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title=&quot;Hello, World!&q...
<python><multithreading><gtk><shared-libraries>
2023-04-20 16:39:09
1
343
Parker
76,066,423
1,942,868
What class instance should be used for request of authenticate()?
<p>I have backend which uses the <code>Ldap</code></p> <pre><code>class MyLDAPBackend(LDAPBackend): def authenticate(self, request, username=None, password=None, **kwargs): print(&quot;Try ldap auth&quot;) print(type(request)) # &lt;class 'django.core.handlers.wsgi.WSGIRequest'&gt; user = LD...
<python><django><ldap><openldap>
2023-04-20 16:35:23
0
12,599
whitebear
76,066,328
17,795,398
How to use kivymd.ResponsiveLayout?
<p>I'm learning <code>kivymd</code>, and I want to use the <code>ResponsiveLayout</code> defined at a <code>.kv</code> file.</p> <p><code>.py</code> code:</p> <pre><code>from kivy.lang import Builder from kivymd.app import MDApp class Test(MDApp): def build(self): return Builder.load_file(&quot;startpage.k...
<python><kivymd>
2023-04-20 16:24:09
1
472
Abel Gutiรฉrrez
76,066,317
1,477,072
How can I annotate a django queryset with more than one values
<p>I have an application that scrapes some eshops every day, and I record the <code>Price</code> of every <code>Item</code>.</p> <p>A simplified version of my models looks like this:</p> <pre class="lang-py prettyprint-override"><code>class Item(models.Model): name = models.CharField(max_length=512, blank=True) c...
<python><django><postgresql><django-orm>
2023-04-20 16:23:17
1
593
Sakis Vtdk
76,066,269
10,472,655
Reticulate wrongly translating values of a column
<p>Right now I'm working in a .Rmd file and using <code>reticulate</code> so I can combine both Python and R chunks.</p> <p>Initially, I'm getting a dataframe like this one below.</p> <pre><code>id device sessions 1 mobile 40 2 desktop 61 3 desktop 55 4 mobile 24 </code></pre> <p>A...
<python><r><r-markdown><reticulate>
2023-04-20 16:17:58
0
343
teogj
76,066,238
2,999,868
Passing BytesIO to BufferedReader results in warning message
<p>I am trying to create a BufferedReader from a BytesIO object but my IDE (PyCharm) is warning me that BufferedReader <code>Expected type 'RawIOBase', got 'BytesIO' instead</code>.</p> <p>The logic seems to work but I'd like to solve this properly if there is a way to do so.</p> <p>Another way to phrase this question ...
<python><minio><bytesio>
2023-04-20 16:13:54
0
952
keith.g
76,066,200
11,923,747
Python does't search for libraries in the right path (windows)
<p>I have 2 installations of Python on my windows computer:</p> <p>Python3.6.5 with Anaconda:</p> <pre class="lang-none prettyprint-override"><code>C:\Users\Pedro\AppData\Local\Continuum\anaconda3\python.exe </code></pre> <p>Python3.8.5 with WinPython:</p> <pre class="lang-none prettyprint-override"><code>C:\Users\Pedr...
<python><python-3.x><windows><path><version>
2023-04-20 16:09:38
1
321
floupinette
76,066,125
16,389,095
Kivy/KivyMD: Add a method when the selection of a drop down item changes
<p>I developed an UI with Kivy / KivyMD with Python. The UI is very simple: when a button is pressed a DropDownItem is added to the layout. I need to add a method that is called every time the selection of the DropDownItem changes. Here is the code:</p> <pre><code>from kivy.lang import Builder from kivymd.app import MD...
<python><kivy><kivy-language><kivymd>
2023-04-20 16:01:20
1
421
eljamba
76,066,092
1,942,505
How to print fetched result in FastSQLite, there is no .cursor() like in SQLite3?
<p>I downloaded <a href="https://pypi.org/project/fastsqlite/" rel="nofollow noreferrer"><code>FastSQLite</code></a> for python , <a href="https://github.com/perseoq/FastSQLite/blob/main/README.md" rel="nofollow noreferrer"><code>Readme</code></a><br> I created a database and table, but I do not know how to print fetch...
<python><sqlite><sqlite3-python>
2023-04-20 15:58:23
0
541
user1942505
76,065,940
512,652
Using a global Popen object from a Flask route
<p>I have a small Flask app, running with Gunicorn configured with one worker. At the app's initialization, it starts up a <code>subprocess.Popen</code> and hangs onto it in a global variable.</p> <pre class="lang-py prettyprint-override"><code>import subprocess def my_init(): ... global MY_SUBPROCESS MY_SUBPR...
<python><flask><subprocess><gunicorn>
2023-04-20 15:42:09
1
19,227
ajwood
76,065,724
10,266,106
Numpy Broadcast Function Across All Array Columns At Once
<p>To preface, looping across multidimensional arrays in Numpy using ndenumderate to perform operations is inefficient, particularly when the array is massive (on the order of millions of indices). With this in mind, I would like to apply a function across all columns (j) of an array's row (i) at once, which I believe ...
<python><arrays><numpy><numpy-ndarray><array-broadcasting>
2023-04-20 15:17:14
0
431
TornadoEric
76,065,718
8,207,701
Text Alignment Not Centered MoviePy
<p>I want to create a subtitleclip that's position on the video is little right to the center but, the text should be aligned to the center.</p> <p>So here's my code</p> <pre><code> generator = lambda txt, font_size: TextClip(txt, font='Arial-Rounded-MT-Bold', fontsize=font_size, color='white', align=&quot;center&qu...
<python><python-3.x><moviepy>
2023-04-20 15:16:44
1
1,216
Bucky
76,065,711
4,108,376
Converting py::array to Eigen::Ref from C++
<p>I'm using pybind for an interface to a program that uses Eigen internally to access a 2D array, and should be able to receive a Numpy array from python.</p> <p>I have a function like this:</p> <pre><code>void A::f(const Eigen::Ref&lt; Eigen::Matrix&lt;double, Eigen::Dynamic, 3, Eigen::RowMajor&gt; &gt;&amp;) // boun...
<python><c++><numpy><eigen><pybind11>
2023-04-20 15:16:12
0
9,230
tmlen
76,065,644
16,363,897
Pandas expanding average per group without changing the order of the rows
<p>I have the following dataframe &quot;df1&quot;:</p> <pre><code> a b week 9 47 19 9 36 44 10 29 46 10 -68 -37 10 -12 90 9 67 66 </code></pre> <p>I want to calculate the expanding average of each column, conditional on the index. This is the expected output:</p> <pre><code> ...
<python><pandas><dataframe>
2023-04-20 15:09:32
2
842
younggotti
76,065,543
4,045,275
Arranging 4 histogram plots in a 2x2 facet grid
<h1>The issue</h1> <p>I have a dataframe with two columns: color and values.</p> <p>Color can be red, yellow, green and black. For each of these 4 colors, I need to plot an histogram with the distribution of &quot;values&quot;. I would like the plots to be arranged in a 2x2 grid.</p> <h1>What I would like to do</h1> <p...
<python><matplotlib><seaborn><facet><facet-grid>
2023-04-20 14:59:44
0
9,100
Pythonista anonymous
76,065,488
19,130,803
Postgres Truncate command: how to check it is successfully executed python
<p>I am working on python web app. I am using <code>postgres</code> database through <code>psycog2</code>. I am making a table empty using command</p> <pre><code>TRUNCATE TABLE some_table_name RESTART IDENTITY; </code></pre> <p>I have an <code>IDENTITY</code>column in the table. I read that it returns the <code>identit...
<python><postgresql>
2023-04-20 14:54:22
0
962
winter
76,065,485
12,870,628
sqlite3 row does not work to make fetchall() a dict instead of tuple
<pre><code>con = sqlite3.connect(&quot;funds.db&quot;) with con: cur = con.cursor() con.row_factory = sqlite3.Row funds = cur.execute(&quot;SELECT * from funds&quot;).fetchall() print(funds) </code></pre> <p>Since i set <code>con.row_factory = sqlite3.Row</code>, i expect funds to re...
<python><sqlite3-python>
2023-04-20 14:54:03
1
495
Justin Chee
76,064,952
9,275,146
Matplotlib Histogram has weird gaps in the data
<p>I have the following dataframe that consists of 50 rows where each row is a year and month formatted as datetime64[ns], with an Order_ct that is a count of number of orders that month formatted as int64, and two other fields.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np ...
<python><pandas><matplotlib><bar-chart>
2023-04-20 13:59:36
0
379
Kreitz Gigs
76,064,896
5,212,614
Can we assign a text index to a list object, rather than a numeric index?
<p>I am merging a bunch of word docs into a list, like this.</p> <pre><code>import os import docx2txt import warnings warnings.filterwarnings('ignore') # all resumes ext = ('.docx') resume_path = 'C:\\Users\\resumes\\' resumes = [] # load the data for files in os.listdir(resume_path): my_text = docx2txt.proc...
<python><python-3.x><list>
2023-04-20 13:54:03
1
20,492
ASH
76,064,880
5,852,692
Converting some elements of a python list and preserving the rest
<p>I am looking for an elegant way to convert some elements of a list and preserve the rest.</p> <p>Consider the following list:</p> <pre><code>list_ = [0, 0, 1, 1, 0, 0] </code></pre> <p>I would like to convert <code>list_</code> to <code>[0, 1, 1, 1, 0, 1]</code>, of course I can write a for loop with some if-stateme...
<python><list><converters>
2023-04-20 13:52:20
2
1,588
oakca
76,064,867
1,354,354
Python Sqlparse: How to get the boolean status if sql query is not in correct format
<p>I have a use case where I need to check the format of the sql query before sending to the the database for execution.</p> <p>If sql query is not in correct format sqlparse should return the false status, if it is in correct format it should return true status.</p> <p>I did not see any function in sqlparse docuementa...
<python><sql-parser>
2023-04-20 13:50:52
0
808
Rahul Neekhra
76,064,826
601,862
How to find out the grids which have the path inside
<p><a href="https://i.sstatic.net/NrnVr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/NrnVr.png" alt="demo image" /></a></p> <p>As you can see, there is a 10 by 10 grids. They are stored in a variable <code>matrix</code>.</p> <p>The <code>matrix</code> stores an 10 by 10 2 dimensional array. In each el...
<python><algorithm>
2023-04-20 13:45:40
0
7,147
Franva
76,064,820
4,497,972
How to create new column in first pandas dataframe using index of second pandas dataframe based on certain conditions in python?
<p>Let me describe the problem using simple example.</p> <p>Lets say we have df1 and df1 created as follows:</p> <pre><code>df1 = pd.DataFrame({'month': [1, 4, 7, 10], 'year': [2012, 2014, 2013, 2014], 'sale': [55, 40, 84, 31]}) df2 = pd.DataFrame({'month1': [2,3,4,1, 4, 7, 10], ...
<python><pandas><dataframe>
2023-04-20 13:44:37
2
535
lonstud
76,064,476
4,495,790
How to get maximum value per rows by top-level groups in multilevel Pandas DataFrame?
<p>I have the following Multilevel DF in Pandas:</p> <pre><code>A B a b a b ---------- 1 2 3 4 2 3 3 2 7 2 1 0 </code></pre> <p>Now I would like to get maximum values in each row per level-0 groups like this:</p> <pre><code>A B ---- 2 4 3 3 7 1 </code></pre> <p>What is the proper query?...
<python><pandas>
2023-04-20 13:11:55
1
459
Fredrik
76,064,417
6,623,277
TKInter widgets having different width even after setting same width
<p>I am trying to build a small window in tkinter, but I observed that different widgets take on different widths even when set with the same width. Here's the output that I can see on running the code:</p> <p><a href="https://i.sstatic.net/k6lld.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/k6lld.png"...
<python><python-3.x><tkinter><tkinter-entry><tkinter-layout>
2023-04-20 13:06:06
1
2,077
KCK
76,064,376
6,411,540
Construct an object using ruamel
<p>I want to create some objects based on arguments in a yaml file. Everything was working fine, but now I want to supply the class with some options from which one should be chosen randomly. I thought I could use the <code>__post_init__</code> method for this, but the learned, that this is intentionally not called bec...
<python><constructor><yaml><ruamel.yaml>
2023-04-20 13:03:01
1
1,273
Darkproduct
76,064,228
3,227,302
area weighted average of raster using polygon - R vs Python
<p>I have an R function in <code>terra</code> package that takes a raster and polygon and calculates the average of the raster for the polygon. In doing so, it uses the area intersection of each raster cell with the polygon as a weight to do the averaging (for e.g. some raster on polygon boundary could be partially int...
<python><r><geopandas><terra><rasterio>
2023-04-20 12:46:27
1
3,845
89_Simple
76,064,194
10,061,193
Store User's Credentials in Python Package
<p>I'm working on a Python package where I need to get credentials (email and password) from the user via CLI and they can enter their credentials just as follows.</p> <pre><code>$ my_package auth --email abc@efg.com --password testpass123 </code></pre> <p>My package is responsible for storing and using the provided cr...
<python><authentication><package><authorization><credentials>
2023-04-20 12:42:40
1
394
Sadra
76,064,091
9,640,238
Select rows between two rows with pandas
<p>There's many answers to how to select rows where values in a column fits between two values, but I can't find how to select all rows between two rows. For instance, say I have a dataframe, with a column that identifies the start and end.</p> <pre class="lang-py prettyprint-override"><code>data = {'record_id' : [1, 1...
<python><pandas>
2023-04-20 12:32:37
2
2,690
mrgou
76,064,067
2,123,706
downlad file from sharepoint via python error: The access policy does not allow token issuance
<p>I was looking <a href="https://stackoverflow.com/questions/53671547/python-download-files-from-sharepoint-site">Python - Download files from SharePoint site</a> to try and download files from sharepoint, but I get this error:</p> <pre><code>ValueError: An error occurred while retrieving token from XML response: AADS...
<python><sharepoint>
2023-04-20 12:30:02
1
3,810
frank
76,064,018
2,912,349
Minimal covering circle for a matplotlib.PathPatch
<p>For an arbitrary matplotlib.PathPatch instance and a given origin, I would like to find the circle with the minimal radius that fully covers the patch. For straight line paths that is straightforward: simply compute the distances between path vertices and the origin; the maximum is the desired radius. However, for p...
<python><matplotlib><bezier>
2023-04-20 12:24:27
1
12,703
Paul Brodersen
76,063,981
11,795,964
Create a new pandas category column on the basis of values in another column
<p>I am a doctor looking at surgery data. There is a column in the data frame for admission method.</p> <pre><code>df['ADMIMETH'] </code></pre> <p>There are a number of codes for admission method, but the categories essentially are emergency or non-emergency.</p> <p>Emergency has 17 codes, non-emergency has 3 codes. I...
<python><pandas><apply>
2023-04-20 12:20:31
0
363
capnahab
76,063,891
995,431
Python Celery chord raises ChordError even when error is handled by callback
<p>I have this problem in a larger application, but have reduced it to the following MRE.</p> <p>I have a Celery chord consisting of two parallel tasks feeding into one final tasks. It's expected that tasks might occasionally permanently fail for external reasons, simulated here by raising <code>Exception</code>. I wis...
<python><celery><celery-task><celeryd>
2023-04-20 12:09:31
0
325
ajn
76,063,762
13,158,157
pyspark isin multiple columns
<p>Coming from pandas to pyspark I understand that you can substitute <code>isin</code> by <code>.join</code> with <code>how='inner'</code> or <code>how='left_anti</code>. This works for me in simple conditions but I cannot figure how to use it in more nuanced cases.</p> <p>I have a case when I want to filter one dataf...
<python><pandas><pyspark>
2023-04-20 11:55:11
0
525
euh
76,063,651
11,426,624
requests does not retrun the full div
<p>I would like to scrape a webpage using BeautifulSoup and requests. The below code works, but I do not get the full div back.</p> <pre><code>import requests cert = (certs['cert'], certs['password']) r = requests.get(url, cert=(certs['cert'], certs['password']), verify=certs['CA_file'...
<python><web-scraping><python-requests>
2023-04-20 11:42:19
1
734
corianne1234
76,063,620
19,386,576
stick top progress bar in python to stdout
<p>How can I get in python a print to stdout with the progress bar pinned to the top to get a result similar to that with the &quot;sudo apt upgrade&quot; command on linux but with the elements that got printed one under the other but with the progress bar above. Im searching for a way to make the progress bar behave a...
<python><python-3.x><terminal><progress-bar><stdout>
2023-04-20 11:37:07
1
608
federikowsky
76,063,383
11,125,112
Bounding Box & Segmentation Mask of a Blender Particle System
<p>I m trying to simulate multiple falling objects with a particle system in blender.</p> <p>To train certain CNN's I require the segmentation mask of single elements that are visible in the scene. Up to now I m only able to perform part of the exporting mask task. Such as exporting a mask by composition nodes or using...
<python><blender><bpy>
2023-04-20 11:06:08
2
464
Daniel Klauser
76,063,210
9,481,479
How to get Bitrate from uridecodebin Deepstream source
<p>For decoding online and local mp4 files, I am using this code snippet to create source bin in Deepstream Python code.(similar to deepstream_test_3 example) This is uridecodebin based source, and handles all decoding part. I need bitrate info of source video, so as I can set the same to encoder of my output video. P...
<python><video-streaming><encoder-decoder><deepstream>
2023-04-20 10:43:08
1
1,004
Nawin K Sharma
76,062,931
3,188,444
How can I save .py text version of jupyter notebook from the notebook itself
<p>I want to save a text version (<code>.py</code>) of a Jupyter notebook (<code>.ipynb</code>) without output for version control purposes.</p> <p>I know you can do this by running <code>jupyter nbconvert</code> in terminal, but how can I automate this by executing this command from within the Jupyter notebook itself?...
<python><jupyter-notebook><nbconvert>
2023-04-20 10:11:01
2
1,138
Kouichi C. Nakamura
76,062,929
4,451,315
Rolling group_by, but truncating each value at midnight
<p>Say I have the following DataFrame:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl import numpy as np from datetime import datetime df = pl.DataFrame({'ts': pl.datetime_range(datetime(2020, 1, 1), datetime(2020, 1, 10), '1h', eager=True)}) df = df.with_columns(value=pl.Series(np.arange(len(...
<python><python-polars>
2023-04-20 10:10:47
1
11,062
ignoring_gravity
76,062,894
403,425
Annotate a QuerySet with Exists instead of Count
<p>I have a model which contains a <code>ManyToManyField</code>:</p> <pre class="lang-py prettyprint-override"><code>class UserHasProduct(Model): user = ForeignKey(User, on_delete=CASCADE) products = ManyToManyField(Product) class Product(Model): is_nfr = BooleanField(default=False) </code></pre> <p>I want...
<python><django><django-orm>
2023-04-20 10:06:24
2
5,828
Kevin Renskers
76,062,688
12,226,377
Scraping Trustpilot and storing results in a pandas dataframe
<p>I am using the following code to extract all the reviews for the first 20 pages from Trustpilot</p> <pre><code>from bs4 import BeautifulSoup import requests import pandas as pd import datetime as dt # Initialize lists review_titles = [] review_dates_original = [] review_dates = [] review_ratings = [] review_texts =...
<python><pandas><dataframe><web-scraping><beautifulsoup>
2023-04-20 09:42:01
2
807
Django0602
76,062,643
245,549
How can I efficiently handle large CSV files in Python?
<p>I have a CSV file with millions of rows and columns that I need to process in Python. However, when I try to load it into memory using pandas or csv modules, my program becomes extremely slow and memory-intensive.</p> <p>What are some efficient techniques or libraries that I can use to handle such large CSV files in...
<python><csv><size>
2023-04-20 09:37:24
1
132,218
Roman
76,062,594
6,352,008
Use the same rule at multiple locations in a pipeline with and without wildcards
<p>With snakemake, I'm trying to apply the same rule to N independent files and to a file which is the merge of all those N files.</p> <p>I've created a minimal example you can find below. That does this: <a href="https://i.sstatic.net/B70WP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/B70WP.png" alt=...
<python><python-3.x><snakemake><directed-acyclic-graphs>
2023-04-20 09:31:07
2
967
Plopp
76,062,543
5,852,692
Pandas apply function to both columns and rows
<p>I have the the following pandas dataframe:</p> <pre><code> COL1 COL2 COL3 N1 1 2 0 N2 2 2 1 N3 3 2 1 </code></pre> <p>I would like to apply a function to each column &amp; row, where e.g.: <code>x[N1, COL1] = x[N1, COL1] / sum(x[_, COL1])</code></p> <p>The result sh...
<python><pandas><function><apply>
2023-04-20 09:25:23
1
1,588
oakca
76,062,394
14,606,987
ValueError: Got unknown type S when using GPT-4 with LangChain for Summarization
<p>I am trying to use LangChain with the GPT-4 model for a summarization task. When I use the GPT-3.5-turbo model instead of GPT-4, everything works fine. However, as soon as I switch to GPT-4, I get the following error:</p> <pre class="lang-bash prettyprint-override"><code>ValueError: Got unknown type S </code></pre> ...
<python><openai-api><langchain>
2023-04-20 09:09:55
2
868
yemy
76,062,338
245,549
How to force a function to treat outputs of different objects identically?
<p>I have this part of the code:</p> <pre><code>llm = OpenAI(temperature = 0) agent = initialize_agent( tools, llm, agent = 'conversational-react-description', verbose = True, memory = memory, return_intermediate_steps = True ) response = agent(prompt) </code></pre> <p>When I run it I get the &q...
<python><oop>
2023-04-20 09:02:53
1
132,218
Roman
76,062,284
9,287,711
replace specific element of Dataframe to value of Series
<p>suppose I have a Dataframe <code>df</code> like</p> <pre><code> a b c 0 1 2 3 1 nan 2 3 2 1 2 nan </code></pre> <p>I want to replace the element which larger than the Series <code>df.count(axis=1)</code> to the element of the Series. Whith the <code>df</code> convert to</p> <pre><code> a b c 0 ...
<python><pandas>
2023-04-20 08:57:43
1
559
xxyao
76,062,151
14,414,944
Why does env cause Python Popen to hang?
<p><strong>Edit:</strong> I've figured out that this problem is being caused by something to do with env. If I remove env from the below, all works well.</p> <p>I've got a bit of a classic Python <code>Popen</code> problem.</p> <p>Below is the code I'm using to create an async iterator from a <code>Popen</code> call. F...
<python><subprocess>
2023-04-20 08:44:00
0
1,011
lmonninger
76,062,119
11,333,604
read nifti files 3d slicer vs other methods
<p>I have some nii.gz files which, when I open using imajeJ , or any python library such as SimpleITK or Monai I get a stack of MRI images, as if taken from top to bottom. That being said, when I open the same file with slicer, I also get a stack of images, taken from the side and from the front, the G and Y channels. ...
<python><medical-imaging><simpleitk>
2023-04-20 08:40:13
2
303
Iliasp
76,062,034
9,948,248
monkey patch not working? (using it to change a function of a class in external library)
<p>I'm trying to change an external library's function (inside of a class). My objective is to, while I execute my python program, change some lines inside that function. I've seen some examples and I think I'm doing it correctly, but maybe there is some nuances I don't fully understand that makes the code not to work....
<python><monkeypatching>
2023-04-20 08:29:20
0
1,018
Aurelie Navir
76,062,022
12,243,638
Fillna with sum of previous row and the change in another column in dataframe
<p>I have data frame which has some <code>nan</code> values. I want to fill them by adding the previous row with the change in the column <code>Factor</code>. The dataframe looks like this:</p> <pre><code> Value Col Factor 2022-11-30 0.020 84 2022-12-31 0.015 77 2023-01-31 NaN 90 2023-0...
<python><pandas><dataframe>
2023-04-20 08:28:00
2
500
EMT
76,061,903
2,405,663
Bokeh chart set x axis label
<p>I m building a charts page using bokeh to plot them. I have some Line chart where I need to plot on x-axis the number of week of the year.</p> <p>So this is the result that I m able to build: <a href="https://i.sstatic.net/MiuiD.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/MiuiD.jpg" alt="enter ima...
<python><charts><bokeh>
2023-04-20 08:11:42
1
2,177
bircastri
76,061,722
9,542,989
Export LangChain Index?
<p>I just created a <code>langchain</code> index in Python by passing in quite a few URLs. I used the <code>UnstructuredURLLoader</code> as my Document Loader.</p> <p>Now, to use <code>UnstructuredURLLoader</code>, I had to install several packages on my environment including several very larges ones like <code>unstruc...
<python><python-3.x><langchain>
2023-04-20 07:52:51
1
2,115
Minura Punchihewa
76,061,672
1,877,002
Detection Docker environment Python
<p>I am running a docker image of Python code in two different environments.</p> <ol> <li>In Windows via cmd <code>docker run --rm --name test -p 9000:8080 estimate_variance</code></li> <li>In Linux via terminal <code>docker run --rm --name test -p 9000:8080 estimate_variance</code></li> </ol> <p>The code itself uses...
<python><python-3.x><amazon-web-services><docker><amazon-s3>
2023-04-20 07:45:22
1
2,107
Benny K
76,061,556
7,012,917
How to enforce start and end date tick labels regardless if it's a major or minor tick?
<p>I have a timeseries (one of many) ranging between the years 2001 and 2023.</p> <p>This is how it looks like when I plot it: <a href="https://i.sstatic.net/je7Aj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/je7Aj.png" alt="enter image description here" /></a></p> <p>As you can see the major ticks ar...
<python><dataframe><matplotlib>
2023-04-20 07:30:36
1
1,080
Nermin
76,061,287
19,553,193
django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint') in Django
<p>It is my first time encountered this error, I've implemented it multiple times on my different projects and migrated to database it works fine , but just this one returns me an error, when I tried to migrate my models.py it says:</p> <pre><code>django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constrain...
<python><django><model>
2023-04-20 06:49:40
0
335
marivic valdehueza
76,061,004
5,750,238
How to calculate distance to nearest flagged row by date difference in pandas?
<p>I need to calculate the distance to the nearest christmas by date, not just naively by number of rows. My toy data has the columns: road_id, traffic, date, and is_christmas.</p> <p>I can do something like the following:</p> <pre><code>import pandas as pd import numpy as np # create example dataframe df = pd.DataFra...
<python><pandas><datetime><group-by>
2023-04-20 05:59:47
1
579
CapnShanty
76,060,853
13,946,204
Is it possible to call self (building) list inside a list comprehension?
<p>Let's say that we have a simple code:</p> <pre class="lang-py prettyprint-override"><code>chars = [&quot;a&quot;, &quot;a&quot;, &quot;b&quot;] added = [] for c in chars: if c in added: added.append(c + '_added_again') else: added.append(c) # added is ['a', 'a_added_again', 'b'] </code></pre> <p>We are...
<python>
2023-04-20 05:29:38
2
9,834
rzlvmp
76,060,833
1,576,710
find elements by class name selenium python is not working for me
<p>I want to get web elements with the same class name. I'll use those to take screenshots of elements for my application. I am using Selenium in Python for this purpose.</p> <pre><code>url = &quot;https://www.pexels.com/search/happy/&quot; driver = webdriver.Chrome(executable_path=ChromeDriverManager().install()) driv...
<python><selenium-webdriver><web-scraping><chrome-web-driver>
2023-04-20 05:27:15
1
447
hina abbasi
76,060,632
2,348,503
How to return the result of llama_index's index.query(query, streaming=True)?
<p>I am trying to return the result of llama_index's <code>index.query(query, streaming=True)</code>.</p> <p>But not sure how to do it.</p> <p>This one obviously doesn't work.</p> <pre class="lang-py prettyprint-override"><code>index = GPTSimpleVectorIndex.load_from_disk(index_file) return index.query(query, streaming...
<python><stream><artificial-intelligence><openai-api><llama-index>
2023-04-20 04:43:12
2
420
Taishi Kato
76,060,592
8,996,209
requests.exceptions.ConnectTimeout error in Azure Cognitive Services Text-to-speech REST API
<p>So, I have been trying process a folder with thousands of text files to convert each one to speech using Azure Cognitive Services Text-to-speech REST API. It works fine until it doesn't. I get errors after several successful conversions. I would like to have a stable connection so I can reliably leave the script run...
<python><azure><rest><text-to-speech><azure-cognitive-services>
2023-04-20 04:32:34
1
335
eera5607
76,060,546
2,288,659
What allows NaN to work with the Python list inclusion operator?
<p>Pretty much anyone who works with IEEE floating-point values has run into NaN, or &quot;not a number&quot;, at some point. Famously, <a href="https://stackoverflow.com/questions/50124383/what-is-the-intuitive-reason-that-nan-nan">NaN is not equal to itself</a>.</p> <pre><code>&gt;&gt;&gt; x = float('nan') &gt;&gt;&g...
<python><nan><equality>
2023-04-20 04:22:55
1
70,851
Silvio Mayolo
76,060,462
5,218,240
Python Pip install another package into site-packages with the same module name existing in that folder
<p>For example, I already have a module named <code>test1</code> in my site-packages folder, <code>test1</code> already toke that folder name under <code>site-packages</code></p> <p>Now I have another package, using the module name <code>test1.subModule1</code>, I decided to install this new package without destroy the...
<python><pip><setuptools><setup.py><python-packaging>
2023-04-20 03:57:43
0
1,215
cinqS
76,060,288
1,362,485
Error trying to use Dask on Kubernetes with distributed workers
<p>I'm attempting to deploy a dask application on Kubernetes/Azure. I have a Flask application server that is the client of a Dask scheduler/workers.</p> <p>I installed the Dask operator as described <a href="https://kubernetes.dask.org/en/latest/#kubecluster" rel="nofollow noreferrer">here</a>:</p> <pre><code>helm ins...
<python><kubernetes><dask><dask-distributed><dask-kubernetes>
2023-04-20 03:13:56
1
1,207
ps0604
76,060,220
2,502,791
nested function calls using with statements for authentication
<p>I have a couple of functions that I'm trying to write for tableau (not that that should matter necessarily). The important bit is that it's hierarchical so projects contain workbooks which contain views. project/workbook/view So I have a function for each <code>get_project</code>, <code>get_workbook</code>, and <c...
<python><tableau-api>
2023-04-20 03:01:34
1
1,718
Faller
76,060,204
2,998,077
To 'overlay' 2 dataframes with noted differences
<p>2 simple dataframes that I want to 'overlay' them, i.e., if the value of the cell in df_history but not in df_now, it will be added into the new df_now with a prefix, like:</p> <p><a href="https://i.sstatic.net/eZFqV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eZFqV.png" alt="enter image descripti...
<python><pandas><dataframe>
2023-04-20 02:56:53
1
9,496
Mark K
76,059,948
2,855,071
pip download mirror in requirements.txt or venv
<p>Is there a way to fix the PyPi download mirror in a requirements.txt file? or somewhere else that gets picked up automatically? I'm based in China, and it's often convenient to use an alternative mirror as the main one can be slow e.g.</p> <pre><code>pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/...
<python><pip>
2023-04-20 01:40:18
1
2,535
innisfree
76,059,825
2,780,906
openpyxl workbook.save() corrupts simple xlsx workbook with external link
<p>I have a simple Excel xlsx file with one sheet and one external link which becomes corrupted if I open it and save it with openpyxl.</p> <p>This is a question similar to others (<a href="https://stackoverflow.com/questions/59308064/openpyxl-workbook-save-function-creates-a-corrupt-and-un-openable-excel-xlsx">here</...
<python><excel><openpyxl>
2023-04-20 00:58:07
1
397
Tim
76,059,773
13,079,519
Gurobi Model search for variable with exact match (or exact match string search)
<p>Trying to use the following code to search for variables that have &quot;732913342082_MAN-1&quot;</p> <pre><code>[var for var in m.getVars() if '732913342082_MAN-1' in var.VarName] </code></pre> <p>but then it is giving me the following result:</p> <pre><code>[&lt;gurobi.Var v1_Severn_732913342082_MAN-1&gt;, &lt;gu...
<python><string><gurobi>
2023-04-20 00:44:26
1
323
DJ-coding
76,059,768
3,719,146
How can schedule stop-start of standard app engine in gcp
<p>I was trying to find out a way to schedule stop/start the latest version of app engine in google cloud, but couldn't find any way for that. I just found gcloud command for stopping/starting a specific version, but don't know how can I schedule gcloud command.</p> <p>We have manual scaling standard app engine , and I...
<python><google-app-engine><google-cloud-platform><terraform><scheduling>
2023-04-20 00:43:12
2
399
mary
76,059,539
2,941,617
Calculating cumulative sum over non unique list elements in pySpark
<p>I have a PySpark dataframe with a column containing lists. The list items might overlap across rows. I need the cumulative sum of unique list elements down through the rows ordered by 'orderCol' column. In my application there might be millions of rows and hundreds of items in each list. I can't seem to wrap my brai...
<python><apache-spark><pyspark>
2023-04-19 23:37:13
1
452
UlrikP