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,005,122
6,278
Running deferred initialization code and gracefully blocking on requests until initialization is complete
<p>I would like to set up Flask so that it first sets up the listening socket, then runs some initialization code, then holds all incoming request processing until the initialization is complete. How do I set that up?</p> <p>My Flask app takes about 30s of initialization (loading AI models, etc.). These are required fo...
<python><flask>
2023-04-13 11:55:14
2
10,251
Henrik Heimbuerger
76,005,083
19,770,795
Why is covariant subtyping of mutable members allowed?
<h2>Invariance of mutable collections</h2> <p>The rationale for why built-in <strong>mutable</strong> collection types in Python are <strong>invariant</strong> is explained well enough in both <a href="https://peps.python.org/pep-0483/#covariance-and-contravariance" rel="nofollow noreferrer">PEP 483</a> and <a href="ht...
<python><mypy><covariance><python-typing>
2023-04-13 11:50:50
0
19,997
Daniel Fainberg
76,005,070
12,639,940
Find all documents between 2 keys inclusive (ranged key search) - MongoDB
<p>I am Emulating Firebase Realtime DB's REST GET endpoint's <code>startAt</code> and <code>endAt</code> filters using MongoDB and FastAPI.</p> <p>I am aware of the $gt and $lt query filters for fields in MongoDB and these work great with numerical values but act kind of weird when comparing values between strings.</p>...
<python><python-3.x><mongodb><pymongo>
2023-04-13 11:49:51
0
516
Kayvan Shah
76,005,058
10,938,315
Testing a method without instantiating class
<p>I followed this approach <a href="https://stackoverflow.com/questions/27105491/how-can-i-unit-test-a-method-without-instantiating-the-class">here</a>, but the issue is that this requires me to duplicate code.</p> <p>I can override the class in my test, but then I also have to copy and paste the method from my origin...
<python><unit-testing>
2023-04-13 11:48:54
1
881
Omega
76,005,035
8,813,699
How do I get n_samples in one call of pm.sample_posterior_predictive() in pymc?
<p>I want to generate multiple samples from one function call of pymc's sample_posterior_predictive(). In the previous version pymc3 there was an argument called 'samples', here is an example <a href="https://www.pymc.io/projects/examples/en/latest/gaussian_processes/GP-Marginal.html" rel="nofollow noreferrer">https://...
<python><pymc><gaussian-process>
2023-04-13 11:45:46
0
1,855
sehan2
76,004,994
2,123,706
download zipped csv from url and convert to dataframe
<p>I want to download and read a file from this site: <a href="http://data.gdeltproject.org/events/index.html" rel="nofollow noreferrer">http://data.gdeltproject.org/events/index.html</a></p> <p>each of the files are of the named <code>YYYYMMDD.export.CSV.zip</code></p> <p>I am stuck at this point in my code:</p> <pre>...
<python><pandas><dataframe><download><zip>
2023-04-13 11:40:59
1
3,810
frank
76,004,898
5,547,553
How to convert polars dataframe column type from float64 to int64?
<p>I have a polars dataframe, like:</p> <pre><code>import polars as pl df = pl.DataFrame({&quot;foo&quot;: [1.0, 2.0, 3.0], &quot;bar&quot;: [11, 5, 8]}) </code></pre> <p>How do I convert the first column to int64 type?<br> I was trying something like:</p> <pre><code>df.select(pl.col('foo')) = df.select(pl.col('foo'))....
<python><dataframe><python-polars>
2023-04-13 11:29:46
1
1,174
lmocsi
76,004,759
14,729,820
How push HF model to the hub
<p>I have a related issue can any one solve it? <a href="https://discuss.huggingface.co/t/typeerror-repository-init-got-an-unexpected-keyword-argument-token/33458/4" rel="nofollow noreferrer">Problem described well here </a></p> <p>I am expacting to pushing the model not only tokenizer and processor as : <a href="https...
<python><deep-learning><nlp><huggingface-transformers><hub>
2023-04-13 11:12:58
1
366
Mohammed
76,004,670
3,645,510
Why adding a object to an attribute of the another object of the same class have the side effect of adding it to both objects in python
<p>It's easier to explain my issue with an example so here it goes:</p> <pre><code>#!/usr/bin/env python3 class Node: _name: str = None _parents = [] def __init__(self, name: str): self._name = name def add_parent(self, node): self._parents.append(node) if __name__ == &quot;__main_...
<python><oop>
2023-04-13 11:03:52
2
390
b1zzu
76,004,593
12,243,638
How to reverse year over year change to fill the nan values?
<p>I have a dataframe, the <code>Value Col</code> ends in 2022-12-31.</p> <pre><code> Value Col Factor 2022-01-31 0.021 5% 2022-02-28 0.020 4% 2022-03-31 0.019 3% 2022-04-30 0.018 2% 2022-05-31 0.017 9% 2022-06-30 0.016 7% 2022-07-31 ...
<python><pandas>
2023-04-13 10:56:05
2
500
EMT
76,004,579
15,358,800
Pandas shift index ignoring passed shift object
<p>Let's say I've df like this</p> <pre><code>import pandas as pd df= pd.date_range('2023-04-01', '2023-05-01') frequency = df.shift(freq='W') print(frequency) </code></pre> <p>output I got freuqnecy as <code>None</code></p> <pre><code>DatetimeIndex(['2023-04-02', '2023-04-09', '2023-04-09', '2023-04-09', ...
<python><pandas><datetime>
2023-04-13 10:54:21
1
4,891
Bhargav
76,004,515
12,236,313
Python-polars: from coefficients, values and (nested) lists to weighted values
<p>Let's say I've got a Polars DataFrame similar to this one:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl from decimal import Decimal df = pl.from_dicts( [ {&quot;id&quot;: 1, &quot;value&quot;: Decimal(&quot;100.0&quot;), &quot;items&quot;: [&quot;A&quot;]}, {&quot;id&q...
<python><python-polars>
2023-04-13 10:45:12
1
1,030
scΕ«riolus
76,004,438
12,783,363
How to detect words in text given a set of words (almost similar) in database?
<p>Assuming we have a database containing the following words:</p> <pre><code>Chicken Wings Chicken Chicken Nuggets Super Chicken Nuggets </code></pre> <p>And the text:</p> <pre><code>Instruction: Add super chicken nuggets and chicken wings to the salad </code></pre> <p>What would the logic/algorithm be if we want to e...
<python><algorithm><nlp>
2023-04-13 10:35:39
2
916
Jobo Fernandez
76,004,164
12,965,658
Merge dataframes having array
<p>I have two data frames.</p> <h1>DF1</h1> <pre><code>isActive,trackedSearchId True,53436615 True,53434228 True,53434229 </code></pre> <h1>DF2</h1> <pre><code>trackedSearchIds,Primary Keyword Group(s) &quot;[53436613, 53436615, 53437436, 53436506]&quot;,SEO - Directory-Deployment &quot;[53435887, 53437509, 53437441, 5...
<python><python-3.x><pandas><dataframe><python-2.7>
2023-04-13 10:03:56
2
909
Avenger
76,003,924
3,377,926
Python typing - TypeVar for something that inherits from multiple base classes
<p>Python's <a href="https://docs.python.org/3/library/typing.html#typing.TypeVar" rel="nofollow noreferrer"><code>TypeVar</code></a> allows setting a <code>bound</code> for a type, like so</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar class A: pass T = TypeVar(&quot;T&quot;, bo...
<python><mypy><python-typing>
2023-04-13 09:36:55
1
1,167
Bendik
76,003,889
497,517
Adding Dates to the X axis on my graph breaks it
<p>I have a CSV file that stores an upload and download speed of my Internet connection every hour. The columns are Date, Time, Download, Upload &amp; ping. see below...</p> <blockquote> <pre><code>230302,2305,835.89,109.91,11.46 230303,0005,217.97,109.58,5.222 230303,0105,790.61,111.41,5.191 230303,0205,724.59,109.23,...
<python><matplotlib>
2023-04-13 09:32:59
3
7,957
Entropy1024
76,003,851
9,827,719
Python Weasyprint to Google Bucket
<p>I am using Google Functions in order to generate PDFs.</p> <p>I want to store the PDFs in a Google Bucket.</p> <p>I know that I can store PDFs as a file using the following code:</p> <pre><code># Write PDF to HTML pdf = &quot;&lt;html&gt;&lt;title&gt;Hello&lt;/title&gt;&lt;body&gt;&lt;p&gt;Hi!&lt;/p&gt;&lt;/body&gt;...
<python><weasyprint><google-bucket>
2023-04-13 09:29:10
1
1,400
Europa
76,003,814
52,917
How to run multiple discord.py bots concurrently with different bot tokens?
<p>I'm trying to create a Discord bot application using discord.py, where I need to run 5 different bots concurrently. I have all the bot tokens stored in a list variable named <code>BOT_TOKENS</code>.</p> <p>I've set up my bot instances and event handlers, but I'm unsure about how to run all bots concurrently using th...
<python><discord.py><python-asyncio>
2023-04-13 09:25:12
1
2,449
Aviad Rozenhek
76,003,740
8,849,755
Plotly multiline legend bullets vertical alignment
<p>Consider the following MWE:</p> <pre class="lang-py prettyprint-override"><code>import plotly.graph_objects as go fig = go.Figure() for i in range(4): fig.add_trace( go.Scatter( x = [1,2,3], y = [i]*3, name = 'A very long legend&lt;br&gt;which I break in&lt;br&gt;mult...
<python><plotly>
2023-04-13 09:16:35
1
3,245
user171780
76,003,623
6,225,526
How to insert and fill the rows with calculated value in pandas?
<p>I have a pandas dataframe with missing theta steps as below,</p> <pre><code>index name theta r 1 wind 0 10 2 wind 30 17 3 wind 60 19 4 wind 90 14 5 wind 120 17 6 wind 210 18 7 wind 240 17 8 wind 270 11 9 wind 300 13 </code></pre> <p>I need to add t...
<python><pandas>
2023-04-13 09:04:40
2
1,161
Selva
76,003,332
6,737,387
How to visualize segment-anything model with edges?
<p>I'm able to use the segment-anything model and visualize their results but they appear different than the demo online.</p> <p>My results look something like this:</p> <p><a href="https://i.sstatic.net/glc11.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/glc11.jpg" alt="enter image description here" /...
<python><pytorch><computer-vision><image-segmentation>
2023-04-13 08:33:45
1
2,683
Hisan
76,003,258
1,678,780
Getting codepage / encoding for windows executables called with subprocess.check_output from python
<p>I have a similar issue to <a href="https://stackoverflow.com/questions/21486703/how-to-get-the-output-of-subprocess-check-output-python-module">How to get the output of subprocess.check_output() python module?</a> but the solution there does not work for German Windows.</p> <p>I execute the following script in pytho...
<python><windows><character-encoding><subprocess>
2023-04-13 08:25:16
0
1,216
GenError
76,003,183
19,491,471
Tenserflow module is giving errors
<p>I am trying to import some modules but I get errors back. These are what I am trying to import and install:</p> <pre><code>%pip install pandas %pip install numpy %pip install requests %pip install beautifulsoup4 %pip install tensorflow import requests import pandas import numpy import requests from bs4 import Beaut...
<python><tensorflow><jupyter-notebook><jupyter>
2023-04-13 08:17:24
0
327
Amin
76,003,126
726,156
ModuleNotFoundError for 'sklearn' as subdependency of numpy
<p>I am using Docker combined with virtualenv to run a project for a client, but getting the error ModuleNotFound for sklearn.</p> <p>In my Pipfile I have added the numpy dependency</p> <pre><code>numpy = &quot;==1.21.6&quot; </code></pre> <p>The error is thrown from the following line</p> <pre><code>np.load(PATH_TO_NP...
<python><python-3.x><docker><numpy><scikit-learn>
2023-04-13 08:11:05
1
1,813
gleerman
76,002,994
13,158,157
pyspark fill values with join instead of isin
<p>I want to fill <a href="/questions/tagged/pyspark" class="post-tag" title="show questions tagged &#39;pyspark&#39;" aria-label="show questions tagged &#39;pyspark&#39;" rel="tag" aria-labelledby="tag-pyspark-tooltip-container">pyspark</a> dataframe on rows where several column values are found in other dataframe col...
<python><pyspark>
2023-04-13 07:57:15
1
525
euh
76,002,781
4,791,603
Looping through pandas dataframe to get highest possible total score of football players with unique clubs
<p>I have a dataframe with football players with their <em>team name, position <em>and</em> total score</em> based on a bunch of factors during the games they played. I want to create a team with the highest total score for different line-ups (4-3-3, 4-4-2, etc.) but the clubs can only occur for 1 player in that team. ...
<python><pandas><dataframe><loops><logic>
2023-04-13 07:34:02
1
327
jscholten
76,002,771
17,530,552
Normalize a list containing only positive data into a range comprising negative and positive values
<p>I have a list of data that only contains positive values, such as the list below:</p> <pre><code>data_list = [3.34, 2.16, 8.64, 4.41, 5.0] </code></pre> <p>Is there a way to normalize this list into a range that spans from -1 to +1?</p> <p>The value <code>2.16</code> should correspond to <code>-1</code> in the norma...
<python><normalization><normalize>
2023-04-13 07:32:51
3
415
Philipp
76,002,614
8,849,755
How to determine whether a fit is reasonable in Python
<p>I am fitting a function to data in Python using <a href="https://lmfit.github.io/lmfit-py/" rel="nofollow noreferrer"><code>lmfit</code></a>. I want to tell whether the fit is good or not. Consider this example (which is actually my data):</p> <p><a href="https://i.sstatic.net/frtUu.png" rel="nofollow noreferrer"><i...
<python><curve-fitting><goodness-of-fit>
2023-04-13 07:12:50
2
3,245
user171780
76,002,506
5,816,253
dictionary from different lists python 3
<p>I have the following lists:</p> <pre class="lang-py prettyprint-override"><code>list1 = [&quot;Hulk&quot;, &quot;Flash&quot;, &quot;Tesla&quot;] list2 = [&quot;green&quot;, &quot;23&quot;, &quot;thunder&quot;] list3 = [&quot;Marvel&quot;, &quot;DC_comics&quot;, &quot;0.0&quot;] </code></pre> <p>and I would like to c...
<python><json><list><dictionary>
2023-04-13 06:59:31
2
375
sylar_80
76,002,461
562,769
Where does "AttributeError: 'VendorAlias' object has no attribute 'find_spec'" come from?
<p>I'm currently trying to update a larger codebase from Python 3.8 to Python 3.11. I use <code>pyenv</code> to manage my Python versions and <code>poetry</code> to manage my dependencies:</p> <pre><code>pyenv local 3.11.3 poetry update </code></pre> <p>When I run <code>pytest</code> I immediately get:</p> <pre><code>p...
<python><django><pytest><python-3.10>
2023-04-13 06:53:08
1
138,373
Martin Thoma
76,002,447
13,262,787
Scapy: failed to set hardware filter to promiscuous mode: A device attached to the system is not functioning
<p>I am trying to send an ICMP packet with python scapy like this:</p> <pre><code>request_packet = IP(dst=&quot;www.google.com&quot;)/ICMP(type=&quot;echo-request&quot;) send(request_packet) </code></pre> <p>but when running the code the following error appears:</p> <pre><code>OSError: \Device\NPF_{5E5248B6-F793-4AAF-B...
<python><windows><scapy>
2023-04-13 06:51:16
0
4,545
Serket
76,002,185
10,856,988
GoogleSheet Column Download Limit
<p>Is there a limit to the number of Columns in a Spreadsheet, which could be downloaded with the googleSheetsApi(Python) ? The response provided only gives the first 7 columns.<br /> On trying to download individual column data beyond Column_7 , gs gives an IndexError(refer image_Response).</p> <p><em><strong>SpreadSh...
<python><google-sheets-api>
2023-04-13 06:13:24
0
1,641
srt111
76,001,985
1,229,966
Overriding python builtin 'print' using pybing11
<p>I'm embedding Python into a C++ app using pybind11. I'm trying to override the Python builtin 'print' function from C++.</p> <pre><code>mBuiltinsMod = py::module::import(&quot;builtins&quot;); mBuiltinsMod.attr(&quot;print&quot;) = py::cpp_function([](py::object msg) { std::cout &lt;&lt; msg.cast&lt;std::string&...
<python><c++><pybind11>
2023-04-13 05:40:48
2
2,739
Dess
76,001,845
19,491,471
Reading a dataset from Kaggle
<p>I am trying to download a dataset from kaggle, the link is: <a href="https://www.kaggle.com/datasets/birdy654/cifake-real-and-ai-generated-synthetic-images" rel="nofollow noreferrer">https://www.kaggle.com/datasets/birdy654/cifake-real-and-ai-generated-synthetic-images</a> there is a download button in this link. Th...
<python><jupyter-notebook><kaggle>
2023-04-13 05:14:00
1
327
Amin
76,001,795
9,757,174
python fastapi giving incorrect responses
<p>I have a fastapi app connected to my firebase firestore. I am writing a simple endpoint to check if the current user has an admin role or not?</p> <p>I have written the following code for the endpoint</p> <pre><code>@router.get(&quot;/isAdmin&quot;) def is_admin(userId: str): # sourcery skip: merge-nested-ifs &...
<python><google-cloud-firestore><fastapi><jsonresponse>
2023-04-13 05:04:52
1
1,086
Prakhar Rathi
76,001,787
874,188
How can I read just one line from standard input, and pass the rest to a subprocess?
<p>If you <code>readline()</code> from <code>sys.stdin</code>, passing the rest of it to a subprocess does not seem to work.</p> <pre><code>import subprocess import sys header = sys.stdin.buffer.readline() print(header) subprocess.run(['nl'], check=True) </code></pre> <p>(I'm using <code>sys.stdin.buffer</code> to avo...
<python><input><subprocess>
2023-04-13 05:04:19
1
191,551
tripleee
76,001,446
10,003,538
My `collate_fn` function got empty data when pass it to collate_fn parameter of Trainer function
<p>I am trying to do fine-tuning an existing hugging face model.</p> <p>The below code is what I collected from some documents</p> <pre><code>from transformers import AutoTokenizer, AutoModelForQuestionAnswering, TrainingArguments, Trainer import torch # Load the Vietnamese model and tokenizer model_name = &quot;vinai...
<python><python-3.x><pytorch><huggingface-transformers>
2023-04-13 03:45:24
1
1,225
Chau Loi
76,001,128
188,331
Splitting dataset into Train, Test and Validation using HuggingFace Datasets functions
<p>I can split my dataset into Train and Test split with 80%:20% ratio using:</p> <pre><code>from datasets import load_dataset ds = load_dataset(&quot;myusername/mycorpus&quot;) ds = ds[&quot;train&quot;].train_test_split(test_size=0.2) # my data in HF have 1 train split only print(ds) </code></pre> <p>which outputs:</...
<python><huggingface-datasets>
2023-04-13 02:16:50
2
54,395
Raptor
76,000,974
4,521,938
Pytorch predict wrong with small batch
<p>Have code:</p> <pre class="lang-py prettyprint-override"><code>firstItem, first_y = dataset[0] secondItem, second_y = dataset[4444] thirdItem, third_y = dataset[55555] print(f&quot;expected: {[first_y, second_y, third_y]}&quot;) X = firstItem.unsqueeze(0) X = torch.cat((X, secondItem.unsqueeze(0)), 0) X = torch.c...
<python><deep-learning><pytorch>
2023-04-13 01:30:59
1
358
kirsanv43
76,000,939
1,973,207
How to fuse 4-bit LLAMA weights with LoRA ones into one .pt file?
<p>I followed <a href="https://github.com/s4rduk4r/alpaca_lora_4bit_readme/blob/main/README.md" rel="nofollow noreferrer">this manual</a> and got <code>llama-7b-hf-int4</code> (got <code>llama-7b-4bit.pt </code>) and <code>samwit/alpaca7B-lora</code> (got <code>adapter_model.bin</code>). Now I want to merge them into a...
<python><deep-learning><pytorch><alpaca>
2023-04-13 01:19:36
0
880
DuckQueen
76,000,922
595,553
update python so that it point to new version
<p>Here I installed Python on Amazon Linux 2. python 2.7.18 was available by default. i installed 3.9.6 but python --version point to python 2</p> <pre><code>[root@AnsibleM Python-3.9.6]# python --version Python 2.7.18 [root@AnsibleM Python-3.9.6]# python3.9 --version Python 3.9.6 [root@AnsibleM Python-3.9.6]# which p...
<python><linux>
2023-04-13 01:11:52
1
753
Satyam Pandey
76,000,750
5,091,720
pandas problem when assigning value using loc
<p>So what is happening is the values in column B are becoming NaN. How would I fix this so that it does not override other values?</p> <pre><code>import pandas as pd import numpy as np # %% # df=pd.read_csv('testing/example.csv') data = { 'Name' : ['Abby', 'Bob', 'Chris'], 'Active' : ['Y', 'Y', 'N'], 'A' :...
<python><pandas><dataframe>
2023-04-13 00:19:21
1
2,363
Shane S
76,000,509
13,538,030
Interactive visualization does not work in Jupyter notebook
<p>I am a beginner for interactive visualization in Jupyter Notebook. Below is the Python code I have been using.</p> <pre><code>import altair as alt alt.Chart(data=dt).mark_point().encode( x=&quot;seq&quot;, y=&quot;v3&quot;, color=&quot;v2&quot;, size='v1' ) </code></pre> <p><code>dt</code> is the dat...
<python><jupyter-notebook><visualization>
2023-04-12 23:16:10
2
384
Sophia
76,000,390
5,696,181
Firefox binary issue when deploying Python script to Heroku server
<p>I am deploying a Python script to Heroku. The Python script includes a Selenium script that uses Firefox. Here is a snippet of the code:</p> <pre><code>def runFirefoxSelenium(): options = FirefoxOptions() options.add_argument('--headless') options.add_argument('--no-sandbox') binary = './bin/Firefox.app/...
<python><selenium-webdriver><heroku><firefox>
2023-04-12 22:53:12
1
1,037
Vaibhav Verma
76,000,363
717,231
Python zipfile fails ("compression method not supported") containing deflate64-compressed content
<p>I have a zip file that I can only unzip using terminal (on mac). I have not tried windows. For reference, I tried opening the file by double clicking in the finder window and I get &quot;Error - 79 Inappropriate file type or format&quot;</p> <p>But this command on terminal works as expected:</p> <pre><code>unzip zip...
<python><macos>
2023-04-12 22:46:23
3
958
Bitmask
76,000,347
10,466,809
Should Optional type annotation be used when an initialized input parameter is immediately set in the function body?
<p>In Python we often have a situation where the default argument for some input parameter is <code>None</code> and, if that is the case, we immediately initialize that variable at the top of the function body for use in the rest of the function. One common use case is for mutable default arguments:</p> <pre><code>def ...
<python><type-hinting>
2023-04-12 22:41:00
3
1,125
Jagerber48
76,000,316
4,670,408
What is the most efficient way to normalize values in a single row in pandas?
<p>I have two types of columns in a pandas dataframe, let's say A and B.</p> <p>How to normalize the values in each row individually using the mean for each type of column efficiently?</p> <p>I can first calculate mean for each column type and then divide each column with it's respective column type mean but it's takin...
<python><pandas><performance>
2023-04-12 22:32:49
2
1,281
Vinay
76,000,175
6,703,783
How to create a dataframe by appending heterogenous column values
<p>I want to create a <code>dataframe</code> like 2 columns and several rows</p> <pre><code>[ ['text1',[float1, float2, float3]] ['text2',[float4, float5, float6]] . . . ] </code></pre> <p>The names of the columns should be <code>content</code> and <code>embeddings</code>. <code>text1</code>, <code>text2</code> ar...
<python><pandas><dataframe>
2023-04-12 22:04:21
2
16,891
Manu Chadha
76,000,163
12,415,855
Google AI Vision / Image labeling?
<p>i try to label images with the Google Vision API - and this code works fine generally:</p> <pre><code>from google.cloud import vision import os import sys if __name__ == '__main__': path = os.path.abspath(os.path.dirname(sys.argv[0])) credsFN = os.path.join(path, &quot;creds.json&quot;) os.environ['GOOGLE_AP...
<python><google-cloud-platform><artificial-intelligence>
2023-04-12 22:01:50
1
1,515
Rapid1898
76,000,138
11,411,944
How can I change the default path for saving figures from an interactive Jupyter shell for Python in Visual Studio Code?
<p>I often generate figures using <code>matplotlib</code>. They get displayed in the shell and there's a little &quot;Save As&quot; icon that lets me save them. Whenever I click on it the default path is my system's root directory &quot;/&quot;. Every time I want to save a figure I have to click through my file system ...
<python><visual-studio-code><jupyter>
2023-04-12 21:56:38
1
490
Haliaetus
76,000,127
12,134,098
Directory of files containerized and deployed in Lambda?
<p>I have a Python package directory for which looks like this:</p> <p><a href="https://i.sstatic.net/bsPdA.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bsPdA.png" alt="enter image description here" /></a></p> <p>I have a Dockerfile which uses AWS provided base image:</p> <pre><code> COPY requirements...
<python><amazon-web-services><docker><aws-lambda>
2023-04-12 21:55:15
1
434
m00s3
76,000,070
8,188,910
Add a 1D numpy array to a 2D array along a new dimension (dimensions do not match)
<p>I want to add a 1D array to a 2D array along the second dimension of the 2D array using the logic as in the code below.</p> <pre><code>import numpy as np TwoDArray = np.random.randint(0, 10, size=(10000, 50)) OneDArray = np.random.randint(0, 10, size=(2000)) Sum = np.array([(TwoDArray+element).sum(axis=1) for elemen...
<python><arrays><numpy><multidimensional-array>
2023-04-12 21:45:24
3
419
Nicolas
76,000,033
14,584,978
Python polars has a modulus operator but it throws an attribute error
<p><strong>Update:</strong> This was due to an older version of polars still running on my machine.</p> <hr /> <p>Please see this documentation: <a href="https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.mod.html" rel="nofollow noreferrer">Docs</a></p> <p>When I run this code:</p> <pre class=...
<python><modulo><python-polars>
2023-04-12 21:39:23
0
374
Isaacnfairplay
76,000,024
930,675
Kivy: Why is my TextInput cursor/caret defaulting to red?
<p>Note the caret color in the my TextInput is defaulting to red. I'm unsure why this would be happening or how to change it?</p> <p><a href="https://i.sstatic.net/5Gj7G.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/5Gj7G.png" alt="enter image description here" /></a></p> <p>This is my code:</p> <pre c...
<python><kivy>
2023-04-12 21:36:52
1
3,195
Sean Bannister
76,000,010
11,922,765
Python Dataframe check if a name exists in the variable columns
<p>I want my dataframe to have two columns. I don't know what there names going to be. I want to assign them through a variable. I want to check if one of the column is not available, then create this new column Code:</p> <pre><code># Columns dataframe or series. It contains names of the actual columns # I get below in...
<python><pandas><dataframe>
2023-04-12 21:35:17
1
4,702
Mainland
75,999,989
7,583,953
Why is float accurate but Decimal is wrong?
<p>We're used to floats being inaccurate for obvious reasons. I thought Decimals were supposed to be accurate though because they represent all the base 10 digits</p> <p>This code gives us the right answer of 9</p> <pre><code>print(27*3/9) </code></pre> <p>So I thought, oh that's integer multiplication followed by divi...
<python><floating-point><decimal>
2023-04-12 21:31:08
2
9,733
Alec
75,999,781
12,436,050
Fill Pandas column with a fix value from a specific index
<p>I have a dataframe with following columns.</p> <pre><code> id label parent 0 ID LABEL SC% split 1 https://lists/100000000006/terms MedDRA RMS List 2 https://lists/100000000006/term...
<python><pandas>
2023-04-12 20:58:53
1
1,495
rshar
75,999,762
3,315,629
Issue consistently mapping a python list to dictionary
<p>I am trying to understand why my list (update_features in code below) isn't consistently mapping properly to a dictionary (update_reno_map in code below). There is a bit of code leading up to the mapping, that i've included to give context to the way the list is created.</p> <pre><code>renouv_dict = {} layer = ifac...
<python><list><dictionary><qgis><pyqgis>
2023-04-12 20:56:20
1
1,045
user25976
75,999,656
11,388,321
Is there a better way to strip and get OpenAI responses?
<p>I'm trying to get at least 1 response for each keyword that is looped to be included in the text prompt, however when I run the python code to generate responses I get the following error:</p> <pre><code>PS C:\Users\...\Documents\Article-gen&gt; &amp; C:/Users/.../AppData/Local/Microsoft/WindowsApps/python3.11.exe c...
<python><python-3.x><openai-api>
2023-04-12 20:41:47
1
810
overdeveloping
75,999,612
2,644,016
Why is a pickled object with slots bigger than one without slots?
<p>I'm working on a program that keeps dying because of the OOM killer. I was hoping for some quick wins in reducing the memory usage without a major refactor. I tried adding <code>__slots__</code> to the most common classes but I noticed the pickled size went up. Why is that?</p> <pre class="lang-py prettyprint-overri...
<python><pickle>
2023-04-12 20:33:14
2
651
parched
75,999,508
11,310,492
Pass a string with quotation marks as variable in Python
<p>I have a function that takes multiple string arguments in the form of e.g. <code>Subscription(items=[&quot;A&quot;, &quot;B&quot;, &quot;C&quot;])</code> (quotation marks are mandatory, alphabet is just an example here). I don't want to write the arguments manually so I have a loop like</p> <pre><code>string=&quot;&...
<python><string>
2023-04-12 20:20:34
3
335
starsnpixel
75,999,481
15,178,267
Django: can I verify email using otp in Django?
<p>I have a question about Django authentication. Is it possible for a user, before they create an account they pass through these steps?</p> <ol> <li>Enter only their email first</li> <li>I send OTP to their email</li> <li>They verify their email using the OTP</li> <li>I then ask for their username, password 1, passwo...
<python><django><django-models><django-forms>
2023-04-12 20:16:59
1
851
Destiny Franks
75,999,468
13,132,640
Convert arbitrary-length nested lists to format for pandas dataframe?
<p>I have an optimization script which outputs data in a format similar to the fake lists below:</p> <pre><code>l1 = [1,2,3,4] l2 = [[5,6,7,8], [9,10,11,12]] l3 = [[13,14,15,16], [17,18,19,20]] </code></pre> <p>All lists are of the same length always (at least, the lists which contain values), but some are ...
<python><pandas><dataframe>
2023-04-12 20:13:56
2
379
user13132640
75,999,444
2,052,436
How to iterate numpy array (of tuples) in list manner
<p>I am getting an error <code>TypeError: Iterator operand or requested dtype holds references, but the REFS_OK flag was not enabled</code> when iterating numpy array of tuples as below:</p> <pre><code>import numpy as np tmp = np.empty((), dtype=object) tmp[()] = (0, 0) arr = np.full(10, tmp, dtype=object) for a, b i...
<python><python-3.x><numpy><iterable-unpacking>
2023-04-12 20:10:02
2
5,087
user2052436
75,999,436
182,683
Parsing input text in a strange format
<p>I have an input document with data in the following format. The three example target words are 'overlook', 'lettered', and 'resignation'. Each is followed by a list of synonyms or, if none were found, just the word None. Because the target word is not included in the list of synonyms, I've prepended &quot;tgws_&quot...
<python><string><parsing><line>
2023-04-12 20:08:53
1
773
David
75,999,364
12,762,467
Why is it not possible to iterate over pandas dataframes?
<p>Let there be several similar dataframes that an operation is to be performed on, e.g. dropping or renaming columns. One may want to do it in a loop:</p> <pre class="lang-py prettyprint-override"><code>this = pd.DataFrame({'text': ['Hello World']}) that = pd.DataFrame({'text': ['Hello Gurl']}) for df in [this, that]...
<python><pandas><dataframe><loops><iteration>
2023-04-12 19:59:19
4
373
Zwiebak
75,999,085
16,707,518
Pick random values from a second table based on join in Python / Pandas
<p>Suppose I have a Python dataframe:</p> <pre><code>A B C A B </code></pre> <p>...and a second dataframe</p> <pre><code>A 3 A 2 A 4 B 5 B 2 B 8 B 7 C 1 C 5 </code></pre> <p>I want to join the second dataframe to the first - but for each value in the first frame, the join should be a random selection from the ...
<python><pandas><join><random>
2023-04-12 19:21:24
2
341
Richard Dixon
75,999,041
7,984,318
pandas how to check if column not empty then apply .str.replace in one line code
<p>code:</p> <pre><code>df['Rep'] = df['Rep'].str.replace('\\n', ' ') </code></pre> <p>issue: if the df['Rep'] is empty or null ,there will be an error:</p> <pre><code>Failed: Can only use .str accessor with string values! </code></pre> <p>is there anyway can handle the situation when the column value is empty or null?...
<python><pandas><dataframe>
2023-04-12 19:15:40
1
4,094
William
75,998,941
4,092,142
Databricks Python wheel based on Databricks Workflow. Acces job_id & run_id
<p>I'm using Python (as Python wheel application) on <strong>Databricks</strong>.</p> <p>I deploy &amp; run my jobs using <strong>dbx</strong>.</p> <p>I defined some <strong>Databricks Workflow</strong> using <strong>Python wheel tasks</strong>.</p> <p>Everything is working fine, but I'm having issue to extract <strong...
<python><pyspark><databricks><azure-databricks><dbutils>
2023-04-12 19:01:00
1
1,286
Gohmz
75,998,924
3,970,738
What is the difference between manager.Pool and Pool in python multiprocessing?
<p>Say I want to share a dictionary between processes. If I have defined a manager, what is the difference between instantiating a pool using <code>manager.Pool()</code> and <code>multiprocessing.Pool()</code>?</p> <p>Ex: What is the difference between the two <code>with</code> statements in <code>main_1</code> and <co...
<python><multiprocessing>
2023-04-12 18:58:17
1
501
Stalpotaten
75,998,669
15,439,115
OutOfBoundsDatetime issue handle in pandas
<p>I am running this code and on a date older then 1677 I guess there will be issue of <code>OutOfBoundsDatetime</code> .</p> <p><strong>my code is</strong></p> <pre><code>import pandas as pd df = pd.DataFrame({'datetime_str': ['2011-01-17 23:20:00' ,'0031-01-17 23:20:00']}) df['datetime_str'] = (pd.to_datetime(df['d...
<python><pandas><datetime><epoch>
2023-04-12 18:21:08
0
309
Ninja
75,998,560
10,918,680
Pairwise plot of 2D heatmap in Plotly Express
<p>I have a Pandas dataframe like the following:</p> <pre><code> df = pd.DataFrame({'gender': [1,2,1,1,2,1], 'rating': [2,1,1,3,4,5], 'speed': [1,5,5,3,2,4], 'value':[4,4,3,2,2,1], 'appearance':[1,2,3,3,1,1], ...
<python><pandas><heatmap><plotly>
2023-04-12 18:04:11
2
425
user173729
75,998,534
495,990
Understanding the difference between these two python requests POST calls (data vs. json args)
<p>This is a toy, non-reproducible example as I can't share the original. I think it's answerable, and might help others. From other SO posts like <a href="https://stackoverflow.com/questions/26685248/difference-between-data-and-json-parameters-in-python-requests-package">this</a> and <a href="https://stackoverflow.com...
<python><python-requests>
2023-04-12 18:00:03
1
10,621
Hendy
75,998,511
3,505,206
polars - memory allocation of N bytes failed
<p>Trying to execute a statement on a file of 30 Gbs containing 26 million records with 33 columns. When we execute on a sample with 10,000 rows, works without any errors. problem exists on the full file. Noticed that I was able to execute the code in jupyter, however this fails when running from VS Code on Windows 10 ...
<python><python-polars>
2023-04-12 17:57:34
0
456
Jenobi
75,998,501
21,420,742
Adding a new column with count in Python
<p>I have a dataset that looks at reports to a manager and would like to create a new column that shows those counts.</p> <p>What I have:</p> <pre><code> ID ManagerID 101 105 102 103 103 105 104 103 105 110 </code></pre> <p>Output I want:</p> <pre><code>ID ManagerID Count 1...
<python><python-3.x><pandas><dataframe><group-by>
2023-04-12 17:54:52
2
473
Coding_Nubie
75,998,434
52,917
how can I customize the way pytest prints objects?
<p>Is there a way I can control the way pytest creates string representations from objects?</p> <p>specifically I am using <code>mongoengine</code> where the objects of type <code>Document</code> are just lazily outputed to console as <code>&quot;&lt;Document: Documment object&gt;&quot;</code> and I'd like to create a ...
<python><pytest><mongoengine>
2023-04-12 17:45:56
0
2,449
Aviad Rozenhek
75,998,423
7,025,033
numpy replace array elements with numpy arrays, according to condition
<pre><code>subst1 = numpy.array([2, 2, 2, 2]) subst2 = numpy.array([3, 3, 3, 3]) a = numpy.array([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0,]]) b = numpy.where(0==a, subst1, subst2) </code></pre> <p><strong>Result:</strong></p> <pre><code>&gt;&gt;&gt; a array([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) &gt...
<python><numpy><numpy-ndarray>
2023-04-12 17:42:20
2
1,230
Zoltan K.
75,998,304
13,689,939
How to Convert Pandas fillna Function with mean into SQL (Snowflake)?
<p><strong>Problem</strong></p> <p>I'm converting a Python Pandas data pipeline into a series of views in Snowflake. The transformations are mostly straightforward, but some of them seem to be more difficult in SQL. I'm wondering if there are straightforward methods.</p> <p><strong>Question</strong></p> <p>How can I wr...
<python><sql><pandas><migration><snowflake-cloud-data-platform>
2023-04-12 17:27:54
1
986
whoopscheckmate
75,998,242
5,561,058
Python.exe in incorrect path despite adding path to Windows
<p>I added the following python paths to the Path in Windows for system variables.</p> <pre><code>C:\Project1\python\Python310-32\Scripts C:\Project1\python\Python310-32 </code></pre> <p>When I run pip upgrade I get the following error:</p> <pre><code>Unable to create process using '&quot;C:\Project0\python\Python310-3...
<python><site-packages>
2023-04-12 17:19:26
1
471
Yash Jain
75,998,241
9,937,874
Pandas read_excel parameter sheet_name
<p>I am building a pipeline that unfortunately requires a data hand off from another team. We have found that the sheet name for a particular piece of data suffers from formatting issues. The sheet is supposed to be named by the month corresponding to the data in all lowercase. However we have received the file multipl...
<python><pandas>
2023-04-12 17:19:23
1
644
magladde
75,998,227
11,065,874
How to define query parameters using Pydantic model in FastAPI?
<p>I am trying to have an endpoint like <code>/services?status=New</code></p> <p><code>status</code> is going to be either <code>New</code> or <code>Old</code></p> <p>Here is my code:</p> <pre class="lang-py prettyprint-override"><code>from fastapi import APIRouter, Depends from pydantic import BaseModel from enum imp...
<python><fastapi><openapi><pydantic>
2023-04-12 17:17:46
1
2,555
Amin Ba
75,997,756
11,167,163
In oracledb How to retrieve the column names of the REF CURSOR output from cursor.execute?
<p>Below is the code I tried which is working fin if I change</p> <pre><code>column_names by column_names = ['Col1','Col2','Col3'] </code></pre> <p>But I need it to be dynamic because the number and the name of the columns can change depending on the procedure I want to execute.</p> <pre><code>cursor.execute(GET_Transa...
<python><oracle-database><plsql><python-oracledb>
2023-04-12 16:20:41
1
4,464
TourEiffel
75,997,720
12,576,581
Can't use aws_cdk.Fn.conditionIf in AutoScalingGroup
<p>I'm currently making a Stack using python aws cdk V2 and I want to make certain conditions be ran on the template instead in CDK synth so by updating a parameter in cloudformation the template can adapt and not have to be re-synthesised.</p> <p>Having that said, I currently have this code to make the AutoScaling Gro...
<python><aws-cdk><aws-auto-scaling>
2023-04-12 16:15:57
1
888
DeadSec
75,997,702
4,621,513
What is the rationale for not allowing to change field types in TypedDict, even to a subtype, when using inheritance?
<p>PEP 589 <a href="https://peps.python.org/pep-0589/#inheritance" rel="nofollow noreferrer">states</a>:</p> <blockquote> <p>Changing a field type of a parent TypedDict class in a subclass is not allowed.</p> <p>Example:</p> <pre><code>class X(TypedDict): x: str class Y(X): x: int # Type check error: cannot o...
<python><inheritance><python-typing>
2023-04-12 16:13:52
1
24,148
mkrieger1
75,997,634
14,637,258
Class variable and __dict__
<p>Why <code>print(b.__dict__)</code> prints<code>{'state': 'Init'}</code> I understand, but why does <code>print(b._di)</code> print<code>{'state': 'Init'}</code>?</p> <pre><code>class A: _di = {} def __init__(self): self.__dict__ = self._di class B(A): def __init__(self): super().__...
<python>
2023-04-12 16:05:24
0
329
Anne Maier
75,997,627
10,282,088
Ace editor is showing the error: Line too long
<p>I use ace-linters for ace editor. It is showing the relevant linter warnings for each line on the left bar.</p> <p><a href="https://i.sstatic.net/AkjWh.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AkjWh.png" alt="enter image description here" /></a></p> <p>I have this <em>line too long</em> error. ...
<python><angular><ace-editor><linter>
2023-04-12 16:04:32
1
538
Abdul K Shahid
75,997,543
10,271,487
Pandas getting nsmallest avg for each column
<p>I have a dataframe of values and I'm trying to curvefit a lower bound based on avg of the nsmallest values.</p> <p>The dataframe is organized with theline data (y-vals) in each row, and the columns are ints from 0 to end (x-vals) and I need to return the nsmallest y-vals for each x value ideally to avg out and retur...
<python><pandas>
2023-04-12 15:54:35
1
309
evan
75,997,515
657,693
Get All Combinations of N-Length For Different Sized Input Lists
<p>I have seen other questions on using <code>itertools</code> to generate combinations from a single list &amp; even a list of lists, but I am looking for something slightly different.</p> <p>I have a list of lists of differing lengths (some are 2-attributes long, some are 4-attributes long). I need to be able to gene...
<python><combinations>
2023-04-12 15:52:10
1
1,366
mattdonders
75,997,482
14,333,315
python variable as a name of list item
<p>I have a list:</p> <pre><code> topics = ['topic1', 'topic2', 'topic3'] </code></pre> <p>and a dict with links to topics values index:</p> <pre><code> values = {'my_value' : &quot;topics[2]&quot;, 'your_value': &quot;topics[0]&quot;} </code></pre> <p>of cause, that statement will not work, but the idea is to have a d...
<python><list><dictionary>
2023-04-12 15:48:00
2
470
OcMaRUS
75,997,169
2,228,592
Django Queryset filtering against list of strings
<p>Is there a way to combine the django queryset filters <code>__in</code> and <code>__icontains</code>.</p> <p>Ex: given a list of strings <code>['abc', 'def']</code>, can I check if an object contains anything in that list.</p> <p><code>Model.objects.filter(field__icontains=value)</code> combined with <code>Model.obj...
<python><django>
2023-04-12 15:18:02
1
9,345
cclloyd
75,997,144
14,269,252
Find the common columns between a list of Data frames
<p>I want to find the common columns between a list of Data frames, the way that I started is, I defined x1 that is a lists of list ( for each data frames columns name), then I extract each sub list to a separate list.</p> <p>I have the output as follows:</p> <pre><code>lst_1=['a1,a2,a3'] </code></pre> <p>which has t...
<python><pandas>
2023-04-12 15:15:43
3
450
user14269252
75,997,054
6,728,100
Trying to visualize topics using pyldavis but it is giving drop error
<p>I am trying to visualize topics using PyLDAVis but the following code is giving error. Not sure what the issue is.</p> <pre><code>import pyLDAvis.gensim_models pyLDAvis.enable_notebook() vis = pyLDAvis.gensim_models.prepare(lda_model, corpus, id2word) pyLDAvis.show(vis) File ~/PycharmProjects/KeyWordExtractor/venv...
<python><topic-modeling><pyldavis>
2023-04-12 15:05:08
3
505
Prince Modi
75,996,969
5,983,691
Arrays differ while using numpy hstack
<p>I have over 1200 images that I resize to be the same (256, 256) size:</p> <pre class="lang-py prettyprint-override"><code>filenames = glob('data/*.png') for filename in filenames: im = skimage.io.imread(filename) im = skimage.transform.resize(im, (256, 256), anti_aliasing=True) im = skimage.uti...
<python><arrays><numpy>
2023-04-12 14:57:23
1
457
osterburg
75,996,948
6,552,836
Bucket Constraint Optimization
<p>I'm trying to design a constraint that is based on optimizing groups/buckets of elements rather than just individual elements. Here is a list of all the constraints I have:</p> <ol> <li>Total sum of all the elements must equal a certain value</li> <li>Total sum of each product (column sum of elements) must equal a c...
<python><optimization><scipy-optimize><constraint-programming>
2023-04-12 14:55:25
1
439
star_it8293
75,996,861
11,277,108
Exception with custom Retry class to set BACKOFF_MAX
<p>I've built a helper function and custom <code>Retry</code> class so I can set <code>BACKOFF_MAX</code> for a <code>requests</code> session as per <a href="https://stackoverflow.com/a/48198708/11277108">this solution</a>:</p> <pre><code>from requests import Session from requests.adapters import HTTPAdapter, Retry c...
<python><python-requests>
2023-04-12 14:47:11
1
1,121
Jossy
75,996,750
9,580,325
Inject dependencies in Flask blueprint
<p>I'm trying to inject dependencies to a flask blueprint:</p> <p>blueprints.py</p> <pre><code>from flask import Blueprint, Response from dependency_injector.wiring import inject, Provide from container import Container from controllers import ServiceController bp = Blueprint(&quot;event&quot;, __name__) @bp.route(&...
<python><flask><dependency-injection>
2023-04-12 14:36:37
1
1,145
Domin
75,996,731
3,505,206
Polars groupby concat on multiple cols returning a list of unique values
<p>Have a polars dataframe with the following data.</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame({&quot;small&quot;: [&quot;Apple Inc.&quot;, &quot;Baidu Inc.&quot;, &quot;Chevron Global&quot;, &quot;Chevron Global&quot;, &quot;Apple Inc.&quot;], &quot;person&quot;: [10, 20, 30, 10, 10], &quot;...
<python><python-polars>
2023-04-12 14:34:35
2
456
Jenobi
75,996,695
19,003,861
How to dynamically generate optimal zoom on folium/leaflet?
<p>I am using <code>leaflet</code> and <code>folium</code> to map out locations.</p> <p>These locations can be filtered out and therefore requires something a bit dynamic.</p> <p>I want to achieve two things:</p> <ol> <li>center the user on the map between the different locations (that works);</li> <li>Now I also want ...
<python><django><django-views><leaflet><folium>
2023-04-12 14:31:32
1
415
PhilM
75,996,408
696,712
Get json data from incoming Flask request.json case insensitive
<p>I'm implementing an API (proxy) that accepts incoming JSON POST data in Flask. I need to process this JSON and after that send it on to a backend API, which was written in another language.</p> <p>The JSON data will be sent by end-users, and they are used to sending this JSON data case-insensitive. This means that t...
<python><json><flask>
2023-04-12 14:04:15
2
4,414
Erik Oosterwaal
75,996,371
10,164,750
Format one column with another column in Pyspark dataframe
<p>I have business case, where one column to be updated based on the value of another 2 columns. I have given an example as below:</p> <pre><code>+-------------------------------+------+------+---------------------------------------------------------------------+ |ErrorDescBefore |name |value |ErrorDesc...
<python><dataframe><apache-spark><pyspark><apache-spark-sql>
2023-04-12 14:00:36
3
331
SDS