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,061,982
16,978,074
How can I print multiple indexes of a certain value in a dictionary?
<p>I'm just learning python and I have a problem. how can I print multiple indexes of a certain value in a dictionary? In particular, I want to print the index of each element of the dictionary_title array which has <code>gender_ids</code> as the key.</p> <pre><code>dictionary_title={ {'label': 'Green', 'genre_ids': 87...
<python><dictionary><indexing>
2023-01-09 19:16:46
2
337
Elly
75,061,820
6,440,589
Caching data: numpy vs pandas vs MySQL
<p>I am currently processing time series data stored into h5 files, each file containing one hour of data.</p> <p>In order to move towards real time processing, I would like to process time series data, <em>one second at a time</em>. The plan is to <strong>aggregate</strong> one second of data, <strong>process</strong>...
<python><mysql><pandas><numpy><caching>
2023-01-09 18:59:31
1
4,770
Sheldon
75,061,799
3,932,263
Combine two pyplot axis into single axis
<p>Note: This is different from the following questions which make the following assumptions:</p> <ul> <li><a href="https://stackoverflow.com/questions/45810557/pyplot-copy-an-axes-content-and-show-it-in-a-new-figure">pyplot - copy an axes content and show it in a new figure</a>: Deletes lines from an axis</li> <li><a ...
<python><matplotlib><axes>
2023-01-09 18:56:41
0
1,399
Maximilian Mordig
75,061,729
4,152,567
Keras Custom Layer gives errors when saving the full model
<pre><code>class ConstLayer(tf.keras.layers.Layer): def __init__(self, x, **kwargs): super(ConstLayer, self).__init__(**kwargs) self.x = tf.Variable(x, trainable=False) def call(self, input): return self.x def get_config(self): #Note: all original model has eager execution ...
<python><keras><tensorflow2.0>
2023-01-09 18:50:04
1
512
Mihai.Mehe
75,061,711
8,322,295
Trying to run sklearn on a loop and store predictions in a dataframe
<p><strong>My problem</strong></p> <p>I've been working for some time on an ML algorithm which predicts redshifts of galaxies based on magnitudes. An MWE here:</p> <p><a href="https://pastebin.com/G19Qx2Yj" rel="nofollow noreferrer">https://pastebin.com/G19Qx2Yj</a></p> <p>The MWE is a self-contained version of my full...
<python><machine-learning><scikit-learn>
2023-01-09 18:48:37
0
1,546
Jim421616
75,061,605
20,589,275
How to add two models in one page Django
<p>When i try to add two models in one page it doesn't work and return the html code:<a href="https://i.sstatic.net/ZxiNN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZxiNN.png" alt="enter image description here" /></a></p> <p>How can i add to the one page two models?</p> <p><strong>views.py</strong><...
<python><django>
2023-01-09 18:36:12
1
650
Proger228
75,061,437
11,937,086
Resample each ID of a dataframe with a given date range
<p>I have a dataframe like the one below. Each week, different IDs receive different tests.</p> <pre><code>date id test received 2023-01-02 a1 a 1 2023-01-02 c3 a 1 2023-01-02 e5 a 1 2023-01-02 b2 b 1 2023-01-02 d4 b 1 2023-01-09 a1 c 1 2023-01-09 b2 c 1 2023-01-09 c3 c 1 </code><...
<python><pandas><padding><resampling>
2023-01-09 18:18:49
1
378
travelsandbooks
75,061,426
2,261,950
python - json loads, how to clear line breaks from outside of key value pairs but keep them within values?
<p>We receive AWS notifications to an automated mailbox in JSON format, I have a python script that should process these, however when im loading the content/body of these emails into JSON it is erroring with</p> <p><code>json.decoder.JSONDecodeError: Extra data: line 5 column 3007 (char 3159)</code></p> <p>When I look...
<python><json>
2023-01-09 18:17:56
2
2,163
AlexW
75,061,424
11,462,274
Working with numpy.where when datetime64 could not be promoted by str_
<pre class="lang-python prettyprint-override"><code>import pandas as pd from datetime import timedelta import numpy as np df = pd.DataFrame({ 'open_local_data':['2022-08-24 15:00:00','2022-08-24 18:00:00'], 'result':['WINNER',''] }) df['open_local_data'] = pd.to_datetime(df['open_local_data']) df['clock_now'] ...
<python><pandas><numpy><datetime>
2023-01-09 18:17:36
2
2,222
Digital Farmer
75,061,362
16,319,191
Convert categories to binary columns (concat the category columns)
<p>Want to convert the categories to binary columns, concatenated to the df. Category column values should be new columns with 0 or 1s for each id based on if the value is present or not.</p> <pre><code>df = pd.DataFrame({&quot;id&quot;: [0,1,1,3,3], &quot;value1&quot;: [&quot;ryan&quot;, &quot;del...
<python><pandas>
2023-01-09 18:11:41
1
392
AAA
75,061,348
4,429,002
Pandas DataFrame Hash Values Differ Between Unix and Windows
<p>I've noticed that hash values created from Pandas DataFrames change depending whether the below snippet is executed on Unix or Windows.</p> <pre><code>import pandas as pd import numpy as np import hashlib df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c'...
<python><pandas><hash><operating-system><hashlib>
2023-01-09 18:10:45
1
309
Moritz
75,061,330
6,423,456
Can Django's Replace be used to replace multiple substrings at once?
<p>In Django, I can have queries that look like this:</p> <pre class="lang-py prettyprint-override"><code>from django.db.models import Value from django.db.models.functions import Replace MyModel.objects.update(description=Replace(&quot;description&quot;, Value(&quot;old_1&quot;), Value(&quot;new_1&quot;))) MyModel.ob...
<python><django>
2023-01-09 18:09:16
1
2,774
John
75,061,301
2,543,622
running sql code in python difference between r''' and f'''
<p>I have a code like below. I noticed that i can replace <code>f'''</code> with <code>r'''</code> what is the difference between those 2 options and when to use it?. it seems that <code>r'''</code> when there is regex in the code? i tried to google but didnt get any good results</p> <pre><code>query = f''' with a as ...
<python><sql><string>
2023-01-09 18:06:23
1
6,946
user2543622
75,061,006
1,862,861
Store all keyboard keys currently being pressed in PyQt5
<p>I'm trying to write a PyQt5 GUI that captures all keyboard keys that are currently being pressed. Based on <a href="https://stackoverflow.com/a/32727764/1862861">this answer</a>, I've tried the following minimal code:</p> <pre class="lang-py prettyprint-override"><code>import sys from PyQt5.QtWidgets import QApplic...
<python><pyqt5><keyboard>
2023-01-09 17:36:16
1
7,300
Matt Pitkin
75,060,938
10,260,243
Line and text don't align in matplotlib
<p>I'm trying to draw a line with text written on it using the following code:</p> <pre><code>def angle_line(A, B): x = B[0] - A[0] y = B[1] - A[1] angle = math.atan2(y, x ) return angle*180/np.pi fig, ax = plt.subplots() xy_init = (0,0) xy_end = (1, 0.5) #PLOT LINE ax.plot((xy_init[0], xy_end[0]), (x...
<python><matplotlib>
2023-01-09 17:29:21
0
4,678
Bruno Mello
75,060,885
14,958,374
GPU out of memory when FastAPI is used with SentenceTransformers inference
<p>I'm currently using FastAPI with <strong>Gunicorn</strong>/<strong>Uvicorn</strong> as my server engine. Inside FastAPI <code>GET</code> method I'm using <code>SentenceTransformer</code> model with <strong>GPU</strong>:</p> <pre><code># ... from sentence_transformers import SentenceTransformer encoding_model = Sen...
<python><pytorch><fastapi><sentence-transformers>
2023-01-09 17:23:48
1
331
Nick Zorander
75,060,822
5,446,749
Right/Left align several values together in Python Logging Formatter
<p>In order to left-align the <code>levelname</code> value inside the logs with 8 chars, one can use <code>%(levelname)-8s</code>.</p> <pre class="lang-py prettyprint-override"><code>import logging logging.basicConfig( level=logging.DEBUG, format=&quot;[%(asctime)s] (%(module)s:%(funcName)s::%(lineno)s) - %(le...
<python><logging><python-logging>
2023-01-09 17:17:12
1
32,794
vvvvv
75,060,820
11,913,986
How to add a pyspark rolling window based on restricted duplicate values
<p>I have a dataframe like this: <a href="https://i.sstatic.net/T2TiV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/T2TiV.png" alt="enter image description here" /></a></p> <p>Reproduce:</p> <pre><code>df = spark.createDataFrame([(1, 4, 3), (2, 4, 2), (3, 4, 5), (1, 5, 3), (2, 5, 2), (3, 6, 5)], ['a', ...
<python><dataframe><apache-spark><pyspark><apache-spark-sql>
2023-01-09 17:17:04
1
739
Strayhorn
75,060,772
8,610,286
How to search for multiple terms in Wikidata API using 'srsearch' (e.g. from Python)?
<p>I am trying to search multiple terms on Wikidata and then parse the results locally using Python.</p> <p>I am currently looping through a list of terms and running the following piece of code:</p> <pre><code>import requests term_list = [&quot;term a&quot;, &quot;term b&quot;] for search_term in term_list: bas...
<python><wikidata><phabricator><wikidata-api>
2023-01-09 17:12:50
0
349
Tiago Lubiana
75,060,698
20,615,590
Scientific notation not working in python
<p>I am using python version <code>3.9.5</code>, and trying to use scientific notation using the <code>format</code> method, but it's not working!</p> <p>I have searched across the web for this, but didn't get anything.</p> <p>I used the formatting method of <code>format(num, f'.{precision}e')</code> to turn it into sc...
<python><python-3.x><formatting><format><scientific-notation>
2023-01-09 17:07:27
1
423
Pythoneer
75,060,695
1,229,624
Why cannot predict in TensorFlow a equation of third degree?
<p>I'm new to TensorFlow. I was able to make simple predication. But when I made changes it stopped working. Why? and how to fix it?</p> <p>I have used this demo. And I was able to solve an equation like this:</p> <p><code>y=2x-1</code></p> <p>By using this code:</p> <pre><code>model=Sequential([Dense(units=1,input_sha...
<python><tensorflow>
2023-01-09 17:07:08
1
24,785
Aminadav Glickshtein
75,060,673
2,156,115
How to print actual shortest path Dijkastra Python
<p>I am an adventofcode solver, and I have a my solution using Dijkastra in Python (see attached code). I have successfully calculated how many steps it takes to get to letter &quot;E&quot;. The solution for a sample data was 31.</p> <p>My solution: <a href="https://github.com/xjantoth/aoc2022/blob/main/day12/solution....
<python><shortest-path>
2023-01-09 17:05:09
1
1,266
user2156115
75,060,600
1,061,892
Reindex from MultiIndex removes row values
<p>I have a case where I have a dataset that I am trying to fill in missing dates for each value in the categorical column I am additionally grouping by data. I was following this <a href="https://stackoverflow.com/questions/14856941/insert-0-values-for-missing-dates-within-multiindex">solution</a>, and at the point wh...
<python><pandas>
2023-01-09 16:59:51
0
5,934
cphill
75,060,534
12,990,185
Python GET Rest API - package is downloaded but I cannot open it (invalid)
<p>I must run python to get some artifacts from repository in following syntax (invoked from batch with its variables) so this part to pass arguments is not changeable.</p> <pre><code>python get_artifacts.py %USERNAME%:%PASSWORD% http://url/artifactory/package.zip </code></pre> <p>My python script is the following:</p>...
<python><rest><python-3.8>
2023-01-09 16:54:09
2
1,260
vel
75,060,528
12,991,231
Given multiple lists, how to find the values between neighboring lists?
<p>I have multiple lists of increasing numbers. The elements in each list are strictly greater than those in its previous neighbor. i.e. <code>[1,2,3], [6,7,8], [10,11,12]</code>.</p> <p>How to find the numbers between neighboring lists? In this case, the results would be <code>[4,5], [9]</code>.</p> <p>If there are on...
<python><list>
2023-01-09 16:53:32
2
337
sensationti
75,060,361
15,500,727
combining specific row conditionally and add output to existing row in pandas
<p>suppose I have following data frame :</p> <pre><code>data = {'age' :[10,11,12,11,11,10,11,13,13,13,14,14,15,15,15], 'num1':[10,11,12,13,14,15,16,17,18,19,20,21,22,23,24], 'num2':[20,21,22,23,24,25,26,27,28,29,30,31,32,33,34]} df = pd.DataFrame(data) </code></pre> <p>I want to sum rows for age 14 and ...
<python><pandas>
2023-01-09 16:39:47
2
485
mehmo
75,060,332
1,373,258
Reading survey data CSV with multiple selection sub-columns?
<p>I would like to import this data from a Navigraph survey results. <a href="https://navigraph.com/blog/survey2022" rel="nofollow noreferrer">https://navigraph.com/blog/survey2022</a></p> <p>The dataset is here: <a href="https://download.navigraph.com/docs/flightsim-community-survey-by-navigraph-2022-data.zip" rel="no...
<python><pandas>
2023-01-09 16:37:49
1
11,617
tmn
75,060,298
8,512,262
Why do the tkinter geometry manager methods return None instead of returning the widget on which they're called?
<p><em><strong>EDIT: I have submitted this as a feature improvement proposal via the GitHub issue tracker for cpython. See <a href="https://github.com/python/cpython/issues/100891" rel="nofollow noreferrer">Issue 100891</a>.</strong></em></p> <hr> <p><em>N.B.: I recognize that this question may border on &quot;opinion-...
<python><tkinter>
2023-01-09 16:34:20
2
7,190
JRiggles
75,060,194
9,944,937
Get the time in hours of a time-series in python
<p>this might seem like a trivia question: I have a list of datapoints that have been recorded every 5 minutes with an overlap of 2.5 minutes (2 and a half minutes). I also have the timestamp of the start of the recording and another timestamp from where I need to start counting the time (e.g. the chronometer start):<a...
<python><pandas><numpy><time><time-series>
2023-01-09 16:26:04
1
1,101
Fabio Magarelli
75,060,025
668,498
Unable to locate package apt-get when building a custom Google Cloud Workstation image
<p>I am trying to &quot;build and push a modified workstations image to a container registry&quot; as explained in this previous <a href="https://stackoverflow.com/questions/74246955/install-php-in-home-folder-of-persistent-disk-in-google-cloud-workstations">SO answer</a>.</p> <p>This is the <code>Dockerfile</code> tha...
<python><google-cloud-platform><apt-get><google-cloud-workstations>
2023-01-09 16:09:51
1
3,615
DanielAttard
75,060,009
4,865,723
Normalize one (umlaut) character results in two
<p>I assume I didn't fully understand <code>unicodedata.normalize()</code> function in Python.</p> <pre><code>from unicodedata import normalize result = normalize('NFKD', 'Ä') print(result) # 'A' print(len(result)) # 2 print(result == 'A') # False print(result[0] == 'A') # True </code></pre> <p>I'm confused wh...
<python><normalize>
2023-01-09 16:08:31
0
12,450
buhtz
75,059,959
3,182,044
sklearn2pmml omits field names
<p>I export an instance of <code>sklearn.preprocessing.StandardScaler</code> into a pmml-file. The problem is, that the names of the fields do not appear in the pmml-file, e.g. when using the iris dataset then the original field names <code>['sepal length (cm)','sepal width (cm)','petal length (cm)','petal width (cm)']...
<python><scikit-learn><sklearn2pmml>
2023-01-09 16:04:57
2
345
dba
75,059,828
12,170,254
event.key seems to not be Key [pynput]
<p>I am writing an application which uses pynput to gather raw keyboard input. I needed a form of key event that could be instantiated, deleted, enabled, and disabled arbitrarily during runtime, so pynput's Global Hotkey system wouldn't work. So, I created my own event class:</p> <pre class="lang-py prettyprint-overrid...
<python><pynput>
2023-01-09 15:56:02
1
521
AwesomeCronk
75,059,798
1,218,369
MacOS `subprocess` raising: FileNotFoundError: /usr/sbin/sysctl
<p>I've suddenly started getting an error on all versions of Python on MacOS reporting the following when using <code>subprocess</code>:</p> <p><code>FileNotFoundError: [Errno 2] No such file or directory: '/usr/sbin/sysctl -n machdep.cpu.brand_string'</code></p> <p>However, <code>/usr/sbin/sysctl</code> does exist, I ...
<python><macos><subprocess><sysctl>
2023-01-09 15:53:48
1
1,035
luke
75,059,652
9,006,687
How to get the document of an enumeration in python
<p>I have plenty of files formated as follows:</p> <pre><code># Content of Enumeration1.py from enum import IntEnum class Enumeration1(IntEnum): &quot;&quot;&quot; Some documentation. &quot;&quot;&quot; key_0 = 0 key_1 = 1 key_2 = 2 </code></pre> <p>How can I extract the documentation using py...
<python><enums>
2023-01-09 15:42:48
1
461
Theophile Champion
75,059,631
16,511,234
How to add a new row with new header information in same dataframe
<p>I have written a code to retrieve JSON data from an URL. It works fine. I give the start and end date and it loops through the date range and appends everything to a dataframe.</p> <p>The colums are populated with the JSON data <code>sensor</code> and its corresponding values, hence the column names are like <code>s...
<python><pandas><dataframe><datetime>
2023-01-09 15:40:42
1
351
Gobrel
75,059,619
897,272
Fastest way to delete all files in large volume in python?
<p>I want to completely clear the content of a very large Linux volume containing a huge number of small files. I know how to delete files, but just doing a for loop that calls delete on each one is very slow.</p> <p>I'd just send a command down to bash to use bash tools, but were running in a docker alpine Linux cont...
<python><python-3.x><performance>
2023-01-09 15:39:16
1
6,521
dsollen
75,059,248
13,083,583
Set comparison optimization
<h3>Description</h3> <p>I have two large lists of sets</p> <pre class="lang-py prettyprint-override"><code>A = [ {...}, ..., {...} ] B = [ {...}, ..., {...} ] </code></pre> <p>I'm performing a very cost-intensive list comprehension that for every element in every set in A checks if there is a match with any element in ...
<python><pandas><numpy><multiprocessing><vectorization>
2023-01-09 15:10:08
2
2,368
do-me
75,059,230
5,455,532
Using `drop_duplicates` on a Pandas dataframe isn't dropping rows
<p><strong>Situation</strong></p> <p>I have dataframe similar to below ( although I've removed many of the rows for this example, as evidenced in the 'index' column):</p> <p><code>df</code></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>id</th> <th>name</th> <th>last_updated...
<python><pandas><dataframe><drop-duplicates>
2023-01-09 15:08:35
2
301
dsx
75,059,168
9,173,710
How to convert multi column expressions from Pandas to Polars
<p>I just found out about the Polars lib and I wanted to convert some old functions to get familiar.</p> <p>However, I stumbled upon an issue with my code. The &quot;Mean_Angle&quot; column is not calculated, and I have no idea if the last part even works as intended, it aborts during the group_by operation as the colu...
<python><python-polars>
2023-01-09 15:04:10
1
1,215
Raphael
75,059,027
572,575
K-Folds cross-validator show KeyError: None of Int64Index
<p>I try to use K-Folds cross-validator with dicision tree. I use for loop to train and test data from KFOLD like this code.</p> <pre><code>df = pd.read_csv(r'C:\\Users\data.csv') # split data into X and y X = df.iloc[:,:200] Y = df.iloc[:,200] X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0...
<python><scikit-learn><cross-validation><k-fold>
2023-01-09 14:53:10
1
1,049
user572575
75,058,810
12,883,297
Create list type new column based on division operation of the existing columns in pandas
<p>I have a data frame</p> <pre><code>df = pd.DataFrame([[&quot;X&quot;,62,5],[&quot;Y&quot;,16,3],[&quot;Z&quot;,27,4]],columns=[&quot;id&quot;,&quot;total&quot;,&quot;days&quot;]) </code></pre> <pre><code>id total days X 62 5 Y 16 3 Z 27 4 </code></pre> <p>Divide <em>total</em> column by <em>days</em>...
<python><python-3.x><pandas><list><dataframe>
2023-01-09 14:35:50
2
611
Chethan
75,058,761
3,696,490
subprocess still needs file after add-data in pyinstaller
<p>I am trying to generate one .exe file with pyinstaller</p> <p>my python file</p> <pre><code>import subprocess proc=r&quot;.\file.exe&quot; CLI_VERSION=subprocess.check_output([proc, '-v'],shell=True).decode('utf-8').strip() print (CLI_VERSION) </code></pre> <p>with file.exe being in the same folder as the python fi...
<python><subprocess><pyinstaller>
2023-01-09 14:32:29
0
550
user206904
75,058,758
4,125,116
Python logging MemoryHandler not passing logs to handler
<p>I have this as python logging configuration in a project with the intention to batch the logs before printing it. But it seems none of the logs are getting printed..</p> <pre><code>logging.config.dictConfig({ &quot;version&quot;: 1, &quot;disable_existing_loggers&quot;: True, &quot;handlers&q...
<python><logging><open-telemetry>
2023-01-09 14:32:00
2
2,042
Rajat Jain
75,058,536
458,700
systemd service keep giving me error when start or get status
<p>I have a python application and I need it to be run as a service, I tried many methods and I was advised to make it as systemd service</p> <p>I searched and tried some code</p> <p>here is my unit code</p> <pre><code>[Unit] Description=Airnotifier Service After=network.target [Service] Type=idle Restart=on-failure U...
<python><ubuntu><systemd><systemctl>
2023-01-09 14:13:36
1
9,464
Amira Elsayed Ismail
75,058,447
11,291,663
Tensorflow 2.4.1 can't find GPUs
<p>I'm trying to run TensorFlow on a Linux machine (ubuntu). I've created a Conda env and installed the required packages but I think that there's something wrong with my versions:</p> <p>Updated versions</p> <blockquote> <p><s>cudatoolkit 11.6.0</s> cudatoolkit 11.2.0</p> <p>cudnn ...
<python><linux><tensorflow><conda>
2023-01-09 14:06:37
1
313
RedYoel
75,058,358
19,125,840
Using ARRAY of POINT-s (Point[]) in SQLModel, SQLAlchemy and PostgreSQL
<p>I have just started working with SQLModel which is built on top of the SQLAlchemy. I want to create a Class Model for table to do selects and inserts. I have one column that is an Array of Points. The DDL for that table looks like that:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE &quot;public&q...
<python><postgresql><sqlalchemy><psycopg2><sqlmodel>
2023-01-09 14:00:05
0
460
demetere._
75,058,236
6,054,066
Sphinx Autosummary (Autodoc) partially imports modules
<p>Sphinx autosummary/autodoc gives error for some of the modules, but not all.</p> <p>My code is opensource: <a href="https://github.com/dream-faster/krisi" rel="nofollow noreferrer">https://github.com/dream-faster/krisi</a></p> <h1>I get the following error:</h1> <pre><code>WARNING: autodoc: failed to import module '...
<python><python-sphinx><python-packaging><autodoc><autosummary>
2023-01-09 13:51:11
1
450
semyd
75,058,235
4,421,575
`pd.compare` when dataframes have different shape
<p>I want to compare two dataframes using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.compare.html" rel="nofollow noreferrer"><code>pd.compare()</code></a>. The method works really well if the shapes of the dataframes are the same, ie, <code>df1.shape == df2.shape</code>.</p> <p>For example:<...
<python><pandas><compare><dimensions>
2023-01-09 13:51:08
0
1,509
Lucas Aimaretto
75,058,224
5,208,088
How to extract field value from protobuf/python object
<p>Using proto3 syntax I am using the protobuf protocol to generate messages and I am programmatically parsing them via python3. Is there some API or method to extract the value in specific fields and manipulate them/do further calculations?</p> <p>Take the following message as an example.</p> <pre><code>message File {...
<python><protocol-buffers>
2023-01-09 13:49:32
1
1,192
Mnemosyne
75,058,215
8,551,424
Obtain the percentage of groupby() count(), save it and plot it
<p>I have a dataframe like the following,</p> <pre><code> Time Value Cluster 1 2020-08-11 06:09:59 0 0 2 2020-08-11 06:14:59 0 12 3 2020-08-11 06:19:59 1 103 4 2020-08-11 06:24:59 0 0 5 2020-08-11 06:29:59 0 12 </code></pre> <p>Basicall...
<python><pandas>
2023-01-09 13:48:41
1
1,373
Lleims
75,058,198
5,166,312
How to reduce size of python/qml application after using cx_Freeze
<p>I do not why, but my exe version of my python+qml/qtQuick application takes on large size. All package has over 550 MB. (folder PySide6 under lib has 400 MB). I suppose there is a lot of useless items in PySide6 folder - how to eliminate it? Another think is that on clean windows installation the exe cannot be start...
<python><qtquick2><cx-freeze>
2023-01-09 13:46:48
0
337
WITC
75,058,098
7,104,332
Determine if all the phrases are found within the input string
<p>What am i doing wrong in the code</p> <h1>Objective of the code is to</h1> <p>Determine if all the phrases are found within the input string.</p> <p>If they're all found (using distance as a measure of leeway) return True. Else False. Example:</p> <ul> <li>input = 'can i go to the bathroom in the morning',</li> <li>...
<python>
2023-01-09 13:38:37
1
474
Rohit Sthapit
75,058,042
7,084,115
NameError: name 'pytest' is not defined - GitHub Actions
<p>I have a simple <code>Docker</code> image that has some python test cases.</p> <p>Here's my <code>Dockerfile</code></p> <pre><code>ARG PYTHON_VERSION=3.8.3-alpine # Use the python image as the base image FROM python:${PYTHON_VERSION} # upgrade pip RUN pip install --upgrade pip # set CUSTOMER_NAME as environment ...
<python><docker><github><github-actions>
2023-01-09 13:33:06
1
4,101
Jananath Banuka
75,058,019
9,374,372
Adding a new nested level value to a MultiIndex DataFrame
<p>How can I add another level value to a MultiIndex Initialized to a certain value (for example None). Hard to describe with words, better graphically, how to add the <code>new</code> value level:</p> <pre><code>df_before a b c d l1 l2 bar one 24 13 8 9 two 11 30 7 23 b...
<python><pandas><multi-index>
2023-01-09 13:31:05
1
505
Fernando Jesus Garcia Hipola
75,057,968
11,479,825
How to compare coordinates in two dataframes?
<p>I have two dataframes</p> <p>df1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>x1</th> <th>y1</th> <th>x2</th> <th>y2</th> <th>label</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>0</td> <td>1240</td> <td>1755</td> <td>label1</td> </tr> <tr> <td>0</td> <td>0</td> <td>1240</td> <td>2</...
<python><pandas>
2023-01-09 13:27:31
1
985
Yana
75,057,908
12,430,846
"ValueError: A given column is not a column of the dataframe" while combining text and categorical features
<p>I have a pandas dataframe:</p> <p>df3:</p> <pre><code>Text | Topic | Label some text | 2 | 0 other text | 1 | 0 text 3 | 3 | 1 </code></pre> <p>I divide in training and test set:</p> <pre><code>x_train, x_test, y_train, y_test = train_test_split(df3[['Text', 'Topic']],df3['Label'], test_size=0...
<python><python-3.x><pandas><scikit-learn>
2023-01-09 13:23:21
1
543
coelidonum
75,057,804
7,949,129
Convenient way to log each line of a function without cluttering the code in Python
<p>Let´s say I have an annoying function which has a lot of if-elses in it and this function has a bug which occurs randomly.</p> <p>I can not reproduce or debug it and I want to add some logging to see which parts of the function have been executed when the error occurs again.</p> <p>Now it would be possible to add a ...
<python><debugging><logging>
2023-01-09 13:14:20
2
359
A. L
75,057,759
14,958,374
FastApi with gunicorn/uvicorn stops responding
<p>I'm currently using <strong>FastApi</strong> with <strong>Gunicorn</strong>/<strong>Uvicorn</strong> as my server engine.</p> <p>I'm using the following config for <strong>Gunicorn</strong>:</p> <pre><code>TIMEOUT 0 GRACEFUL_TIMEOUT 120 KEEP_ALIVE 5 WORKERS 10 </code></pre> <p><strong>Uvicorn</strong> has all defaul...
<python><docker><fastapi><gunicorn><uvicorn>
2023-01-09 13:10:23
1
331
Nick Zorander
75,057,500
8,188,120
Indexing Pandas DataFrame containing lists of strings after loading pickled DataFrame
<p>I'm trying to get the row indices of a pandas DataFrame, where the entries are being queried for containing a string amongst a list.</p> <p>However, after pickling a DataFrame and then loading, the column data seems to handle differently than when working prior to pickling.</p> <p>e.g. for the following DataFrame</p...
<python><pandas><string><dataframe><dtype>
2023-01-09 12:48:48
0
925
user8188120
75,057,460
2,707,864
Convert string of a named expression in sympy to the expression itself
<p><strong>Description of the practical problem</strong>: <br> I have defined many expression using <code>sympy</code>, as in</p> <pre><code>import sympy as sp a, b = sp.symbols('a,b', real=True, positive=True) Xcharles_YclassA_Zregion1 = 1.01 * a**1.01 * b**0.99 Xbob_YclassA_Zregion1 = 1.009999 * a**1.01 * b**0.99 Xbo...
<python><expression><sympy>
2023-01-09 12:44:23
2
15,820
sancho.s ReinstateMonicaCellio
75,057,423
14,494,483
Streamlit how to use session state with Aggrid to keep the selection even after switching pages?
<p>This is potentially an easy one, but I just can’t figure out how to do it. Here’s a simple reproducible code example. How to use session state to keep the tickbox selection, even after switching pages (you will need to create a page folder to include multi pages)?</p> <pre><code>import pandas as pd import streamlit ...
<python><ag-grid><session-state><streamlit>
2023-01-09 12:40:47
1
474
Subaru Spirit
75,057,418
8,792,159
How to create a polar plot with error bands in plotly?
<p>This post is closely related to <a href="https://stackoverflow.com/questions/41497257/error-bars-on-a-radar-plot">this one</a> but I need a solution that works with plotly and python. I would like to use <code>plotly</code> to create a polar plot with error bands. My dataset can be divided into multiple groups, wher...
<python><plotly><polar-coordinates><radar-chart>
2023-01-09 12:40:28
1
1,317
Johannes Wiesner
75,057,304
11,857,780
What is the fastest way to filter a pandas time series?
<p>What is the fastest way to filter a pandas time series? For now I use boolean masking to filter the time series ts:</p> <pre><code>import time from datetime import datetime import pandas as pd import statistics # create time series idx = pd.date_range(start='2022-01-01', end='2023-01-01', freq=&quot;min&quot;) ts =...
<python><pandas><filter><series><mask>
2023-01-09 12:31:30
1
325
DerDressing
75,057,274
8,405,296
Saving Custom TableNet Model (VGG19 based) for table extraction - Azure Databricks
<p>I have a model based on <a href="https://github.com/jainammm/TableNet" rel="nofollow noreferrer">TableNet</a> and <a href="https://www.mathworks.com/help/deeplearning/ref/vgg19.html" rel="nofollow noreferrer">VGG19</a>, the data (Marmoot) for training and the saving path is mapped to a datalake storage (using Azure)...
<python><azure><tensorflow><azure-databricks><vgg-net>
2023-01-09 12:28:07
1
1,362
Lidor Eliyahu Shelef
75,057,218
8,583,502
How to combine a masked loss with tensorflow2 TimeSeriesGenerator
<p>We are trying to use a convolutional LSTM to predict the values of an image given the past 7 timesteps. We have used the tensorflow2 TimeSeriesGenerator method to create our time series data:</p> <pre><code> train_gen = TimeseriesGenerator( data, data, length=7, batch_size=32, ...
<python><time-series><conv-neural-network><lstm><tensorflow2.0>
2023-01-09 12:22:28
1
402
Boomer
75,057,110
458,700
how to make your python web app always running on ubuntu machine
<p>I have a web app that I deployed to a machine that has ubuntu 20 installed to be able to run the app I should open ssh to the ubuntu machine and then run this command</p> <pre><code>cd mywebapp python3 app.py </code></pre> <p>it works successfully, but once I close the ssh console or reboot the machine or anything h...
<python><linux><ubuntu>
2023-01-09 12:11:53
2
9,464
Amira Elsayed Ismail
75,057,097
3,650,983
pytorch dataset with 2 transformation train and validation
<p>I would like to use 2 different transformation one for training and the second one for validation and test. I mean to add some augmentation during the train process and validate/test without this augmentation.</p> <p>What's the pytorch way to do so?</p> <p>I mean to run 2 different transforms with torch.utils.data.S...
<python><machine-learning><pytorch><dataset><training-data>
2023-01-09 12:11:05
1
4,119
ChaosPredictor
75,056,713
10,035,978
Connect to OPCUA server with username and password
<p>I am using UAExpert application and i am connecting to my machine with these settings: <a href="https://i.sstatic.net/UcGy0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UcGy0.png" alt="enter image description here" /></a></p> <p>I want to connect to my device with python. I have this code but it do...
<python><opc-ua><opc>
2023-01-09 11:36:22
1
1,976
Alex
75,056,435
13,517,174
How can you run singular parametrized tests in pytest if the parameter is a string that contains spaces?
<p>I have a test that looks as following:</p> <pre><code>@pytest.mark.parametrize('param', ['my param', 'my param 2']) def test_param(self,param): ... </code></pre> <p>This works fine when calling this test with</p> <pre><code>python3 -m pytest -s -k &quot;test_param&quot; </code></pre> <p>However, if I wan...
<python><pytest>
2023-01-09 11:11:11
5
453
Yes
75,056,418
1,479,974
Anaconda Installation Failed on macOS Ventura
<p>I am trying to install Anaconda on my new MacBook which has Ventura 13.1 installed.</p> <p>I am installing only for myself and the installation fails.</p> <p>Can someone please help?</p> <p><strong>Edit 1</strong></p> <p>I have followed <a href="https://docs.anaconda.com/anaconda/user-guide/troubleshooting/#the-inst...
<python><python-3.x><macos><anaconda><macos-ventura>
2023-01-09 11:10:19
3
6,544
chintan s
75,056,311
13,505,957
Explode raises values error ValueError: columns must have matching element counts
<p>I have the following dataframe:</p> <pre><code>list1 = [1, 6, 7, [46, 56, 49], 45, [15, 10, 12]] list2 = [[49, 57, 45], 3, 7, 8, [16, 19, 12], 41] data = {'A':list1, 'B': list2} data = pd.DataFrame(data) </code></pre> <p>I can explode the dataframe using this piece of code:</p> <pre><code>data.explode('A')....
<python><pandas><dataframe>
2023-01-09 10:59:54
2
1,107
ali bakhtiari
75,056,198
8,771,126
Using SQLAlchemy to execute an SQL statement with named parameters
<p>Why can't I raw insert a list of dicts with SQLalchemy ?</p> <pre><code>import os import sqlalchemy import pandas as pd def connect_unix_socket() -&gt; sqlalchemy.engine: db_user = os.environ[&quot;DB_USER&quot;] db_pass = os.environ[&quot;DB_PASS&quot;] db_name = os.environ[&quot;DB_NAME&quot;] uni...
<python><python-3.x><sqlalchemy><pg8000>
2023-01-09 10:50:56
1
358
IndiaSke
75,056,150
15,445,589
Communication between Microservices in Google App Engine
<p>I have currently 5 different services in Google App Engine all of them are in FastAPI Python standard environment. When a service gets called they call an authorization service and continue if permissions are valid. Im using firewall rule to disable all incoming requests but allow my computer. When using the firewal...
<python><google-app-engine><google-cloud-platform><microservices><fastapi>
2023-01-09 10:46:33
1
641
Kevin Rump
75,056,147
1,711,088
Numpy. How to split 2D array to multiple arrays by grid?
<p>I have a numpy 2D-array:</p> <pre><code>c = np.arange(36).reshape(6, 6) [[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35]] </code></pre> <p>I want to split it to multiple 2D-arrays by grid 3x3. (It's like ...
<python><arrays><numpy><split><slice>
2023-01-09 10:46:14
1
976
Massimo
75,056,143
3,540,903
threadpool executor inside processpoolexecutor RuntimeError: There is no current event loop in thread
<p>I have a processpoolexecutor into which I submit multiple disk read/write calls. I want to create a threadpool inside every process for performance benefits.</p> <p>below is my attempt to override and modify _process_worker method of concurrent.futures process.py to use with ProcessPoolExecutor. I am trying to run t...
<python><python-asyncio><concurrent.futures>
2023-01-09 10:46:05
1
312
CodeTry
75,056,128
460,544
When is a default object created in Python?
<p>I have a Python (3) structure like following:</p> <ul> <li>main_script.py</li> <li>util_script.py</li> <li>AccessClass.py</li> </ul> <p>The <code>main</code> script is calling a function in <code>util</code> with following signature:</p> <pre><code>def migrate_entity(project, name, access=AccessClass.AccessClass()):...
<python>
2023-01-09 10:45:01
2
962
Sven
75,055,890
2,280,741
FastAPI - Cannot use `Response` as a return type when `status_code` is set to 204
<p>I've been using the following code for my <code>/healthz</code>:</p> <pre class="lang-py prettyprint-override"><code>@router.get(&quot;/healthz&quot;, status_code=status.HTTP_204_NO_CONTENT, tags=[&quot;healthz&quot;], summary=&quot;Service for 'Health Check'&quot;, description=&quot;This ent...
<python><fastapi>
2023-01-09 10:25:27
1
3,996
Rui Martins
75,055,788
5,774,969
Get Azure Batch job and task ID from python
<p>When running a custom python script using Azure Batch I am interested in getting access to, and logging, the JobID and TaskID of the tasks I am running on the compute node. Mainly for later traceability and debugging purposes. My desire is to get access to these parameters from within the python script that is being...
<python><azure><azure-batch>
2023-01-09 10:16:33
1
502
AstroAT
75,055,750
16,607,067
ModuleNotFoundError: No module named 'config' outside django app
<p>I am using <code>cookiecutter-django</code> on my project and having problem while trying to import settings from config outside app. Getting error <code>ModuleNotFoundError: No module named 'config'</code> <strong>Project structure</strong></p> <pre class="lang-bash prettyprint-override"><code>project ┣ .envs ┃ ┗...
<python><django><cookiecutter-django>
2023-01-09 10:12:00
1
439
mirodil
75,055,683
10,748,412
Python - What is wrong with this fucniton declaration?
<pre><code>def convert(self, path: str): ^ SyntaxError: invalid syntax </code></pre> <p>i am getting a SyntaxError. I checked online and saw this is how it should be declared. what is wrong with this?</p>
<python><django><django-rest-framework>
2023-01-09 10:04:50
2
365
ReaL_HyDRA
75,055,530
20,732,098
Get Duplicated Rows in Dataframe and Overwrite them Python
<p>I have the following Dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>errorId</th> <th>start</th> <th>end</th> <th>timestamp</th> <th>uniqueId</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>1404</td> <td>2022-04-25 02:10:41</td> <td>2022-04-25 02:10:46</td> <td>...
<python><pandas><dataframe>
2023-01-09 09:51:08
1
336
ranqnova
75,055,413
2,707,342
GraphQL returns null for update and delete mutation
<p>I am using graphene-django library for integrating GraphQL Schema into my Django application.</p> <p>I have implemented Queries; get all and get specific, as well as implemented create, update and delete Mutations. All endpoints are working as expected except for the <strong>update</strong> and <strong>delete</stron...
<python><python-3.x><graphql><graphene-django>
2023-01-09 09:40:52
1
571
Harith
75,055,126
16,978,074
create an edge list that groups films by genre, i.e. join two films of the same genre
<p>I've just been using python and I want to build an edge list that groups together the titles of movies that have a genre in common. I have this dictionary:</p> <pre><code>dictionary_title_withonegenere= {28: ['Avatar: The Way of Water', 'Violent Night', 'Puss in Boots: The Last Wish'], 12: ['Avatar: The Way of Water...
<python><dictionary><edge-list>
2023-01-09 09:13:09
2
337
Elly
75,055,028
6,708,782
Print pandas rows cells as string
<p>I'm trying to print a data frame where each cell appears as a string:</p> <p><strong>Dataset</strong></p> <pre><code> a b c 0 car new york queens 1 bus california los angeles 2 aircraft illinois chicago 3 rocket texas houston ...
<python><pandas>
2023-01-09 09:02:21
2
602
ladybug
75,054,985
1,057,473
Django Unit test is written but coverage report says there are missing statements
<p>I try to get coverage reports using a simple django model.</p> <p>Unit test for model was written but report says there are missing statements.</p> <p>The model:</p> <pre><code>from django.db import models from model_utils import FieldTracker from generics.base_model import BaseModelMixin class AModel(BaseModelMix...
<python><django><unit-testing><code-coverage>
2023-01-09 08:58:09
0
1,271
Sencer H.
75,054,857
4,495,238
Reading GPKG format file over Apache Beam
<p>I have a requirement to parse and load <code>gpgk</code> extension file to Bigquery table through apache beam (Dataflow runner). I could see that beam has feature called <a href="https://beam.apache.org/documentation/io/developing-io-python/" rel="nofollow noreferrer">Geobeam</a>, but i couldn't see reference for lo...
<python><gis><google-cloud-dataflow><apache-beam><apache-beam-io>
2023-01-09 08:45:48
1
699
Vibhor Gupta
75,054,569
9,751,001
How can I add a title and change other plot aesthetics for an UpSet plot in python?
<p>I have installed and imported the following (using Google Colab):</p> <pre><code>!pip install upsetplot import numpy as np import pandas as pd import matplotlib.pyplot as plt import upsetplot from upsetplot import generate_data, plot from upsetplot import UpSet from upsetplot import from_contents </code></pre> <p...
<python><pandas><matplotlib><visualization><upsetplot>
2023-01-09 08:10:46
1
631
code_to_joy
75,054,166
898,042
How to update count in dynamo table with 2 fields
<p>The Dynamodb table has 1 partition key and 2 fields. I'm trying to increment a or b by 1.</p> <p>I get cur_count for a or b(which is 0) from the table and +1 to it.</p> <p>The error:</p> <pre><code>An error occurred (ValidationException) </code></pre> <p>When calling the UpdateItem operation:</p> <pre><code>Invalid...
<python><amazon-web-services><amazon-dynamodb>
2023-01-09 07:19:28
1
24,573
ERJAN
75,054,152
17,402,986
Not Authorised Error: AWS lambda ec2.run_instances from launch template with boto3
<p>I am trying to run aws ec2 instances from my lambda. Creating instance from local machine works when I tried this -</p> <pre><code>import boto3 launchTemplateId = 'lt-000' ec2 = boto3.client('ec2', region_name='ap-xx-1') template_specifics = { 'LaunchTemplateId': launchTemplateId } resp = ec2.run_instances( ...
<python><amazon-web-services><amazon-ec2><boto3>
2023-01-09 07:18:18
1
1,205
ashraf minhaj
75,054,091
3,099,733
How to print literal/quoted string in python for safety purpose?
<p>Given the following python script:</p> <pre class="lang-py prettyprint-override"><code>s = &quot;hello world&quot; print(s) </code></pre> <p>When you run it you will get</p> <pre class="lang-bash prettyprint-override"><code>hello world </code></pre> <p>If I want the output to be</p> <pre><code>&quot;hello world&quot...
<python>
2023-01-09 07:10:31
2
1,959
link89
75,053,839
3,179,698
Python pandas keep first columns' order unchanged while second col sort by ascending order
<p>Hi I want to keep the column infoid order unchanged but sort date in increasing order(acsending) Is that possible?</p> <pre><code>statisticsdate infoid 20230108 46726004 20230106 46726004 20230108 46725082 20230107 46725082 20230108 46725081 20230108 46724162 20230108 46720662 <...
<python><pandas><dataframe>
2023-01-09 06:32:37
2
1,504
cloudscomputes
75,053,771
12,724,372
fastest way to replace values in one df with values from another df
<p>I have a dataframe df1 that looks like this :</p> <pre><code>class val 12 1271 12 1271 34 142 34 142 </code></pre> <p>and another df2 that looks like this</p> <pre><code>class val 12 123 34 141 69 667 </code></pre> <p>What would be the fastest way to map CorrectVal to df1...
<python><pandas>
2023-01-09 06:21:14
1
1,275
Devarshi Goswami
75,053,702
2,913,139
python mysql - is commit() required for SELECT?
<p>I have a very simple python code getting some data from mysql:</p> <pre><code> version = 1 with conn.cursor() as cur: query = f'select latest_version from version' cur.execute(query) for row in cur: version = int(row[0]) cur.close() print(version) </code></pre...
<python><mysql>
2023-01-09 06:09:48
1
617
user2913139
75,053,357
8,283,848
url tag not finding existing 'google_login' view function of django-allauth
<p>I have a simple HTML content point towards the Google Login, as below.</p> <pre><code># foo.html &lt;a class=&quot;p-2 text-dark&quot; href=&quot;{% url 'google_login' %}&quot;&gt;Google Login&lt;/a&gt; </code></pre> <p>This simple demo project <em><strong>was</strong></em> using <code>django==3.2.x</code> and <cod...
<python><django><django-urls><django-allauth>
2023-01-09 05:02:06
0
89,380
JPG
75,053,273
1,436,800
How to save list of objects in DRF
<p>I am new to django. I have following model:</p> <pre><code>class Standup(models.MOdel): team = models.ForeignKey(&quot;Team&quot;, on_delete=models.CASCADE) standup_time = models.DateTimeField(auto_now_add=True) employee = models.ForeignKey(&quot;Employee&quot;, on_delete=models.CASCADE) update_t...
<python><django><django-models><django-rest-framework><django-views>
2023-01-09 04:46:31
3
315
Waleed Farrukh
75,053,239
11,266,345
Downloading pytorch3d installtion no c++ compiler
<p>I have been trying to download pytorch3d on my PC however it keeps failing. I believe its because of the c++ compiler but I am not sure.</p> <pre><code>FAILED: C:/Users/Virtual Machine/AppData/Local/Temp/pip-req-build-fu0xd6su/build/temp.win-amd64-cpython-310/Release/Users/Virtual Machine/AppData/Local/Temp/pip-req-...
<python><c++><pip><pytorch><pytorch3d>
2023-01-09 04:39:12
0
341
Sai Veeramachaneni
75,053,229
668,498
ModuleNotFoundError: No module named '_bz2' in Google Cloud Workstation
<p>I launched a new Google Cloud Workstation and create a single python file with these contents:</p> <pre><code>import bz2 import binascii original_data = 'This is the original text.' print ('Original :', len(original_data), original_data) compressed = bz2.compress(original_data) print ('Compressed :', len(com...
<python><google-cloud-platform><bzip2><bz2><google-cloud-workstations>
2023-01-09 04:36:03
0
3,615
DanielAttard
75,053,220
12,131,472
from dataframe to the body of Email automatically,several formatting issues: thousand separator, color(red for negative number and green for positive)
<p>I have a dataframe look like this</p> <pre><code> date value value 2 daily value change shortCode TD1 2023-01-06 38.67 15162.0 -1.00 TD2 2023-01-06 53.42 33952.0 -0.40 TD3C ...
<python><pandas><dataframe><email><formatting>
2023-01-09 04:34:27
1
447
neutralname
75,053,092
597,858
Able to plot 2 graphs in a row but not 3. get ValueError: values must be a 1D array
<p>This is the dataframe:</p> <pre><code>Data for last 8 months date close volume change% obv compare close_trend 6 2022-06-30 00:00:00+05:30 18760.40 358433 5.52 1358338 True 18482.242046 7 2022-07-31 00:00:00+05:30 20015.10 252637 6.27 1610975 True 1890...
<python><matplotlib>
2023-01-09 04:04:53
0
10,020
KawaiKx