QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
75,176,124
791,025
Python Enum with auto generated string names for typer
<p>I'm using <code>python 3.8.10</code> with <code>typer 0.7.0</code> and wanting to use an enum I have defined in my project as an input argument.</p> <p>I've previously used something like the following with argparse and, alongside setting <code>choices=list(ModelTypeEnum)</code>, it's worked fine - note that this is...
<python><python-3.x><string><enums>
2023-01-19 17:31:33
1
2,132
AdmiralJonB
75,176,106
8,884,239
Oracle OJDBC Class not found exception using PySpark with jupyter notebook
<p>I am trying to read data from Oracle DB by using JDBC connection and I am getting following error:</p> <p>&quot;name&quot;: &quot;Py4JJavaError&quot;, &quot;message&quot;: &quot;An error occurred while calling o36.load.\n: java.lang.ClassNotFoundException: \nFailed to find data source: ojdbc. Please find packages at...
<python><apache-spark><pyspark><jupyter-notebook><ojdbc>
2023-01-19 17:30:30
0
301
Bab
75,176,073
1,142,881
How to broadcast-map by columns from one dataframe to another?
<p>I'd like to broadcast or expand a dataframe columns-wise from a smaller set index to a larger set index based on a mapping specification. I have the following example, please accept small mistakes as this is untested</p> <pre><code>import pandas as pd # my broadcasting mapper spec mapper = pd.Series(data=['a', 'b',...
<python><pandas>
2023-01-19 17:27:11
2
14,469
SkyWalker
75,176,014
6,290,211
Inclusive argument is not working as expected in pd.date_range()
<p>With <code>pandas 1.40</code> it was introduced the argument <code>inclusive</code> in the class <code>pd.date_range()</code>. Reading the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>inclusive{“both”, “ne...
<python><pandas><date-range>
2023-01-19 17:21:16
2
389
Andrea Ciufo
75,175,999
3,029,274
Dict Update method only adds last value
<p>I have the following code (link <a href="https://www.online-python.com/l8qyPLY0iZ" rel="nofollow noreferrer">here</a>)</p> <p>I have looked at similar posts and examples online but have not been able to understand / resolve the issue on why <code>.update</code> only adds the last value to the dictionary</p> <pre><co...
<python>
2023-01-19 17:20:23
1
2,090
Maddy
75,175,995
3,795,219
Show Python method's API documentation from a URL on hover in VSCode
<p><strong>Is it possible to have VSCode show a Python method's online documentation upon mouse-over/hover?</strong></p> <p>For example, <a href="https://pytorch.org/docs/stable/index.html" rel="nofollow noreferrer">PyTorch API Docs</a> are hosted online and the method hierarchy is simple to navigate. When I hover of a...
<python><visual-studio-code><code-documentation>
2023-01-19 17:20:06
0
8,645
Austin
75,175,835
1,157,639
Creating a multilevel dataframe by clubbing columns with the same name under top level
<p>Consider the following input dataframe:</p> <pre><code> index | col_1 | col_2 | 1 | 1234 | 4567 | 2 | 3456 | 9453 | </code></pre> <p>Each column of...
<python><pandas><dataframe><multi-level>
2023-01-19 17:06:18
1
776
Anshul
75,175,797
338,479
Apply function to each element of a list in place
<p>Similar question to <a href="https://stackoverflow.com/q/25082410/338479">Apply function to each element of a list</a>, however the answers to that question (list comprehension or map()) really return a new list to replace the old one.</p> <p>I want to do something like this:</p> <pre><code>for obj in myList: ob...
<python><list>
2023-01-19 17:02:18
1
10,195
Edward Falk
75,175,720
823,633
Filter a dataframe by column index in a chain, without using the column name or table name
<p>Generate an example dataframe</p> <pre><code>import random import string import numpy as np df = pd.DataFrame( columns=[random.choice(string.ascii_uppercase) for i in range(5)], data=np.random.rand(10,5)) df V O C X E 0 0.060255 0.341051 0.288854 0.740567 0.2362...
<python><pandas><dataframe>
2023-01-19 16:55:40
3
1,410
goweon
75,175,711
1,052,870
Unable to parallelise workloads on the KubeCluster operator for Dask
<p>I want to be able to run multiple &quot;workflows&quot; in parallel, where each workflow submits Dask tasks and waits for it's own Dask tasks to complete. Some of these workflows will then need to use the results of it's first set of tasks to run more tasks in Dask. I want the workflows to share a single Dask cluste...
<python><asynchronous><async-await><dask>
2023-01-19 16:55:00
0
2,081
wwarby
75,175,659
8,040,369
Replace special character "-" with 0 integer value
<p>I am traversing an excel sheet using openpyxl() and copying over the contents to another excel.</p> <pre><code>import openpyxl NEW_EXCEL_FILE = openpyxl.load_workbook('workbook1.xlsx') NEW_EXCEL_FILE_WS = NEW_EXCEL_FILE.active SHEET = NEW_EXCEL_FILE.get_sheet_by_name(sheet_name) for i,row in enumerate(SHEET.iter_ro...
<python><python-3.x><replace>
2023-01-19 16:50:53
1
787
SM079
75,175,635
1,273,751
Run python script then enter interactive session in ipython
<p>I have found ways to run a python script and then enter interactive mode:</p> <ul> <li><a href="https://stackoverflow.com/questions/13432717/enter-interactive-mode-in-python">Enter Interactive Mode In Python</a></li> <li><a href="https://stackoverflow.com/questions/50917938/enabling-console-features-with-code-intera...
<python><ipython><interactive>
2023-01-19 16:49:00
0
2,645
Homero Esmeraldo
75,175,617
10,007,302
Using regular expression to remove commonly used company suffixes from a list of companies
<p>I have the following code that I use to generate a list of common company suffixes below:</p> <pre><code>import re from cleanco import typesources, import string def generate_common_suffixes(): unique_items = [] company_suffixes_raw = typesources() for item in company_suffixes_raw: for i in ite...
<python><python-3.x><regex>
2023-01-19 16:46:54
1
1,281
novawaly
75,175,306
1,773,592
How do I structure a repo with Cloud Run needing higher level code?
<p>I have added code to a repo to build a Cloud Run service. The structure is like this: <a href="https://i.sstatic.net/77dxk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/77dxk.png" alt="enter image description here" /></a></p> <p>I want to run <code>b.py</code> in <code>cr</code>.</p> <p>Is there any...
<python><docker><google-cloud-run>
2023-01-19 16:24:05
1
3,391
schoon
75,175,220
12,082,289
Sqlalchemy in-memory database for MSSQL
<p>I'm trying to setup tests for my project and want to use an in memory database for those tests. Based on some examples I found online I've been able to get an in memory sqlite database working...</p> <pre><code>class TestService: def setup_method(self) -&gt; None: sqlite_shared_name = &quot;test_db_{}&qu...
<python><sql-server><sqlalchemy>
2023-01-19 16:17:34
1
565
Jeremy Farmer
75,175,081
667,440
Why isn't Anaconda working inside of one of my Conda environments while using Ubuntu LTS?
<p>I'm not sure why I can't get Anaconda to launch while I'm inside of one of my Conda environments; I'm using Ubuntu LTS. While I'm in the base environment, I can run the following command in my terminal and Anaconda will start up just fine.</p> <pre><code>anaconda-navigator </code></pre> <p>I also set up a Conda envi...
<python><ubuntu><anaconda><conda>
2023-01-19 16:05:32
1
1,140
j.jerrod.taylor
75,174,976
17,696,880
Capture all capitalized words in a row in a capture group only if they are before the end of the string or if they are before a punctuation mark or \n
<pre class="lang-py prettyprint-override"><code>import re def test_extraction_func(input_text): word = &quot;&quot; try_save_name = False #Not stop yet #Here I have tried to concatenate a substring at the end to try to establish it as a delimiter # that allows me to identify whether or not it is the ...
<python><python-3.x><regex><string><regex-group>
2023-01-19 15:58:05
1
875
Matt095
75,174,904
9,911,256
Python3 get key from dict.items() maximum value
<p>I'm not a Python programmer. Having a Python3 dictionary like this,</p> <pre><code>d={&quot;a&quot;:&quot;1&quot;, &quot;b&quot;:&quot;2&quot;} </code></pre> <p>How can I get the key for the largest value (that is, 'b') in a simple form?</p> <p>Of course, I can write some spaghetti,</p> <pre><code>def get_max_key(da...
<python><python-3.x><dictionary>
2023-01-19 15:53:40
1
954
RodolfoAP
75,174,753
17,969,875
Universal method in python for trying to parse a value to a chosen type
<p>Is there a method in python that could allow me to parse a given value to a chosen type?</p> <p>It might be a lib that works in a similar manner.</p> <p>If there is not a method, how can I create something like it?</p> <p>Example (parsing list[str] to list[int]):</p> <pre class="lang-py prettyprint-override"><code>#...
<python><python-3.x><pydantic>
2023-01-19 15:41:48
1
731
PedroDM
75,174,679
7,446,003
Using django form wizard with allauth
<p>Currently my user sign up process is implemented with allauth. Does anyone have any experience of how to make this a multipage process e.g. with form wizard from formtools?</p> <p>forms.py (stored at users/forms.py)</p> <pre><code> class UserCreationForm1(forms.UserCreationForm): error_message = forms.UserCreat...
<python><django><django-allauth><django-formtools>
2023-01-19 15:37:09
0
422
RobMcC
75,174,553
9,257,578
GOT TypeError: deprecated() got an unexpected keyword argument 'name' in boto3
<p>Boto3 was running successfully the day before but when i ran today i am getting these errors <code>import boto3</code></p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;/home/root1/.local/lib/python3.10/site-packages/boto3/__init__.py&quot;, li...
<python><boto3>
2023-01-19 15:27:49
0
533
Neetesshhr
75,174,474
12,244,355
Python: How to sum up the values of a dictionary list in a column
<p>I have a DataFrame like this:</p> <pre><code>timestamp asks 2022-01-01 00:00:00 [{'price':'0.99', 'size':'12311'},{'price':'0.991', 'size':'20013'}] 2022-01-01 01:00:00 [{'price':'0.99', 'size':'3122'},{'price':'0.991', 'size':'43221'}] ... </code></pre>...
<python><pandas><list><dataframe><dictionary>
2023-01-19 15:20:53
1
785
MathMan 99
75,174,405
3,099,733
Is it possible to remove unecessary nested structure in yaml file?
<p>I need to set a param that is deep inside a yaml object like below:</p> <pre class="lang-yaml prettyprint-override"><code>executors: hpc01: context: cp2k: charge: 0 </code></pre> <p>Is it possible to make it more clear, for example</p> <pre class="lang-yaml prettyprint-override"><code>executors: ...
<python><yaml>
2023-01-19 15:15:18
2
1,959
link89
75,174,228
2,244,766
python argparser help in case of positional + REMAINDER
<p>having a code like below</p> <pre><code>&gt;&gt;&gt; import argparse &gt;&gt;&gt; parser=argparse.ArgumentParser() &gt;&gt;&gt; parser.add_argument('must_have', help='this is a required arg') &gt;&gt;&gt; parser.add_argument('-o', '--optional', help='some optional arg') &gt;&gt;&gt; parser.add_argument('--others', n...
<python><argparse>
2023-01-19 15:01:23
1
4,035
murison
75,174,096
6,054,066
How to get pandas to roll through entire series?
<h1>Pandas Rolling function</h1> <h2>Last elements when window_size == step_size</h2> <p>I can't seem to get the last three element of an example 9 element series to be rolled on, when my window size and step size are both 3.</p> <p>Is the below an intended behaviour of <code>pandas</code>?</p> <h3>My desired outcome</...
<python><pandas><dataframe><pandas-rolling>
2023-01-19 14:49:23
1
450
semyd
75,174,062
639,676
How to implement a fast type inference procedure for SKI combinators in Python?
<p>How to implement a fast simple type inference procedure for <a href="https://en.wikipedia.org/wiki/SKI_combinator_calculus" rel="nofollow noreferrer">SKI combinators</a> in Python?</p> <p>I am interested in 2 functions:</p> <ol> <li><p><code>typable</code>: returns true if a given SKI term has a type (I suppose it s...
<python><algorithm><functional-programming><lambda-calculus><combinators>
2023-01-19 14:45:51
1
4,143
Oleg Dats
75,173,924
4,954,079
Fastest way to apply function along axes
<p>In a time-critical code fragment, I need to apply a function along different axes of a tensor and sum results. A peculiar feature is that the number of axes of the tensor (<code>ns_test</code>) can be large. I came up with two implementations, where I move the current axis (<code>moveaxis</code>) to either zeroth (<...
<python><numpy><optimization><tensor>
2023-01-19 14:35:54
1
367
yarchik
75,173,896
15,366,635
How to multiply each digit by a number in a list in order
<p>I'm trying to create a program that will multiply each digit with a number in the list in order</p> <p>so lets say my inputted number is <code>1234</code>, then</p> <ul> <li><code>1</code> will be multiplied by <code>4</code></li> <li><code>2</code> will be multiplied by <code>8</code></li> <li><code>3</code> will b...
<python>
2023-01-19 14:33:25
0
1,341
I_love_vegetables
75,173,872
12,181,868
Semantic Search regardless of database type
<p>I can apply semantic search on a specific table of the database. But my goal is to achieve a module that can use search queries on a related table and database. Any database should be flexibly integrated with the system.</p> <ul> <li><strong>Example:</strong> Might be possible, my question is ambiguous. In that case...
<python><database><elasticsearch><semantics><opensemanticsearch>
2023-01-19 14:31:54
0
348
Muhammad Afzaal
75,173,822
5,743,711
The sklearn.manifold.TSNE gives different results for same input vectors
<p>I give TSNE a list of vectors, some of these vectors are exactly the same. But the output of fit() function can be different for each! IS this expected behavior? How can i assure each input vector will be mapped to same output vector?</p> <p>Exclamation, I cannot tell for sure, but I even noticed that the first entr...
<python><scikit-learn><tsne>
2023-01-19 14:28:27
1
1,408
Samer Aamar
75,173,552
3,450,064
Matplotlib, plot a vector of numbers as a rectangle filled with numbers
<p>So let's say I have a vector of numbers.</p> <pre class="lang-py prettyprint-override"><code>np.random.randn(5).round(2).tolist() [2.05, -1.57, 1.07, 1.37, 0.32] </code></pre> <p>I want a draw a rectangle that shows this elements as numbers in a rectangle. Something like this:</p> <p><a href="https://i.sstatic.net/...
<python><matplotlib>
2023-01-19 14:10:07
3
11,300
CentAu
75,173,357
4,691,830
deep copy of GeoDataFrame becomes Pandas DataFrame
<p>When I <a href="https://docs.python.org/3/library/copy.html" rel="nofollow noreferrer">deepcopy</a> a <code>geopandas.GeoDataFrame</code> without a &quot;geometry&quot; column, the copy becomes a <code>pandas.DataFrame</code>. Why does this happen? I looked on the main branches on Github and neither Pandas nor Geopa...
<python><pandas><geopandas><deep-copy>
2023-01-19 13:57:21
0
4,145
Joooeey
75,173,255
11,502,612
Is it possible to keep the format of INI file after change it with ConfigParser?
<p>Is it possible that <code>ConfigParser</code> keeps the format of <code>INI</code> config file? I have config files which have comments and specific <code>section</code>/<code>option</code> names and if a read and change the content of file the <code>ConfigParser</code> re-format it (I can solve the <code>section</c...
<python><python-3.x><configuration><ini><configparser>
2023-01-19 13:50:20
3
5,389
milanbalazs
75,173,213
7,084,115
Python how to iterate over a list inside another list
<p>I have the following list of lists as below:</p> <pre><code>my_list = [ ['first-column', 'DisplayName', 'FLOW TRIGGERED: 636e56d390c8c0910d592cc6', 'ClassificationType', 'NLU', 'KeyPhrases', 'MetaIntent', 'Description', 'test description', 'SampleSentences', [], 'Regexes'], ['first-column', 'DisplayName', '...
<python><csv>
2023-01-19 13:47:16
1
4,101
Jananath Banuka
75,173,128
10,967,204
QVideoWidget() is not working with Frameless Window and Translucent Background
<p>I am making a videoplayer with <strong>QMediaplayer and QVideoWidget</strong> using <strong>PySide2</strong>. Everything works as expected but when I use:</p> <pre><code> self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) </code></pre> <p>The sound...
<python><pyside2><qvideowidget>
2023-01-19 13:39:05
1
7,216
ncica
75,173,034
10,596,488
Remove key but keep value in JSON [Python]
<p>I need to &quot;Semi-Flatten&quot; a JSON object where i have a JSON object with nested items. I have tried to use the flat_json with pandas and other &quot;flatten_json&quot; and json_normalize code in stackoverflow but i end up with completely flatten JSON (something i do not need).</p> <p>Here is the JSON structu...
<python><json><pandas><dataframe>
2023-01-19 13:32:36
1
353
Ali Durrani
75,173,005
12,845,199
Check for previous value condition, and grabbing sucessor value with condition
<p>I have the following sample series</p> <pre><code>s = {0: 'feedback ratings-positive-unexpected origin', 1: 'decision-tree identified-regex input', 2: 'feedback ratings-options input', 3: 'feedback ratings-options-unexpected origin', 4: 'checkout order-placed input', 5: 'decision-tree identified-regex input'} <...
<python><pandas>
2023-01-19 13:30:48
1
1,628
INGl0R1AM0R1
75,172,995
5,947,182
ModuleNotFoundError in regular .py files, but working when run with pytest .py files
<p>I'm writing a concurrency test where the code opens two separate playwright browsers and run them separately and concurrently. The structure is as follows</p> <pre><code>MoveMouse | ----__init__.py ----MoveMouse.py UnitTest | ----__init__.py ----TestMoveMouse | --...
<python><modulenotfounderror>
2023-01-19 13:30:05
1
388
Andrea
75,172,921
6,282,576
Groupby and count number of children where each child has more than a specific number of children itself
<p>I have three models, <code>Business</code>, <code>Employee</code>, and <code>Client</code>, where each business can have many employees and each employee can have many clients:</p> <pre class="lang-py prettyprint-override"><code>class Business(models.Model): name = models.CharField(max_length=128) menu = mod...
<python><django><django-models><django-orm>
2023-01-19 13:24:20
1
4,313
Amir Shabani
75,172,878
17,561,414
explode function on struct type pyspark
<p>I would like to get the seperate <code>df</code> per level from <code>JSON</code> file. Below code allows me to go 2 level deep but later I cant use <code>explode</code> function <code>due to data type mismatch: input to function explode should be array or map type, not struct</code> error on <code>df_4</code>.</p> ...
<python><json><pyspark><flatten><melt>
2023-01-19 13:20:47
0
735
Greencolor
75,172,585
7,762,646
Python decorator to determine the memory size of objects in a function
<p>I would like to develop a Python decorator that tells me the <a href="https://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python/30316760#30316760">real memory size</a> of the objects in a Python function.</p> <pre><code>from pympler import asizeof import functools def get_size(fu...
<python><python-3.x><memory-management><python-decorators>
2023-01-19 12:56:32
0
1,541
G. Macia
75,172,484
2,318,839
UTF-8 support in reportlab (Python)
<p><strong>Problem</strong></p> <p>I can't create a PDF from <code>UTF-8</code> encoded text using <a href="https://docs.reportlab.com/reportlab/userguide/ch1_intro/" rel="nofollow noreferrer">reportlab</a>. What I get is a document full of black squares.</p> <p>See the screenshot below:</p> <p><a href="https://i.sstat...
<python><pdf><utf-8><reportlab>
2023-01-19 12:48:10
1
14,526
Artur Barseghyan
75,172,467
848,292
Extrude a concave, complex polygon in PyVista
<p>I wish to take a concave and complex (containing holes) polygon and extrude it 'vertically' into a polyhedron, purely for visualisation. I begin with a shapely <a href="https://shapely.readthedocs.io/en/stable/manual.html?highlight=Polygon#Polygon" rel="nofollow noreferrer"><code>Polygon</code></a>, like below:</p> ...
<python><cad><pyvista>
2023-01-19 12:47:03
1
4,931
Anti Earth
75,172,022
12,226,377
Token indices sequence length warning while using pretrained Roberta model for sentiment analysis
<p>I am presently using a pretrained Roberta model to identify the sentiment scores and categories for my dataset. I am truncating the length to 512 but I still get the warning. What is going wrong here? I am using the following code to achieve this:</p> <pre><code>from transformers import AutoTokenizer from transforme...
<python><sentiment-analysis><roberta-language-model><roberta>
2023-01-19 12:08:53
1
807
Django0602
75,171,845
19,270,168
Discord API cloudflare banning my repl.it repo
<pre class="lang-py prettyprint-override"><code>#type: ignore import os from keep_alive import keep_alive from discord.ext import commands import discord import asyncio import datetime import re DC_TOK = os.environ['DC_TOK'] bot = commands.Bot(command_prefix='!', intents=discord.Intents(4194303)) @bot.event async d...
<python><discord><discord.py><replit>
2023-01-19 11:53:40
1
1,196
openwld
75,171,569
4,908,844
Why is read_csv so much slower to parse dates than to_datetime
<p>I am using jupyter notebook and reading a .csv file with pandas read_csv. When using the following code, it takes a reeeeeeeally long time (more than 10 minutes). The dataset has 70821 entries.</p> <pre><code> [Input] df = pd.read_csv(&quot;file.csv&quot;, parse_dates=[0]) df.head() [Output] ...
<python><pandas><csv><datetime>
2023-01-19 11:29:46
0
361
Mrob
75,171,558
13,489,354
Python subprocess.Popen() is not starting the subprocess properly
<p>I have a python test that startes a tcp server as subprocess.</p> <pre><code>def test_client(self): if sys.platform.startswith('linux'): proc = subprocess.Popen([f'{self.bin_output_path}/CaptureUnitHalServer'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) ...
<python><windows><subprocess>
2023-01-19 11:28:41
0
501
Simon Rechermann
75,171,541
13,345,744
How to convert categorial data into indices with nan values present in Python?
<p><strong>Context</strong></p> <p>I have created a function, that converts <code>Categorial Data</code> into its unique indices. This works great with all values except <code>NaN</code>. It seems that the comparison with <code>NaN</code> does not work. This results in the two problems seen below.</p> <hr /> <p><strong...
<python><pandas><numpy><series><categorical-data>
2023-01-19 11:26:49
2
1,721
christophriepe
75,171,486
10,122,801
Python loop and reassign quantities based on limits
<p>Community!</p> <p>I've been stuck on solving a problem for quite a while now. I guess it's a simple error in my for-loop, but I can't seem to locate where it fails.</p> <p><strong>What am I trying to accomplish?</strong></p> <ol> <li>Loop through a dataset (from .csv) in format shown below.</li> <li>Assess limits pr...
<python><python-3.x><pandas><csv>
2023-01-19 11:22:03
1
431
Havard Kleven
75,171,353
9,749,124
K-Means model always predicts the same class after saving and loading
<p>I have created K-Means clustering model with Python and Sklearn. Now I want to save the model and vectoriser so that I can make predictios.</p> <p>This is my model:</p> <pre><code># Vectoriser - CountVectorizer transformerVectoriser = CountVectorizer(analyzer = 'word', ngram_range = (1, 4), vocabulary = vocab_list) ...
<python><machine-learning><scikit-learn>
2023-01-19 11:10:43
1
3,923
taga
75,171,352
2,706,344
Inserting an array with less elements as new column to an existing DataFrame
<p>Using the <code>df.insert() function</code> I want to add to an existing <code>DataFrame</code> a new column which I have in terms of an array (without any indexing). I know that my array has less entries than the DataFrame rows. This is intended. I want NaN values in the end of the new column to match the size of t...
<python><pandas>
2023-01-19 11:10:30
1
4,346
principal-ideal-domain
75,171,296
3,586,606
Benefit of using generators while sending API calls
<p>The code below is sending request to some server, and getting a JSON object as a response. Then, it is iterating over the response, and printing it.</p> <p>I don't understand, what is the benefit of using generator in this case?</p> <pre><code>def crawl(): response = requests.get('https://swapi.co/api/people') ...
<python><python-requests><generator>
2023-01-19 11:05:45
1
487
CleverDev
75,171,196
12,403,550
pyjanitor.pivot_longer: Unpivot multiple sets of columns with common prefix
<p>Reprex csv:</p> <pre><code>col,ref_number_of_rows,ref_count,ref_unique,cur_number_of_rows,cur_count,ref_unique region,2518,2518,42,212,212,12 country,2518,2518,6,212,212,2 year,2518,2518,15,212,212,15 </code></pre> <p>I want to unpivot the dataset, where a <code>type</code>column contains the prefix of each column s...
<python><janitor><pyjanitor>
2023-01-19 10:56:50
1
433
prayner
75,170,806
12,267,943
How to mark duplicate rows with the index of the first occurrence in Pandas?
<p>I'm trying to write a script that finds duplicate rows in a spreadsheet. I'm using the <strong>Pandas</strong> library. This is the initial dataframe:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({'title': [1, 2, 3, 4, 5, 6, 7, 8], 'val1': [1.1, 1.1, 2...
<python><excel><pandas><dataframe>
2023-01-19 10:24:36
3
349
nsog8sm43x
75,170,611
959,936
How to run a docker container with a previously determined ip address with the python docker sdk?
<p>On console this does the trick:</p> <pre><code>docker run --net mynet --ip 172.18.0.22 --dns=&quot;8.8.8.8&quot; -d testimage </code></pre> <p>is there an easy equivalent with the python docker sdk like this?</p> <pre><code>container = client.containers.run(&quot;alpine&quot;, &quot;ls /&quot;, detach=True, ipv4_add...
<python><docker>
2023-01-19 10:09:17
1
9,263
Jurudocs
75,170,495
1,436,800
How to apply permissions on perform_create in ViewSet DRF
<p>This is my View Set:</p> <pre><code>class MyViewSet(ModelViewSet): serializer_class = MySerializer queryset = MyClass.objects.all() def get_serializer_class(self): if self.request.user.is_superuser: return self.serializer_class return serializers.MyUserSerializer def...
<python><django><django-rest-framework><django-views><django-permissions>
2023-01-19 09:59:29
4
315
Waleed Farrukh
75,170,451
11,479,825
Expand column containing list of tuples into the current dataframe
<p>I have a dataframe in the following format:</p> <pre><code>df = pd.DataFrame({'column_with_tuples': [[('word1', 10), ('word2', 20), ('word3', 30)], [('word4', 40), ('word5', 50), ('word6', 60)]], 'category':['category1','category2']}) </code></pre> <p>I want to move the tuples into two separate co...
<python><pandas>
2023-01-19 09:56:26
3
985
Yana
75,170,207
19,041,437
How to change decimal format inside a transform_calculate function (Altair)
<p>I'm trying to limit the numbers after the decimal in the text displayed in my graph, but I'm having a hard time doing so inside a transform_calculate function, this is what it looks like : (I am printing the equation to a linear regression under the form y = ax + b))</p> <pre><code> params = alt.Chart(df).transfo...
<python><linear-regression><altair>
2023-01-19 09:37:05
1
502
grymlin
75,170,120
4,432,671
NumPy: create ndarray of objects
<p>I like to create a numpy array -- with a shape, say [2, 3], where each array element is a list. Yes, I know this isn't efficient, or even desirable, and all the good reasons for that -- but can it be done?</p> <p>So I want a 2x3 array where each point is a length 2 vector, <em>not</em> a 2x3x2 array. Yes, really.</p...
<python><numpy>
2023-01-19 09:30:13
3
3,737
xpqz
75,170,069
6,803,114
Strip colum values if startswith a specific string pandas
<p>I have a pandas dataframe(sample).</p> <pre><code>id name 1 Mr-Mrs-Jon Snow 2 Mr-Mrs-Jane Smith 3 Mr-Mrs-Darth Vader </code></pre> <p>I'm looking to strip the &quot;Mr-Mrs-&quot; from the dataframe. i.e the output should be:</p> <pre><code>id name 1 Jon Snow 2 Jane Smith 3 Darth Vader </code></pre> <p>...
<python><pandas>
2023-01-19 09:26:25
1
7,676
Shubham R
75,169,981
10,695,613
Convert huge Polars dataframe to dict without consuming too much RAM
<p>When I load my parquet file into a Polars DataFrame, it takes about 5.5 GB of RAM. Polars is great compared to other options I have tried. However, Polars does not support creating indices like Pandas. This is troublesome for me because one column in my DataFrame is unique and the pattern of accessing the data in th...
<python><dictionary><parquet><python-polars>
2023-01-19 09:18:07
2
405
BovineScatologist
75,169,919
12,436,050
Explode is not working on pandas dataframe
<p>I have a dataframe with following columns</p> <pre><code> col1 col2 col3 col4 0 HP:0005709 ['HP:0001770'] Toe syndactyly SNOMEDCT_US:32113001, C0265660 1 HP:0005709 ['HP:0001780'] Abnormality of toe C2674738 2 EFO:0009136 ['HP:0001507'] Growth ab...
<python><pandas><dataframe><split><explode>
2023-01-19 09:12:46
3
1,495
rshar
75,169,907
11,867,978
unable to write tuple into xslx file using python without pandas?
<p>I am trying to write the output into xslx file, but able to only write the headers not able to write the data below headers.</p> <pre><code>import xlsxwriter csv_columns = ( 'id', 'name', 'place', 'salary', 'email', ) details = [{'id':1, 'name': 'A', 'place':'B', 'salary': 2, 'email': 'c@d.com'}, {'i...
<python><python-3.x><excel>
2023-01-19 09:11:42
3
448
Mia
75,169,874
9,880,480
Is it possible to set the exploration rate to 0, and turn off network training for a Stable Baselines 3 algorithm?
<p>After training a stable baselines 3 RL algorithm (I am using mainly PPO) I want to set the exploration rate to 0, and turn off network training so I always get the same output (action) from the model when given the same input (observation). Is it possible to do that? If not, is there a reason for why it should not b...
<python><reinforcement-learning><stable-baselines>
2023-01-19 09:07:59
1
397
HaakonFlaar
75,169,785
661,716
python dataframe number of last consequence rows less than current
<p>I need to set number of last consequence rows less than current.</p> <p>Below is a sample input and the result.</p> <pre><code>df = pd.DataFrame([10,9,8,11,10,11,13], columns=['value']) df_result = pd.DataFrame([[10,9,8,11,10,11,13], [0,0,0,3,0,1,6]], columns=['value', 'number of last consequence rows less than curr...
<python><pandas><dataframe>
2023-01-19 08:59:52
1
1,226
tompal18
75,169,714
16,396,496
change the level of a column, when concat two data frames with the same column
<p>referral url : <a href="https://stackoverflow.com/questions/40464706/pandas-concatenating-two-multi-index-dataframes">Pandas - concatenating two multi-index dataframes</a></p> <p>result what I want</p> <pre><code> Name Q1 Q2 Q3 Student Name IS CC ...
<python><pandas>
2023-01-19 08:54:00
1
341
younghyun
75,169,594
9,749,124
Setting minimal number of data that goes into one cluster
<p>I have dataset of 20.000 rows. Al rows contain textual data. I want to use K-Means so that I can check how many clusters do I have. Optimal number of clusters that I get is 120 (based on silhouette_score).</p> <p>This is my code:</p> <pre><code>from sklearn.cluster import KMeans from sklearn.metrics import silh...
<python><machine-learning><scikit-learn>
2023-01-19 08:41:33
1
3,923
taga
75,169,458
14,353,779
Pandas map values from Dictionary efficiently
<p>I have a pandas dataframe <code>df</code> :-</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">ID</th> <th style="text-align: center;">COST</th> <th style="text-align: center;">1F</th> <th style="text-align: center;">2F</th> <th style="text-align: center;">3F</t...
<python><pandas><numpy>
2023-01-19 08:26:05
1
789
Scope
75,169,404
6,653,602
Is there a way to use Mongoexport with Airflow?
<p>I am trying to write Airflow DAG which will export data from certain collection in the MongoDB database. Is there any way to use Mongoexport with the Airflow?</p> <p>I was thinking of something like this, based on airflow documentation:</p> <pre><code>def exportFromMongoCollection(): try: hook = MongoHoo...
<python><mongodb><airflow>
2023-01-19 08:21:08
1
3,918
Alex T
75,169,392
12,454,639
Django app not able to find database engine when engine is specified
<p>I have tried everything I can think of to run my initial migrations using <code>python manage.py migrate</code> and get my django app up. I am currently getting this error:</p> <pre><code>Traceback (most recent call last): File &quot;manage.py&quot;, line 24, in &lt;module&gt; execute_from_command_line(sys.arg...
<python><python-3.x><django>
2023-01-19 08:19:50
3
314
Syllogism
75,169,381
8,855,527
Email Validator in Django Ninja
<p>I found that Django Ninja uses Pydantic. I have created a Schema from Django model,</p> <pre><code>class UserSchema(ModelSchema): class Config: model = User model_fields = [&quot;username&quot;, &quot;first_name&quot;, &quot;last_name&quot;, &quot;email&quot;] class CreateUserSchema(UserSchema)...
<python><pydantic><django-ninja>
2023-01-19 08:18:52
3
577
CC7052
75,169,350
10,437,110
How to replace 0 with "NA" and all other values to 0 in Python DataFrame?
<p>Consider a dataframe</p> <pre><code>dict = {'col1': [1,2,np.nan,4], 'col2': [1,2,0,4], 'col3': [0,2,3,4], 'col4': [1,2,0,np.nan], } df = pd.DataFrame(dict) </code></pre> <pre><code>&gt;&gt; df col1 col2 col3 col4 0 1.0 1 0 1.0 1 2.0 2 2 2.0 2 NaN 0 3 0.0 3 4.0 4 4 Na...
<python><pandas><dataframe>
2023-01-19 08:15:27
2
397
Ash
75,169,333
293,594
Is there a way to calculate the half range Fourier series in SymPy?
<p>For example, if I want the Fourier series of the function <em>f(x) = x(π-x)</em> on [0, π], I can calculate the coefficients of the sine series:</p> <p><a href="https://i.sstatic.net/vP4GJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vP4GJ.png" alt="enter image description here" /></a></p> <p>which...
<python><math><sympy>
2023-01-19 08:14:11
2
25,730
xnx
75,169,313
8,176,763
python path directing to older version in PATH
<p>In Linux when I issue the following command:</p> <pre><code>echo $PATH /opt/python/3.10.8/bin/python3:/home/d5291029/.local/bin:/home/d5291029/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/puppetlabs/bin </code></pre> <p>I get this. My <code>.bash_profile</code> is this:</p> <pre><code># .bash_profile ...
<python><linux>
2023-01-19 08:12:08
1
2,459
moth
75,169,285
20,589,275
How to change numbers in a list to make it monotonically decreasing?
<p>I have got a list:</p> <pre><code>first = [100, 110, 60] </code></pre> <p>How to make that: if the next number is greater than the previous one, then it is necessary to reduce this number like preceding number. For example, the answer should be:</p> <pre><code>ans = [100, 100, 60] </code></pre> <p>The second example...
<python>
2023-01-19 08:08:45
6
650
Proger228
75,168,725
5,371,582
Memory leak in Midas depthmap computation?
<p>I'm using Midas very like in <a href="https://huggingface.co/spaces/akhaliq/DPT-Large" rel="nofollow noreferrer">Huggingface's demo</a>.</p> <p>My issue is that the RAM usage increase at each depth map computation.</p> <p>Here is the full code.</p> <pre><code>#!venv/bin/python3 from pathlib import Path import psuti...
<python><opencv><pytorch><memory-leaks>
2023-01-19 07:02:27
0
705
Laurent Claessens
75,168,665
794,535
"Unsupported number of image dimensions" while using image_utils from Transformers
<p>I'm trying to follow this HuggingFace tutorial <a href="https://huggingface.co/blog/fine-tune-vit" rel="nofollow noreferrer">https://huggingface.co/blog/fine-tune-vit</a></p> <p>Using their &quot;beans&quot; dataset everything works, but if I use my own dataset with my own images, I'm hitting &quot;Unsupported numbe...
<python><numpy><machine-learning><pytorch><huggingface-transformers>
2023-01-19 06:53:46
3
400
Pablo Mendes
75,168,484
7,218,871
PIL Python: A rounded rectangle image converted to numpy array is all zeros
<pre><code>a_rect = Image.new('RGBA', (400, 100)) draw = ImageDraw.Draw(a_rect) draw.rounded_rectangle((0, 0, 400, 100), outline=None, radius=75, fill='blue' ) a_rect </code></pre> <p><a href="https://i.sstatic.net/dyS2M.png" re...
<python><python-imaging-library>
2023-01-19 06:30:08
0
620
Abhishek Jain
75,168,470
7,657,180
Read numbers on image using OCR python
<p>I am trying to extract numbers on images using OpenCV in Python and tesseract. Here's my try but I got nothing. The code doesn't return the expected numbers</p> <pre><code>import fitz, pytesseract, os, re import cv2 sTemp = &quot;Number.png&quot; directory = '.\MyFolder' def useMagick(img): pytesseract.pytesse...
<python><opencv><imagemagick><ocr><tesseract>
2023-01-19 06:28:32
1
9,608
YasserKhalil
75,168,443
10,062,025
How to fix chromedriver status code -6 in colab
<p>I've been running this in collab without a trouble until just today. No changes was made to the code, however the error just appear today. The error shown:</p> <pre><code>Message: Service chromedriver unexpectedly exited. Status code was: -6 </code></pre> <p>My code is as follow</p> <pre><code># install chromium, it...
<python><selenium-chromedriver>
2023-01-19 06:23:48
0
333
Hal
75,168,396
13,061,012
How to create a function in Python to offset a datetime object by a certain number of months
<p>How can I create a function in Python that takes a datetime object and an integer as inputs, and returns a new datetime object with the desired offset?</p> <p>I tried before with this:</p> <pre><code>from datetime import datetime, timedelta def get_offset_datetime(source_date_time, month_offset): year, month, d...
<python><datetime>
2023-01-19 06:17:02
1
1,108
Hossein Vejdani
75,168,219
15,632,586
How do we create GV files with non-overlapping subgraphs from a GV file?
<h3>Graph</h3> <p>I am having a GV file containing 3 subgraphs:</p> <ol> <li><code>cluster_1</code></li> <li><code>cluster_2</code></li> <li><code>cluster_3</code></li> </ol> <p>Source of <code>Final_Graph.gv</code>:</p> <pre><code>digraph Final_Graph { graph [center=true rankdir=LR ratio=compress size=&quot;15,10&...
<python><graphviz>
2023-01-19 05:51:09
1
451
Hoang Cuong Nguyen
75,168,100
2,616,753
How can I define a Python Callable type for annotating a decorator, where the decorator uses some parameters and absorbs the rest in **kw?
<p>I'm looking to annotate a decorator in Python 3.11, where</p> <ol> <li>the decorated functions use keyword-only parameters,</li> <li>the decorated functions share a small number of keyword-only parameters, say <code>a</code> &amp; <code>b</code>,</li> <li>the decorator's inner function uses those parameters, and</li...
<python><python-3.x><python-decorators><mypy><python-typing>
2023-01-19 05:33:24
0
2,083
chris
75,168,079
9,090,340
filter data based on a condition in json
<p>I am working on a requirement where I need to filter data if a condition is satisfied from json data into a data frame in python. When I use the below code I run into following error. I am trying to filter data based on a random condition here, I am checking if the Country Code is US then I need data frame to be pop...
<python><json><pandas><dataframe>
2023-01-19 05:30:31
1
937
paone
75,167,963
14,923,024
polars slower than numpy?
<p>I was thinking about using <code>polars</code> in place of <code>numpy</code> in a parsing problem where I turn a structured text file into a character table and operate on different columns. However, it seems that <code>polars</code> is about 5 times slower than <code>numpy</code> in most operations I'm performing....
<python><numpy><python-polars>
2023-01-19 05:08:38
1
457
AAriam
75,167,941
326,389
Python inequality comparison dealing with floating point precision
<p>I need to compare floating point numbers with inequalities:</p> <pre class="lang-py prettyprint-override"><code>if x &gt;= y: </code></pre> <p>However, due to floating point precision issues, sometimes this fails when it should succeed (<code>x = 0.21</code> and <code>y= 0.21000000000000002</code>). I was thinking t...
<python><python-3.x><numpy><floating-accuracy><inequality>
2023-01-19 05:04:43
1
52,820
at.
75,167,840
758,982
pyspark dataframe schema, not able to set nullable false for csv files
<p>I am trying to load csv file using pyspark. I am giving my own schema with columns nullable false, still when I print schema it shows them true. I checked the file data, there are no null entries for columns which are nullable false.</p> <p><strong>Code</strong></p> <pre><code>from pyspark.sql.types import * udemy_...
<python><dataframe><csv><pyspark><schema>
2023-01-19 04:45:32
2
394
Harbeer Kadian
75,167,811
17,101,330
Unwanted additional/current matplotlib window while embedding in tkinter gui
<p>I'm plotting streamed data with tkinter but my app opens the current plot in an additional window:</p> <p><a href="https://i.sstatic.net/kR4a5.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kR4a5.jpg" alt="" /></a></p> <p>My App looks something like this:</p> <pre><code>import tkinter as tk from tkin...
<python><matplotlib><tkinter>
2023-01-19 04:39:41
1
530
jamesB
75,167,660
11,065,874
why two equal ranges are different objects in cpython?
<p>I am wondering why</p> <pre><code>a = &quot;abcdghf23&quot; b = &quot;abcdghf23&quot; c = range(100) d = range(100) e = [] f = [] </code></pre> <p><code>a is b</code> retruns True</p> <p>while <code>c is d</code> returns False</p> <p>and <code>e is f</code> returns False</p> <p>actually the question is why id of a...
<python><object><cpython>
2023-01-19 04:06:22
0
2,555
Amin Ba
75,167,317
134,044
Make Pydantic BaseModel fields optional including sub-models for PATCH
<p>As already asked in <em><strong>similar</strong></em> questions, I want to support <code>PATCH</code> operations for a FastApi application where the caller can specify as many or as few fields as they like, of a Pydantic <code>BaseModel</code> <em><strong>with sub-models</strong></em>, so that efficient <code>PATCH<...
<python><fastapi><crud><pydantic>
2023-01-19 02:51:30
1
4,109
NeilG
75,167,258
12,709,566
Discord Bot joins voice channel muted
<p>I am trying to make my discord bot play an MP3 file in a voice channel, however, upon joining the discord bot remains muted, and therefore the audio file isn't audible, even if it may be playing. Here is my code:</p> <pre><code>@client.event async def on_ready(): print(f'{client.user} is now running') channe...
<python><discord><discord.py><bots>
2023-01-19 02:39:44
3
603
hmood
75,167,203
2,138,610
ML model fit with training data outperforms model fit with generator
<p>My ultimate goal is to fit a ML autoencoder by inputting a data generator into the <em>fit</em> method within the keras API. However, I am finding that models fit with a generator are inferior to models fit on the raw data themselves.</p> <p>To demonstrate this, I've taken the following steps:</p> <ol> <li>define a...
<python><tensorflow><machine-learning><keras><autoencoder>
2023-01-19 02:27:21
1
872
Alex Witsil
75,167,166
10,200,497
Delete rows from pandas dataframe by using regex
<p>This is my dataframe:</p> <pre><code>df = pd.DataFrame( { 'a': [ '#x{LA 0.098:abc}', '#x{LA abc:0.31}', '#x{BC abc:0.1231}', '#x{LA 0.333:abc}', '#x{CN 0.031:abc}', '#x{YM abc:12345}', '#x{YM 1222:abc}', ] } )...
<python><pandas>
2023-01-19 02:20:00
1
2,679
AmirX
75,167,124
9,934,276
Check if its a table inside a td
<p>Supposed I have a HTML like this:</p> <pre><code>&lt;tr&gt; &lt;td colspan=&quot;2&quot;&gt;&lt;br&gt; &lt;blockquote&gt; &lt;p align=&quot;center&quot;&gt;&lt;br&gt;Test&lt;br&gt;&lt;/p&gt; &lt;p align=&quot;center&quot;&gt;&lt;b&gt;Test2&lt;/b&gt;&lt;/p&gt;&lt;b&gt; &lt;/b&gt; &lt;p&g...
<python><beautifulsoup>
2023-01-19 02:09:44
1
1,750
Beginner
75,167,112
11,930,470
How to create a dictionary from list with single for loop?
<p>List is a = [1,2,3]</p> <p>How to get the dictionary from that list like below?</p> <p>{1: 1, 1: 2, 1: 3, 2: 1, 2: 2, 2: 3, 3: 1, 3: 2, 3: 3}</p> <p>Condition is to do not use two for loops.</p> <p>It was asked in an interview, but I was not able to implement without two for loops so I thought interviewer might be w...
<python><python-3.x>
2023-01-19 02:07:08
2
407
Kalyan Kumar
75,167,035
17,900,955
JWT authentication does not work in Django Rest Framework after deploying it to IIS on live server
<p>I built a Rest API using Django's Rest framework. And I've deployed it on Windows OS's IIS. When I deploy the application to the live IIS server, it throws the following issue even though it functions well on the local IIS server. I have used <a href="https://pypi.org/project/wfastcgi/" rel="nofollow noreferrer">wfa...
<python><django><windows><iis><django-rest-framework>
2023-01-19 01:47:28
1
497
Parth Panchal
75,167,022
8,089,312
AttributeError: 'XGBRegressor' object has no attribute 'feature_names_in_'
<p>I'm building a model with XGBRegressor. After fitting the model, I want to visualise the feature importance.</p> <pre><code>reg = xgb.XGBRegressor(base_score=0.5, booster='gbtree', n_estimators=1000) reg.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_test, y_test)], verbose=100) fi = pd.DataFrame(data=reg....
<python><xgboost>
2023-01-19 01:45:59
1
1,744
Osca
75,166,900
8,869,570
df.index vs df["index"] after resetting index
<pre><code>import pandas as pd df1 = pd.DataFrame({ &quot;value&quot;: [1, 1, 1, 2, 2, 2]}) print(df1) print(&quot;-------------------------&quot;) print(df1.reset_index()) print(&quot;-------------------------&quot;) print(df1.reset_index().index) print(&quot;-------------------------&quot;) print(df1.reset_index(...
<python><pandas><dataframe>
2023-01-19 01:15:40
3
2,328
24n8
75,166,877
5,212,614
How can we count items greater than a value and less than a value?
<p>I have this DF.</p> <pre><code>import pandas as pd import scipy.optimize as sco pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) data = [['ATTICA',1,2,590,680],['ATTICA',1,2,800,1080],['AVON',14,2,950,1250],['AVON',15,3,500,870],['AVON',20,4,1350,1700]] df = pd.DataFrame(data, co...
<python><python-3.x><pandas><dataframe>
2023-01-19 01:09:53
1
20,492
ASH
75,166,819
2,487,509
how do install python packages using python3.11 -m pip
<p>I am trying to install a python application (elastalert2) which requires the latest version of python on an Ubuntu 20.04 machine.</p> <p>I have managed to install python3.11 and my searching suggested strongly that to install packages in this environment I should use python3.11 -m pip install but when I try I get:<...
<python><pip>
2023-01-19 00:57:54
1
610
Russell Fulton