QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
74,787,475
13,517,174
How do you slice an array of a dynamic dimension in numba?
<p>I have a script that looks as following:</p> <pre><code>import numba as nb @nb.njit def test(v): n = 1 if len(v.shape)&gt;1: n = max(n,v.shape[1]) return n test(np.array([1,2])) </code></pre> <p>This works fine without the <code>njit</code> decorator, but when I use it like in my example I get th...
<python><numba>
2022-12-13 15:47:04
0
453
Yes
74,787,251
4,613,465
TensorFlow display progress while iterating dataset
<p>I have a very large dataset (raw files ~750GB) and I created a cached dataset pipeline using the TensorFlow data API like this:</p> <pre><code>dataset = tf.data.Dataset.from_generator(MSUMFSD(pathlib.Path(dataset_locations[&quot;mfsd&quot;]), True), output_types=(tf.string, tf.float32)) </code></pre> <p>This dataset...
<python><tensorflow><dataset><pipeline><data-preprocessing>
2022-12-13 15:30:37
1
772
Fatorice
74,787,173
8,755,105
marshmallow - How can I map the schema attribute to another key when deserializing?
<p>I need to have a &quot;from&quot; field in my marshmallow schema, but since it is a Python reserved keyword, I am unable to use the name.</p> <p>Input data has &quot;from&quot; key and deserialized map should also have &quot;from&quot; key. Stumbled upon <a href="https://stackoverflow.com/questions/51727441/marshmal...
<python><marshmallow>
2022-12-13 15:25:11
1
903
Roman Yakubovich
74,787,150
2,725,810
Cache performance of Python array (not list)
<p>I understand that Python's <code>array</code> provided by the array module stores consecutively the actual values (not pointers). Hence I would expect that, when elements of such an array are read in order, CPU cache would play a role.</p> <p>Thus I would expect that Code A below should be faster than Code B (the di...
<python><arrays><cpu-cache>
2022-12-13 15:23:13
1
8,211
AlwaysLearning
74,787,078
11,252,809
Alpine x-transition doesn't work inside jinja2 template for loop
<p>Inside this code, I can get the two divs to toggle when showOriginal is toggled, but the animation simply doesn't work? In this case, summaries are sqlmodel objects rendered by Jinja2.</p> <pre><code> {% for summary in summaries %} &lt;div x-data=&quot;{showOriginal: true }&quot; class=&quot; flex flex-row&quot;...
<javascript><python><jinja2><fastapi><alpine.js>
2022-12-13 15:18:12
1
565
phil0s0pher
74,787,036
10,357,604
How to resolve this pip install error (when trying to install mxnet)?
<p>I am working with anaconda &amp; run the cmd:<code>pip instal mxnet</code>. I already tried to upgrade <code>pip,wheel,setuptools</code>. &amp; to instal it with <code>--no-use-pep517</code>,<code>--no-cache-dir</code> &amp; <code>--pre</code> as recommended here:<a href="https://bobbyhadz.com/blog/python-eror-legac...
<python><numpy><pip><legacy><mxnet>
2022-12-13 15:15:06
1
1,355
thestruggleisreal
74,786,966
12,760,550
How to confirm that sequences of ids in a column comply to a given rule?
<p>I have a dataframe that contains the information of different &quot;contract types&quot; in a company: Employee, Consultant, Non Employee.</p> <p>Each row represents a contract and one person (meaning someone with same first name and last name) can have more than 1 contract, and the contract can be either one of the...
<python><pandas><dataframe><filter><lambda>
2022-12-13 15:10:16
1
619
Paulo Cortez
74,786,941
17,762,566
How to match substring in a list of nested dictionary in python?
<p>I am stuck with the below issue where I am trying to search for specific <code>value</code> in a nested dictionary inside of a nested list. It doesn't have to completely match but more like <code>contains</code>. Below is the example data</p> <pre><code>data=[[{'A': 'test1'}, {'A': 'test2'}, {'BB': {'A': '111testabc...
<python><python-3.9>
2022-12-13 15:08:34
3
793
Preeti
74,786,854
5,921,731
Networkx cutting of the image
<p>I am trying to create a graph using NetworkX using the following code:</p> <pre><code>def plotgraph(stringdatafile,alldelays,columns): &quot;&quot;&quot;Plots a temporal causal graph showing all discovered causal relationships annotated with the time delay between cause and effect.&quot;&quot;&quot; ...
<python><networkx>
2022-12-13 15:02:59
1
472
sidra Aleem
74,786,712
12,709,265
Read image labels from a csv file
<p>I have a dataset of medical images (<code>.dcm</code>) which I can read into <code>TensorFlow</code> as a batch. However, the problem that I am facing is that the labels of these images are in a <code>.csv</code>. The <code>.csv</code> file contains two columns - <code>image_path</code> (location of the image) and <...
<python><python-3.x><tensorflow><tensorflow2.0>
2022-12-13 14:53:59
1
1,428
Shawn Brar
74,786,592
9,390,633
Split a dataframe by length of characters
<p>I have a table like</p> <pre class="lang-none prettyprint-override"><code>--------------------| Val --------------------| 1, M A ,HELLO,WORLD | 2, M 1A,HELLO WORLD | --------------------- </code></pre> <p>I want to split the above dataframe so it contains the three columns below.</p> <pre class="lang-none prettyprin...
<python><apache-spark><pyspark>
2022-12-13 14:44:14
4
363
lunbox
74,786,423
726,730
python check web radio url
<p><strong>File: check_web_radio.py</strong></p> <pre class="lang-py prettyprint-override"><code>from subprocess import Popen import subprocess import os import sys def check_retransmition(stream_url): try: print(&quot;Checking url:&quot;+str(stream_url)) if os.path.exists(&quot;outputfile.mp3&quot...
<python><webradio>
2022-12-13 14:29:46
1
2,427
Chris P
74,786,177
3,247,006
split() vs rsplit() in Python
<p>I used <code>split()</code> and <code>rsplit()</code> as shown below:</p> <pre class="lang-py prettyprint-override"><code>test = &quot;1--2--3--4--5&quot; print(test.split(&quot;--&quot;)) # Here print(test.rsplit(&quot;--&quot;)) # Here </code></pre> <p>Then, I got the same result as shown below:</p> <pre class="l...
<python><split>
2022-12-13 14:11:16
2
42,516
Super Kai - Kazuya Ito
74,786,109
1,142,881
Zombie xlwings Python processes hanging after closing excel
<p>Is there a way from VBA to kill hanging zombie <a href="https://docs.xlwings.org/en/stable/index.html" rel="nofollow noreferrer">xlwings</a> Python processes before opening or after closing Excel? I'm happy to take a solution from either VBA or Python, I don't really mind which.</p> <p>For example, in VBA I could do...
<python><excel><vba><xlwings><taskkill>
2022-12-13 14:06:57
1
14,469
SkyWalker
74,786,100
1,264,820
Typing and pint
<p>I'm using <code>pint</code> to use and convert units. I wanted to create classes which restricts the quantities only to &quot;[time]&quot; or &quot;[length]&quot; dimensions, so as a first approach I did the following:</p> <pre class="lang-py prettyprint-override"><code>from pint import Quantity, DimensionalityError...
<python><mypy><typing><pint>
2022-12-13 14:06:07
1
1,483
JLDiaz
74,786,083
6,729,591
Fill a plot with color from a y upwards to infinity
<p>I am trying to indicate a &quot;dangerous&quot; zone in my sns boxplot.</p> <p>So far this is what i came up with:</p> <pre class="lang-py prettyprint-override"><code>plt.fill_between([0, 6], [danger, danger], danger * 1.2, color='salmon', alpha=0.5) </code></pre> <p>But since I use <code>sns</code> boxplot, the x v...
<python><matplotlib><seaborn>
2022-12-13 14:04:59
0
1,404
Dr. Prof. Patrick
74,786,028
20,078,696
How to convert window coords into turtle coords (Python Turtle)
<p>I am trying to create a program to move the turtle to where the mouse is. I am doing:</p> <pre><code>import turtle t = turtle.Turtle() canvas = turtle.getcanvas() while True: mouseX, mouseY = canvas.winfo_pointerxy() t.goto(mouseX, mouseY) </code></pre> <p>but the turtle keeps moving off the screen. I read...
<python><coordinates><turtle-graphics><python-turtle>
2022-12-13 14:01:13
2
789
sbottingota
74,786,016
2,457,899
Install GRASS GIS and use it with python in Linux machines?
<p>Is there a bash script to install GRASS GIS and use it with python in Linux machines?</p>
<python><linux><gis><grass>
2022-12-13 13:59:58
2
4,041
gcamargo
74,785,987
7,800,760
Python: sum dataframe rows with same datetime year
<p>I have a dataframe with two datetime columns and a third column with a numeric value. Here is an example:</p> <pre><code>2019-01-01 00:00:00 2019-12-31 00:00:00 118433.0 2020-01-01 00:00:00 2020-12-31 00:00:00 120087.0 2021-01-01 00:00:00 2021-06-30 00:00:00 63831.0 2021-07-01 00:00:00 2021-12-31 00:00:00 63089.0 20...
<python><pandas><datetime>
2022-12-13 13:57:24
0
1,231
Robert Alexander
74,785,938
7,133,942
How to change the size of the axis values in Matplotlib
<p>I have the following Matplotlib plot:</p> <pre><code>import numpy as np import statsmodels.api as sm import matplotlib.pyplot as plt price_values = [[4.2], [4.1], [4], [3.8], [3.9], [4.2], [4.5], [4.8], [5.2], [5.2], [5.2], [5.6], [5.2], [5.1], [5.3], [6],...
<python><matplotlib>
2022-12-13 13:54:04
0
902
PeterBe
74,785,911
12,113,958
Add row duplicated for a value missed in a Series
<p>I want to add a row that is a duplicate of the previous one for a missed value</p> <pre><code>df = pd.DataFrame({'A':[0,1,2,3,5,6,7], 'B':['green','red','blue','blue','black','white','green']}) </code></pre> <p>In this case the missed value in A column is 4 so I want add row with value 4 in column A and blue in colu...
<python><pandas><dataframe>
2022-12-13 13:52:00
1
529
luka
74,785,745
986,437
doubts about python3 absolute imports
<p>I know in python we can use absolute imports and these imports start at the root folder of the poject, example:</p> <pre><code>MyProject ├── module1.py ├── module2.py ├── package1 | ├──__init__.py | └── module3.py └── package2 ├── __init__.py └── module4.py </code></pre> <p>My question is, how does pytho...
<python><import>
2022-12-13 13:38:41
1
2,892
GionJh
74,785,736
3,752,268
How to periodically call instance method from a separate process
<p>I'm trying to write a class to help with buffering some data that takes a while to read in, and which needs to be periodically updated. The python version is 3.7. There are 3 criteria I would like the class to satisfy:</p> <ul> <li>Manual update: An instance of the class should have an 'update' function, which reads...
<python><multiprocessing>
2022-12-13 13:37:37
2
2,816
bjarkemoensted
74,785,720
1,635,525
python: prevent discarding of the function return value
<p>There's a common error in the code where people write something like:</p> <pre><code>if (id): query.filter(row.id == id) </code></pre> <p>instead of</p> <pre><code>if (id): query = query.filter(row.id == id) </code></pre> <p>The code looks &quot;valid&quot; and it's very hard to spot these by hand. In C++ th...
<python><mypy><pylint><nodiscard>
2022-12-13 13:35:46
0
586
salmin
74,785,680
15,852,600
How to format a dataframe having many NaN values, join all rows to those not starting with NaN
<p>I have the follwing <code>df</code>:</p> <pre><code>df = pd.DataFrame({ 'col1': [1, np.nan, np.nan, np.nan, 1, np.nan, np.nan, np.nan], 'col2': [np.nan, 2, np.nan, np.nan, np.nan, 2, np.nan, np.nan], 'col3': [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 3, np.nan], 'col4': [np.nan, np.nan, np.nan, 4, n...
<python><pandas><dataframe>
2022-12-13 13:32:03
3
921
Khaled DELLAL
74,785,615
4,865,723
Seaborns tight layout do cut the plot title
<p>In the plot the title is cut on the right side of it because I used <code>tight_layout()</code>.</p> <p><a href="https://i.sstatic.net/3U0q0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/3U0q0.png" alt="enter image description here" /></a></p> <p>Can I prevent this somehow?</p> <p>Here is the MWE fo...
<python><seaborn>
2022-12-13 13:27:00
1
12,450
buhtz
74,785,610
2,244,274
GUNICORN FastAPI Deployment with Proxy
<p>I am currently setting up a FastAPI application to run on an AWS RockyLinux 8 instance with a <a href="https://gunicorn.org/" rel="nofollow noreferrer">gunicorn</a> deployment. Most of the documentation that I have read recommends NGINX as a proxy server.</p> <p>I currently have an Apache sever running on this insta...
<python><nginx><fastapi><gunicorn>
2022-12-13 13:26:39
0
999
Jamie_D
74,785,520
13,775,706
generate a occupancy map from x, y coordinates of an irregular shape, script dying from SIGKILL
<p>I have a number of CSV files with x, y, and z coordinates. These coordinates are not long/lat, but rather a distance from an origin. So within the CSV, there is a 0,0 origin, and all other x, y locations are a distance from that origin point in meters.</p> <p>The x, and y values will be both negative and positive fl...
<python><occupancy-map>
2022-12-13 13:19:29
2
304
Michael
74,785,502
2,919,585
Python: Iteratively change superclass methods
<p>I want to create a class <code>Packet</code> identical to <code>list</code> except that it can be compared to <code>int</code> objects. Comparing to an <code>int</code> shall return the same result as comparing to a <code>Packet</code> containing only that <code>int</code>. The following definition does what I want....
<python><inheritance><operator-overloading><super>
2022-12-13 13:18:00
1
571
schtandard
74,785,476
13,635,877
use a list plus some strings to select columns from a dataframe
<p>I am trying to make a dynamic list and then combine it with a fixed string to select columns from a dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame([], columns=['c1','c2','c3','c4']) column_list= ['c2','c3'] df2 = df[['c1',column_list]] </code></pre> <p>but I get the following error:</p> <pre><co...
<python><pandas><dataframe>
2022-12-13 13:15:36
1
452
lara_toff
74,785,427
17,696,880
How to capture string of characters from where it is indicated to the first point followed by a line break?
<pre class="lang-py prettyprint-override"><code>import re x = &quot;&quot;&quot;44 5844 44554 Hi hi! , sahhashash; asakjas. jjksakjaskjas. ooooooppkkk&quot;&quot;&quot; #both initial after the last line break that they have within their capture range # ((?:\w+)?) ---&gt; with a capturing group this pattern can c...
<python><python-3.x><regex><string><regex-group>
2022-12-13 13:11:16
2
875
Matt095
74,785,327
1,831,518
Programmatically trigger a SageMaker's Notebook instance
<p>So to start with, I currently have a system on AWS that does the following</p> <ol> <li>Collects user data (consent is assumed of course) and store it in an S3 bucket</li> <li>Uses Sagemaker notebook instance to train on the user data and deploys an endpoint. The endpoint is later invoked by a lambda function (I fol...
<python><amazon-web-services><amazon-s3><jupyter-notebook><amazon-sagemaker>
2022-12-13 13:03:34
1
3,094
A.Shoman
74,785,245
1,969,638
How do I use a match statement to pattern match the class of multiple values in python?
<p>I have a union type, and I can create a value for it like so:</p> <pre><code>import random class X: s: str = 'ab' MyType = int | X def get_value() -&gt; MyType: if random.random() &gt; 0.5: return 3 return X() a = get_value() </code></pre> <p>And I can use a match statement to pattern match on...
<python><switch-statement><pattern-matching><union-types><pyright>
2022-12-13 12:57:17
1
905
Zantier
74,785,188
4,564,080
Pytorch complaining about input and label batch size mismatch
<p>I am using Huggingface to implement a BERT model using <code>BertForSequenceClassification.from_pretrained()</code>.</p> <p>The model is trying to predict 1 of 24 classes. I am using a batch size of 32 and a sequence length of 66.</p> <p>When I try to call the model in training, I get the following error:</p> <pre c...
<python><pytorch><huggingface-transformers>
2022-12-13 12:53:33
1
4,635
KOB
74,785,155
14,058,726
How to slice a pandas DataFrame between two dates (day/month) ignoring the year?
<p>I want to filter a pandas DataFrame with DatetimeIndex for multiple years between the 15th of april and the 16th of september. Afterwards I want to set a value the mask.</p> <p>I was hoping for a function similar to <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.between_time.html" rel="nofoll...
<python><pandas><dataframe>
2022-12-13 12:51:31
1
6,392
mosc9575
74,785,131
9,333,987
Nested dictionary with key: list[key:value] pairs to dataframe
<p>I'm currently struggling with creating a dataframe based on a dictionary that is nested like <code>{key1:[{key:value},{key:value}, ...],key2:[{key:value},{key:value},...]}</code> And I want this to go into a dataframe, where the value of <code>key1 and key2</code> are the index, while the <code>list</code> nested <...
<python><pandas><dataframe>
2022-12-13 12:49:15
2
339
Wokkel
74,785,045
8,496,414
Best way to get a specific column as y in pandas DataFrame
<p>I want to extract one specific column as y from a pandas DataFrame.<br /> I found two ways to do this so far:</p> <pre><code># The First way y_df = df[specific_column] y_array = np.array(y_df) X_df = df.drop(columns=[specific_column]) X_array = np.array(X_df) # The second way features = ['some columns in my dataset...
<python><pandas><feature-extraction>
2022-12-13 12:42:37
1
537
Sara
74,785,000
10,938,315
regex split on uppercase, but ignore titlecase
<p>How can I split <code>This Is ABC Title</code> into <code>This Is, ABC, Title</code> in Python? If is use <code>[A-Z]</code> as regex expression it will be split into <code>This, Is, ABC, Title</code>? I do not want to split on whitespace.</p>
<python><regex>
2022-12-13 12:39:12
1
881
Omega
74,784,836
7,713,770
How to calculate the difference between dictionary and list values?
<p>I currently have a <code>dictionary</code> and a <code>list</code>, and I would like to subtract the list values from the respective dictionary values (based on index position). This is what I have tried so far:</p> <pre class="lang-py prettyprint-override"><code>dict1 = { &quot;appel&quot;: 3962.00, &quot;w...
<python>
2022-12-13 12:25:28
2
3,991
mightycode Newton
74,784,774
3,416,725
How to sum specific row values together in Sparse COO matrix to reshape matrix
<p>I have a sparse coo matrix built in python using the scipy library. An example data set looks something like this:</p> <pre><code>&gt;&gt;&gt; v.toarray() array([[1, 0, 2, 4], [0, 0, 3, 1], [4, 5, 6, 9]]) </code></pre> <p>I would like to add the 0th index and 2nd index together and the 1st index and t...
<python><numpy><scipy><sparse-matrix>
2022-12-13 12:20:40
2
493
mp252
74,784,575
17,277,677
summing by keywords and by groups in pandas
<p>I have a following problem:</p> <p>a dataframe with keywords and groups:</p> <p><a href="https://i.sstatic.net/xKaxR.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xKaxR.png" alt="enter image description here" /></a></p> <p>my task is to look for these keywords in another dataframe in the given descr...
<python><pandas><dataframe>
2022-12-13 12:01:57
1
313
Kas
74,784,338
5,024,631
Pandas new column with groupby correlation results
<p>Here's my dataframe:</p> <pre><code>sample_df = pd.DataFrame({'id': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'], 'values_1':[2,4,6,8,12,13,13,17], 'values_2':[3,6,7,9,3,2,2,5]}) </code></pre> <p>I would like to add a new column with some summary statistics such as the...
<python><pandas><group-by><correlation>
2022-12-13 11:44:51
2
2,783
pd441
74,784,295
9,182,743
Install package using setup.py
<p>I want to create and install my own packages, so I can import functionality.py into script.py into otehr functions in the program. Following on from <a href="https://www.datasciencelearner.com/importerror-attempted-relative-import-parent-package/" rel="nofollow noreferrer">these instructions</a>, I have:</p> <h2>Pro...
<python><import><setup.py>
2022-12-13 11:41:09
1
1,168
Leo
74,784,277
4,720,018
How to impose constraints on sub-dependencies in setuptools?
<h3>Background</h3> <p>Suppose my package depends on the <code>foo</code> package, and <code>foo</code>, in turn, depends on the <code>bar</code> package, specifically <code>bar&gt;=1.0.0</code>.</p> <p>In other words, <code>bar</code> is a sub-dependency for my package.</p> <p>Following <a href="https://packaging.pyth...
<python><dependencies><setuptools>
2022-12-13 11:39:43
1
14,749
djvg
74,784,248
12,811,183
List comprehension with pattern match in Python
<p>I have one list named <em>columns</em>, and I have to create one nested list based on a split of the elements (the first three).</p> <p>For example, I will divide this element '101 Drive 1 A' in '101 Drive 1' and make a group.</p> <pre><code>columns = ['101 Drive 1 A','101 Drive 1 B','102 Drive 2 A','102 Drive 2 B',...
<python><list-comprehension>
2022-12-13 11:37:42
2
521
sizo_abe
74,784,126
848,746
List comprehension on a list of dictionaries
<p>I have a list of dictionaries like so:</p> <pre><code>[{'end': 34, 'entity_group': 'ORG', 'score': 0.99919325, 'start': 0, 'word': ' Community College Alabama'}, {'end': 54, 'entity_group': 'LOC', 'score': 0.90115756, 'start': 42, 'word': ' Maxwell Blvd'}, {'end': 66, 'entity_group': 'LOC', 'sc...
<python>
2022-12-13 11:28:44
3
5,913
AJW
74,783,807
1,892,584
Making tqdm write to log files
<p><a href="https://github.com/tqdm/tqdm" rel="noreferrer">tqdm</a> is a nice python library to keep track of progress through an iterable.</p> <p>It's default mode of operation is to repeatedly clear a line and <a href="https://github.com/tqdm/tqdm/issues/750" rel="noreferrer">redraw with a carriage</a> but this prod...
<python><logging><tqdm><python-logging>
2022-12-13 11:03:20
2
1,947
Att Righ
74,783,571
16,389,095
How to find all occurences of a substring in a numpy string array
<p>I'm trying to find all occurences of a substring in a numpy string array. Let's say:</p> <pre><code>myArray = np.array(['Time', 'utc_sec', 'UTC_day', 'Utc_Hour']) sub = 'utc' </code></pre> <p>It should be case insensitive, so the method should return [1,2,3].</p>
<python><arrays><string><numpy>
2022-12-13 10:45:03
3
421
eljamba
74,783,412
6,212,718
Python streamlit - subprocess
<p>I have created a streamlit app which runs fine on my local machine. However, I cannot get it running on the streamlit-cloud. In a nutshell my app does the following:</p> <ol> <li>take some user input</li> <li>create a markdown file from the input (&quot;deck.md&quot;)</li> <li>convert markdown file to html file (&qu...
<python><subprocess><streamlit><npx>
2022-12-13 10:31:33
0
1,489
FredMaster
74,783,366
142,234
Python multiple modules in the same root folder import error
<p>I'm trying to organise my python project with the following structure:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul id="myUL"&gt; &lt;li&gt;&lt;span&gt;Roo...
<python><python-module>
2022-12-13 10:28:23
0
13,915
bAN
74,783,300
125,673
Python Pandas: Using corrwith and getting "outputs are collapsed"
<p>I want to find out how a column of data in a matrix correlates with the other columns in the matrix. The data looks like; <a href="https://i.sstatic.net/CickG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/CickG.png" alt="enter image description here" /></a> I use the following code;</p> <pre><code>s...
<python><pandas><visual-studio-code><jupyter>
2022-12-13 10:22:22
1
10,241
arame3333
74,783,236
10,581,944
Is there a way to compare two dataframes and report which column is different in Pyspark?
<p>I'm using <code>df1.subtract(df2).rdd.isEmpty()</code> to compare two dataframes (assuming the schema of these two df are the same, or at least we expect them to be the same), but if one of the column doesn't match, I can't tell from the output logs, and it takes long time for me to find out the issue in the data (a...
<python><dataframe><apache-spark><pyspark><apache-spark-sql>
2022-12-13 10:16:50
1
3,433
wawawa
74,783,147
20,279,779
Count the frequency of users occuring in a list using python
<p>I have a table in postgresql database. From that table I have extracted data using the sql statement mentioned below:</p> <pre><code>sql_statement = &quot;&quot;&quot; select a.slno, a.clientid, a.filename, a.user1_id, b.username, a.user2_id, c.username as username2, a.uploaded_ts, a.status_id from m...
<python><postgresql>
2022-12-13 10:10:58
2
343
AstroInTheOcean
74,783,117
7,295,169
How to translate C double two-dim data using python ctypes?
<p>I try use python <code>ctypes</code> call a dll and translate <code>api</code> in python code. But I meet a function that have two-dimensional array and I dont know how to translate it now.I had forgot my <code>C++&amp;C</code> language. <code>TCHAR</code> is a type like this <code>char *p</code>.</p> <h4>show in r...
<python><ctypes>
2022-12-13 10:09:35
1
1,193
jett chen
74,783,071
5,376,493
Reading binary file to find a sequences of ints little endian (permutations)
<p>Try to read a binary file (firmware) with a sequences like</p> <pre><code>\x01\x00\x00\x00\x03\x00\x00\x00\x02\x00\x00\x00\x04\x00\x00\x00 </code></pre> <p>Little endian integer 1,3,2,4</p> <p>Attempt:</p> <pre><code>with open(&quot;firm.bin&quot;, 'rb') as f: s = f.read() N = 16 allowed = set(range(4)) for val...
<python>
2022-12-13 10:06:17
3
1,189
dev
74,783,066
1,070,092
Python/PySide6: Apply different style to sub class
<p>Cant figure out the solution of the problem. The style of the sub class is identical to the base class:</p> <pre><code>import sys from PySide6.QtGui import * from PySide6.QtWidgets import * from PySide6.QtCore import * class MyLabel(QLabel): def __init__(self, pText: str) -&gt; None: super().__init__() ...
<python><pyside6>
2022-12-13 10:05:59
1
345
Vik
74,783,029
10,992,997
avoid blank line when reading names from .txt into python list
<p>I'm trying read a list of names from a .txt file into python so I can work with it.</p> <pre><code>humans = ['Barry', 'Finn', 'John', 'Jacob', '', 'George', 'Ringo', ''] with open(p_to_folder / 'humans.txt', 'w') as f:#using pathlib for my paths for h in humans: f.write(f'{h}\n') </code></pre> <p>What I...
<python><if-statement><list-comprehension>
2022-12-13 10:03:05
2
581
KevOMalley743
74,782,990
1,139,541
Patch method in a package that is shadowed in __init__.py
<p>I have a folder structure like this:</p> <pre><code>├─ some_module/ │ ├─ __init__.py │ ├─ module.py ├─ main.py </code></pre> <p>With the sub-module being shadowed by its content:</p> <pre><code># __init__.py from .module import module __all__ = [&quot;module&quot;] </code></pre> <pre><code># module.py def module_...
<python>
2022-12-13 10:00:37
1
852
Ilya
74,782,988
12,777,005
Why are half my uniforms missing when initializing a compute shader using python modernGL?
<p>Here is the problem: I'm creating a compute shader in python for radiative transfer using modernGL. But upon creation, it does not contain all the uniforms I declare in the shader code. Here is my (simplified) python code:</p> <pre><code># Creation of the context context = mgl.create_standalone_context(require=440) ...
<python><glsl><compute-shader><python-moderngl>
2022-12-13 10:00:28
1
325
Azireo
74,782,925
5,191,553
select color attributes via python in blender
<p>Is it possible to select color attributes in blender with python? Idea is to do the same like clicking on the vertex color in viewport. The goal is to make the colors visible in the viewport.</p> <p>My current approach looks like this:</p> <pre><code># accessing color attributes test_1 = bpy.data.meshes['Cube'].colo...
<python><colors><blender><vertex>
2022-12-13 09:54:43
1
531
Christoph Müller
74,782,862
12,740,468
Fancy indexing in numpy
<p>I am basically trying to do something like this but without the for-loop... I tried with <code>np.put_along_axis</code> but it requires <code>times</code> to be of dimension 10 (same as last index of <code>src</code>).</p> <pre class="lang-py prettyprint-override"><code> import numpy as np src = np.zeros((5,5,10), ...
<python><numpy>
2022-12-13 09:50:12
1
358
Antoine Collet
74,782,778
18,396,935
Pass from one file to another a constant variable, without using function parameters
<p>I have the following code to generate probability labels on generated tabular dataframes.</p> <pre><code>from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import KFold from sklearn.model_selection import GridSearchCV, cross_val_score from keras.models import Sequential from keras.layer...
<python><dataframe><keras><scikit-learn>
2022-12-13 09:44:08
1
366
Carola
74,782,709
5,515,287
How to embed and run a jar file using python
<p>I have a python script that will run the jar file when script is executed:</p> <pre><code>import subprocess jdk_path = &quot;jdk\\bin\\java.exe&quot; jfx_path = &quot;javafx\\lib&quot; modules = &quot;javafx.controls,javafx.fxml,javafx.swing&quot; jar_file = &quot;setup.jar&quot; command = jdk_path + &quot; --modul...
<python><auto-py-to-exe>
2022-12-13 09:38:58
1
3,123
Mustafa Poya
74,782,602
9,786,534
How to add a constant to negative values in array
<p>Given the xarray below, I would like to add 10 to all negative values (i.e, -5 becomes 5, -4 becomes 6 ... -1 becomes 9, all values remain unchanged).</p> <pre class="lang-py prettyprint-override"><code>a = xr.DataArray(np.arange(25).reshape(5, 5)-5, dims=(&quot;x&quot;, &quot;y&quot;)) </code></pre> <p>I tried:</p>...
<python><dask><python-xarray>
2022-12-13 09:30:02
2
324
e5k
74,782,472
2,075,630
Redirect subprocess stdout to stderr
<p>A standard feature Python's <code>subprocess</code> API is to combine STDERR and STDOUT by using the keyword argument</p> <pre><code>stderr = subprocess.STDOUT </code></pre> <p>But currently I need the opposite: Redirect the STDOUT of a command to STDERR. Right now I am doing this manually using <code>subprocess.get...
<python><subprocess><io-redirection>
2022-12-13 09:19:28
1
4,456
kdb
74,782,345
8,481,155
Apache Beam Count Rows and store in a variable Python
<p>I'm trying to count the number of elements in a PCollection and store it in a variable which I want to use it for further calculations. Any guidance on how I can do it?</p> <pre><code>import apache_beam as beam pipeline = beam.Pipeline() total_elements = ( pipeline | 'Create elements' &gt;&gt; beam.Create(...
<python><python-3.x><apache-beam>
2022-12-13 09:07:07
2
701
Ashok KS
74,782,227
607,846
Combine yielded values into a list
<p>I wish to create a list of objects in a unit test, but skip an object's creation if its corresponding config is None. This is an attempt, but can it be done better?</p> <pre><code>def object_factory(config, model): if config is not None: yield model(**config) def objects_factory(config1, config2): r...
<python>
2022-12-13 08:58:19
1
13,283
Baz
74,782,137
12,201,407
Python Datetime Subtraction include 0 to hour section
<p>I've 2 strings of datetime, I need to subtract those to get duration but when subtracted for hour section it only contain 1 digit eg: 1:30, 2:30 So, my question is can we get subtracted datetime or string which includes 0 at the beginning eg: 01:30, 02:30. Only for 1 - 9 hours include 0. Assume that there will be no...
<python><datetime><python-datetime><timedelta><python-dateutil>
2022-12-13 08:49:52
2
738
jeevu94
74,781,783
2,975,438
Pandas: how to add column with True/False if another column contain duplicate or not
<p>I have the following dataframe:</p> <pre><code>d_test = {'name' : ['Beach', 'Dog', 'Bird', 'Dog', 'Ant', 'Beach']} df_test = pd.DataFrame(d_test) </code></pre> <p>I want to add column <code>duplicate</code> with True/Fasle for each entry. I want <code>False</code> only for case if there only one entry in the column ...
<python><pandas>
2022-12-13 08:15:53
1
1,298
illuminato
74,781,771
14,046,645
How we can resolve "Solving environment: failed with initial frozen solve. Retrying with flexible solve." issue while installing the new conda package
<p>I have tried to install new package in conda for windows using the following command:</p> <p><code>conda install -c conda-forge python-pdfkit</code></p> <p>but got the following error:</p> <blockquote> <p>Collecting package metadata (current_repodata.json): done Solving environment: failed with initial frozen solve....
<python><python-3.x><anaconda><pdfkit><python-pdfkit>
2022-12-13 08:14:37
6
471
Rajesh Potnuru
74,781,686
16,971,617
Adding np array objects to a list
<p>I am trying to append a sub image which is numpy array objects to a list.</p> <pre class="lang-py prettyprint-override"><code> temp = [] for color in COLOUR_RANGE: #Some code to extract the color region which is represented in numpy if cv2.contourArea(coloured_cnt) &gt; 400: ...
<python><numpy>
2022-12-13 08:05:12
1
539
user16971617
74,781,683
12,064,467
Applymap on all but one Pandas DataFrame?
<p>I have a DataFrame <code>df</code> that looks like this:</p> <pre><code> 0 1 2 3 4 5 0 first M A F I L 1 second M A F I L 2 third M S F I I 3 fourth M S F I L 4 fifth M L F F I </code></pre> <p>I would like to change each element of each colu...
<python><pandas><dataframe>
2022-12-13 08:04:42
1
522
DataScienceNovice
74,781,617
1,106,951
How to import a class located in another root directory folder
<p>Using Python 3.7.9 and having a file directory hierarchy like this</p> <pre><code>Application | | | └── __init__.py | ├── CLS │ └── Article.py │ └── __init__.py │ └── OUT └── publish.py └── __init__.py </code></pre> <p>As you can see I have the <code>__init__.py</code> located in all folders <c...
<python>
2022-12-13 07:57:40
1
6,336
Behseini
74,781,604
4,821,337
How to read the value from kubernetes secret in python application and set them as environment variable
<p>I am trying to get values from kubernetes secret in my python application as environment variables, I see that secrets are created as separate files and mounted on a specific path(in my case I mount them on etc/secrets/azure-bs. There are five secret files namely</p> <ol> <li>accessKeyId</li> <li>bucket.properties</...
<python><environment-variables><azure-blob-storage><kubernetes-helm><kubernetes-secrets>
2022-12-13 07:56:28
1
359
capedCoder
74,781,497
10,394,971
How to create a dataframe using pandas based on comparing index with values of multiple columns in other dataframe
<p>I have two data source:</p> <pre><code>raw_data = {'site_394$line_2420$tag_144': {1670231589000: 7, 1671231589000: 7, 1672231589000: 9, 1673231589000: 7}, 'site_395$line_2420$tag_154': {1670231589000: 9, 1671231589000: 10, 1672231589000: 25, 1673231589000: 6}} </code></pre> <p>and</p> <pre><code>events_...
<python><pandas>
2022-12-13 07:46:51
1
2,635
Irfanuddin
74,781,114
12,559,770
Group overlaping start-end coordinates within groups in pandas
<p>I have a dataframe such as:</p> <pre><code>Groups Scaff start end G1 Scaff1 2278 4437 G1 Scaff1 2788 3048 G1 Scaff1 3959 4183 G1 Scaff1 4201 4407 G1 Scaff2 4553 5000 G1 Scaff2 6321 7700 G1 Scaff3 2870 5083 G1 Scaff4 1923 2042 G1 Scaff5 663 ...
<python><python-3.x><pandas>
2022-12-13 07:09:41
1
3,442
chippycentra
74,781,063
8,551,737
Converted tf.keras.layers.Conv2DTranspose to tflite can't run on the gpu
<p>I tried to converting tf2 keras model with Conv2DTranspose layer to tflite.</p> <p>But after converting to tflite, <strong>this model generates automatically <code>Shape</code> and <code>Pack</code> operation</strong>. That is a quiet problem for me because <strong>these operation can't be supported by mobile gpu</s...
<python><tensorflow><keras><tensorflow2.0><tflite>
2022-12-13 07:03:39
1
455
YeongHwa Jin
74,781,034
8,888,469
How to plot the frequency chart and world cloud from the frequency list created in Pandas
<p>I have data frame of n-grams frequency which is created by below code. How can create frequency plot and word cloud from the below output.</p> <p><strong>Code</strong></p> <pre><code>from sklearn.feature_extraction.text import CountVectorizer word_vectorizer = CountVectorizer(ngram_range=(3,3), analyzer='word') spar...
<python><pandas><matplotlib><nltk><word-cloud>
2022-12-13 06:59:41
0
933
aeapen
74,780,965
8,208,006
ls command - on progressive chunks in linux - large directory
<p>I have problem of listing files from really big directory.</p> <p><code>ls -l *.pdf</code> command is taking lot of time and for every disconnection its starting from first.</p> <p>i have tried few things</p> <pre><code>ls -l /**/*.pdf </code></pre> <p>and</p> <pre><code>find ./*.pdf -type d -maxdepth 1 -printf '%f\...
<python><linux><powershell><shell>
2022-12-13 06:51:58
0
4,607
Naga kiran
74,780,953
8,219,760
Add row-wise accuracy to a seaborn heatmap
<pre class="lang-py prettyprint-override"><code>import seaborn as sb import numpy as np from matplotlib import pyplot as plt A = np.array([[10, 5], [3, 10]], dtype=np.int32) plt.figure() sb.heatmap( A, square=True, annot=True, xticklabels=[&quot;False&quot;, &quot;Positive&quot;], ...
<python><numpy><matplotlib><seaborn>
2022-12-13 06:50:40
1
673
vahvero
74,780,800
59,300
How can I get a correct decimal results for a Python modulo operation (without extra libs)?
<p>I am trying to get a correct decimal (not scientific) expression for the following equation. It seems, by default, Python prints the scientific notation. I am using Python on an embedded system, so I cannot easily install libs. I am looking for a default way to get the correct result.</p> <pre><code>&gt;&gt;&gt; 429...
<python><math><modulo>
2022-12-13 06:31:22
1
7,437
wishi
74,780,599
1,473,517
How to do division of very large integers rounded to nearest integer?
<p>I have two very large integers x, y. How can I compute x/y rounded to the nearest integer in pure Python? x//y will give me the correct answer but rounded down.</p> <p>The numbers are big enough that round(x/y) will not give the correct answer due to floating point precision.</p> <p>I would like to avoid using any...
<python>
2022-12-13 06:06:30
2
21,513
Simd
74,780,524
6,787,723
how to get ray task again while the driver submit the task died?
<p>I have a question a bit similar to <a href="https://stackoverflow.com/questions/69613739/how-to-kill-ray-tasks-when-the-driver-is-dead">How to kill ray tasks when the driver is dead</a></p> <pre><code>ray.init(f&quot;ray://{head_ip}:10001&quot;) @ray.remote def compute(compute_params): # do some long computatio...
<python><ray>
2022-12-13 05:55:25
1
645
Tarjintor
74,780,473
2,975,438
How to do effective matrix computation and not get memory overload for similarity scoring?
<p>I have the following code for similarity scoring:</p> <pre><code>from rapidfuzz import process, fuzz import pandas as pd d_test = { 'name' : ['South Beach', 'Dog', 'Bird', 'Ant', 'Big Dog', 'Beach', 'Dear', 'Cat'], 'cluster_number' : [1, 2, 3, 3, 2, 1, 4, 2] } df_test = pd.DataFrame(d_test) names = df_test[...
<python><pandas><dataframe><rapidfuzz>
2022-12-13 05:49:25
1
1,298
illuminato
74,780,461
1,652,954
how to convert nested loops with body to parallelized iterables for multiprocessing
<p>i have the below two nested loops. i want to use them as iterables passed to .map operator to parallelize their execution.i am familiar with the following notation:</p> <pre><code>with PoolExec(max_workers=int(config['MULTIPROCESSING']['proceses_count']),initializer=self.initPool,initargs=(arg0,arg1,arg2,arg3,arg4,a...
<python><multiprocessing><python-multiprocessing>
2022-12-13 05:47:47
2
11,564
Amrmsmb
74,780,293
12,249,019
AWS S3 conditions and AWS lambda suffix/prefix
<p>I would like to upload image files to AWS S3 bucket which triggers a Lambda function that modify the images, using python <code>boto3</code> library and presigned URLs.<br /> And I would like to implement the following rules:</p> <ol> <li>Use the Content-Type condition to restrict the files to be uploaded only to im...
<python><amazon-web-services><amazon-s3><aws-lambda><boto3>
2022-12-13 05:17:50
1
389
yh6
74,780,215
7,984,318
Where are the python packages installed in docker
<p>I'm using docker in my Mac.</p> <p>Dockerfile:</p> <pre><code>#Dockerfile,Image,Container FROM python:3.8 ADD main.py . ADD test.py . ADD spy511282022.csv . RUN pip install requests pandas sqlalchemy RUN pip list CMD [&quot;python&quot;,&quot;./test.py&quot;] </code></pre> <p>My question is where are the packa...
<python><docker><docker-compose><dockerfile>
2022-12-13 05:05:23
1
4,094
William
74,780,164
13,285,583
PySpark Pandas UDF don't work on M1 Apple Silicon
<p>My goal is to use PySpark. The problem is when I tried to use Pandas UDF, it throws an error.</p> <p>What I did:</p> <ol> <li><code>pip install pyspark</code>.</li> <li>Initialize spark</li> </ol> <pre><code>from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() </code></pre> <ol start="3">...
<python><pandas><numpy><apache-spark><pyspark>
2022-12-13 04:58:24
0
2,173
Jason Rich Darmawan
74,780,158
982,786
ESports Match Predictor (Machine Learning)
<p>I think I'm starting to get the hang of some of the basics for machine learning, I've already completed three tutorial projects for stock price predicting, wine rating predictor, and a money ball (mlb) project. Now I am looking to do something a little more advanced with a personal project, but I can't seem to find ...
<python><python-3.x><machine-learning>
2022-12-13 04:57:10
2
3,599
Nefariis
74,780,128
4,451,521
A scattermapbox shows but it does not hover
<p>I have a dataframe df and I do</p> <pre><code> fig.add_trace(go.Scattermapbox( lat=one_mesh_p['lat'], lon=one_mesh_p['lon'], mode=&quot;markers&quot;, marker = { 'size': 5, 'color': &quot;blue&quot; }, ...
<python><plotly>
2022-12-13 04:54:15
0
10,576
KansaiRobot
74,780,034
8,303,951
TypeError: cannot pickle '_io.BufferedReader' object when sending e-mail with Django-mailer and Djoser
<h1>The problem</h1> <p>I'm trying to send a <a href="https://djoser.readthedocs.io/en/latest/settings.html#send-activation-email" rel="nofollow noreferrer">Djoser user's activation email</a> using <a href="https://github.com/pinax/django-mailer/" rel="nofollow noreferrer">django-mailer</a>.</p> <p>However, I receive t...
<python><django><django-rest-framework><djoser><django-mailer>
2022-12-13 04:38:46
0
476
Joao Albuquerque
74,779,902
678,572
Any dict-like mappable objects in Python that only show preview of contents when __repr__?
<p>I'm looking for an object I can use to store largish dataframes and sklearn objects. Ideally I would like to store them as <code>pd.Series</code> because it has the behavior I'm looking for in that I can do the following:</p> <ul> <li>Get the object using some key:value pair</li> <li>Preview truncates large outputs<...
<python><pandas><dictionary><mapping><namedtuple>
2022-12-13 04:14:11
0
30,977
O.rka
74,779,670
219,153
How to make a title for this multi-axis matplotlib plot?
<p>This function:</p> <pre><code>def plotGrid(ax, grid, text=''): ax.imshow(grid, cmap=cmap, norm=Normalize(vmin=0, vmax=9)) ax.grid(True, which='both', color='lightgrey', linewidth=0.5) ax.set_yticks([x-0.5 for x in range(1+len(grid))]) ax.set_xticks([x-0.5 for x in range(1+len(grid[0]))]) ax.set_xtickl...
<python><matplotlib>
2022-12-13 03:30:13
1
8,585
Paul Jurczak
74,779,644
20,762,114
Mapping a Python dict to a Polars series
<p>In Pandas we can use the <code>map</code> function to map a dict to a series to create another series with the mapped values. More generally speaking, I believe it invokes the index operator of the argument, i.e. <code>[]</code>.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd dic = { 1: 'a'...
<python><dataframe><python-polars>
2022-12-13 03:24:27
5
317
T.H Rice
74,779,376
656,780
Perl's Inline::Python Leads to Odd Error on AlmaLinux 8, but Not CentOS 7
<p>I'm trying to use <code>Inline::Python</code> to access the Braintree API that isn't available in Perl directly. It's code that has been working for years on a CentOS 7 server, but as I'm trying to move this code to a new, AlmaLinux 8 server, the very same code I've used for six years won't run, immediately failing ...
<python><perl><braintree>
2022-12-13 02:29:51
1
1,139
Timothy R. Butler
74,779,301
14,109,040
unable to assign free hole to a shell error when flattening polygons
<p>I have a list of polygons and I want to group them by the road_name property and flatten the polygons.</p> <p>I tried the following:</p> <pre><code>{&quot;type&quot;: &quot;FeatureCollection&quot;, &quot;features&quot;: [{&quot;type&quot;: &quot;Feature&quot;, &quot;properties&quot;: {&quot;compositeid&quot;: &quot;...
<python><geopandas><shapely>
2022-12-13 02:18:08
1
712
z star
74,779,287
8,124,392
How to access a Google Form from the Google API?
<p>The following code accesses Google Sheets in my account:</p> <pre><code>import gspread, json import pandas as pd from google.auth import default from google.colab import auth auth.authenticate_user() creds, _ = default() gc = gspread.authorize(creds) SCOPE = [&quot;https://spreadsheets.google.com/feeds&quot;] SE...
<python><pandas><google-sheets><google-api><google-forms>
2022-12-13 02:14:15
0
3,203
mchd
74,779,215
904,050
Building Python against Openssl 3.0 in nonstandard location
<p>I have successfully source compiled OpenSSL 3.0 and installed it in <code>/some/dir</code> via the following sequence:</p> <pre><code>$ wget https://github.com/openssl/openssl/archive/refs/tags/openssl-3.0.7.tar.gz $ tar -xvf openssl-3.0.7.tar.gz $ cd openssl-openssl-3.0.7/ $ ./Configure CC=clang --prefix=/some/dir ...
<python><openssl>
2022-12-13 02:01:03
0
5,311
user14717
74,779,179
3,102,471
Python CSV returning individual characters, expecting strings
<p>This program uses Python's CSV module to process a stream containing a CR/LF delimited list of comma separated values (CSV). Instead of getting a list of strings, with each string representing the text that appears between the delimiters (the commas), I'm getting a list of characters. The program uses <code>subpro...
<python><csv>
2022-12-13 01:54:37
1
1,150
mbmast
74,779,110
1,897,151
dataclass json for python make optional attribute
<p>Having this dataclass wish to be reuse in 2 different scenario</p> <pre><code>class TestResponse: name: str parameters: Optional[list[ActionParameters]] </code></pre> <p>when call it with</p> <pre><code>TestResponse( name=name, ) </code></pre> <p>without adding parameter attribute, will h...
<python>
2022-12-13 01:39:19
0
503
user1897151