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,407,085
1,609,428
how to keep continental U.S.A. from shapefile at the zip code level?
<p>I have downloaded the large <code>.shapefile</code> at the <code>zip code</code> level from Census.</p> <p>The link is here : cb_2017_us_zcta510_500k.shp (<a href="https://www2.census.gov/geo/tiger/TIGER_RD18/LAYER/ZCTA520/" rel="nofollow noreferrer">https://www2.census.gov/geo/tiger/TIGER_RD18/LAYER/ZCTA520/</a>) T...
<python><geopandas><shapefile>
2023-02-10 04:51:17
1
19,485
ℕʘʘḆḽḘ
75,407,052
3,368,722
Installing test files with pyproject.toml and setuptools
<p>I'm migrating an old python project to the new <code>pyproject.toml</code> based system and am having trouble with getting files that are required by tests to install. Inside the <code>pyproject.toml</code> I have:</p> <pre><code>[tool.setuptools] package-data = {&quot;my_pkg_name&quot; = [&quot;tests/*.sdf&quot;, &...
<python><setuptools><python-packaging><pyproject.toml>
2023-02-10 04:46:38
1
1,226
LemonPi
75,407,048
1,028,270
Is it possible to programmatically generate a pyi file from an instantiated class (for autocomplete)?
<p>I'm creating a class from a dictionary like this:</p> <pre><code>class MyClass: def __init__(self, dictionary): for k, v in dictionary.items(): setattr(self, k, v) </code></pre> <p>I'm trying to figure out how I can get Intellisense for this dynamically generated class. Most IDEs can read pyi...
<python><python-3.x><mypy>
2023-02-10 04:45:58
1
32,280
red888
75,406,876
1,277,488
Issue using nested serializer with django-rest-framework
<p>I'm trying to create a nested serializer, <code>UserLoginSerializer </code>, composed of a <code>UserSerializer</code> and a <code>NotificationSerializer</code>, but I'm getting this error when it tries to serialize:</p> <blockquote> <p>AttributeError: Got AttributeError when attempting to get a value for field <cod...
<python><django><serialization><django-rest-framework>
2023-02-10 04:13:39
1
2,385
Dylan
75,406,821
13,176,726
How to assign the lastest terms and condtions to users upon sign in in a djanog project
<p>I have the following model for the terms and conditions:</p> <pre><code>class TermsAndConditions(models.Model): text = models.TextField() date_modified = models.DateTimeField(auto_now=True) def __str__(self): return f'Terms and conditions, last modified on {self.date_modified}' class UserAgreem...
<python><django>
2023-02-10 04:03:26
1
982
A_K
75,406,645
90,338
How to compute expectancy in a dataframe across rows
<p>I have a dataframe that contains day, symbol, strategy, and pnl. I want to analyze and compare pnl in a couple of ways.</p> <p>I'd like to get the win-rate &amp; expectancy when grouped by symbol and strategy. So I've done this:</p> <pre><code>def stats(s): winrate = s['isWinner']['count'] / (s['isWinner']['co...
<python><pandas>
2023-02-10 03:26:39
1
990
greymatter
75,406,634
10,613,037
Sort dates in mm/dd/yy and dd/mm/yy where I know the month they are from
<p>I have a column of date <strong>strings</strong> I know are from a single month, in this case the dates are all between January and February 2020. I want to sort them in ascending order. However, they are in different formats some in mm/dd/yy, some in dd/mm/yy. How can I sort them?</p> <pre class="lang-py prettyprin...
<python><pandas>
2023-02-10 03:24:28
1
320
meg hidey
75,406,630
9,386,819
Do built-in Python classes have attributes, and if so, how do I find those that are available to the class?
<p>This feels like a simple question, but I can't seem to figure out the answer after much searching. I'm wondering if, for instance, lists have attributes. By attributes I mean values that are accessed by dot notation (not methods). Do strings have them?</p> <p>If I assign a string value to a variable:</p> <p><code>te...
<python><class><attributes>
2023-02-10 03:23:26
2
414
NaiveBae
75,406,627
14,293,020
Python streamline algorithm
<p><strong>Goal:</strong></p> <p>I have 2 arrays <code>vx</code> and <code>vy</code> representing velocity components. I want to write a streamline algorithm:</p> <ol> <li>Input the coordinates of a point (<code>seed</code>)</li> <li>Evaluate which pixels are on the path of the input point based on its velocity compone...
<python><scipy><interpolation><ode>
2023-02-10 03:22:45
2
721
Nihilum
75,406,542
8,584,998
Pandas is Reading .xlsx Column as Datetime rather than float
<p>I obtained an Excel file with complicated formatting for some cells. Here is a sample:</p> <p><a href="https://i.sstatic.net/ZkzJ0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZkzJ0.png" alt="enter image description here" /></a></p> <p>The &quot;USDC Amount USDC&quot; column has formatting of &quot...
<python><python-3.x><excel><pandas><openpyxl>
2023-02-10 03:03:27
2
1,310
EllipticalInitial
75,406,426
8,076,158
How do I retrieve the input parameters for the current object
<p>How do I get the raw value which was passed to MyClass by Factory Boy?</p> <pre><code>class MyClass: def __init__(self, raw): self.processed = f'***{raw}***' class MyClassFactory(factory.Factory): class Meta: model = MyClass raw = factory.fuzzy.FuzzyChoice(['a', 'b']) o = MyClassFacto...
<python><factory-boy>
2023-02-10 02:39:08
1
1,063
GlaceCelery
75,406,249
5,567,893
How can I map the node index in pytorch geometric graph?
<p>I'd like to mapping node index to the original name in pytorch geometric graph for extracting node embedding.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import torch import pandas as pd data = {'source': ['123', '2323', '545', '4928', '398'], 'target': ['2323', '398', '958', '203'...
<python><networkx><pytorch-geometric>
2023-02-10 01:58:28
1
466
Ssong
75,406,196
1,050,648
Tensorflow Keras Model subclassing -- call function
<p>I am experimenting with self supervised learning using tensorflow. The example code I'm running can be found in the Keras examples website. <a href="https://keras.io/examples/vision/nnclr/" rel="nofollow noreferrer">This is the link</a> to the NNCLR example. The Github link to download the code can be <a href="https...
<python><tensorflow><keras>
2023-02-10 01:44:56
1
1,529
HuckleberryFinn
75,406,182
4,505,601
pyexcel get_book and get_records functions throw exceptions for XLSX files
<p>I'm trying to open an XLSX file using <code>pyexcel</code>. But it fails for both <code>get_book</code> and <code>get_records</code> with the following error. However if I try to read the same file converted to <code>xls</code> it does work. I get the files uploaded by users: so can not restrict uploading files in X...
<python><excel><xlsx><pyexcel>
2023-02-10 01:42:27
1
1,178
Indika Rajapaksha
75,406,055
10,853,071
Weird behavior on String vs Categorical Dtypes
<p>I´ve been facing a very weird, or could I say, a bug, when handling some categorical vs string Dtypes. Take a look at this simple example dataframe :</p> <pre><code>import pandas as pd import numpy as np data = pd.DataFrame({ 'status' : ['pending', 'pending','pending', 'canceled','canceled','canceled', 'confirm...
<python><pandas>
2023-02-10 01:12:49
1
457
FábioRB
75,406,037
5,091,720
Python Pandas SQLAlchemy how to make connection to a local SQL Server
<p>I am trying to connect to a local network SQL Server using SQLAlchemy. I don't know how to use SQLAlchemy for doing this. Other examples I have seen do not use the more modern Python (3.6+) f-string. I need to have data in a Pandas dataframe &quot;df&quot;. I'm not 100% sure but this local server does not have a use...
<python><sql-server><pandas><sqlalchemy>
2023-02-10 01:09:07
1
2,363
Shane S
75,405,951
10,620,003
Put a bar as background of bars in histogram plot
<p>I have a histogram plot and different bars has different color. I want to show a background (the same width as the bar width) and also change the bar from rectangular to oval. I attached an that show the way I want.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd rating = [9, 5,...
<python><matplotlib>
2023-02-10 00:53:30
1
730
Sadcow
75,405,795
944,849
Google Cloud Buildpack custom source directory for Python app
<p>I am experimenting with Google Cloud Platform buildpacks, specifically for Python. I started with the <a href="https://github.com/GoogleCloudPlatform/buildpack-samples/tree/master/sample-functions-framework-python" rel="nofollow noreferrer">Sample Functions Framework Python</a> example app, and got that running loca...
<python><google-cloud-functions><buildpack>
2023-02-10 00:24:13
1
15,101
user944849
75,405,790
4,348,400
Why doesn't PriorityQueue waitlist protect lexicographical order of surgeries?
<p>This is a toy example of a waitlist (`PriorityQueue') in which each surgery on the waitlist should have a lexicographical order on the pairs (p, date). The p is an integer and the date is a datetime object.</p> <p>Clearly integers in python have an order, but so do these datetime objects. And I had thought that <a h...
<python><pandas><datetime><priority-queue><lexicographic>
2023-02-10 00:24:01
1
1,394
Galen
75,405,785
12,424,975
pipenv and OS X Monterey - can't install dependencies from Pipfile
<p>I am running OS X Monterey 12.6.3 and I installed pipenv 2023.2.4 via brew with <code>brew install pipenv</code>.</p> <p>I have the following <a href="https://github.com/Evo-Learning-project/sai_evo_backend/blob/master/Pipfile" rel="nofollow noreferrer">Pipfile</a> and <a href="https://github.com/Evo-Learning-projec...
<python><python-3.x><pip><homebrew><pipenv>
2023-02-10 00:22:37
1
668
Samuele B.
75,405,766
5,920,741
Do tasks within a Celery chord always execute in order?
<p>Are tasks within a celery chord guaranteed to execute in the order that they were started? I repeated this example many times and the order was identical. From the docs, I interpreted that the tasks will occur concurrently and so the order would be unpredictable. I added a <code>time.sleep(random())</code> and the r...
<python><redis><celery>
2023-02-10 00:18:51
1
732
AmourK
75,405,637
504,877
PerformanceWarning for Pandas dataframe decoding URL string
<p>I have a dataframe with a URL encoded column &quot;event_properties_searchterm&quot;.</p> <p>I use the following code to clean up, it works exactly as I expected but I got this warning:</p> <blockquote> <p>PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling <code>frame.insert</...
<python><pandas>
2023-02-09 23:50:38
0
765
Tyn
75,405,521
2,228,155
python pandas resample monthly aggregated data to daily, then aggregate back to weekly
<p>Here is my example data:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>team</th> <th>sales</th> <th>month</th> </tr> </thead> <tbody> <tr> <td>a</td> <td>100</td> <td>1/1/2023</td> </tr> <tr> <td>a</td> <td>200</td> <td>2/1/2023</td> </tr> <tr> <td>b</td> <td>600</td> <td>1/1/2023</td>...
<python><pandas><date><time-series>
2023-02-09 23:29:23
1
1,055
barker
75,405,220
4,770,906
Why is PySpark logger not logging INFO statements?
<p>In the PySpark code below, I am attempting to ensure INFO statements are logged. However, I am only seeing WARN, ERROR and FATAL messages. How do I update the logger <code>('Example Processor')</code> to have a log level of INFO, and log everything out?</p> <p>Note: DEBUG logging works, and logs everything for DEBUG...
<python><java><logging><pyspark>
2023-02-09 22:44:29
1
514
mikey8989
75,405,194
317,460
How to forward headers using FastAPI - Tracing use cases
<p>Below is simple server written with FastAPI and running with Uvicorn.</p> <p>In order to send the value to the next hop, the '/destination' url, I need to pass the value to the forward_request method.</p> <p>In this implementation, passing the value is easy, because the calls' depth is just 1 function more.</p> <p>B...
<python><http-headers><fastapi><trace><jaeger>
2023-02-09 22:40:42
0
3,627
RaamEE
75,405,100
11,405,455
create a new folder everyday as per UTC time in my s3 bucket and save json files in it
<p>I want to create a new folder everyday as per UTC time in my s3 bucket, the dict should be saved in json format in that folder</p> <p><strong>My_Attempt</strong></p> <pre><code> import pytz import datetime import botocore import boto3 s3 = sessi...
<python><amazon-web-services><amazon-s3>
2023-02-09 22:27:16
1
443
Khaned
75,404,979
10,001,610
Why does my context manager not exit on exception
<p>I am learning about context managers and was trying to build one myself. The following is a dummy context manager that opens a file in read mode (I know I can just do <code>with open(...): ...</code>. this is just an example I built to help me understand how to make my own context managers):</p> <pre class="lang-py ...
<python><python-decorators><contextmanager>
2023-02-09 22:11:43
1
310
Eyal Kutz
75,404,886
8,869,570
What is the conventional way in Python for defining attributes in an abstract base class?
<p>In C++, I often times will declare attributes in an abstract base class and not instantiate it in the constructor (it doesn't make much sense to do that for my use cases) because the instantiation is meant to occur in the subclasses.</p> <p>In Python, I am wondering what I can achieve the analogous behavior when dec...
<python><inheritance><abstract-class>
2023-02-09 22:01:47
0
2,328
24n8
75,404,738
10,620,003
Select the color of the bar in histogram plot based on its value
<p>I have thousands of data that I want to plot the histogram of them. I want to put the different colors based on the values of the histogram. My values are between <strong>0-10</strong>. So, I want to put the color of the bar from red to green. And if it is close to zero, the color should be red and if it is close to...
<python><matplotlib>
2023-02-09 21:45:32
1
730
Sadcow
75,404,668
10,088,007
Parse datetime from CSV, assign timezone and convert to another timezone - Polars Python
<p>I have a column of timestamps in a CSV file, like <code>2022-01-03 17:59:16.254</code>. As an external information, I know this time is in JST.</p> <p>I am trying to parse this string into datetime, assign JST timezone (without changing the timestamp), and convert it to CET.</p> <p>An attempt:</p> <pre><code>new = p...
<python><datetime><python-polars>
2023-02-09 21:37:27
1
332
Kocas
75,404,631
200,985
Python Postgres Connections with Green Threads
<p>I am using psycopg2 and I have more than one green thread in my application. Each thread gets connections using <code>psycopg2.connect</code>. Sometimes I get the following error:</p> <pre class="lang-none prettyprint-override"><code>error: Second simultaneous read on fileno 14 detected. Unless you really know what...
<python><postgresql><multithreading><psycopg2><green-threads>
2023-02-09 21:33:18
1
7,855
lmat - Reinstate Monica
75,404,602
8,667,016
Using an `if` statement inside a Pandas DataFrame's `assign` method
<h2>Intro and reproducible code snippet</h2> <p>I'm having a hard time performing an operation on a few columns that requires the checking of a condition using an <code>if/else</code> statement.</p> <p>More specifically, I'm trying to perform this check within the confines of the <a href="https://pandas.pydata.org/docs...
<python><pandas><dataframe><if-statement><lambda>
2023-02-09 21:30:28
3
1,291
Felipe D.
75,404,552
1,226,649
KeOps (Kernel Operations on the GPU) on Windows
<p>When installing <a href="https://github.com/getkeops/keops" rel="nofollow noreferrer">KeOps</a> on Windows 10 with:</p> <pre><code>pip install pykeops </code></pre> <p>I get very a famous error:</p> <pre><code>ModuleNotFoundError: No module named 'fcntl' </code></pre> <p>I know, that <code>fcntl</code> does not exis...
<python><windows><gpu>
2023-02-09 21:23:57
0
3,549
dokondr
75,404,497
11,755,414
How do I replace part of string with various combinations in lookup in Python?
<p>I have the following code replacing every element with it's short form in the lookup:</p> <pre><code>case = [&quot;MY_FIRST_RODEO&quot;] lookup = {'MY': 'M', 'FIRST': 'FRST', 'RODEO' : 'RD', 'FIRST_RODEO': 'FRD', 'MY_FIRST': 'MF', 'MY_FIRST_RODEO': 'MFR'} case_mod = [] for string in case: words = string.split(&q...
<python><string><lookup><python-itertools>
2023-02-09 21:18:46
1
774
flying_fluid_four
75,404,491
7,388,758
How to fix mypy type Any error in sqlalchemy Table.columns
<p>I'm still new to type hints. Here's the minimal code example of the error I'm getting:</p> <pre><code>import sqlalchemy as sa t = sa.Table(&quot;a&quot;, sa.MetaData(), sa.Column(&quot;id_&quot;, sa.Integer)) cols = t.columns </code></pre> <p>This raises the following error when I run mypy:</p> <pre><code>error: Ex...
<python><sqlalchemy><type-hinting><mypy>
2023-02-09 21:17:36
2
433
Miguel
75,404,470
17,696,880
How to make a list of lists with each of the possible combinations of the elements of a previous list?
<pre class="lang-py prettyprint-override"><code>import re input_info_list = [['corre', 'salta', 'dibuja'], ['en el bosque', 'en el patio'], ['2023-02-05 00:00 am', '2022-12-29 12:33 am _--_ 2023-01-25 19:13 pm']] print(reordered_input_indo_list) # --&gt; output new list </code></pre> <p>I want to create a list that s...
<python><python-3.x><list><loops><data-structures>
2023-02-09 21:14:33
0
875
Matt095
75,404,376
11,092,636
Mapping a pandas dataframe to a n-dimensional array, where each dimension corresponds to one of the x columns
<p>I have a dataframe with columns <code>x0 x1 x2 x3 x4</code> and <code>y0 y1 y2 y3 y4</code>.</p> <p>First ten rows:</p> <pre class="lang-py prettyprint-override"><code> Id x0 x1 x2 x3 x4 y0 y1 y2 y3 y4 0 0 -5.0 -5.0 -5.0 -5.0 -5.0 268035854.2037072 0.94956508069182 3520.756822078...
<python><pandas><dataframe>
2023-02-09 21:00:37
1
720
FluidMechanics Potential Flows
75,404,321
4,570,472
PyCharm: Stuck on Introspecting SSH server because two-factor login required for rsync
<p>I work on a cluster that requires two-factor login for every new connection. When I try creating a remote python interpreter in PyCharm, I can successfully connect, which requires 1 round of two-factor login via Duo. But then, PyCharm tries to test whether rsync works, which requires another round of two-factor auth...
<python><pycharm><remote-debugging>
2023-02-09 20:53:10
1
2,835
Rylan Schaeffer
75,404,289
12,394,134
Simulating different data with decorators in python
<p>I am trying to force myself to understand how decorators work and how I might use them to run a function multiple times.</p> <p>I am trying to simulate datasets with three variables, but they vary on their sample size and whether the sampling was conditional or not.</p> <p>So I create the population distribution tha...
<python><decorator>
2023-02-09 20:48:34
0
326
Damon C. Roberts
75,404,232
6,077,239
How to use apply better in Polars?
<p>I have a polars dataframe illustrated as follows.</p> <pre><code>import polars as pl df = pl.DataFrame( { &quot;a&quot;: [1, 4, 3, 2, 8, 4, 5, 6], &quot;b&quot;: [2, 3, 1, 3, 9, 7, 6, 8], &quot;c&quot;: [1, 1, 1, 1, 2, 2, 2, 2], } ) </code></pre> <p>The task I have is</p> <ol> <li>gr...
<python><python-polars>
2023-02-09 20:42:27
1
1,153
lebesgue
75,404,177
5,924,264
Is "Dict" a keyword in python?
<p>In the codebase I'm looking at at work, there's a line</p> <pre><code>values = Dict[int, List[QuantityClass]] </code></pre> <p>I cannot find where <code>Dict</code> is defined anywhere in the codebase when I did a grep, and I don't think it's a keyword in Python? This isn't a keyword right? It looks like some kind o...
<python><dictionary>
2023-02-09 20:36:50
1
2,502
roulette01
75,403,887
8,297,745
Cannot use a decorator on a child class inheriting from a parent class but can use it on the object itself
<p>I am creating a class inheriting from a parent class. The parent class is Telebot and the child class is my own Telegram BOT class. I am doing this to create a standard BOT that multiple scripts will call and implement with default actions etc.</p> <p>Then I am trying to implement a decorator to treat default incomi...
<python><telegram>
2023-02-09 20:05:10
1
849
Raul Chiarella
75,403,882
1,658,105
Add a data directory outside Python package directory
<p>Given the following directory structure for a package <code>my_package</code>:</p> <pre><code>/ ├── data/ │ ├── more_data/ │ └── foo.txt ├── my_package/ │ ├── __init__.py │ └── stuff/ │ └── __init__.py ├── README.md ├── setup.cfg ├── setup.py </code></pre> <p>How can I make the <code>data/</code> direc...
<python><setuptools><setup.py><python-packaging><python-importlib>
2023-02-09 20:04:26
2
1,150
Androvich
75,403,841
11,940,250
How do I create a 16-bit grayscale image from my array dataset
<p>I want to convert a height map from NASA database into an image file. There is already a bit about this on the net and that helped me to read the file into an array and it looks like this:</p> <pre><code>data = [(113.0, 39.0, 1242), (113.00027777777778, 39.0, 1231), (113.00055555555555, 39.0, 1232), (113.00083333333...
<python><numpy><image-processing><arraylist>
2023-02-09 20:00:16
1
419
Spiri
75,403,840
2,726,900
Why does HVAC does not see secrets in HashiCorp Vault?
<p>I'm trying to use HashiCorp Vault with the HVAC Python client.</p> <p>I've run vault docker container (development mode config) on localhost, created a KV secret engine <code>kv1</code> (with version 1 API), added a secret <code>mega_secret</code>, added a key/value (<code>&quot;hell&quot; --&gt; &quot;yeah&quot;</c...
<python><hashicorp-vault><hvac>
2023-02-09 20:00:11
1
3,669
Felix
75,403,816
6,251,742
Why `.decode("utf-16")` with ASCII encoded string sometime crash?
<p>I wanted to show how we can reduce the number of character required to code a script in Python using encoding conversion, and I took the <a href="https://docs.python.org/3/faq/programming.html#is-it-possible-to-write-obfuscated-one-liners-in-python" rel="nofollow noreferrer">Mandelbrot set obfuscated example</a> fro...
<python><decode><utf-16>
2023-02-09 19:58:12
1
4,033
Dorian Turba
75,403,728
11,809,811
check if Toplevel windows was closed?
<p>I have a tkinter app, created with customtkinter:</p> <pre><code>import customtkinter class App(customtkinter.CTk): def __init__(self): super().__init__() Extra() self.mainloop() class Extra(customtkinter.CTkToplevel): def __init__(self, *args, **kwargs): super().__init__(*...
<python><tkinter><customtkinter>
2023-02-09 19:48:37
1
830
Another_coder
75,403,654
1,795,357
How do I connect to a MySQL5 DB using mysql-connector-python?
<p>I believe the crux of the issue is the version mismatch, but I'm not sure how to get around this.</p> <p>This is my conda environment file:</p> <pre><code>channels: - anaconda - defaults - conda-forge dependencies: - _libgcc_mutex=0.1=conda_forge - _openmp_mutex=4.5=2_gnu - bzip2=1.0.8=h7f98852_4 - ca-...
<python><mysql><python-3.x>
2023-02-09 19:40:43
1
2,179
ajoseps
75,403,349
13,382,982
Use a class variable across inheritance in Python
<p>In Python, I want to define a top level class that can depend on a class variable. Then I want to be able to change that variable at the class level, for children of the class, but still inherit the functionality that uses that variable.</p> <p>In general, my Parent class has some functions that depend on configurat...
<python><inheritance>
2023-02-09 19:10:41
2
405
Santiago Cuellar
75,403,301
12,043,946
Scipy.Stats Error. Why is the function stats.combine_pvalues not accepting my weights for Stouffer method?
<p>I have two dictionaries,</p> <pre><code> import scipy.stats import numpy as np import pandas as pd exp_pvalues={'SC_1': array([0.96612999, 0.30348366]), 'SC_2': array([0.66871158, 0.0011381 ]), 'SC_3': array([0.66871158, 0.0011381 , 0.96612999, 0.30348366]), 'SC_4': array([0.66871158, 0.0011381 , 0.46018094, 0.3...
<python><arrays><p-value><probability-distribution>
2023-02-09 19:05:38
1
392
d3hero23
75,403,127
5,268,999
How to negate a predicate in Python?
<p>I have a predicate function that accepts a string and evaluates it to <code>bool</code>:</p> <pre><code>def pred(line): return someval in line </code></pre> <p>Now I have a strings list and want to select only those which don't match the predicate. I'd expect code like below:</p> <pre><code>my_list = [&quot;Tha...
<python><functional-programming>
2023-02-09 18:47:08
2
334
Antonio
75,403,048
19,675,781
Python calculate correlation of a column against entire dataframe grouped by index
<p>I have a dataframe of size (109049, 29184) that looks like this:</p> <pre><code>df: Ford Honda GM index Sedan 4 1 8 Sedan 5 2 7 Sedan 6 3 6 Sedan 7 4 5 SUV 8 5 7 SUV 1 6 6 SUV 2 7 5 SUV 3 8 4 </code></pre> <p>This data frame has 22 different in...
<python><pandas><dataframe><statistics>
2023-02-09 18:38:41
1
357
Yash
75,403,031
15,363,250
How to compare 2 jsons and if one is bigger than other, add the missing ones to the json with less elements?
<p>I have an error in the data entry in one of my tables, so data I use is sometimes incomplete, as you can see in the example below, where some users have more questions answered then the others.</p> <pre><code>| user_id| user_name | client_preferences +--------+-----------------+-----...
<python><pandas><pyspark><databricks>
2023-02-09 18:37:17
0
450
Marcos Dias
75,403,024
832,490
mypy complains about classmethod
<p>I have a trivial dataclass (from pydantic)</p> <pre><code>from pydantic.dataclasses import dataclass from abc import ABCMeta from abc import abstractmethod @dataclass class BaseEntity(metaclass=ABCMeta): @classmethod @abstractmethod def from_dict(cls, other: dict): ... @abstractmethod ...
<python><mypy><pydantic>
2023-02-09 18:36:31
2
1,009
Rodrigo
75,403,007
3,084,842
Annotating top of stacked barplot in matplotlib
<p>I made a stacked barplot in matplotlib and want to print the total of each bar at the top,</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame() df['year'] = ['2012','2013','2014'] df['test 1'] = [4,17,5] df['test 2'] = [1,4,1] df['test 2a'] = [1,1,2] df['test 3']...
<python><pandas><matplotlib><formatting>
2023-02-09 18:34:53
1
3,997
Medulla Oblongata
75,402,849
9,861,647
Pandas reformat and Melt
<p>I have this pandas data frame which has 65 columns Full month:</p> <pre><code>ID Name Date 2022-12-1-IN 2022-12-1-OUT 2022-12-2-IN 2022-12-2-OUT ... 2022-12-31-IN 2022-12-31-OUT n_cols = df.shape[1] # Create a list of the new column names new_col_names = [] for i in range(3, n_cols)...
<python><dataframe>
2023-02-09 18:19:18
1
1,065
Simon GIS
75,402,818
10,714,156
PyTorch: `DataLoader()` for aggregated/clustered/panel data
<p>Say I have a data set with multiple observations per individual (also known as <strong>panel data</strong>). Hence, I want to sample them together; that is to say <strong>I want to sample my dataset at the level of the <em>individuals</em>, not at the level of the observations</strong> (or rows).</p> <p>That being s...
<python><pandas><dataframe><pytorch><dataloader>
2023-02-09 18:16:25
1
1,966
Álvaro A. Gutiérrez-Vargas
75,402,817
2,989,642
How to properly call a multithreaded method inside a class in Python?
<p>I've got a method to download a bunch of files, and then do things with them.</p> <p>The multithreaded download methods worked when not in a class, but when I put them inside the class, they cease processing immediately after initiating the first file in the list. There are no errors thrown; the URL call is good, e...
<python><multithreading><multiprocessing>
2023-02-09 18:16:04
0
549
auslander
75,402,809
21,182,228
Connection pool exhausted error (psycopg2)
<p>I am making an api that listens to webhook events , and every few hours I get &quot;connection pool exhausted&quot; error, which does not make any sense , since I am returning the connection to the pool at the end of each request</p> <p>this is the python code</p> <pre class="lang-py prettyprint-override"><code>POOL...
<python><database><postgresql><psycopg2>
2023-02-09 18:15:20
0
1,126
Mike Lennon
75,402,713
9,878,135
How to access a FastAPI Depends value from a Pydantic validator?
<p>Let's say I have a route that allows clients to create a new user</p> <p>(pseudocode)</p> <pre class="lang-py prettyprint-override"><code>@app.route(&quot;POST&quot;) def create_user(user: UserScheme, db: Session = Depends(get_db)) -&gt; User: ... </code></pre> <p>and my <code>UserScheme</code> accepts a field s...
<python><fastapi><pydantic><starlette>
2023-02-09 18:06:18
1
1,328
Myzel394
75,402,602
7,706,354
python executing powershell script but no effect
<pre><code> import subprocess command = r&quot;[System.Windows.Forms.Clipboard]::SetFileDropList('E:\xampp\htdocs\tadiya\webpack.mix.js')&quot; result = subprocess.Popen( [&quot;powershell.exe&quot;, command], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = result.communicate() print(stdout) pri...
<python>
2023-02-09 17:57:08
0
7,616
lava
75,402,584
1,815,710
String interpolation with Python AND Javascript from server to client
<p>Is there a way to pass a string to be interpolated to Javascript coming from Python?</p> <p>For example, to string interpolate a Python string, I <code>f-strings</code> like so</p> <pre><code>&gt;&gt;&gt; friend = &quot;Bob&quot; &gt;&gt;&gt; f&quot;Hey there, {friend}&quot; Hey there, Bob </code></pre> <p>However, ...
<javascript><python><string><ecmascript-6>
2023-02-09 17:54:37
1
16,539
Liondancer
75,402,537
1,765,579
How to specify the path of Python Script located locally OR within Karate project in karate.exec() command?
<p>I want to execute a python script which is located either:</p> <ol> <li>On my Local System or,</li> <li>Within the Karate project itself</li> </ol> <p>My question is how to specify the paths of the above scripts location into karate.exec() command. I Tried giving the path but while executing it says working director...
<python><karate>
2023-02-09 17:49:32
1
1,417
Thonas1601
75,402,454
15,176,150
Can Anaconda tell you Conda-Forge url of an installed package?
<p>I'm trying to build a dependency tree for a series of python package installs, and I'd like to include the conda-forge url for each package.</p> <p>Is there a way to find the url of an installed package using the command line interface?</p>
<python><installation><package><anaconda><conda>
2023-02-09 17:40:52
1
1,146
Connor
75,402,315
7,658,051
Ansible: How to access a stored csv, order its rows by certain columns and then save it
<p>In my Ansible playbook there is a task which saves data into a csv at path /tmp/.</p> <p>The generated csv has 4 columns: 'idm', 'idc', 'day', 'time'.</p> <p>data example:</p> <pre><code>idm idc day time 34 3 2023-02-09 12:57:34 56 6 2023-02-10 20:25:12 78 2 2023-02-11 04:01:00 </code></pre> <p>N...
<python><csv><ansible>
2023-02-09 17:29:23
2
4,389
Tms91
75,402,084
13,696,853
PyTorch Not Recognizing CUDA (Error 803: system has unsupported display driver / cuda driver combination)
<p>I'm running PyTorch on Linux.</p> <p>The OS is Ubuntu 22.04.1. The GPU is NVIDIA RTX A4000. CUDA Version 11.5.</p> <p>Additionally, I am running the CUDA 11.7 version of PyTorch.</p> <p>When I run Python3 on the terminal, PyTorch is unable to detect CUDA. I have tried rebooting but the issue persists.</p> <pre><code...
<python><pytorch><cuda><nvidia>
2023-02-09 17:08:50
1
321
Raiyan Chowdhury
75,401,921
11,167,163
with pandas read_sql, how do I run procedure with parameters?
<p>I have a stored procedure which as been created like this :</p> <pre><code>create or replace PROCEDURE MyTestProcedure(p_date IN DATE) AS OUTPUT SYS_REFCURSOR; BEGIN END </code></pre> <p>I would like to execute it doing :</p> <pre><code>pd.read_sql(&quot;&quot;&quot;EXECUTE MyTestProcedure @p_date=(TO_DATE('2022-02-...
<python><pandas><plsql>
2023-02-09 16:54:18
0
4,464
TourEiffel
75,401,900
9,840,684
Labelling legend values for Axes3D chart
<p>I have a data frame with the following values and would like to create a 3D plot showing Recency, Frequency, and Monetary values labelled by the categories/loyalty levels (bronze, silver, gold, platinum) assigned to them. The relevant data looks as follows:</p> <p><code>RFMScores.head()</code></p> <p><a href="https:...
<python><matplotlib>
2023-02-09 16:52:21
1
373
JLuu
75,401,881
8,869,570
How to use multiple variable annotations for a abstract class instance variable?
<p>I need to declare an abstract instance variable in an abstract base class. After looking at <a href="https://stackoverflow.com/questions/51055750/python-abstract-instance-variable">Python: abstract instance variable?</a>, it seems the one way to do that is with type annotations, e.g.,,</p> <pre><code>class base(ABC)...
<python><python-typing>
2023-02-09 16:50:45
0
2,328
24n8
75,401,855
10,296,584
Pandas add a total column after every year column in a multilevel dataframe
<p>I have created the below pivotable in pandas</p> <pre><code>&gt;&gt;&gt; out Year 2021 2022 2023 Month Feb Mar Sep Oct Dec Jan Jun Aug Oct Jun Sep Nov Dec ID 1 0 8 1.5 6.5 6 8 8 2 7.0 ...
<python><pandas><dataframe><sum><pivot-table>
2023-02-09 16:48:38
2
597
Atharva Katre
75,401,834
10,620,003
Create a dataframe with 1 rows and n*m column with an existing dataframe with n rows and m columns
<p>I have a dataframe and I want to stick the values and create one row with 6 columns. Here is my dataframe.</p> <pre><code> time val1 val2 0 2020-01-01 1 4 1 2020-01-02 2 5 2 2020-01-03 3 6 </code></pre> <p>I want to create the following dataframe:</p> <pre><code> val1 val2 val3 ...
<python><dataframe>
2023-02-09 16:46:46
2
730
Sadcow
75,401,761
12,276,162
Change Verbosity of Keras train_on_batch()?
<p>I am training a GAN using Keras's <code>train_on_batch()</code> command. This is very similar to Keras's <code>fit()</code>. However, in the documentation for <code>fit()</code>, there is a parameter for <code>verbose</code>, which changes how often a progress bar is printed to the console.</p> <p>My model has many ...
<python><tensorflow><machine-learning><keras><artificial-intelligence>
2023-02-09 16:41:49
1
499
lowlyprogrammer
75,401,738
6,382,526
DatetimeRangeSlide updating network graph with bokeh
<p>I would like to update a network graph using a datetime range slider with Bokeh. So appearing/disappearing nodes depending on the datetime range, and also width of edges is proportional to the number of connections between sources and target within datetime range.</p> <p>So far here is my code:</p> <pre><code>nb_con...
<python><slider><networkx><bokeh><bokehjs>
2023-02-09 16:39:20
0
897
Laure D
75,401,587
6,068,731
Cannot import from module inside the same package, from a subpackage
<p>I have the following structure</p> <pre><code>folder/ ├─ subfolder/ │ ├─ __init__.py │ ├─ script.py ├─ __init__.py ├─ module.py </code></pre> <p>Inside <code>script.py</code> I want to import the function <code>my_function</code> from <code>module.py</code>. I have tried various variants</p> <pre class="lang-py pr...
<python>
2023-02-09 16:29:18
0
728
Physics_Student
75,401,420
8,869,570
"class attribute" terminology in python
<p>This is a pedantic question, but I feel I've been reading some conflicting uses of the term &quot;class attribute&quot; in Python.</p> <p>My understanding and usage of &quot;attribute&quot; of a class has always been to mean some variable associated with the class, whether it is a class or instance variable.</p> <p>...
<python><attributes><terminology>
2023-02-09 16:16:31
1
2,328
24n8
75,401,348
4,935,567
Selenium Chrome driver headless mode not working
<p>My code worked perfectly until yesterday when I updated <em>Google Chrome</em> to version <strong>110.0.5481.77</strong>. Now it's not working in headless mode:</p> <pre class="lang-py prettyprint-override"><code>options.add_argument(&quot;--headless&quot;) </code></pre> <p>I even tried adding <code>options.add_argu...
<python><selenium><selenium-webdriver><selenium-chromedriver><google-chrome-headless>
2023-02-09 16:10:40
1
2,618
Masked Man
75,401,318
10,623,489
Django append to FileField
<p>Is there any way to append directly to a FileField in django? Doing something like this:</p> <pre class="lang-py prettyprint-override"><code>class ChunkedUpload(models.Model): id = models.CharField(max_length=128) data = models.FileField(upload_to='chunked_uploads/') def append_chunk(self, chunk, create...
<python><django><append><filefield>
2023-02-09 16:08:46
1
367
Borhink
75,401,309
10,296,584
Pandas sort multilevel columns with year and month
<p>I have created a pivotable in pandas with multilevel columns, but the order of columns are not sorted -</p> <pre><code>Year 2022 2021 2023 Month Jan Feb Mar Jan Dec Jun </code></pre> <p>What I want:</p> <pre><code>Year 2021 2022 2023 Month Jan Mar Jan Fe...
<python><pandas><dataframe><sorting><pivot-table>
2023-02-09 16:08:08
1
597
Atharva Katre
75,401,247
6,077,239
How can I use polars.when based on whether a column name is None?
<p>I have a python function which takes a polars dataframe, a column name and a default value. The function will return a polars series (with length the same as the number of rows of the dataframe) based on the column name and default value.</p> <ul> <li>When the column name is None, just return a series of default val...
<python><dataframe><python-polars>
2023-02-09 16:03:15
1
1,153
lebesgue
75,401,217
1,442,881
Python UDP socketserver returning empty message
<p>I have a UDP socketserver program that I use to demonstrate how UDP works (code for the server and client are below). I run this on a server, then have the <code>client.py</code> program send a message and receive a reply. I am unfortunately running into an issue that seems to only occur on campus Wifi. On campus wi...
<python><sockets><udp><socketserver>
2023-02-09 16:01:17
1
918
Ryan
75,401,114
10,115,878
Reading text from image, facing problem because of the font
<p><a href="https://i.sstatic.net/ietDJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ietDJ.png" alt="enter image description here" /></a></p> <p>I am trying to read this image and do the arithmetic operation in the image. For some reason i am not able to read 7 because of the font it has. I am relativ...
<python><ocr><tesseract><python-tesseract>
2023-02-09 15:51:21
1
560
Anish Jain
75,400,855
3,713,835
How to concat 2 or more sqlalchemy rowproxy
<p>I have 2 tables with same structure but in different db instance &amp; schema. So I run 2 queries:</p> <pre><code>rows1 = conn1.execute(query1) rows2 = conn2.execute(query2) </code></pre> <p>is there any magic to concat/combine these 2 result?(rows1 &amp; row2)</p> <p>is it possible like list: <code>rows = rows1 + r...
<python><sqlalchemy>
2023-02-09 15:31:46
1
424
Niuya
75,400,685
7,655,151
Python Protocols: cannot understand 'class objects vs protocols"
<p>I'm reading PEP 544, specifically the <a href="https://peps.python.org/pep-0544/#type-and-class-objects-vs-protocols" rel="nofollow noreferrer">section for class objects vs protocols</a>, and I cannot understand the last example given there, I'll copy paste it here:</p> <blockquote> <p>A class object is considered a...
<python><typing><pep>
2023-02-09 15:19:23
1
440
danielcaballero88
75,400,650
572,575
Python BeautifulSoup cannot read data from div tag
<p>I try to read data from this div tag from <a href="https://finance.yahoo.com/" rel="nofollow noreferrer">website</a>.</p> <pre><code>&lt;div class=&quot;Bgc($lv2BgColor) Bxz(bb) Ovx(a) Pos(r) Maw($newGridWidth) Miw($minGridWidth) Miw(a)!--tab768 Miw(a)!--tab1024 Mstart(a) Mend(a) Px(20px) Py(10px) D(n)--print&quot;&...
<python><web-scraping><beautifulsoup>
2023-02-09 15:15:57
2
1,049
user572575
75,400,589
16,414,611
Open multiple tabs in a browser using Playwright
<p>I am trying to open multiple tabs from the same browser using the mentioned playwright code. The browser I'm trying to use is Firefox. Firefox is opening multiple windows instead of tabs. With Chrome it is successfully opening multiple tabs from the same browser. I have searched for different solutions but the resul...
<python><python-3.x><playwright><playwright-python>
2023-02-09 15:11:12
1
329
Raisul Islam
75,400,306
6,579,048
How to print the "original name" of an input
<p>I'm trying to do a comparison of multiple numbers and print out the result in a string type. Here's a simplified ver.</p> <pre><code>a = input() b = input() c = input() Com = [a, b, c] print (min(Com) + &quot; is the smallest, the value is %s&quot; %min(Com)) </code></pre> <p>For example, when I input 1,2,3 to a,b,...
<python><list>
2023-02-09 14:49:07
1
321
Chu
75,400,210
14,667,788
How to get full html body of google search using requests
<p>I have a following problem. I would like to get full HTML body of google search output.</p> <p>Suppose, I would like to google <code>Everton stadium address</code>. This is my python code:</p> <pre class="lang-py prettyprint-override"><code>import urllib.request as urllib2 user_agent = 'Mozilla/5.0 (Windows; U; Win...
<python><python-requests>
2023-02-09 14:41:53
1
1,265
vojtam
75,400,186
6,367,971
Total count of spaces in specific dataframe column
<p>I have a dataframe and I want to count the number of spaces present for all strings in <code>Col1</code>.</p> <pre><code> Col1 Col2 file_name 0 AAA A XYZ test1.csv 1 B BBB XYZ test1.csv 2 CC CC RST test1.csv 3 DDDDD XYZ test2.csv 4 AAAAX WXY test3.csv </code></pre> <p>So I want t...
<python><pandas><dataframe>
2023-02-09 14:40:04
3
978
user53526356
75,400,176
11,462,274
Drop duplicate columns when they have the same name and same values in a DataFrame with different types, for example dictionaries
<p>Example of my DataFrame (I'm putting it with a divider in commas because the print in the terminal is too big):</p> <pre class="lang-none prettyprint-override"><code>_item_name_to_attribute_name_overrides,_datetime_created,_datetime_updated,event,elapsed_time,market_count,_data,marketCount,event.id,event.name,event....
<python><pandas><datetime>
2023-02-09 14:39:14
1
2,222
Digital Farmer
75,400,165
825,489
Pandas DataFrame - Best way to transform multiple input columns to multiple output columns?
<p>I have a simple function that takes a sequence of numbers, and returns a tuple of 4 values, eg the (min, max, first, last) elements of the sequence. <em>(This is just an example; I can't just use builtins to get each value; I need to actually use my function).</em> I'd like to apply this function to all columns of a...
<python><pandas><dataframe>
2023-02-09 14:38:05
1
1,269
Bean Taxi
75,400,040
1,323,992
Why sqlalchemy postgres engine connection commits automatically?
<p>For some reason engine connection commits automatically, which is not desired. I want to commit explicitly. Here's my code (<a href="https://docs.sqlalchemy.org/en/14/tutorial/index.html" rel="nofollow noreferrer">it repeats official tutorial verbatim</a>):</p> <pre class="lang-py prettyprint-override"><code>from sq...
<python><postgresql><sqlalchemy><autocommit>
2023-02-09 14:27:11
1
846
yevt
75,399,983
2,371,684
Python file read write issue
<p>I am trying to add course data to a course, I enter id, name, start and end date, credits. Then I load a file with educations to connect the course, I choose one with the index nr, then I add the education name data to course and finally save the data back to the courses.json file.</p> <p>But when I look at the cour...
<python>
2023-02-09 14:22:15
1
1,575
user2371684
75,399,909
17,561,414
try except AttributeError bugs
<p>I'm trying to add <code>try</code> and <code>except</code> to my code but it does not work.</p> <pre class="lang-py prettyprint-override"><code>def _get_table_df(self, table): l = module.send_command(name='Read', attributes={'type': table, 'method':'all', 'limit':'1', 'enable_custom':1}) so = Beauti...
<python><except>
2023-02-09 14:16:23
0
735
Greencolor
75,399,810
5,040,775
Cannot upgrade pandas on Pycharm
<p>When I enter the command <code>pip install pandas==1.3.0</code> on a virtual environment from PyCharm, I get the following error.</p> <blockquote> <p>ERROR: Could not find a version that satisfies the requirement pandas==1.3.0 (from versions: 0.1, 0.2, 0.3.0, 0.4.0, 0.4.1, 0.4.2, 0.4.3, 0.5.0, 0.6.0, 0.6.1, 0.7.0, 0...
<python><pip>
2023-02-09 14:08:56
1
3,525
JungleDiff
75,399,746
1,185,081
Certificate issue when installing Apache Airflow
<p>Trying to install Airflow on a Windows server, I receive lost of certificate errors. Is there a way to bypass certificates checking while installing?</p> <p><strong>For GitPython:</strong></p> <pre><code>C:\apache-airflow-2.5.1&gt;pip install GitPython WARNING: Retrying (Retry(total=4, connect=None, read=None, redir...
<python><airflow>
2023-02-09 14:04:51
1
2,168
user1185081
75,399,734
3,406,193
Type hint a tuple whose length is the same as *args but different element types
<p>Python supports defining functions that take a variable-length sequence of arguments with <code>*args</code>. The type annotation in those cases is expected to describe the type of the individual elements in the sequence. But how can one describe the return type of the function if its length is supposed to depend on...
<python><python-typing>
2023-02-09 14:04:02
0
4,044
mgab
75,399,706
2,836,172
pip can't find a matching version when installing flask-user in a docker image
<p>I have several packages in my <code>requirements.txt</code> file, but only <code>Flask-User</code> can't be installed:</p> <pre><code>ERROR: Could not find a version that satisfies the requirement Flask-User (from versions: 0.3, 0.3.1, 0.3.2, 0.3.3, 0.3.4, 0.3.5, 0.3.6, 0.3.7, 0.3.8, 0.4.0, 0.4.1, 0.4.2, 0.4.3, 0.4....
<python><docker><pip><package>
2023-02-09 14:01:45
1
1,522
Standard
75,399,697
12,993,568
Parametrize input datasets in kedro
<p>I'm trying to move my project into a kedro pipeline but I'm struggling with the following step:</p> <p>my prediction pipeline is being run by a scheduler. The scheduler supplies all the necessary parameters (dates, country codes etc.). Up until now I had a CLI which would get input parameters such as below</p> <p><c...
<python><kedro>
2023-02-09 14:01:26
1
352
w_sz
75,399,617
12,814,680
Filtering an array on nested values by using values from another array
<p>I have this array of 3 objects. The parameter that interests me is &quot;id&quot;, that is nested into &quot;categories&quot; attribute.</p> <pre><code>list = [ { &quot;title&quot;: &quot;\u00c9glise Saint-Julien&quot;, &quot;distance&quot;: 1841, &quot;excursionDistance&quot;: 1575, &quot;categori...
<python>
2023-02-09 13:55:08
0
499
JK2018
75,399,522
19,828,155
How should I send a Post request to create an object that has a foreign key relationship
<p>hey yall im trying to learn the Django rest framework and im getting stuck trying to create a new product in my db via a POST request</p> <p>i have a model called Product which has a bunch of fields for all the product details, one of those fields (brand) is a foreign key to another table containing all my brands</p...
<python><django><django-rest-framework>
2023-02-09 13:47:09
2
404
spaceCabbage