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,166,767
1,659,362
Improve Pandas performance for very large dataframes?
<p>I have a few Pandas dataframes with several millions of rows each. The dataframes have columns containing JSON objects each with 100+ fields. I have a set of 24 functions that run sequentially on the dataframes, process the JSON (for example, compute some string distance between two fields in the JSON) and return a ...
<python><pandas><dataframe><performance>
2023-01-19 00:47:16
1
549
hologram
75,166,765
3,247,006
"formfield_overrides" vs "formfield_for_dbfield()" vs "form" vs "get_form()" to change the width of the field in Django Admin
<p>For example, there is <strong><code>Person</code> model</strong> below:</p> <pre class="lang-py prettyprint-override"><code># &quot;models.py&quot; from django.db import models class Person(models.Model): name = models.CharField(max_length=20) age = models.PositiveSmallIntegerField() def __str__(s...
<python><django><django-models><django-admin><django-widget>
2023-01-19 00:47:12
1
42,516
Super Kai - Kazuya Ito
75,166,575
687,739
Binary incompatibility after Cythoning on Mac M2
<p>I have a custom module that includes a <code>setup.py</code> file.</p> <p>I run <code>python setup.py build_ext --inplace</code> in a Conda-built virtual environment on an M2 Mac.</p> <p>I get the following runtime error during runtime (truncated):</p> <p><code>ValueError: libs.portfolio_manager.lib.adjustment.Adjus...
<python><cython>
2023-01-19 00:14:56
0
15,646
Jason Strimpel
75,166,572
9,470,078
Numpy split that returns an ndarray
<p>Is there a method analogous to <code>numpy.split</code> that returns a <code>numpy.ndarray</code> instead of a <code>list</code>? Assuming that the array splits evenly is fine (to prevent jagged arrays).</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>x = np.arange(9.0) print(np.split(x, 3)) ...
<python><numpy>
2023-01-19 00:14:29
1
1,157
Monolith
75,166,505
9,543,330
keep the same name until value = true in another pandas column
<p>I have a dataframe with 3 columns: <code>session_id</code>, <code>name</code>, <code>reset_flag</code>.</p> <p>I need to make a new column, <code>new_name</code>, where the new name will be set to the first <code>name</code> where <code>reset_flag=True</code>, and then it will continue as that name WITHIN that sess...
<python><pandas>
2023-01-19 00:03:53
3
1,094
yulGM
75,166,456
9,749,124
How to set colours with big contrast on Matplotlib scatter plot
<p>I want to plot scatter plot of my clusters. I have done it with this:</p> <pre><code>figure(figsize=(22, 25), dpi = 80) plt.scatter(reduced_features[:, 0], reduced_features[:,1], c = kmeans.predict(vec_matrix_pca), s = 7) plt.scatter(reduced_cluster_centers[:, 0], reduced_cluster_centers[:, 1], marker = 'x', s = 120...
<python><matplotlib>
2023-01-18 23:55:13
1
3,923
taga
75,166,348
640,558
group by removing column I'd like to group by in pandas
<p>I'm trying to take a list of list and then add it to pandas to sum up by one value.</p> <p>My list of list:</p> <pre><code>[['she', 'walked', 4], ['she', 'my', 3], ['she', 'dog', 2], ['she', 'to', 1], ['sniffed', 'I', 5], ['sniffed', 'walked', 4], ['sniffed', 'my', 3], ['sniffed', 'dog', 2], ['sniffed', 'to'...
<python><pandas>
2023-01-18 23:35:13
1
26,167
Lostsoul
75,166,262
875,295
When is the fork of preload done in gunicorn?
<p>I'm trying to understand something that I don't think is in the doc of gunicorn. For the feature <code>preload_app</code> it says <code>Load application code before the worker processes are forked.</code> , but when is the process actually forked, and how can gunicorn know when it should fork ?</p> <p>For instance, ...
<python><fastapi><gunicorn>
2023-01-18 23:20:01
0
8,114
lezebulon
75,166,187
306,296
How do I determine that a folder really exists in a Streamed Google Drive?
<p>I have a Google Drive that had a large number of changes accidentally made to its file and folder structure externally, which I am trying to undo. I am trying to run a Python script on a Windows machine (disconnected from the Internet, so not currently syncing said Google Drive) that has a previous version of the fo...
<python><os.walk><scandir>
2023-01-18 23:06:00
0
484
allenrabinovich
75,166,140
14,355,404
How to connect to Azure Devops git repo through databricks?
<p>I want to create a python notebook in databricks that will do the following -</p> <ol> <li>Connect to Azure Devops Git repo</li> <li>Make couple of changes in a yaml file</li> <li>Commit the changes in the master branch</li> <li>Push the changes back to repo</li> </ol> <p>I tried the below code to achieve step 1:</p...
<python><git><azure-devops><databricks-repos>
2023-01-18 22:58:39
0
389
user19930511
75,165,837
7,984,318
pandas how to count boolean column value and the distinct count of other columns at the same time
<p>I have a Dataframe df, you can have it by running the following code:</p> <pre><code>import pandas as pd from io import StringIO df = &quot;&quot;&quot; month status_review supply_review case_id 2023-01-01 False False 12 2023-01-01 ...
<python><python-3.x><pandas><dataframe>
2023-01-18 22:18:10
2
4,094
William
75,165,794
3,728,901
Cannot install keras on Windows OS
<p>Environment: Windows 11 x64, run CMD as Administrator, command</p> <pre><code>pip install keras </code></pre> <p>Console log</p> <pre><code>Microsoft Windows [Version 10.0.22621.1105] (c) Microsoft Corporation. All rights reserved. C:\Windows\System32&gt;conda install -c conda-forge tensorflow Collecting package me...
<python><tensorflow><keras><pip>
2023-01-18 22:12:16
1
53,313
Vy Do
75,165,781
3,763,616
How to round numbers in place in a string in python
<p>I'd like to take some numbers that are in a string in python, round them to <strong>2 decimal spots</strong> in place and return them. So for example if there is:</p> <pre><code>&quot;The values in this string are 245.783634 and the other value is: 25.21694&quot; </code></pre> <p>I'd like to have the string read:</...
<python><rounding>
2023-01-18 22:09:16
4
489
Drthm1456
75,165,770
5,032,387
Beta distribution with bounds at [0.1, 0.5]
<p>I'd like to construct a beta distribution where the mu and sigma are 0.28 and 0.003, respectively, and the distribution is bound at [0.1, 0.5].</p> <pre><code>import numpy as np import pandas as pd import plotly.express as px from scipy import stats mu = 0.28 stdev = 0.003 lb = 0.1 ub = 0.5 def calc_alpha(x, y): ...
<python><scipy><beta-distribution>
2023-01-18 22:07:20
2
3,080
matsuo_basho
75,165,751
6,282,633
How to safely cast a python variable to a literal type?
<p>Say I have an arbitrary value, how do I check that the value is a valid value for a given literal type?</p> <p>Some explanation or useful examples what i expected:</p> <pre class="lang-py prettyprint-override"><code>KnownFormats = Literal[&quot;json&quot;, &quot;py&quot;, &quot;txt&quot;] def do_something(format: Kn...
<python><python-typing>
2023-01-18 22:04:25
1
674
Michael Chen
75,165,745
1,330,719
Cannot determine if type of field in a Pydantic model is of type List
<p>I am trying to automatically convert a Pydantic model to a DB schema. To do that, I am recursively looping through a Pydantic model's fields to determine the type of field.</p> <p>As an example, I have this simple model:</p> <pre class="lang-py prettyprint-override"><code>from typing import List from pydantic import...
<python><python-typing><pydantic>
2023-01-18 22:03:55
2
1,269
rbhalla
75,165,736
3,728,901
Collecting package metadata (current_repodata.json): failed
<p>Environment: Windows 11 x64, run CMD as Administrator:</p> <pre><code>conda install -c conda-forge tensorflow </code></pre> <p>Error</p> <pre><code>Microsoft Windows [Version 10.0.22621.1105] (c) Microsoft Corporation. All rights reserved. C:\Windows\System32&gt;conda install -c conda-forge tensorflow Collecting pa...
<python><tensorflow><anaconda><conda>
2023-01-18 22:02:39
0
53,313
Vy Do
75,165,690
3,611,472
Keep the sum of two objects updated as one (or both) objects gets updated
<p>I want to create a class in Python that implements a <code>__add__</code> object method that allows summing two objects of the same class. Let's call this class <code>Indicator</code> and the two objects to sum <code>ind1</code> and <code>ind2</code>. The <code>Indicator</code> object has only one property <code>ele...
<python><class>
2023-01-18 21:55:44
3
443
apt45
75,165,684
13,218,664
Is there a way to connect to the database after the initial connection is made using mysql-connector?
<p>I am trying to connect to a MYSQL instance using <code>mysql.connector</code> for python. Once the initial connection is established, I want to connect to the database as input by the user. Here is my implementation:</p> <pre class="lang-py prettyprint-override"><code>... import mysql.connector as sqlcon connectio...
<python><mysql><mysql-connector-python>
2023-01-18 21:55:08
1
342
ag2byte
75,165,452
5,623,899
VSCode and Jupyter Notebooks on WSL2. Previewing a notebook and then closing the window results in a "unsaved changes" warning. What is this?
<p>VSCode and Jupyter Notebooks on WSL2. Previewing a notebook and then closing the window results in a &quot;unsaved changes&quot; warning. What is this?</p> <p>What did I do?</p> <ul> <li>open a project with vs code <code>code /path/to/project</code></li> <li><code>git pull</code> to make sure everything is up to dat...
<python><visual-studio-code><jupyter-notebook>
2023-01-18 21:25:41
0
5,218
SumNeuron
75,165,431
12,436,050
Regex to extract substring from pandas DataFrame column
<p>I have following column in a DataFrame.</p> <pre class="lang-py prettyprint-override"><code>col1 ['SNOMEDCT_US:32113001', 'UMLS:C0265660'] ['UMLS:C2674738', 'UMLS:C2674739'] ['UMLS:C1290857', 'SNOMEDCT_US:118930001', 'UMLS:C123455'] </code></pre> <p>I would like extract the value after UMLS: and store it in another ...
<python><pandas><string><list><dataframe>
2023-01-18 21:22:46
2
1,495
rshar
75,165,383
15,781,591
How make stacked bar chart from dataframe in python
<p>I have the following dataframe:</p> <pre><code> Color Level Proportion ------------------------------------- 0 Blue 1 0.1 1 Blue 2 0.3 2 Blue 3 0.6 3 Red 1 0.2 4 Red 2 0.5 5 Red...
<python><pandas><matplotlib><bar-chart>
2023-01-18 21:16:41
2
641
LostinSpatialAnalysis
75,165,351
6,342,337
How can I return progress_hook for yt_dlp using FastAPI to end user?
<p>Relevant portion of my code looks something like this:</p> <pre><code>@directory_router.get(&quot;/youtube-dl/{relative_path:path}&quot;, tags=[&quot;directory&quot;]) def youtube_dl(relative_path, url, name=&quot;&quot;): &quot;&quot;&quot; Download &quot;&quot;&quot; relative_path, _ = set_path(re...
<python><fastapi><yt-dlp>
2023-01-18 21:12:49
1
1,837
ScipioAfricanus
75,165,283
1,148,979
Modbus home assistant and python struct (little endian, big endian, negative values from uint16)
<p>I have a question regarding to modbus settings. I have read the documentation carefully, tried to search some topics, but unfortunately I did not find an answer to my problem.</p> <p>I have a heat pump, which is able to communicate through modbus. In the past without HA I had my own application on ESP8266, reading t...
<python><endianness><modbus><home-assistant><uint16>
2023-01-18 21:04:52
2
1,048
tomdelahaba
75,165,254
4,133,188
Row-wise sorting a batch of pytorch tensors by column value
<p>I would like to sort each row in a <code>bxmxn</code> pytorch tensor (where <code>b</code> represents the batch size) by the k-th column value in each row. So my input tensor is <code>bxmxn</code>, and my output tensor is also <code>bxmxn</code> with the rows of each <code>mxn</code> tensor rearranged based on the k...
<python><pytorch>
2023-01-18 21:01:58
1
771
BeginnersMindTruly
75,165,180
10,705,248
How to fit and calculate conditional probability of copula in Python
<p>I would like to fit a copula to a dataframe with 2 columns: <code>a</code> and <code>b</code>. Then I have to calculate the conditional probability of <code>a</code> &lt; 0, when <code>b</code>&lt;-2 (i.e. P(a&lt;0|b&lt;-1).</p> <p>I have tried the following code in python using the library <code>copula</code>; I am...
<python><cdf><probability-distribution>
2023-01-18 20:54:35
1
854
lsr729
75,165,064
4,418,481
Make Dash callback return results while it is still executing
<p>I'm creating a Dash app and in some parts of it, I have a button and a loader.</p> <p>Once the user clicks the button, I want the loader to appear while the calculations are performed (might take 1-2 minutes) and when it's done to remove the loader.</p> <p>In order to do so, I created a callback that has as an input...
<python><callback><plotly-dash>
2023-01-18 20:41:22
2
1,859
Ben
75,165,026
4,029,467
How to keep html entity such as `&#9746` intact in beautiful soup?
<p>My goal is to read an html document using beautiful soup, add <code>ids</code> to some tags and write the html back to file.</p> <p>The html document has html entities such as <code>&amp;#9746</code> representing <code>☒</code>. When I create a beautiful soup object, the html entity gets converted to <code>☒</code>....
<python><html><beautifulsoup>
2023-01-18 20:37:21
1
399
kyc12
75,164,984
13,488,334
Python - View & remove all unused dependencies in requirements.txt
<p>Somewhere along the way, the requirements.txt in my Python application has become extremely bloated. There are 100+ dependencies listed and iteratively going through it and removing each dependency until the application breaks is not an option.</p> <p>Does anyone know of a tool that can show which packages in the re...
<python><dependencies><python-packaging><requirements.txt>
2023-01-18 20:32:51
2
394
wisenickel
75,164,945
7,984,318
pandas how to count column boolean value that based on group
<p>I have a Dataframe df ,you can have it by running the following code:</p> <pre><code>import pandas as pd from io import StringIO df = &quot;&quot;&quot; month status_review supply_review 2023-01-01 False False 2023-01-01 True ...
<python><pandas><dataframe>
2023-01-18 20:28:46
3
4,094
William
75,164,872
3,507,584
Bar polar with areas proportional to values
<p>Based on <a href="https://stackoverflow.com/questions/75126470/barplot-based-on-coloured-sectors/75128286#75128286">this question</a> I have the plot below. The issue is plotly misaligns the proportion between plot area and data value. I mean, higher values (e.g. going from 0.5 to 0.6) lead to a large increase in ar...
<python><plotly><bar-chart><polar-coordinates><plotly-express>
2023-01-18 20:19:31
1
3,689
User981636
75,164,809
5,212,614
How can we do Dense Rank on a field in a dataframe?
<p>I am trying to dense rank a field, from the highest number (lowest rank) to the lowest number (highest rank). I tried this.</p> <pre><code>df['DenseRank'] = df['CountsOfCircuits'].rank(ascending=False) </code></pre> <p>The max number I have in 'CountsOfCircuits' is 804. I want this to be ranked as 1, but I'm getting...
<python><python-3.x><dataframe><rank>
2023-01-18 20:12:54
0
20,492
ASH
75,164,772
15,376,262
Expand list of dates by incrementing dates by one day in python
<p>In Python I have a list of dates as strings:</p> <pre><code>dates = ['2022-01-01', '2022-01-08', '2022-01-21'] </code></pre> <p>I would like to increment these dates by one day and add them to this list, like so:</p> <pre><code>dates_new = ['2022-01-01', '2022-01-02', '2022-01-08', '2022-01-09', '2022-01-21', '2022-...
<python><list><date>
2023-01-18 20:09:25
3
479
sampeterson
75,164,716
4,133,188
Finding closest matches (by distance metric) in two batches of pytorch tensors
<p>I am trying to find the closest matches between two batches of pytorch tensors. Assuming I have a batch of <code>mxn</code> tensors with batch size <code>b1</code> and a batch of <code>mxn</code> tensors with batch size <code>b2</code>, I would like to find:</p> <ul> <li>The distance between each <code>mxn</code> t...
<python><pytorch>
2023-01-18 20:04:19
1
771
BeginnersMindTruly
75,164,640
707,145
Facing issues when running a shiny app for Python locally
<p>I want to run <a href="/questions/tagged/shiny" class="post-tag" title="show questions tagged &#39;shiny&#39;" aria-label="show questions tagged &#39;shiny&#39;" rel="tag" aria-labelledby="shiny-container">shiny</a> app for <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&...
<python><cmd><py-shiny>
2023-01-18 19:56:17
1
24,136
MYaseen208
75,164,598
5,224,236
how to handle sign-in popups with python selenium
<p>Using selenium I need to handle this Chrome popup on a virtual machine, even when the remote desktop connection to it is closed.</p> <p><a href="https://i.sstatic.net/ep1s9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ep1s9.png" alt="enter image description here" /></a></p> <p>I manage to get the c...
<javascript><python><selenium>
2023-01-18 19:51:38
3
6,028
gaut
75,164,545
396,014
InportError: cannot import 'Node2Vec'
<p>I am trying to use node2vec and I can't get past the import section:</p> <pre><code>import networkx as nx from node2vec import Node2Vec </code></pre> <p>Second line throws error</p> <pre><code>Traceback (most recent call last): File &quot;node2vec2.py&quot;, line 2, in &lt;module&gt; from node2vec import Node2...
<python><git>
2023-01-18 19:46:39
1
1,001
Steve
75,164,413
5,223,033
For a given wikipedia article, find all wikipedia articles containing hyperlink to the input article in the text
<p>Let me try to explain my problem: For a Wikipedia article url, Let's say Yann LeCun (<a href="https://en.wikipedia.org/wiki/Yann_LeCun" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Yann_LeCun</a>), I would like to retrieve URLs of wikipedia articles that contains a word with this hyperlink. In this case, ...
<python><wikipedia><wikipedia-api>
2023-01-18 19:32:34
1
1,844
zwlayer
75,164,370
11,670,455
Python Polars: how to convert a list of dictionaries to polars dataframe without using pandas
<p>I have a list of dictionaries like this:</p> <pre><code>[{&quot;id&quot;: 1, &quot;name&quot;: &quot;Joe&quot;, &quot;lastname&quot;: &quot;Bloggs&quot;}, {&quot;id&quot;: 2, &quot;name&quot;: &quot;Bob&quot;, &quot;lastname&quot;: &quot;Wilson&quot;}] </code></pre> <p>And I would like to transform it to a polars da...
<python><python-polars>
2023-01-18 19:28:43
2
379
Frank Jimenez
75,164,339
14,167,846
Supblots to include radar plot
<p>I'm running into issues with some subplots. I've provided some sample code to generate the types of plots I would like to create. I'd like these to be the same size, side by side.</p> <p>I'm am having a really hard time figuring out how to create the subplots though. I keep running into some issues with the thetag...
<python><matplotlib><subplot><radar-chart>
2023-01-18 19:25:59
1
545
pkpto39
75,164,321
10,256,274
get xml comment using python
<p>I am trying to get the comment from my xml file, but do not know how. The reason is because currently the xml doesnt have time data, but it is located in the comment. I wanted to grab <code>18 OCT 2022 1:40:55 PM</code> and convert it into epoch timestamp. Can someone help me?</p> <pre><code>&lt;!-- My Movies, Gene...
<python><xml>
2023-01-18 19:24:15
1
429
Nelly Yuki
75,164,206
12,875,823
FastAPI + pytest unable to clean Django ORM
<p>I'm creating a FastAPI project that integrates with the Django ORM. When running pytest though, the PostgreSQL database is not rolling back the transactions. Switching to SQLite, the SQLite database is not clearing the transactions, but it is tearing down the db (probably because SQLite uses in-memory db). I believe...
<python><django><pytest><fastapi>
2023-01-18 19:14:43
1
998
acw
75,163,923
17,696,880
Remove from a list of strings, those strings that have only empty spaces or that are made up of less than 3 alphanumeric characters
<pre class="lang-py prettyprint-override"><code>import re sentences_list = ['Hay 5 objetos rojos sobre la mesada de ahí.', 'Debajo de la mesada hay 4 objetos', '', ' ', &quot;\taa!&quot;, '\t\n \n', '\n ', 'ai\n ', 'Salto rapidamente!!!', 'y la vio volar', '!', ' aa', 'aa', 'día'] #The problem with this is that...
<python><python-3.x><regex><list><regex-group>
2023-01-18 18:44:56
2
875
Matt095
75,163,544
10,924,836
Calculating of tolerance
<p>I am working with one data set. Data contains values with different decimal places. Data and code you can see below :</p> <pre><code>data = { 'value':[9.1,10.5,11.8, 20.1,21.2,22.8, 9.5,10.3,11.9, ] } df = pd.DataFrame(data, columns = ['value'])...
<python><pandas><numpy>
2023-01-18 18:12:46
1
2,538
silent_hunter
75,163,524
859,227
Clearing the line before carriage return
<p>In the following code, I would like to show the progress of two loops with the iteration number for the outer loop and dots for the inner loop.</p> <pre><code>import time def foo(): for j in range(0,100): if j % 10 == 0: print('.', end='', flush=True, sep='') time.sleep(0.2) for ...
<python>
2023-01-18 18:10:43
0
25,175
mahmood
75,163,508
4,706,745
How to create a regular expression to replace a url?
<p>I'm trying to create a regular expression using re.sub() that can replace a URL from a string for example.</p> <pre><code>tool(id='merge_tool', server='http://localhost:8080') </code></pre> <p>I created a regular expression that returns a string something like given below.</p> <pre><code> a = &quot;https:192.168.1.1...
<python><regex>
2023-01-18 18:09:09
1
4,217
jax
75,163,472
3,352,254
Calculate the rolling mean of every n-th element over an m-element window in python
<p>Suppose I have a vector like so:</p> <pre><code>s = pd.Series(range(50)) </code></pre> <p>The rolling sum over, let's say a 2-element window is easily calculated:</p> <pre><code>s.rolling(window=2, min_periods=2).mean() </code></pre> <pre><code>0 NaN 1 0.5 2 1.5 3 2.5 4 3.5 5 4.5 6 5.5 7 6.5 ...
<python><pandas><window><rolling-computation>
2023-01-18 18:05:39
2
825
smaica
75,163,465
11,869,866
Pydantic model with Union field with one option mark as deprecated
<p>I have some Pydantic models with fields that are unions of different models. I'm looking for a way to make some models of the union deprecated in my fastapi generated doc.</p> <p>I can make the whole field deprecated with : <code>Field(default=None, deprecated=True)</code></p> <p>but i find no way to do it on one of...
<python><fastapi><swagger-ui><jsonschema><pydantic>
2023-01-18 18:04:29
1
1,339
Bastien B
75,163,410
9,118,312
pandas groupby().apply() grouping the same group again and again under different names
<p>I have a pandas data from made up of various columns. Among them are 'branch' and 'barcode', by which I would like to group the dataframe and apply a function. Something I have done thousands of times before.</p> <p>But this time it is showing behavior I've never seen before. Instead of sending each group to the fun...
<python><pandas><group-by>
2023-01-18 18:00:11
1
608
Bigga
75,163,396
8,795,358
How to convert JSON string (with double quotes in its values) to python dictionary
<p>I have some JSON files like this:</p> <pre><code>{ &quot;@context&quot;: &quot;http://schema.org&quot;, &quot;@type&quot;: &quot;Product&quot;, &quot;name&quot;: &quot;ADIZERO ADIOS PRO 2 Löparskor&quot;, &quot;@id&quot;: &quot;adidas-adizero-adios-pro-2-loparskor&quot;, &quot;color&quot;: &quot;...
<python><json><string>
2023-01-18 17:59:12
1
359
Tanhaeirad
75,163,224
16,937,053
New variable in pandas conditioned on two variables where one variable transcend multiple rows
<p>I want to add a column <code>col3</code> to my data frame <code>df</code> with the binary outcome <code>yes</code> or <code>no</code> .</p> <p>The issue is that the values in <code>col3</code> should be conditioned on <code>col1</code> and <code>col2</code> in the sense that the outcome will be <code>yes</code> if t...
<python><pandas><if-statement><conditional-statements>
2023-01-18 17:42:46
2
341
Marco Liedecke
75,163,188
6,694,814
Python - jinja2 template picks up only the first record from the data
<p>I would like to make the on-click feature with a circle coming up when clicking on the marker. So far I've developed the class which includes relevant elements as shown in the code below:</p> <pre><code>df = pd.read_csv(&quot;survey.csv&quot;) class Circle(MacroElement): def __init__(self): for i,row in df.ite...
<python><pandas><jinja2><folium>
2023-01-18 17:39:18
1
1,556
Geographos
75,163,082
9,070,040
Fix pyrIght warning "Import [module] could not be resolved"?
<p>I have the following <code>Projects</code> folder structure:</p> <p><a href="https://i.sstatic.net/bJX0v.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bJX0v.png" alt="enter image description here" /></a></p> <p>and the file <code>Tasks/Scripts/test.py</code> (shown below) attaches <code>util.py</cod...
<python><neovim><pyright><nvim-lspconfig>
2023-01-18 17:29:50
1
671
Manojit
75,163,008
12,114,641
Efficient way to open and close file with while loop in python
<p>I'm writing a crawl where I crawl pages on a website and collects links which I write in a file. I can think of two options as mentioned below. I'm using first method right now which I know is not efficient as there will be file open and close in each loop but it is safe in the sense as it will write into file and i...
<python>
2023-01-18 17:23:22
2
1,258
Raymond
75,162,837
974,555
How can I use filter predicates for a geometry column?
<p>When reading a DataFrame from a parquet file using <code>pandas.read_parquet</code>, I can use the <a href="https://arrow.apache.org/docs/python/generated/pyarrow.parquet.ParquetDataset.html" rel="nofollow noreferrer">pyarrow filters</a> API to read only a subset of rows. This equally works for geopandas. For exam...
<python><geopandas><pyarrow>
2023-01-18 17:09:54
0
26,981
gerrit
75,162,832
913,098
How to look at a previous pytest results output in Pycharm?
<p>I am running a long Pytest folder, with hundreds of tests.</p> <p>Some of them fail.</p> <p>When I fix one, I want to run it, and still have the previous long run results available. What currently happens is Pycharm only shows the last run results.</p> <p>How can I show the results of a previous pytest run in Pychar...
<python><debugging><pycharm><pytest>
2023-01-18 17:09:21
1
28,697
Gulzar
75,162,788
966,179
Is it possible to use `_getattr__`-generated methods in a subclass?
<p>I have a class whose methods may or may not be auto-generated. I want to be able to call these methods from a subclass, but can't figure out how to do that.</p> <p>Consider this code:</p> <pre><code>class Upgrader: max = 99 def _upgrade_no_op(self, db): if self.version &lt; Upgrader.max: ...
<python><inheritance>
2023-01-18 17:06:07
1
2,622
Matthias Urlichs
75,162,495
1,298,416
Comparing numbered urls in django template
<p>&quot;In urls.py I have:</p> <pre><code>path(&quot;viewer/&lt;str:case&gt;&quot;, views.viewer, name=&quot;viewer&quot;), </code></pre> <p>This works when I go to the viewer:</p> <pre><code>&lt;a class=&quot;nav-link dropdown-toggle {% if request.resolver_match.url_name == &quot;viewer&quot; %}active{% endif %}&quot...
<python><django><django-templates>
2023-01-18 16:41:42
1
341
user1298416
75,162,381
1,274,613
Python pattern for read-only attributes in a typed context
<p>Our code is quite strict in separating private, protected, and public attributes of our Python objects, following the convention that private attributes start with <code>__</code> (and are thus mangled to include the class name), protected attributes start with <code>_</code> and public attributes don't start with <...
<python><mypy><private-members>
2023-01-18 16:32:25
1
6,472
Anaphory
75,162,377
17,473,587
Apply function to specific element's value of a list of dictionaries
<pre><code>tbl_headers = db_admin.execute(&quot;SELECT name, type FROM PRAGMA_TABLE_INFO(?);&quot;, table_name) </code></pre> <p><code>tbl_headers</code> is same below:</p> <pre><code>[{'name': 'id', 'type': 'INTEGER'}, {'name': 'abasdfasd', 'type': 'TEXT'}, {'name': 'sx', 'type': 'TEXT'}, {'name': 'password', 'type': ...
<python><python-3.x><dictionary>
2023-01-18 16:32:10
1
360
parmer_110
75,162,293
14,724,837
How to read the rest in Pretty MIDI?
<p>I am using Pretty MIDI in Python. Currently, I want to use pretty midi, a python tool to read the MIDI pitch and length. <a href="https://craffel.github.io/pretty-midi/" rel="nofollow noreferrer">https://craffel.github.io/pretty-midi/</a>. However, I found that the MIDI will skip the rest and jump to the next note d...
<python><midi>
2023-01-18 16:25:51
0
689
Megan
75,162,222
17,561,414
How to change the schema of the spark dataframe
<p>I am reading a JSON file with <code>spark.read.json</code> and it automatically gives me the dataframe with schema but is it possible to change the schema of exisiting Dataframe with the below schema?</p> <pre><code>schema = StructType([StructField(&quot;_links&quot;, MapType(StringType(), MapType(StringType(), Stri...
<python><apache-spark><pyspark>
2023-01-18 16:19:42
1
735
Greencolor
75,161,984
1,977,614
Passing range of numbers from terminal to Python script
<p>I have a python script which is executed from terminal as</p> <p><code>script.py 0001</code></p> <p>where <code>0001</code> indicates the subcase to be run. If I have to run different subcases, then I use</p> <p><code>script.py 0001 0002</code></p> <p>Question is how to specify a range as input? Lets say I want to r...
<python><bash><terminal><sequence>
2023-01-18 16:02:39
2
5,858
SKPS
75,161,980
143,931
Change pandas default string format for Timestamps
<p><strong>TL;DR:</strong></p> <p>Is there a way to change the <em>default</em> string representation of <a href="https://pandas.pydata.org/docs/reference/api/pandas.Timestamp.html" rel="nofollow noreferrer">pandas' <code>Timestamp</code>s</a>?</p> <p><strong>Long version:</strong></p> <p>For example, say I was not int...
<python><pandas>
2023-01-18 16:02:24
0
8,472
fuenfundachtzig
75,161,850
10,574,250
Writing a parquet file from python that is compatible for SQL/Impala
<p>I am trying to write a pandas Dataframe to a parquet file that is compatible with a table in Impala but am struggling to find a solution.</p> <p>My df has 3 columns</p> <pre><code>code int64 number float name object </code></pre> <p>When I create this into a parquet file and load it into impala, the python schem...
<python><apache-spark><impala><pyarrow>
2023-01-18 15:51:21
1
1,555
geds133
75,161,667
1,518,100
why implement abstractmethod as staticmethod
<p>I'm learning python design patterns from github repo <a href="https://github.com/faif/python-patterns" rel="nofollow noreferrer">faif/python-patterns</a> and found the example <a href="https://github.com/faif/python-patterns/blob/master/patterns/behavioral/chain_of_responsibility.py#L52" rel="nofollow noreferrer">ch...
<python><inheritance><abstract>
2023-01-18 15:36:32
1
4,435
Lei Yang
75,161,551
9,657,938
Failed to load server-wide module `web
<p>i facing this error when i try to run odoo15 on Debian 11 server and try to run it on nginx here is the odoo log file</p> <pre><code>2023-01-18 16:35:48,178 48668 INFO ? odoo: database: odoo15@default:default 2023-01-18 16:35:48,181 48668 CRITICAL ? odoo.modules.module: Couldn't load module web 2023-01-18 16:35:48,1...
<python><odoo><odoo-15><odoo-enterprise>
2023-01-18 15:27:09
1
369
Sideeg MoHammed
75,161,513
2,396,640
Can't pause python process using debug
<p>I have a python script which starts multiple sub processes using these lines :</p> <pre><code>for elm in elements: t = multiprocessing.Process(target=sub_process,args=[elm]) threads.append(t) t.start() for t in threads: t.join() </code></pre> <p>Sometimes, for some reason the thread halts and the scr...
<python><vscode-debugger>
2023-01-18 15:23:59
2
369
user2396640
75,161,498
4,391,249
Is there a more succinct way to type hint `Union[NDArray[np.float64], Sequence[float]`?
<p>Suppose there is a function that takes numpy arrays as inputs, but it's okay if a user passes in lists (which is often the case). What's a right way to hint that:</p> <ol> <li>The function does numpy-based arithmetic.</li> <li>But it's okay to provide lists (or sequences).</li> <li>The underlying data type is <code>...
<python><numpy><typing>
2023-01-18 15:23:21
0
3,347
Alexander Soare
75,161,027
1,584,906
Accessing UVC camera controls from PyGST
<p>I'm using PyGST to display the feed from a UVC webcam inside a PyQt application. I can access some camera controls, such as brightness and contrast, directly using the corresponding properties of the <code>v4l2src</code> elements. However, I'd like to access additional controls, namely focus, available through <code...
<python><gstreamer><webcam><pygst>
2023-01-18 14:48:03
0
1,465
Wolfy
75,160,906
46,634
Python code for generating valid BIP-39 mnemonic words for a bitcoin wallet not working
<p>I am trying to generate valid <a href="https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki" rel="nofollow noreferrer">BIP-39</a> mnemonic <a href="https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt" rel="nofollow noreferrer">words</a> for a bitcoin wallet in Python, but I am encountering an ...
<python><hash><cryptography><checksum><bitcoin>
2023-01-18 14:38:42
1
3,261
Pietro Speroni
75,160,904
9,323,635
Create a history dataframe to save historical values python
<p>I need to create a history dataframe (history_df), in python, that stores the all the content of other dataset (current_df), that is being refreshed every hour.</p> <p>The contents of the current_df are being erased with the new ones because its primary key is the Robot ID column, so that´s why I need the history_df...
<python><dataframe><pyspark>
2023-01-18 14:38:38
1
771
HRDSL
75,160,879
11,542,205
Paginate data from two tables that are sorted by the creation date and located in different databases
<p>Table A is in a PostgreSQL database, while Table B is in a MongoDB database.</p> <p>I want to paginate the data in both tables programmatically and without merging them, and the result pages should be ordered by the <code>creation_date</code> attribute in both tables.</p> <hr /> <p>Example:</p> <p>Schema of table A ...
<javascript><python><java><mongodb><postgresql>
2023-01-18 14:36:48
0
1,248
Tarek Hammami
75,160,861
1,512,250
converting feet-inch string DataFrame column to centimeters
<p>I have a column of basketball players height:</p> <pre><code>0 6-10 1 6-9 2 7-2 3 6-1 4 6-6 ... 4545 6-11 4546 7-1 4547 6-1 4548 7-1 4549 6-3 </code></pre> <p>I want to convert the values from feet to cm. I made a split: <code>player_data['height'].str.sp...
<python><arrays><pandas><series>
2023-01-18 14:34:58
1
3,149
Rikki Tikki Tavi
75,160,843
5,561,649
Can exceptions still interrupt the execution when they are wrapped in an appropriate try/except block?
<p>I have some debugging code (involving <code>debugpy.connect()</code>) in a custom package, which is expected to raise an exception if the debug server isn't currently launched. The thing is, that code is wrapped in a <code>try / except Exception</code> clause, as I don't want it to interrupt the execution of the pr...
<python><exception><pip><debugpy>
2023-01-18 14:33:43
0
550
LoneCodeRanger
75,160,816
4,491,532
Bokeh iterator callbacks
<p>I just found this interesting example of using easily Bokeh widgets in a notebook.</p> <p><a href="https://github.com/bokeh/bokeh/blob/3.0.3/examples/output/jupyter/push_notebook/Jupyter%20Interactors.ipynb" rel="nofollow noreferrer">https://github.com/bokeh/bokeh/blob/3.0.3/examples/output/jupyter/push_notebook/Jup...
<python><jupyter-notebook><bokeh>
2023-01-18 14:31:48
1
357
polgia0
75,160,757
10,197,418
How to properly set binary flags in a Python polars dataframe
<p>When implementing a binary flag column in Python <strong>polars v0.15.15</strong>, I came across some seemingly weird behavior. Given a df</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ &quot;col1&quot;: [0,1,2,3], &quot;flag&quot;: [0,0,0,0] }) </cod...
<python><binary><python-polars>
2023-01-18 14:27:48
1
26,076
FObersteiner
75,160,501
7,525,747
Modify the elements of a list inside a for loop (Python equivalent of Matlab code with a nested loop)
<p>I have the following Matlab code (adopted from Programming and Numerical Methods in MATLAB by Otto&amp;Denier, page 75)</p> <pre><code>clear all p = input('Enter the power you require: '); points = p+2; n = 1:points; for N = n sums(N) = 0; for j = 1:N sums(N) = sums(N)+j^p; end end </code></pre...
<python><list><loops><matlab>
2023-01-18 14:09:02
2
579
Dimitris
75,160,262
7,184,301
Mock a Lambda Layer in AWS Lambda Function
<p>I want to unit test my AWS Lambda Function. The problem is, the Lambda Functions rely on Lambda Layers, which are called in AWS Lambda environment</p> <pre><code>import os import function from lambda_layer #this is called fine in AWS Lambda, but not locally def lambda_handler(event, context): result = function(...
<python><aws-lambda><mocking><python-unittest><aws-lambda-layers>
2023-01-18 13:50:21
1
387
James
75,160,191
11,252,809
Poetry is being overwritten in docker and I can't see why - can you spot problem?
<p>Here's the error after I try to run poetry directly (I gave up on PATH whilst troubleshooting) in a docker container:</p> <p><code>Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: &quot;~/.local/share/pypoetry/venv/bin/poe...
<python><docker><python-poetry>
2023-01-18 13:44:51
2
565
phil0s0pher
75,160,154
15,637,940
create dataclass with optional attribute
<p>I'm trying create dataclass with optional attribute <code>is_complete</code>:</p> <pre><code>from dataclasses import dataclass from typing import Optional @dataclass(frozen=True) class MyHistoricCandle: open: float high: float low: float close: float volume: int time: datetime is_comple...
<python><python-3.x><python-dataclasses><python-3.10>
2023-01-18 13:41:53
1
412
555Russich
75,160,109
2,340,127
Python3 and pytest: jinja2.exceptions.TemplateNotFound:
<p>i'm creating some unit tests and i'm facing this issue</p> <blockquote> <p>FAILED test_views_home.py::test_index - jinja2.exceptions.TemplateNotFound: index.html</p> </blockquote> <p>this is part of my testing code:</p> <pre><code>templates = Jinja2Templates('templates') def test_index(): @router.get('/', inclu...
<python><jinja2><pytest>
2023-01-18 13:38:56
2
581
emboole
75,160,060
1,103,911
Conditional assignment to multiple columns in pandas
<p>Using pandas 1.42</p> <p>Having a DataFrame with 5 columns: A, B, C, D, E</p> <p>I need to assign values from columns D and E to columns A and B if the value of column C is true. I want to achieve this in one line using the <code>.loc</code> method.</p> <h4>example</h4> <div class="s-table-container"> <table class="...
<python><pandas><dataframe>
2023-01-18 13:35:27
1
588
Eliy Arlev
75,159,821
13,455,916
Installing Python 3.11.1 on a docker container
<p>I want to use <code>debian:bullseye</code> as a base image and then install a specific Python version - i.e. 3.11.1. At the moment I am just learning docker and linux.</p> <p>From what I understand I can either:</p> <ol> <li>Download and compile sources</li> <li>Install binaries (using apt-get)</li> <li>Use a Pytho...
<python><docker>
2023-01-18 13:17:00
3
347
andrewthedev
75,159,784
1,794,714
Convert python pandas iterator and string concat into pyspark
<p>I am attempting to move a process from Pandas into Pyspark, but I am a complete novice in the latter. Note: This is an EDA process so I am not too worried about having it as a loop for now, I can optimise that at a later date.</p> <p>Set up:</p> <pre><code>import pandas as pd import numpy as np import pyspark.pandas...
<python><pandas><apache-spark><pyspark>
2023-01-18 13:13:57
1
391
FitzKaos
75,159,782
672,305
ValidationError pass multi level dictionary insted of single dict
<p>Is there a way to raise a ValidationError with nested dict of errors?. For example:</p> <pre><code>raise ValidationError({ &quot;index_errors&quot;: {&quot;index1&quot;: { &quot;test_con&quot;: &quot;Error text example&quot;, &quot;test_con2&quot;: &quot;Error ...
<python><django>
2023-01-18 13:13:45
1
865
pikk
75,159,744
17,473,587
How to Negate in this Jinja if condition?
<p>I have this in template:</p> <pre><code>{% if cell %}{% set cell = &quot;b&quot; %}{% endif %} </code></pre> <p>What is contradiction of above conditional?</p> <p>This not works:</p> <pre><code>{% if !cell %} </code></pre>
<python><jinja2>
2023-01-18 13:10:19
1
360
parmer_110
75,159,721
5,919,632
How to export Enterprise Architect diagram links to csv using python?
<p>I want to export Enterprise Architect model relation links to CSV file.</p> <p>I'm doing it using python in given way.</p> <pre class="lang-py prettyprint-override"><code>import win32com.client def ea(): try: eaApp = win32com.client.Dispatch('EA.App') eaRep = eaRep.Repository except: ...
<python><enterprise-architect>
2023-01-18 13:08:16
2
647
Akash Pagar
75,159,677
6,564,294
I do not want to write and read the same document in python
<p>I have pdf files where I want to extract info only from the first page. My solution is to:</p> <ol> <li>Use PyPDF2 to read from S3 and save only the first page.</li> <li>Read the same one-paged-pdf I saved, convert to byte64 and analyse it on AWS Textract.</li> </ol> <p>It works but I do not like this solution. What...
<python><amazon-web-services><pdf><amazon-textract>
2023-01-18 13:05:19
1
324
Chukwudi
75,159,675
1,378,055
Installing Open3d-Ml with Pytorch (on MacOs)
<p>I created a <code>virtualenv</code> with <code>python 3.10</code> and installed open3d and PyTorch according to the instructions on open3d-ml webpage: <a href="https://github.com/isl-org/Open3D-ML" rel="nofollow noreferrer">Open3d-ML</a> but when I tested it with <code>import open3d.ml.torch</code> I get the error: ...
<python><python-3.x><pytorch><open3d>
2023-01-18 13:05:12
3
445
Bruce
75,159,579
4,495,238
Data not getting written to Joining Column
<p>Following Python Apache Beam code is not writing Null Value to Bigquery field <code>sum_rpp_million</code>. All other columns are getting loaded as per expectations.</p> <p>I am expecting that it should write Sum calculated at PCollection <code>data_sum</code> to all records of Pcollection <code>data_loading</code>....
<python><google-cloud-platform><google-cloud-dataflow><apache-beam>
2023-01-18 12:56:13
1
699
Vibhor Gupta
75,159,453
542,270
Specifying local relative dependency in pyproject.toml
<p>I have the following project structure:</p> <pre><code>root - sample/ - src/ - tests/ - pyproject.toml - libs/ - lol/ - src/ - tests/ - pyproject.toml </code></pre> <p>I'd like to specify <code>lol</code> as a dependency for <code>sample</code> in <code>sample/pyproject.toml</co...
<python><pip><pyproject.toml>
2023-01-18 12:47:11
5
85,464
Opal
75,159,336
245,362
Using Box with PyO3
<p>I have a struct in Rust that works like a linked-list that I want to expose to Python. The struct has a <code>parent</code> field, which is a reference to a parent which is a struct of the same type. I need to wrap this in a <code>Box</code>, since Rust complains about needing indirection if I don't, but then PyO3 g...
<python><rust><pyo3>
2023-01-18 12:36:11
1
563
David Chanin
75,159,310
9,106,985
Abaqus Python: Accessing XYDataFromHistory at particular nodes
<p>I have defined the following in an attempt to export HISTORY OUTPUT data at specified nodes from abaqus odb file. It is not clear to me how to resolve this error. Any suggestions?</p> <pre><code>from odbAccess import def main(): odb=openOdb('name.odb') ['Spatial acceleration: A1 at Node 84735155 in NSET S...
<python><abaqus><abaqus-odb>
2023-01-18 12:34:22
1
575
shoggananna
75,159,278
4,865,723
How to get a Series's parent DataFrame in Pandas?
<p>Does a <code>pandas.Series</code> instance do know it's parent <code>pandas.DataFrame</code> when it comes from there?</p> <p>Example:</p> <pre><code>import pandas df = pandas.DataFrame({'col': range(10)}) series_column = df.col print('My parent is {}'.format(series_column.parent)) # or print('My parent is {}'.f...
<python><pandas>
2023-01-18 12:31:58
0
12,450
buhtz
75,159,093
8,849,071
How to make only a method generic in a python class
<p>I have the following base class to represent fields:</p> <pre class="lang-py prettyprint-override"><code>T = TypeVar(&quot;T&quot;) @dataclass class BaseClass(Generic[T]): def validate(self, value: T): raise NotImplementedError </code></pre> <p>I also have an enum to represent the available implementat...
<python><python-3.6><mypy>
2023-01-18 12:15:34
1
2,163
Antonio Gamiz Delgado
75,158,916
10,413,428
fstring float to int with leading zeros
<p>I need to generate a string from a float which is always the length of 5. For example:</p> <pre class="lang-py prettyprint-override"><code>input_number: float = 2.22 output_str = &quot;00222&quot; </code></pre> <p>The float never larger then 999.xx and can have an arbitrary number of decimal places. I came up with t...
<python><f-string>
2023-01-18 12:00:11
3
405
sebwr
75,158,879
12,965,658
Python regex for url
<p>I need help to create regex for the url.</p> <p>The part https://test/ is fixed and will be in all samples.</p> <p>I want to to have regex which can have values after test between starting with a letter from a to j (case insensitive) and can have any digit or character after it.</p> <p>Valid samples:</p> <pre><code>...
<python><regex>
2023-01-18 11:55:51
1
909
Avenger
75,158,684
11,308,029
How to send event to Sentry without Sentry-SDK?
<p>I need to run Python script without external dependencies so I can not use SDK for python. I also do not want call external tools like sentry-cli from script for that purpouse</p> <p>I need simply send two events to specific Project, using DSN.</p> <p>I can not google it or find in <a href="https://docs.sentry.io/ap...
<python><logging><alert><monitoring><sentry>
2023-01-18 11:39:33
1
702
Archirk
75,158,670
7,216,834
How to merge list of dictionary into one dictionary in python, the value should be of list if the key has different values?
<p>I have a list of dictionaries,</p> <pre><code>lst = [{'A':1,'B':2,'C':4},{'A':2,'B':2,'C':4},{'A':3,'B':2,'C':4}] </code></pre> <p>I want to merge this into one dictionary and put the values inside list if a key has different values.</p> <pre><code>desired output = {'A':[1,2,3},'B':2,'C':4} </code></pre> <p>I tried ...
<python><python-3.x><dictionary>
2023-01-18 11:37:57
1
1,325
Jennifer Therese