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
74,956,129
20,176,161
Computing % return using groupby returns NaN
<p>I have a dataframe that looks like this</p> <pre><code> city Year Asset_Type TotalTransac NbBiens psqm_city 0 Agadir 2010.0 Appart 3225 3156 6276.923077 1 Agadir 2010.0 Maison_Dar 37 37 8571.428571 2 Agadir 2010.0 Villa 107 103 ...
<python><dataframe><lambda><group-by>
2022-12-29 21:17:05
0
419
bravopapa
74,955,937
14,462,728
Issue installing Scrapy using Python 3.11 on Windows 11
<p>I'm using Windows 11, Python 3.10.1. I created a virtual environment using <code>venv</code>, and installed scrapy, and all requirements. <strong>Everything worked perfectly!</strong> Then I installed Python 3.11.1, created a virtual environment using <code>venv</code>, installed scrapy, and I received an error:</p...
<python><visual-c++><pip><scrapy><pipenv>
2022-12-29 20:50:06
1
454
Seraph
74,955,744
10,118,393
Confluent kafka create_topics is failing to create kafka topics from pycharm but works fine from python terminal
<p>I am just playing around with confluent kafka python APIs. Here I am running a 3 worker kafka cluster service on local (<em><strong>localhost:9902,localhost:9903,localhost:9904</strong></em>) and trying to create a topic via python API of confluent kafka using below function</p> <pre><code>from confluent_kafka impor...
<python><apache-kafka><pycharm>
2022-12-29 20:22:42
1
1,102
akhil pathirippilly
74,955,725
3,322,222
Getting the generic arguments of a subclass
<p>I have a generic base class and I want to be able to inspect the provided type for it. My approach was using <a href="https://docs.python.org/3/library/typing.html#typing.get_args" rel="nofollow noreferrer"><code>typing.get_args</code></a> which works like so:</p> <pre class="lang-py prettyprint-override"><code>from...
<python><generics><python-typing>
2022-12-29 20:20:56
2
781
yotamN
74,955,701
10,146,441
RabbitMQ headers binding is not working as expected, Header exchange is routing message to all the bound queues
<p>I want to route rabbitmq messages based on headers and I have created a appropriate infrastructure including headers exchange, queues, bindings etc. Below is the complete code for the <code>consumer.py</code></p> <pre><code>import pika # define variables url = &quot;amqp://rabbitmq-host/&quot; exchange = 'headers-e...
<python><rabbitmq><pika><python-pika>
2022-12-29 20:17:34
1
684
DDStackoverflow
74,955,684
15,171,387
How to perform filter map reduce equivalent in Pyhon?
<p>Let's assume there are two lists like:</p> <pre><code>list1 = [&quot;num&quot;, &quot;categ&quot;] all_names = [&quot;col_num1&quot;, &quot;col_num2&quot;, &quot;col_num3&quot;, &quot;col_categ1&quot;, &quot;col_categ2&quot;, &quot;col_bol1&quot;, &quot;col_bol2&quot;, &quot;num_extra_1&quot;, &quot;num_extra_2&quot...
<python><python-3.x><list><filter>
2022-12-29 20:15:01
2
651
armin
74,955,525
3,311,276
understand setting up database using sqlalchamy and avoid errorAttributeError: type object 'User' has no attribute 'query' in flask app
<p>I am a beginner writing a todo app in flask and in writing database application, at least I have never setup db for any production app myself.</p> <p>I have written this code (<strong>models.py</strong>) that uses sqlalchemy ORM to define table model.</p> <pre><code>from sqlalchemy import create_engine, Column, Inte...
<python><flask><sqlalchemy><flask-sqlalchemy>
2022-12-29 19:57:51
1
8,357
Ciasto piekarz
74,955,487
4,391,249
How would I implement my own container with type hinting?
<p>Say I want to make a container class <code>MyContainer</code> and I want to enable its use in type hints like <code>def func(container: MyContainer[SomeType])</code>, in a similar way to how I would be able to do <code>def func(ls: list[SomeType])</code>. How would I do that?</p>
<python><types>
2022-12-29 19:53:11
1
3,347
Alexander Soare
74,955,415
8,681,229
decorator argument: unable to access instance attribute
<h2>Context</h2> <p>class <code>MyMockClient</code> below has two methods:</p> <ul> <li><code>push_log</code>: pushes one <code>log</code> from list <code>self.logs</code> and pops it</li> <li><code>push_event</code>: pushes one <code>event</code> from list <code>self.events</code> and pops it</li> </ul> <p>Both method...
<python><class><methods><decorator>
2022-12-29 19:43:32
1
3,294
Seymour
74,955,370
6,483,314
How to sample based on long-tail distribution from a pandas dataframe?
<p>I have a pandas dataframe of 1000 elements, with value counts shown below. I would like to sample from this dataset in a way that the value counts follow a long-tailed distribution. For example, to maintain the long-tailed distribution, <code>sample4</code> may only end up with a value count of 400.</p> <pre><code> ...
<python><pandas>
2022-12-29 19:38:21
1
369
HumanTorch
74,955,363
5,713,713
Use Python version v0 task fails in azure pipeline
<pre><code>- task: UsePythonVersion@0 inputs: versionSpec: '3.x' addToPath: true architecture: 'x64' </code></pre> <p><strong>I get the following error on ubuntu18.04:</strong></p> <pre><code>##[error]Version spec 3.x for architecture x64 did not match any version in Agent.ToolsDirectory. </code><...
<python><azure-devops><azure-pipelines><pipeline><azure-pipelines-build-task>
2022-12-29 19:37:45
1
443
Mukesh Bharsakle
74,955,285
1,362,485
Dask rolling function fails with message to repartition dataframe
<p>I'm getting this error when I run a dask rolling function to calculate a moving average:</p> <pre><code>df['some_value'].rolling(10).mean() </code></pre> <p>Error:</p> <blockquote> <p>Partition size is less than overlapping window size. Try using &quot;df.repartition&quot; to increase the partition size.</p> </bloc...
<python><pandas><dask><dask-distributed><dask-dataframe>
2022-12-29 19:25:24
1
1,207
ps0604
74,955,261
1,145,760
Split a large object into constant size list entries via list comprehension
<p>How to split a <code>bytes</code> object into a list/tuple of constant size objects? Ignore padding. Something like</p> <pre><code>max_size = 42 def foo(b: bytes): return [b[i:j] for (i, j) in range(max_size)] foo(b'a' * 100000) </code></pre> <p>but working.</p> <p>The 'list comprehension' part is only because i...
<python><list-comprehension>
2022-12-29 19:22:04
1
9,246
Vorac
74,955,223
569,976
AWS kills my opencv script, resource limits exceeded?
<p>I have the following Python / OpenCV code which is supposed to take a filled out document (new.png), line it up with the reference document (ref.png) and put the result in output.png. Unfortunately, sometimes when I run it I get a &quot;Killed&quot; message in bash. I guess <a href="https://stackoverflow.com/q/19189...
<python><linux><amazon-web-services><opencv>
2022-12-29 19:16:20
1
16,931
neubert
74,955,215
13,860,217
Scrapy loop over spider
<p>I'd like to loop over my <code>scrapy.Spider</code> somehow like this</p> <pre><code>for i in range(0, 10): class MySpider(scrapy.Spider, ABC): start_urls = [&quot;example.com&quot;] def start_requests(self): for url in self.urls: if dec == i: ...
<python><loops><scrapy><web-crawler>
2022-12-29 19:15:29
1
377
Michael
74,955,052
12,361,700
Create multiprocessing pool outside main to avoid recursion
<p>I have a py file with functions that requires multiprocessing, so i do something like this:</p> <pre><code>pool = Pool() def function_(): pool.map(...) </code></pre> <p>Then, I'll import this file into the main one, but when i run <code>function_</code> I get:</p> <blockquote> <p>daemonic processes are not allowed...
<python><multithreading><multiprocessing>
2022-12-29 18:55:47
2
13,109
Alberto
74,954,959
5,212,614
Can't upgrade geopandas
<p>I looked at the documentation for geopandas.</p> <p><a href="https://geopandas.org/en/v0.4.0/install.html" rel="nofollow noreferrer">https://geopandas.org/en/v0.4.0/install.html</a></p> <p>Apparent, this is how you install geopandas: <code>conda install -c conda-forge geopandas</code></p> <p>I tried that and I'm get...
<python><python-3.x><geopandas>
2022-12-29 18:45:13
2
20,492
ASH
74,954,928
6,067,528
How to disable import logging from Pyinstaller executable
<p>How can I disable all the import logging that is fired off when running the executable compiled by Pyinstaller?</p> <p>This is my set up:</p> <pre><code>a = Analysis([&quot;model_trainer.py&quot;], pathex=[], binaries=BINARIES, datas=DATA_FILES, hiddenimports=HIDDE...
<python><pyinstaller>
2022-12-29 18:42:22
1
1,313
Sam Comber
74,954,747
15,171,387
Compare a string that was read from a config ini file in Python?
<p>I have a config.ini file like this:</p> <pre><code>[LABEL] NAME = &quot;eventName&quot; </code></pre> <p>And I am reading it into my python code as shown below. However, when I compare it with the exactly the same string, the result is <code>False</code>. I wonder if I should use a different way to read this or I ne...
<python><python-3.x><config><ini>
2022-12-29 18:22:49
2
651
armin
74,954,704
159,508
Confused Pip install with Virtual Environments
<p>Probably a rookie question: I created a project folder, cd'ed to it, created a virtual environment via</p> <pre class="lang-none prettyprint-override"><code>python -m venv .venv </code></pre> <p>and it made the VE in the right place with what looks like the right stuff. But pip-installing modules <em>sometimes</em> ...
<python><pip><python-venv>
2022-12-29 18:17:38
0
1,303
Bob Denny
74,954,628
848,277
Getting the current git hash of a library from an Airflow Worker
<p>I have a library <code>mylib</code> that I want to get the current git hash for logging purposes when I run an Airflow Worker via the <code>PythonOperator</code>, <a href="https://stackoverflow.com/questions/14989858/get-the-current-git-hash-in-a-python-script">I know several methods to get the latest git hash</a>, ...
<python><git><airflow>
2022-12-29 18:09:20
1
12,450
pyCthon
74,954,469
7,624,196
mypy: how to ignore specified files (not talking about how to ignore errors)
<p>I want to let mypy ignore a specified file. I'm <strong>not talking about just ignoring error</strong> (which already answered in many places), rather I want mypy to completely ignore specified files.</p> <p>When applying mypy to jax library, mypy somehow hangs. For example, let's say there is a file named <code>mai...
<python><mypy>
2022-12-29 17:51:32
0
1,623
HiroIshida
74,954,463
11,013,499
how do I show decimal point in print function in python?
<p>I am trying to find the roots of an equation and I need to print the roots with 10 decimal points I used the following code but it produced an error. how can I tell python to print 10 decimal points?</p> <pre><code>def find_root(a1,b1,c1,d1,e1,f1,a2,b2,c2,d2,e2,f2): coeff=[a1-a2,b1-b2,c1-c2,d1-d2,e1-e2,f1-f2] ...
<python><numpy>
2022-12-29 17:51:02
2
1,295
david
74,954,281
12,084,907
How to capture the Name of a Table in a Database when running a stored procedure on multiple tables
<p>I am currently making a python program that will run a stored procedure which has multiple select statements for multiple different tables. I am storing the results in a dataframe and the displaying it with a treeview. I want to make it so that the user can see what table each row of the results came from. I was won...
<python><sql-server><dataframe><stored-procedures>
2022-12-29 17:31:27
0
379
Buzzkillionair
74,954,233
4,478,466
How to get static files to work when testing the Flask REST API with flask_testing framework
<p>I'm making a Flask REST API with Flask-RESTX library. One part of API are also calls that generate PDF documents. To generate documents I'm using some font files and images from the <code>static/</code> directory. Everything is working when I'm running the API, but when I'm trying to call the same calls from my test...
<python><flask>
2022-12-29 17:26:59
1
658
Denis Vitez
74,954,027
12,596,824
Dataframe with Path column - creating new columns
<p>I have the following dataframe. I want to create new columns based on the FilePath column.</p> <pre><code>FilePath S:\\colab\a.csv S:\\colab\b.csv S:\\colab\c.csv S:\\colab\apple\dog.txt S:\\colab\apple\cat.pdf </code></pre> <p>Below is the expected output. I want to get the hierarchy of the files in a string and co...
<python><pandas><path>
2022-12-29 17:04:38
1
1,937
Eisen
74,953,960
14,141,126
Send email with plain text and html attachment
<p>I'm trying to send email that contain both plain text in the body and html attachment. I've succeeded in adding the attachment but can't figure out how to add the plain text to the body. Any help is appreciated.</p> <p>Here is the code:</p> <pre><code>from email.mime.multipart import MIMEMultipart from email.mime.ba...
<python>
2022-12-29 16:57:20
1
959
Robin Sage
74,953,923
5,398,127
Prophet CMDStanpy error - Procedure Entry Point Not Located
<p>I am trying to use prophet library.</p> <p>The 'cmdstanpy' and 'prophet' packages are successfully installed. But I am getting this error while running my model - &quot;The procedure entry point _ZNt3bb19task_scheduler_init10initilaizeEiy could not be located in the dynamic link library D:/ProgramData/ Anaconda3/Lib...
<python><model-fitting><prophet>
2022-12-29 16:53:20
1
3,480
Stupid_Intern
74,953,856
7,148,573
Flask traceback only shows external libraries
<p>I'm running a Flask app and get the following error message:</p> <pre><code> * Debugger is active! * Debugger PIN: ****** 127.0.0.1 - - [29/Dec/2022 12:21:53] &quot;GET /authorization/****/authorize HTTP/1.1&quot; 302 - 127.0.0.1 - - [29/Dec/2022 12:21:53] &quot;GET /authorization/****/test HTTP/1.1&quot; 500 - Tra...
<python><flask>
2022-12-29 16:48:07
1
1,740
Raphael
74,953,822
9,182,743
Separate script's functions into modules, callable by 2 separate mains
<p>I have a single script that:</p> <ol start="0"> <li>imports 2 sets of data: df_height['user', 'height'], df_age['user', 'age']</li> <li>clean the data</li> <li>analyse the data: i) sum(height), ii) mean(age), iii) sum(height) * mean(age)</li> <li>display the data.</li> </ol> <p>I want to:</p> <ul> <li>Separate the f...
<python><import><module><project>
2022-12-29 16:45:15
1
1,168
Leo
74,953,809
18,110,596
Select the rows with top values until the sum value reach the 30% of total value in Python Pandas
<p>I'm using Python pandas and have a data frame that is pulled from my CSV file:</p> <pre><code>ID Value 123 10 432 14 213 12 ''' 214 2 999 43 </code></pre> <p>I was advised using the following code can randomly select some rows with the condition that the sum of the se...
<python><pandas>
2022-12-29 16:44:02
2
359
Mary
74,953,747
192,204
Why is the spaCy Scorer returning None for the entity scores but the model is extracting entities?
<p>I am really confused why the Scorer.score is returning ents_p, ents_r, and ents_f as None for the below example. I am seeing something every similar with my own custom model and want to understand why it is returning None?</p> <p><strong>Example Scorer Code - Returning None for ents_p, ents_r, ents_f</strong></p> <p...
<python><spacy><named-entity-recognition><precision-recall>
2022-12-29 16:37:40
2
9,234
scarpacci
74,953,725
12,065,403
Efficient file format to store nested objects
<p>I am working on a python project where I have nested objects. I know the structure of each entity. I am looking for a way to save it.</p> <p><strong>Here is a very simple example:</strong></p> <p>A User always have:</p> <ul> <li>an id (int)</li> <li>a name: (string)</li> <li>a list of items (0, 1 or many)</li> </ul>...
<python>
2022-12-29 16:34:54
0
1,288
Vince M
74,953,674
15,725,039
Need to output a function That takes in strings and ints in python
<p>The function in question is:</p> <pre><code>switch({source}, condition1, Condition Nth, value1, value Nth) </code></pre> <p>The Way I need to output it involves using 0 and 1s (True/False) and will look like this:</p> <pre><code>&quot;switch([.]ALARM,1,0,On,Off, Unknown)&quot; </code></pre> <p>Where the 1 and 0 need...
<python><string><formatting><format><concatenation>
2022-12-29 16:30:11
1
330
JQTs
74,953,624
2,998,077
Python to bin calculated results from a function
<p>A function is defined to perform some calculation (in this example, it's to sum). The calculated result is to be put into bins (of each 10 as an interval, such as &lt;10, 10-19, 20-29 etc).</p> <p>What is the smart way to do so?</p> <p>I have a dump way, which created a dictionary to list all the possible calculated...
<python><function>
2022-12-29 16:25:17
1
9,496
Mark K
74,953,594
14,558,228
how to create cascade window in python3 win32gui
<p>i want to cascade window in pywin32 module. i use: <code>win32gui.CascadeWindow()</code> but rased an error:</p> <blockquote> <p>AttributeError: module 'win32gui' has no attribute 'CascadeWindow'. how can i fix this?</p> </blockquote> <p>AttributeError: module 'win32gui' has no attribute 'CascadeWindow'. Did you mea...
<python><windows><winapi><pywin32><windows-api-code-pack>
2022-12-29 16:22:13
1
453
xander karimi
74,953,540
4,391,249
What is `np.ndarray[Any, np.dtype[np.float64]]` and why does `np.typing.NDArray[np.float64]` alias it?
<p>The <a href="https://numpy.org/devdocs/reference/typing.html" rel="nofollow noreferrer">documentation</a> for <code>np.typing.NDArray</code> says that it is &quot;a generic version of <code>np.ndarray[Any, np.dtype[+ScalarType]]</code>&quot;. Where is the generalization in &quot;generic&quot; happening?</p> <p>And i...
<python><numpy><python-typing>
2022-12-29 16:17:22
1
3,347
Alexander Soare
74,953,510
3,860,847
How to pass unencoded URL in FastAPI/Swagger UI via GET method?
<p>I would like to write a FastAPI endpoint, with a Swagger page (or something similar) that will accept a non-encoded URL as input. It should preferably use <code>GET</code>, <strong>not</strong> <code>POST</code> method.</p> <p>Here's an example of a <code>GET</code> endpoint that <strong>does</strong> require double...
<python><swagger><fastapi><swagger-ui><urlencode>
2022-12-29 16:14:32
1
3,136
Mark Miller
74,953,359
3,433,489
matplotlib pcolor gives blank plot when data is a single column
<p>When I use pcolor involving meshes and data consisting of a single column, the resulting plot is just white everywhere. What am I doing wrong?</p> <pre><code>import matplotlib.pyplot as plt from numpy import array U = array([[0],[1]]) V = array([[0],[0]]) data = array([[0.4],[0.5]]) plt.pcolor(U,V,data) plt.show(...
<python><matplotlib>
2022-12-29 16:00:35
1
1,009
user3433489
74,953,271
15,263,719
is it safe to trow exception in python ThreadPool executor map?
<p>I have created this example code to try to explain what my question is about:</p> <pre class="lang-py prettyprint-override"><code>from concurrent.futures import ThreadPoolExecutor def my_method(x): if x == 2: print(&quot;error&quot;) raise Exception(&quot;Exception raised&quot;) else: p...
<python><python-3.x><concurrency><threadpool><concurrent.futures>
2022-12-29 15:51:59
1
360
Danilo Bassi
74,953,267
18,110,596
Randomly select 30% of the sum value in Python Pandas
<p>I'm using Python pandas and have a data frame that is pulled from my CSV file:</p> <pre><code>ID Value 123 10 432 14 213 12 ''' 214 2 999 43 </code></pre> <p>I want to randomly select some rows with the condition that the sum of the selected values = 30% of the tota...
<python><pandas>
2022-12-29 15:51:48
1
359
Mary
74,953,042
505,188
Python Scrape Weather Site Returns Nothing
<p>I'm trying to scrape a forecast table from wunderground. When inspecting the website, I see this: <a href="https://i.sstatic.net/KqJF2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KqJF2.png" alt="enter image description here" /></a></p> <p>Here is the code...When I run this, I get no results.</p> <...
<python><web-scraping><beautifulsoup>
2022-12-29 15:32:18
1
712
Allen
74,952,981
19,003,861
Django_filters - ModelChoiceFilter - How to filter based on the page_ID the user is visiting
<p>I would like the user to be able to filter based on categories. I am using <code>django_filters</code>.</p> <p>Two important things:</p> <ol> <li>These categories are not hard coded in the model. They are instead provided by <code>Venue</code>. <code>Venue</code> is the user the categories are displayed to.</li> <li...
<python><django><django-views><django-filter>
2022-12-29 15:26:01
1
415
PhilM
74,952,776
3,302,016
Merge 2 Dataframes using start_date & end_date
<p>I have 2 dataframes which look something like this.</p> <p>Train Departure Details (<code>data_df</code>)</p> <pre><code>pd.DataFrame(columns=['Train', 'Origin', 'Dest', 'j_type', 'bucket', 'dep_date'], data = [['AB001', 'NZM', 'JBP', 'OP', 'S1', '2022-12-27'], ['AB001', 'NZM', 'JBP...
<python><pandas>
2022-12-29 15:06:39
1
4,859
Mohan
74,952,571
2,696,230
pandas.Series.str.replace returns nan
<p>I have some text stored in pandas.Series. for example:</p> <pre><code>df.loc[496] 'therapist and friend died in ~2006 Parental/Caregiver obligations:\n' </code></pre> <p>I need to replace the number in the text with full date, so I wrote</p> <pre><code>df.str.replace( pat=r'(?:[^/])(\d{4}\b)', repl= lambda...
<python><pandas><regex><python-re>
2022-12-29 14:48:31
1
1,763
Abdulkarim Kanaan
74,952,552
10,434,565
Python and Plotly: Two sliders that controls an intersection of the data to plot
<p>I'm trying to make a plot where I have two sliders that filter on a single plot. The data is a video sequence that is generated from a ML model and is a 4-d tensor, where the dimensions are Epoch x Frame x Height x Width. Ideally, I want to have one slider over Epoch to see how each frame evolves as the ML model evo...
<python><plotly>
2022-12-29 14:46:12
0
331
truvaking
74,952,545
10,966,677
openpyxl delete rows from formatted table / error referencing table
<p>I am trying to delete rows from a formatted table in Excel using the <code>delete_rows()</code> method. However, this does not delete the rows but only the content of the cells.</p> <p>As an info, you can format a range as table using openpyxl as described in the documentation: <a href="https://openpyxl.readthedocs....
<python><excel><openpyxl>
2022-12-29 14:45:50
2
459
Domenico Spidy Tamburro
74,952,504
6,446,053
Elagent way multiplying diffrent constant value to diffrent columns in Pandas
<p>The objective is to multiply some constant value to a column in Pandas. Each column has its own constant value.</p> <p>For example, the columns <code>'a_b_c','dd_ee','ff_ff','abc','devb'</code> are multiply with constant 15,20,15,15,20, respectively.</p> <p>The constants values and its associated column is store in ...
<python><pandas><performance>
2022-12-29 14:41:27
3
3,297
rpb
74,952,320
950,275
Django and pylintt: inconsistent module reference?
<p>Possibly because of my noobness, I can't get pylint and django management commands to agree about how to import files in my project.</p> <h2>Setup</h2> <pre><code># venv cd $(mktemp -d) virtualenv venv venv/bin/pip install django pylint pylint-django # django venv/bin/django-admin startproject foo touch foo/__init__...
<python><django><pylint>
2022-12-29 14:25:42
2
380
Nitz
74,952,037
14,190,526
Python a handy way to mock/patch only "top-level" / first call to object
<p>Firstly the code:</p> <pre><code>class Foo: ... def apply_* ... ... def apply_all(self, ) -&gt; None: self.apply_goal_filter() self.apply_gender_filter() self.apply_age_filter() ... # Many apply_* </code></pre> <p>To test this function I should mock every <code>appl...
<python>
2022-12-29 13:58:00
1
1,100
salius
74,951,826
7,422,352
Correct number of workers for Gunicorn
<p>According to the Gunicorn's <a href="https://docs.gunicorn.org/en/latest/design.html#how-many-workers" rel="nofollow noreferrer">documentation</a>, the number of workers recommended are <code>(2 * #cores) + 1</code>.</p> <p>They have provided the following explanation:</p> <blockquote> <p>Generally we recommend (2 x...
<python><gunicorn>
2022-12-29 13:39:10
1
5,381
Deepak Tatyaji Ahire
74,951,747
2,039,339
Overfitted model performs poorly on training data
<p>What can be the cause of accuracy being &gt;90% while model predicts one class in 100% cases in multiclass clasification problem? I would expect that the overfitted model with high accuracy for training data will predict well on training data.</p> <p>Model:</p> <pre><code>model = tf.keras.Sequential([ tf.keras.lay...
<python><tensorflow><keras>
2022-12-29 13:31:02
1
406
Khamyl
74,951,508
6,067,528
Why is warning log not being passed through my custom formatter?
<p>I'm trying to have every log message my python application produces formatted with my custom formatter. The issue is that my application is not logging everything with my customer formatter, i.e. this RunTimeWarning:</p> <p><code>__main__:1: RuntimeWarning: divide by zero encountered in true_divide</code></p> <p>whe...
<python><logging><python-logging>
2022-12-29 13:09:17
1
1,313
Sam Comber
74,951,506
12,097,553
django query: groupby and keep rows that are the most recent
<p>I am struggling on a query that is supposed to group by a model attribute and return for each unique value of that model attribute, the row that has the most recent date.</p> <p>I can't manage to get the output that I am looking for in a way that will be digestible for my template.</p> <p>here is the model I am tryi...
<python><django>
2022-12-29 13:09:09
2
1,005
Murcielago
74,951,416
16,332,690
Adding element of a range of values to every N rows in a pandas DataFrame
<p>I have the following dataframe that is ordered and consecutive:</p> <pre class="lang-py prettyprint-override"><code> Hour value 0 1 41 1 2 5 2 3 7 3 4 107 4 5 56 5 6 64 6 7 46 7 8 50 8 9 95 9 10 81 10 11 8 11 12 ...
<python><pandas>
2022-12-29 13:00:38
2
308
brokkoo
74,951,314
5,398,127
Unable to install fastquant in new virtualenv conda
<p>In base environment I have already installed fastquant package</p> <p>but after creating and activating new conda environment I am not able to install the fastquant package.</p> <p>I already have pandas 1.5.2</p> <p>but when I install fastquant it is trying to install pandas 1.1.5 as it is a dependency</p> <pre><cod...
<python><pandas><package><anaconda><conda>
2022-12-29 12:48:00
1
3,480
Stupid_Intern
74,951,298
11,885,361
TypeError: slice indices must be integers or None or have an __index__ method error in scraping a help page
<p>I created python script to scrape <strong>facebook</strong> <em>help page</em>. I wanted to scrape <code>cms_object_id</code>, <code>cmsID</code>, <code>name</code>. so these values are in a script tag then firstly tried to find all <code>&lt;script&gt;</code> tags then tried to iterate over this and then there is <...
<python><python-3.x><web-scraping><beautifulsoup><python-requests>
2022-12-29 12:46:01
1
630
hanan
74,951,293
8,618,380
Big Query: Create table with time partitioning and clustering fields using Python
<p>I can successfully create a Big Query table in Python as:</p> <pre><code>from google.cloud import bigquery bq_client = bigquery.Client() table_name = &quot;my_test_table&quot; dataset = bq_client.dataset(&quot;MY_TEST_DATASET&quot;) table_ref = dataset.table(table_name) table = bigquery.Table(table_ref) table = bq...
<python><google-bigquery>
2022-12-29 12:44:57
1
1,975
Alessandro Ceccarelli
74,951,025
11,693,768
Covert a column of integers and interger + strings into all integers using multiplication based on what is in the string
<p>How do I convert this column of values, mostly integers, and some strings to all integers.</p> <p>The column looks like this,</p> <pre><code>x1 ___ 128455551 92571902 123125 985166 np.NaN 2241 1.50000MMM 2.5255MMM 1.2255MMMM np.NaN ... </code></pre> <p>And I want it to look like this, where the rows with MMM, the ch...
<python><pandas><dataframe><numpy>
2022-12-29 12:18:58
3
5,234
anarchy
74,951,017
9,142,914
Tensorflow 1.15, Keras 2.2.5, on_batch_end or on_train_batch_end not triggering
<p>This is my custom callblack:</p> <pre><code>class CustomCallback(keras.callbacks.Callback): def on_train_begin(self, logs=None): print(&quot;on_train_begin&quot;) def on_train_batch_end(self, batch, logs=None): print(&quot;on_train_batch_end&quot;) def on_batch_end(self, batch, logs=N...
<python><tensorflow><keras>
2022-12-29 12:18:35
1
688
ailauli69
74,950,971
10,037,034
How to solve great expectations "MetricResolutionError: Cannot compile Column object until its 'name' is assigned." Error?
<p>I am trying to use great expectations.<br /> The function I want to use is <code>expect_compound_columns_to_be_unique</code>. This is the code (main code - template):</p> <pre><code>import datetime import pandas as pd import great_expectations as ge import great_expectations.jupyter_ux from great_expectations.core...
<python><great-expectations>
2022-12-29 12:14:03
1
1,311
Sevval Kahraman
74,950,933
12,858,691
Pandas automatically infer best dtype: str to int not working
<p>On a dataframe with &gt; 100 columns I want pandas (v1.4.2) to <strong>automatically</strong> convert all columns to the &quot;best&quot; dtype. According to the docs <a href="https://pandas.pyda" rel="nofollow noreferrer">df.convert_dtypes()</a> or <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFr...
<python><pandas><dataframe><dtype>
2022-12-29 12:08:56
1
611
Viktor
74,950,904
11,665,178
Unable to import module 'lambda_function': No module named 'pymongo'
<p>I have followed this <a href="https://docs.aws.amazon.com/lambda/latest/dg/python-package.html#python-package-create-package-with-dependency" rel="nofollow noreferrer">guide</a> last year to build my AWS python archive and it was working.</p> <p>Today i have automated my code deployment and it was not working (i am ...
<python><python-3.x><amazon-web-services><aws-lambda><pymongo>
2022-12-29 12:06:17
2
2,975
Tom3652
74,950,802
10,517,777
Export features to excel after fit-transform of the TFIDFVectorizer
<p>Python Version: 3.7</p> <p>Hi everyone:</p> <p>I am using the tfidfVectorizer from the library scikit-learn as follow:</p> <pre><code>vec_body = TfidfVectorizer(**vectorizer_parameters) X_train_features = vec_body.fit_transform(X_train) </code></pre> <p><code>X_train</code> contains the email body. If I understood c...
<python><scikit-learn><tfidfvectorizer>
2022-12-29 11:54:33
1
364
sergioMoreno
74,950,760
10,639,382
Pandas Grouping Weekly Data
<p>I want to group data based on each week and found the solution in the following post, <a href="https://www.statology.org/pandas-group-by-week/" rel="nofollow noreferrer">https://www.statology.org/pandas-group-by-week/</a></p> <p>According to the post, following the two operations below allows you to group the data p...
<python><pandas>
2022-12-29 11:50:11
1
3,878
imantha
74,950,696
10,428,677
Add year values to all existing rows in dataframe
<p>I have a dataframe that looks like this:</p> <pre><code>df_dict = {'country': ['Japan','Japan','Japan','Japan','Japan','Japan','Japan', 'Greece','Greece','Greece','Greece','Greece','Greece','Greece'], 'product': [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &qu...
<python><pandas>
2022-12-29 11:44:48
1
590
A.N.
74,950,685
10,303,685
How to monitor internet connectivity using infinite while loop Python?
<p>I am using an infinite while loop to perform specific function if internet is available. And to print an statement if internet is not available. Following is the code.</p> <pre><code>import requests,time while True: print(&quot;HI&quot;) try: requests.get('https://www.google.com/').status_code ...
<python><python-3.x><python-requests><except>
2022-12-29 11:42:58
1
388
imtiaz ul Hassan
74,950,461
10,437,110
How to create a column to store trailing high value in Pandas DataFrame?
<p>Consider a DataFrame with only one column named values.</p> <pre><code>data_dict = {values:[5,4,3,8,6,1,2,9,2,10]} df = pd.DataFrame(data_dict) display(df) </code></pre> <p>The output will look something like:</p> <pre><code> values 0 5 1 4 2 3 3 8 4 6 5 1 6 2 7 9 8 2 9 10 </code></pre> <p>I w...
<python><pandas><dataframe>
2022-12-29 11:20:41
1
397
Ash
74,950,386
1,016,004
Static type hint for decorator that adds attribute to a class
<p>Is it possible to create a type hint for a class decorator that adds an attribute to the given class? Since PEP612 it's possible to use <code>ParamSpec</code> and <code>Concatenate</code> for decorators that modify signatures, but I haven't found any equivalents for decorators that modify classes.</p> <pre class="la...
<python><python-3.x><python-decorators><python-typing>
2022-12-29 11:12:47
0
6,505
Robin De Schepper
74,950,359
2,245,136
Check if a function has been called from a loop
<p>Is it possible to check dynamically whether a function has been called from within a loop?</p> <p>Example:</p> <pre><code>def some_function(): if called_from_loop: print(&quot;Hey, I'm called from a loop!&quot;) for i in range(0, 1): some_function() some_function() </code></pre> <p>Expected output:...
<python><loops>
2022-12-29 11:10:45
1
372
VIPPER
74,950,298
4,853,434
Python Kafka Consumer in docker container localhost
<p>I try to consume some messages created with a spring-boot kafka producer on localhost.</p> <p>For the consumer I have the following python code (consumer.py):</p> <pre><code>from kafka import KafkaConsumer # To consume latest messages and auto-commit offsets print(&quot;consume...&quot;) consumer = KafkaConsumer('u...
<python><docker><apache-kafka>
2022-12-29 11:04:37
1
859
simplesystems
74,950,152
6,400,443
Fastest way to calculate cosine similartity between two 2D arrays
<p>I have one array A containing 64000 embeddings and an other array B containing 12000 embeddings (each of the embedding is 1024 floats long).</p> <p>Now I want to calculate the cosine similarity for all the pairs between array A and array B (cartesian product).</p> <p>To perform that (using pandas), I merge array A w...
<python><numpy><numba>
2022-12-29 10:49:38
1
737
FairPluto
74,949,892
19,106,705
Implementing a conv2d backward in pytorch
<p>I want to implement backward function of conv2d.</p> <p>Here is an <a href="https://pytorch.org/docs/stable/notes/extending.html" rel="nofollow noreferrer">example of a linear function</a>:</p> <pre class="lang-py prettyprint-override"><code># Inherit from Function class LinearFunction(Function): @staticmethod ...
<python><pytorch><backpropagation>
2022-12-29 10:23:40
1
870
core_not_dumped
74,949,838
20,574,508
How FastAPI manages WFT Forms?
<p>I am migrating from Flask to FastAPI and it is not clear to me how FastAPI manages WTF Forms.</p> <p>I would like to use forms in Classes. However, I don't know if there is a correct way to do it in FastAPI, and if not what is the recommended solution to manage forms easily.</p> <p>Here is a code example:</p> <pre><...
<python><fastapi><wtforms>
2022-12-29 10:18:33
1
351
Nicolas-Fractal
74,949,666
6,322,082
Data cleaning in python/pyspark: Conditional (for/if) exits prematurely before all the code is applied to the data
<p>I have a problem which looks similarly to this: I have three groups of salary classes, High/Medium/Low. On each group I need to perform some operations (adding columns, cleaning, ...). However, some groups (in my code example High and Low) share several identical cleaning operations. In order to avoid code duplicati...
<python><apache-spark><pyspark>
2022-12-29 10:00:24
1
371
Largo Terranova
74,949,599
6,446,053
How to efficiently collapse recurrent columns into rows in Pandas
<p>The objective is to collapse a <code>df</code> with the following columns</p> <pre><code>['ID', 'St ti', 'Comp time', 'Email', 'Name', 'Gr Name\n', 'As Na (P1)\n', 'Fr ID (P1)\n', ' Role &amp; royce ', 'Cradle insigt', 'Co-exist network', 'Ample Tree (P1)\n', 'As Na (P2)\n', 'Fr ID (P2)\n', ' R...
<python><pandas><performance>
2022-12-29 09:53:20
1
3,297
rpb
74,949,556
3,375,378
Poetry fails to install tensorflow
<p>I've got a poetry project. My environment is Conda 22.9.0 on a windows machine with poetry version 1.2.2:</p> <p>This is my pyproject.toml file:</p> <pre><code>[tool.poetry] name = &quot;myproject&quot; version = &quot;0.1.0&quot; description = &quot;&quot; [tool.poetry.dependencies] # REVIEW DEPENDENCIES python = ...
<python><tensorflow><python-poetry>
2022-12-29 09:49:08
8
2,598
chrx
74,949,518
5,581,893
Python: await the generator end
<p>Current versions of Python (Dec 2022) still allow using @coroutine decorator and a generation can be as:</p> <pre><code>import asyncio asyncify = asyncio.coroutine data_ready = False # Status of a pipe, just to test def gen(): global data_ready while not data_ready: print(&quot;not ready&quot;) ...
<python><async-await><python-asyncio><generator><coroutine>
2022-12-29 09:45:15
1
8,759
Dan D
74,949,432
18,756,733
If list contains an item, then list equals to item
<p>I don't know how to formulate the question correctly: I have a list of lists, which contains multiple items.</p> <pre><code>mylist=[['a','b','c','₾'],['x','t','f','₾'],['a','d'],['r','y'],['c','₾'],['a','b','c','i'],['h','j','l','₾']] </code></pre> <p>If any of the lists contains symbol '₾', I want to append the sym...
<python><list>
2022-12-29 09:35:09
4
426
beridzeg45
74,949,362
20,646,427
How to show history of orders for user in Django
<p>I will pin some screenshots of my template and admin panel I have history of orders in admin panel but when im trying to show title and img of order product in user profile in my template that`s not working and i got queryset Im sorry for russian words in my site, i can rescreen my screenshots if you need that</p> <...
<python><django><django-templates>
2022-12-29 09:27:47
3
524
Zesshi
74,949,189
9,640,238
Strip tags and keep content with Beautifulsoup
<p>I thought this question would have been answered 1000 times, but apparently not (or I'm not looking right!). I want to clean up some overloaded HTML content with BeautifulSoup and remove unwanted tags. In some cases (e.g. <code>&lt;span&gt;</code> or <code>&lt;div&gt;</code>), I want to preserve the content of the t...
<python><html><beautifulsoup>
2022-12-29 09:10:08
1
2,690
mrgou
74,949,121
4,451,521
Two lists in python. Check when the elements are of the same sign
<p>I have two lists in python</p> <pre><code>list1=[1,3,5,-3,-3] list2=[2,-3,3,-3,5] </code></pre> <p>I want to produce a list that is true when the elements are of the same sign</p> <pre><code>result=[True,False,True,True,False] </code></pre> <p>which is the fastest and more pythonic way to do this?</p> <p>EDIT:</p> <...
<python>
2022-12-29 09:02:31
1
10,576
KansaiRobot
74,949,106
360,274
Consistently coloring tracks by elevation across multiple maps with gpxplotter
<p>I use <a href="https://gpxplotter.readthedocs.io/en/latest/" rel="nofollow noreferrer">gpxplotter</a> and <a href="https://python-visualization.github.io/folium/" rel="nofollow noreferrer">folium</a> to generate maps from GPX tracks. I use the following <a href="https://gpxplotter.readthedocs.io/en/latest/source/gpx...
<python><maps><folium><gpx>
2022-12-29 09:01:12
1
2,194
martin
74,948,945
4,451,521
How can I use fill_between if the points I have are array with single value
<p>I have a matplotlib script.</p> <p>In it in the end I have</p> <pre><code>x_val=[x[0] for x in lista] y_val=[x[1] for x in lista] z_val=[x[2] for x in lista] ax.plot(x_val,y_val,'.-') ax.plot(x_val,z_val,'.-') </code></pre> <p>This script plots well <em>eventhough</em> the values in <code>y_val</code> and <code>z_v...
<python><matplotlib>
2022-12-29 08:44:38
1
10,576
KansaiRobot
74,948,609
14,457,833
The PyQt5 programme automatically stops working after some time when using setTextCursor()
<p>I have a <strong>PyQt5 GUI</strong> that is in charge of taking voice input from the user and converting it to text. </p> <p>Everything was fine until I was told to add a new feature where the user can edit text while speaking. The cursor should not move to the start or end of a paragraph; it should stay where it is...
<python><linux><qt><pyqt5><pyaudio>
2022-12-29 08:03:22
1
4,765
Ankit Tiwari
74,948,525
20,051,041
FutureWarning: save is not part of the public API in Python
<p>I am using Python to convert Pandas df to .xlsx (in Plotly-Dash app.). All working well so far but with this warning tho:</p> <p><strong>&quot;FutureWarning: save is not part of the public API, usage can give unexpected results and will be removed in a future version&quot;</strong></p> <p>How should I modify the cod...
<python><excel><warnings>
2022-12-29 07:51:00
2
580
Mr.Slow
74,948,340
5,336,651
How to generate complex Hypothesis data frames with internal row and column dependencies?
<p>Is there an elegant way of using <code>hypothesis</code> to directly generate complex <code>pandas</code> data frames with internal row and column dependencies? Let's say I want columns such as:</p> <pre><code>[longitude][latitude][some-text-meta][some-numeric-meta][numeric-data][some-junk][numeric-data][… </code></...
<python><pytest><python-hypothesis>
2022-12-29 07:28:56
1
401
curlew77
74,948,277
17,696,880
How to operate with dates that dont have a 4-digit year? Is it possible extract this year number and adapt it so that datetime can operate with this?
<p>I was having a <code>ValueError</code> every time I tried to pass a date whose years are not 4 digits to some function of the <code>datetime</code> module, in this case the operation to be performed is to add or subtract days</p> <pre class="lang-py prettyprint-override"><code>import datetime def add_or_subtract_da...
<python><python-3.x><regex><datetime><python-datetime>
2022-12-29 07:21:35
1
875
Matt095
74,948,261
16,186,109
Is there any way to connect my google calendar to google colab?
<p>I created a project using the Google Cloud Console and created an OAuth screen. But when I used Python in colab to access the calendar, I got an error message that I don't have a proper redirect uri. Is there any way to bypass accessing my Google Calendar with my login credentials rather than using an access token <...
<python><google-colaboratory><google-calendar-api>
2022-12-29 07:19:31
0
325
Vinasirajan Vilakshan
74,948,111
7,959,614
Get shape parameters of scipy.stats.beta from shape of PDF
<p>I have the following script from the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html" rel="nofollow noreferrer">docs</a></p> <pre><code>import numpy as np import scipy.stats as ss import matplotlib.pyplot as plt fig, ax = plt.subplots(1) a = 1.25 b = 1.5 x = np.linspace(ss.bet...
<python><scipy>
2022-12-29 06:55:20
1
406
HJA24
74,947,992
17,374,216
How to remove the error "SystemError: initialization of _internal failed without raising an exception"
<p>I am trying to import Top2Vec package for nlp topic modelling. But even after upgrading pip, numpy this error is coming.</p> <p>I tried</p> <pre><code>pip install --upgrade pip </code></pre> <pre><code>pip install --upgrade numpy </code></pre> <p>I was expecting to run</p> <pre><code>from top2vec import Top2Vec mod...
<python><import><nlp><google-colaboratory>
2022-12-29 06:37:49
5
571
Sayonita Ghosh Roy
74,947,797
17,103,465
Fetching the column values from another table to create a new column in the main table : Pandas Merging with square brackets
<p>As you can see below, I have two tables main table and reference table . In the main table I have a column 'Subject' which contains tr_id within the '[]' separated by ',' . I have it to match with my reference table using the 'tr_id' to fetch the 'test_no' as 'Linked_Test_No' in my main table.</p> <p>main table :</...
<python><pandas>
2022-12-29 06:04:54
1
349
Ash
74,947,815
889,213
numpy.vectorize: "ValueError: setting an array element with a sequence"
<p>I'm having trouble when using np.vectorize in my code:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from sklearn.neighbors import KNeighborsClassifier length = 1000 evens = np.array([np.arange(0, length*2, 2)]) odds = np.array([np.arange(1, length*2, 2)]) zeroes = np.array([np.resize([[0...
<python><numpy>
2022-12-29 06:01:14
0
7,458
thiagoh
74,947,583
2,878,290
PyArrow Issues in Dataframe
<p>I am using Prophet lib to develop the analytics data but if we are using different source of the data, we are encountering as below kind of error.</p> <blockquote> <p>PythonException: An exception was thrown from a UDF: 'pyarrow.lib.ArrowTypeError: Expected a string or bytes dtype, got float64</p> </blockquote> <p>C...
<python><dataframe><pyspark><pyarrow>
2022-12-29 05:27:50
0
382
Developer Rajinikanth
74,947,546
7,959,614
Selenium driver get_log() stops suddenly
<p>I have a script that creates multiple <code>selenium.webdriver</code>-instances, executes a js-script and reads the resulting logs of them. Most of the time the script runs without problems, but in a few cases the logs suddenly stop <em>after running for a while</em>. I am not sure how to mimic the error.</p> <p>My ...
<python><multithreading><selenium>
2022-12-29 05:21:08
2
406
HJA24
74,947,485
3,899,975
Horizontal barplot with offset in seaborn
<p>My dataset is like this, where the data points in each row or column are pandas objects. <a href="https://i.sstatic.net/QmDGR.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/QmDGR.png" alt="enter image description here" /></a></p> <p>Here is the dataset: <a href="https://github.com/aebk2015/multiplebo...
<python><matplotlib><seaborn>
2022-12-29 05:12:39
1
1,021
A.E
74,947,453
16,869,946
Returning most recent row with certain values in Pandas
<p>I have a dataframe sorted by <code>ID</code> and in descending order of Date in Pandas that looks like</p> <pre><code>ID Date A Salary 1 2022-12-01 2 100 1 2022-11-11 3 200 1 2022-10-25 1 150 1 2022-05-17 4 160 2 2022-12-01 2 170 2 2022-11-19 1 220 2 2022-10-10 1 160 3 2022-11-11 3 35...
<python><python-3.x><pandas><dataframe><datetime>
2022-12-29 05:05:36
2
592
Ishigami
74,947,421
2,956,053
Do pyperclip3 or pasteboard support paste of PNG on macOS
<p>I am trying to figure out how to paste a PNG graphic from the clipboard into a Python script on macOS. I have looked into using the pyperclip, pyperclip3, and pasteboard modules. I cannot get any of these to work. I am able to paste text from the clipboard, but not PNG.</p> <p>The project description for <a href=...
<python><macos><pyperclip><pasteboard>
2022-12-29 05:00:05
2
586
MikeMayer67
74,947,287
6,291,574
how to merge next nearest data points using a common datetime stamp value for a group?
<p>I have two data frames like the samples given below:</p> <pre><code>df1 = pd.DataFrame({&quot;items&quot;:[&quot;i1&quot;, &quot;i1&quot;, &quot;i1&quot;, &quot;i2&quot;,&quot;i2&quot;, &quot;i2&quot;], &quot;dates&quot;:[&quot;09-Nov-2022&quot;, &quot;10-Aug-2022&quot;, &quot;27-May-2022&quot;, &quot;20-Oct-2022&qu...
<python><pandas><dataframe><group-by><data-science>
2022-12-29 04:36:20
1
1,741
durjoy
74,947,247
6,210,219
Update series values with a difference of 1
<p>I have a certain series on in dataframe.</p> <pre><code>df=pd.DataFrame() df['yMax'] = [127, 300, 300, 322, 322, 322, 322, 344, 344, 344, 366, 366, 367, 367, 367, 388, 388, 388, 388, 389, 389, 402, 403, 403, 403] </code></pre> <p>For values very close to one another, say, with a difference of 1, I would like to obli...
<python><arrays><pandas><dataframe><series>
2022-12-29 04:27:08
1
728
Sati