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,229,875
9,983,652
how to replace part of string using regular expression?
<p>I have a dataframe like this:</p> <pre><code>fict={'well':['10B23','10B23','10B23','10B23','10B23','10B23'], 'tag':['15B22|TestSep_OutletFlow','15B22|TestSep_GasOutletFlow','15B22|TestSep_WellNum','15B22|TestSep_GasPresValve','15B22|TestSep_Temp','WHT']} df=pd.DataFrame(dict) df well tag 0 10B23 15...
<python><pandas><dataframe>
2023-01-25 05:04:55
1
4,338
roudan
75,229,630
14,297,619
Correct approach on throwing raise exception
<p>I have this code smell in my sonarScan which is throwing me &quot;Add logic to this except clause or eliminate it and rethrow the exception automatically.&quot;</p> <p>for an example , i am trying to raise a fileNotFoundError and code is working perfectly fine in my server . am i doing the right approach on this ?</...
<python><exception><static-analysis>
2023-01-25 04:13:40
0
334
Farid Arshad
75,229,588
2,961,927
Validation but not cross validation in Python sklearn Lasso
<p>I need to train a LASSO model using <code>sklearn</code>. I am given a pair of <strong>specifically designed</strong> training and validation datasets.</p> <p>The goal is to let the algorithm autogenerate a sequence of <code>alpha</code>s (the L1 penalty strength), and for each <code>alpha</code>, fit a model with t...
<python><machine-learning><scikit-learn><lasso-regression>
2023-01-25 04:03:51
1
1,790
user2961927
75,229,453
13,534,073
PyInstaller collect package issue (Google Analytics)?
<p>I have the below imports:</p> <pre><code>from apiclient import discovery from oauth2client.service_account import ServiceAccountCredentials </code></pre> <p>I'm trying to make a single file exe file by running:</p> <pre><code>pyinstaller --onefile -w --icon=icon.ico --add-data client_secrets.json;. main.py --collec...
<python>
2023-01-25 03:29:26
1
581
squidg
75,229,395
10,748,412
TypeError: '<' not supported between instances of 'torch.device' and 'int'
<pre><code>2023-01-25 08:21:21,659 - ERROR - Traceback (most recent call last): File &quot;/home/xyzUser/project/queue_handler/document_queue_listner.py&quot;, line 148, in __process_and_acknowledge pipeline_result = self.__process_document_type(message, pipeline_input) File &quot;/home/xyzUser/project/queue_ha...
<python><machine-learning><huggingface-transformers><torch>
2023-01-25 03:16:10
1
365
ReaL_HyDRA
75,229,357
3,508,811
How to run a command with %?
<p>I am trying to run command <code>git log origin/master..HEAD --format=format:&quot;%H&quot;</code> in python as below but running into below error,I tried to escape <code>%</code> but that doesn't fix the error, any idea how to fix it?</p> <pre><code>def runCmd2(cmd): logger.info(&quot;Running command %s&quot;%c...
<python><string-formatting>
2023-01-25 03:07:41
3
925
user3508811
75,229,333
402,649
Pandas does not have a function "read_sql"
<p>Python 3.6 on RHEL 8, Pandas 1.1.5</p> <p>Trying to use pandas to do a query, <code>pd.read_sql(&lt;my query&gt;, conn).to_dict(orient=&quot;records&quot;)</code></p> <p>Error message is: <code>AttributeError: module 'pandas' has no attribute 'read_sql'</code></p> <p>At the command line, <code>python3 -c &quot;impor...
<python><python-3.x><pandas><python-3.6>
2023-01-25 03:03:10
0
3,948
Wige
75,229,250
15,632,586
Is there a method to run a Conda environment in Google Colab?
<p>I have a YML file for a Conda environment that runs with Python 3.8.15 (<code>environment.yml</code>). I am currently trying to load that file into my Google Colab, based on this answer: <a href="https://stackoverflow.com/questions/53031430/conda-environment-in-google-colab-google-colaboratory/62346425#62346425">con...
<python><anaconda><conda><google-colaboratory>
2023-01-25 02:43:27
2
451
Hoang Cuong Nguyen
75,229,224
10,970,202
How to download yum packages on windows or from some website?
<p>When creating virtual env via <code>python3.7 -m venv myenv</code> I get following error:</p> <pre><code>Error: Command '[/home/..../python3', '-lm', 'ensurepip', '--upgrade', '--deault-pip'] returned non-zero exit status 1 </code></pre> <p>This seems to be solved my installing 3 python packages via: <code>apt-get/y...
<python><linux><redhat><python-venv>
2023-01-25 02:37:22
0
5,008
haneulkim
75,229,154
874,380
How to set up JupyterHub/JupyterLab with different conda environments correctly?
<p>A little background: I want to use JupyterHub/JupterLab to allow my students to design notebooks in a collaborative manner. In principle, I have a JupyterLab running with collaboration which seems to work. However, from what I can tell, JupyterLab does not come with user management, right? So anyone with the link an...
<python><jupyter-notebook><jupyter><jupyter-lab><jupyterhub>
2023-01-25 02:20:25
0
3,423
Christian
75,229,145
875,295
can I share a multiprocessing.Manager() instance across 3 processes?
<p>I'm trying to understand if I'm allowed to do the following in python:</p> <ul> <li>create a <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Manager" rel="nofollow noreferrer">manager</a> instance in my program</li> <li>fork the existing process N times</li> <li>in my initial process,...
<python><multiprocessing>
2023-01-25 02:17:54
1
8,114
lezebulon
75,229,007
11,922,765
pandas plot every Nth index but always include last index
<p>I have a plot, and I want to display only specific values. The plot looks good and not clumsy. In the below, I want to display values every two years but I don't want miss displaying the last value.</p> <pre><code>df = Year Total value 0 2011 11.393630 1 2012 11.379185 2 2013 10.722502 3 201...
<python><pandas><dataframe><matplotlib><plot>
2023-01-25 01:48:24
1
4,702
Mainland
75,228,886
6,367,971
Split CSV into multiple files based on column value
<p>I have a poorly-structured CSV file named <code>file.csv</code>, and I want to split it up into multiple CSV using Python.</p> <pre><code>|A|B|C| |Continent||1| |Family|44950|file1| |Species|44950|12| |Habitat||4| |Species|44950|22| |Condition|Tue Jan 24 00:00:00 UTC 2023|4| |Family|Fish|file2| |Species|Bass|8| |Spe...
<python><pandas><csv>
2023-01-25 01:21:25
3
978
user53526356
75,228,819
9,668,218
How to find values in a column of a PySpark DataFrame that don't exist in another DataFrame?
<p>I have two PySpark DataFrames, both have a column named &quot;Country&quot;. One DataFrame is the reference and I want to compare name of the countries in the 2nd DataFrame with the reference DataFrame to find the difference. The output that I want is a list of countries in the 2nd DataFrame that don't exist in the ...
<python><dataframe><apache-spark><pyspark><compare>
2023-01-25 01:03:53
1
1,033
Mohammad
75,228,701
13,638,243
Implementing ERGMs with PyMC
<p>I am trying to implement ERGMs with PyMC. <br> <br> I've found <a href="https://socialabstractions-blog.tumblr.com/post/53391947460/exponential-random-graph-models-in-python" rel="nofollow noreferrer">this</a>, <a href="https://gist.github.com/dmasad/78cb940de103edbee699" rel="nofollow noreferrer">this</a>, <a href=...
<python><pymc3><pymc>
2023-01-25 00:37:35
0
363
Neotenic Primate
75,228,631
2,383,842
How can I pipe JPEG files into FFMPEG and create an RTSP, H.264 stream?
<p>I have an input RTSP stream that I would like to manipulate on a frame-by-frame basis using openCV. After these changes are applied, I'd like to create a separate RTSP stream from those frames. I'm piping the resulting JPEG images to FFMPEG via STDIN. I need the intermediate frame to be a JPEG.</p> <p>In other wor...
<python><opencv><ffmpeg><subprocess><rtsp>
2023-01-25 00:23:13
0
415
Michael Schmidt
75,228,574
448,862
How do you selcet the specific cell in a QTableView
<p>In Python, using a QTableView how do I get a specific cell and how do I set the current cell.</p>
<python><pyqt><qtableview>
2023-01-25 00:13:54
1
342
QuentinJS
75,228,549
4,451,521
To print or not to print in pytest
<p>When talking about pytest we know two things:</p> <ol> <li>When a test pass, no output is given in principle</li> <li>Sometimes the assertion failures can have very cryptic messages.</li> </ol> <p>I took a course that solved this by using <code>print</code> to clarify desired outputs and calling the pytest as <code>...
<python><pytest>
2023-01-25 00:08:39
2
10,576
KansaiRobot
75,228,471
1,828,539
Why are miniconda envs located in /path/to/miniconda/base/envs/ ? [homebrew install]
<p>I installed miniconda via homebrew (<a href="https://formulae.brew.sh/cask/miniconda" rel="nofollow noreferrer">cask</a>)</p> <pre><code>brew install miniconda </code></pre> <p>And created a new environment <code>myenv</code></p> <pre><code>conda create -n myenv </code></pre> <p>I noticed that the path for this envi...
<python><conda><homebrew><miniconda>
2023-01-24 23:54:48
1
2,376
Carmen Sandoval
75,228,418
3,591,044
Adding line breaks and white space to string programmatically
<p>I have a string with multiple line breaks in it. An example looks as follows:</p> <pre><code>s = &quot;This is a conversation between a Human and person alpha.\n\n1) Human: Hello\n2)person alpha:What's up?\n3)Human:Not much, how about you?4) person alpha: I'm watching TV.\n5) Human: What are you watching?\n6) person...
<python><string><replace>
2023-01-24 23:43:39
2
891
BlackHawk
75,228,285
9,749,124
ValueError: Input contains NaN, ... when doing fit_transform() in BERTopic
<p>I want to make BERTopic model with my clustering algorithm (KMeans) and my Vectorizer (Count Vectorizer), but I keep getting this warning and error when I want to do .fit_transform(data) :</p> <p>Warining:</p> <pre><code>/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/bertopic/vectorize...
<python><machine-learning><bert-language-model>
2023-01-24 23:22:42
1
3,923
taga
75,228,274
15,724,084
python tkinter module Label widget wrapped in oop
<p>I am practicing on my personal project to create oop from tkinter module. I have written a code block where I try to create Label widget by imperative code line, then within a class.</p> <pre><code>from tkinter import * app=Tk() app.geometry('500x300') Button(app,width=13,height=1,text='scrape').pack() var_str=Str...
<python><oop><tkinter>
2023-01-24 23:20:37
1
741
xlmaster
75,228,151
7,102,346
Why does an inherited, nested class not recognise its nested, parent class in its own method's type hint?
<p>That title is a handful, so let me share a code snippet first...</p> <pre class="lang-py prettyprint-override"><code>class Parent: class GenericNode(): def __init__(self, name: str) -&gt; None: self.name: str = name class SpecificNode(Node): def __init__(self, name: str) -&gt; No...
<python><oop><type-hinting><python-3.11>
2023-01-24 22:58:00
0
370
Marty Cagas
75,228,061
2,897,989
Jupyter on Kubeflow more unstable than locally - even with better specs
<p>I'm trying to run some SciKit-Learn training in a Jupyter Notebook running on (Charmed) Kubeflow. I've done the same training locally on my Windows laptop also on a Jupyter Notebook, and it works well. I try to run the same on Kubeflow Jupyter (with the notebook instance having better specs than my laptop, the latte...
<python><jupyter-notebook><kubeflow>
2023-01-24 22:46:50
1
7,601
lte__
75,228,036
4,784,433
How to use ANTLR4 to get a list of functions and classes in string format regardless of the programming language?
<p>Say we have some files &quot;index.js&quot;, &quot;main.java&quot;, &quot;test.rs&quot;, and I want to output a list of functions/classes (along with doc comments) in these files.</p> <p>For example:</p> <pre><code>output: [ &quot;function jsFunction() { console.log(&quot;hello world!&quot;); }&quot;, &quot;clas...
<python><antlr><antlr4>
2023-01-24 22:42:40
2
641
PipEvangelist
75,227,988
2,009,558
why can I model some of these ellipses with skimage and not others?
<p>I am cross-posting this from GitHub as I am not sure whether the issue is a problem with my data or a bug. <a href="https://github.com/scikit-image/scikit-image/issues/6699" rel="nofollow noreferrer">https://github.com/scikit-image/scikit-image/issues/6699</a></p> <p>I have thousands of elliptical features in my mic...
<python><computational-geometry><scikit-image>
2023-01-24 22:35:55
1
341
Ninja Chris
75,227,947
19,130,803
Dash: how to write callback for html.Form component
<p>I am developing a dash app. I am creating a form using <strong>html.Form</strong> component.</p> <pre><code>html.Form( id=&quot;form_upload&quot;, name=&quot;form_upload&quot;, method=&quot;POST&quot;, action=&quot;/upload&quot;, encType=&quot;multipart/form-data&quot;, # accept=&quot;application/o...
<python><plotly-dash>
2023-01-24 22:30:13
1
962
winter
75,227,885
11,627,201
How can stomp with RabbitMQ be faster than just a normal websocket?
<p>Sending 100 000 messages of 300 characters from a python server to a JavaScript client using RabbitMQ and STOMP takes 10-20 seconds:</p> <p>Python server:</p> <pre class="lang-py prettyprint-override"><code>import stomp PORT = 61613 LOCALHOST = '0.0.0.0' conn = stomp.Connection11([(LOCALHOST, PORT)]) # conn.start...
<python><websocket><rabbitmq><python-asyncio><stomp>
2023-01-24 22:21:45
0
798
qwerty_99
75,227,868
10,963,057
plotly (python) linechart with changing color
<p>I am looking for a solution to create a plotly linechart, build with go.Scattter like this example:</p> <p><a href="https://i.sstatic.net/yVpFN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/yVpFN.png" alt="enter image description here" /></a></p> <p>what i already tried:</p> <pre><code>import plotly...
<python><colors><plotly>
2023-01-24 22:20:03
2
1,151
Alex
75,227,661
940,490
Dynamically creating serializable classes in Python
<p>I am trying to update a class that is supposed to be used as a custom type for the <code>multiprocessing.manager</code> and imitate a basic dictionary. All works well on Linux, but things fail on Windows and I understood that the problem lies in a possibly suboptimal creation mechanism that it uses that involves a c...
<python><oop><python-multiprocessing><python-class>
2023-01-24 21:51:29
1
1,615
J.K.
75,227,369
12,647,327
Aiokafka consumer process events in parallel
<p>I'm just getting started with kafka, I have a k8s cluster in which I want to deploy event listeners. When I have one listener running, everything works fine, but with several pods they process events in parallel, I would like the event to be processed only once. How can I achieve this?</p> <p>My listener code:</p> <...
<python><kubernetes><apache-kafka><aiokafka>
2023-01-24 21:14:53
1
323
Kabiljan Tanaguzov
75,227,205
1,330,381
How to configure thread names for multiprocessing.BaseManager instances
<p>There's some usage of these BaseManager types in some code I'm debugging. <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.managers.BaseManager" rel="nofollow noreferrer">https://docs.python.org/3/library/multiprocessing.html#multiprocessing.managers.BaseManager</a></p> <pre class="lan...
<python><python-multiprocessing>
2023-01-24 20:55:25
1
8,444
jxramos
75,227,167
8,372,455
pandas df index to list
<p>Im trying to run a pandas df <em><strong>index</strong></em> to list (time series data) with <code>index_list = df.index.values.tolist()</code> and it will output data like this:</p> <pre><code>index_list: [1674576900000000000, 1674577800000000000, 1674578700000000000, 1674579600000000000, 1674580500000000000, 1674...
<python><pandas>
2023-01-24 20:51:48
1
3,564
bbartling
75,227,108
11,922,765
AttributeError: 'DataFrame' object has no attribute 'to_flat_index'
<p>I am importing an HTML file. It has the data in a weird format and with multi index.</p> <p><a href="https://i.sstatic.net/40iKg.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/40iKg.png" alt="enter image description here" /></a></p> <p>I am particularly interested in importing the table 'Photovoltaic...
<python><html><pandas><dataframe>
2023-01-24 20:45:17
1
4,702
Mainland
75,227,024
3,247,006
How to print object's values with "annotate()" and "for loop" in ascending order?
<p>I have <code>Category</code> and <code>Product</code> models below. *I use <strong>Django 3.2.16</strong>:</p> <pre class="lang-py prettyprint-override"><code># &quot;models.py&quot; from django.db import models class Category(models.Model): name = models.CharField(max_length=20) class Product(models.Model): ...
<python><django><for-loop><django-queryset><django-annotate>
2023-01-24 20:36:07
1
42,516
Super Kai - Kazuya Ito
75,227,019
130,964
skimage/imageio fails to read grayscale images
<p>I have been reading images using (Python) <code>skimage.imread</code> (or <code>imageio.imread</code>) for months successfully, but now, without changing the code, I get failures when reading grayscale images. My collaborators can read the files. The image properties are:</p> <pre><code> identify test/resources/bio...
<python><scikit-image><python-imageio>
2023-01-24 20:35:15
1
38,146
peter.murray.rust
75,227,015
11,909,334
Error mkdocstrings generation error "No module named"
<p>I was building a documentation site for my python project using mkdocstrings.</p> <p>For generating the code referece files I followed this instructions <a href="https://mkdocstrings.github.io/recipes/" rel="noreferrer">https://mkdocstrings.github.io/recipes/</a></p> <p>I get these errors:</p> <pre><code> INFO ...
<python><documentation><docstring><mkdocs>
2023-01-24 20:35:05
3
637
Ezequiel González Macho
75,226,965
169,992
How is the PyTorch Tensor source code organized?
<p>I am going to see if it's possible to port PyTorch to TypeScript, but not sure how the PyTorch repo is organized. It appears a lot of it is CUDA/C++, and I don't seem to find a <a href="https://github.com/pytorch/pytorch/find/master" rel="nofollow noreferrer">tensor.py</a> anywhere. Where is the source code the <a h...
<python><pytorch>
2023-01-24 20:29:59
0
80,366
Lance Pollard
75,226,632
9,194,965
datetime conversion of a column results in pandas warning
<p>I am trying to convert a column in a pandas dataframe to datetime format as follows:</p> <pre><code>df[&quot;date&quot;] = pd.to_datetime(df[&quot;date&quot;]) </code></pre> <p>Although this works as expected, pandas gives the following warning:</p> <pre><code>A value is trying to be set on a copy of a slice from a ...
<python><pandas><dataframe><datetime>
2023-01-24 19:56:19
1
1,030
veg2020
75,226,607
12,436,050
Get all the rows with max value in a pandas dataframe column in Python
<p>I have a pandas dataframe with following columns.</p> <pre><code>col1 col2 col3 col4 A101 3 LLT 10028980 A101 7 LLT 10028980 A101 7 PT 10028980 A102 5 LLT 10028981 A102 3 PT 10028981 A103 2 PT 10028982 A103 4 LLT 10028982 </code></pre> <p>I would like t...
<python><pandas><group-by><max>
2023-01-24 19:53:50
2
1,495
rshar
75,226,465
15,584,917
Installed cd-hit (using conda) for Jupyter Notebook but command not found?
<p>I installed the package cd-hit in a Jupyter notebook. It seems successfully installed.</p> <pre><code>conda install -c bioconda cd-hit </code></pre> <p>However when I try to run cd-hit I get the error <code>command not found</code></p> <p>I am using</p> <pre><code>%%bash cd-hit -i input.fasta -o output.fasta -c .99...
<python><bash><jupyter-notebook><conda>
2023-01-24 19:40:43
0
339
1288Meow
75,226,279
16,169,533
Sort a string in the list alphabetacaly
<p>i have the following list:</p> <pre><code>strs = [&quot;tea&quot;,&quot;tea&quot;,&quot;tan&quot;,&quot;ate&quot;,&quot;nat&quot;,&quot;bat&quot;] </code></pre> <p>i want to sort the strings in that list to be like that:</p> <pre><code>strs = [&quot;aet&quot;,&quot;aet&quot;,&quot;ant&quot;,&quot;aet&quot;,&quot;ant...
<python><arrays><list><sorting>
2023-01-24 19:23:01
2
424
Yussef Raouf Abdelmisih
75,226,158
12,596,824
Checking paths in Python
<p>I have a path like so:</p> <pre><code>S:\Test\Testing\Tested\A\B\C </code></pre> <p>and a list</p> <pre><code>include = ['S:\Test\Testing', 'S:\Domino\Testing', 'S:\Money\tmp'] </code></pre> <p>How do I check if the path I have starts with any of the paths in this list?</p> <p>So in this case t...
<python><path>
2023-01-24 19:09:05
3
1,937
Eisen
75,226,105
11,308,308
Message not received by mqtt client
<p>I'm trying to send a message to a device using mqtt. The sender can publish a message. It is received by the queue which I made sub to the topic. The receiver is subscribed to the topic. Yet it receives no message.</p> <pre><code>class MQTTSub: class MQTTClient: def __init__(self, host: str): ...
<python><mqtt><mosquitto><paho>
2023-01-24 19:03:26
0
567
SamHuffman
75,225,989
17,696,880
Why does this regex capture a maximum of 2 capture groups and not all those within the input string?
<pre class="lang-py prettyprint-override"><code>import re def verify_need_to_restructure_where_capsule(m): capture_where_capsule = str(m.group(1)) print(capture_where_capsule) return capture_where_capsule input_text = &quot;Rosa está esperándote ((PL_ADVB='saassa')abajo). Estábamos ((PL_ADVB='la casa cua...
<python><python-3.x><regex><string><regex-group>
2023-01-24 18:52:33
1
875
Matt095
75,225,969
388,916
How to configure root logger + custom logger without duplicate log entries
<p>I want to configure the root logger and my project's custom logger separately. Here's my current logging configuration:</p> <pre class="lang-py prettyprint-override"><code>logging.config.dictConfig( { ...
<python><logging><python-logging>
2023-01-24 18:50:45
1
59,976
Hubro
75,225,904
402,649
Python WSGI can't find local modules?
<p>I am trying to get my Flask application to work with WSGI under Apache on RHEL 8. A flat file with no imports works fine, and the development server works fine, but WSGI returns module not found errors. This is my file strucuture:</p> <pre><code>/var/www/FLASKAPPS/myapp/ utility/ configuration.py ...
<python><python-3.x><mod-wsgi><wsgi>
2023-01-24 18:43:54
1
3,948
Wige
75,225,893
15,176,150
Why is pandas.read_sas() making random mistakes?
<p>I'm trying to work on a SAS dataset using pandas. The dataset is in <code>sas7bdat</code> format, and is encoded in <code>iso-8859-15</code>. The dataset is 230,000 rows long and 1300 columns wide.</p> <p>I'm using the following command to load the data into pandas:</p> <pre><code>pandas.read_sas('my_file.sas7bdat',...
<python><pandas><dataframe><encoding><sas>
2023-01-24 18:42:45
1
1,146
Connor
75,225,845
3,417,592
How can I run Django on a subpath on Google Cloud Run with load balancer?
<p>I'll preface by noting that I have a system set up using Google Cloud Run + Load Balancer + IAP to run a number of apps on <a href="https://example.com/app1" rel="nofollow noreferrer">https://example.com/app1</a>, <a href="https://example.com/app2" rel="nofollow noreferrer">https://example.com/app2</a>, etc, and up ...
<python><django><google-cloud-run><google-cloud-load-balancer>
2023-01-24 18:37:58
1
1,951
Nathan Lloyd
75,225,561
2,985,796
Apply 1D array representing index to element translation over 2D array of index values?
<p>I have a 2D array</p> <pre><code>arr = np.array([ [ 1, 2, -1, -1], [ 0, 1, -1, -1], [ 3, 5, -1, -1], [ 7, 8, -1, -1], [ 6, 7, -1, -1], [ 9, 11, -1, -1]]) </code></pre> <p>Its elements are related to the indices of some other array. A <code>-1</code> value represent &quot;no index&quot;. I also...
<python><arrays><indexing>
2023-01-24 18:11:24
2
7,178
KDecker
75,225,556
9,274,940
Group by the all the columns except the first one, but aggregate as list the first column
<p>Let's say, I have this dataframe:</p> <pre><code>df = pd.DataFrame({'col_1': ['yes','no'], 'test_1':['a','b'], 'test_2':['a','b']}) </code></pre> <p>What I want, is to group by all the columns except the first one and aggregate the results where the group by is the same.</p> <p>This is what I'm trying:</p> <pre><cod...
<python><pandas>
2023-01-24 18:10:37
1
551
Tonino Fernandez
75,225,413
8,981,474
Why does a second call to discover() result in an import error?
<p>I want to run both two separate test suites, using the standard library <code>unittest</code>.</p> <p>Specifically, I want to use the <code>load_tests</code> approach to test discovery, as described in the documentation for <a href="https://docs.python.org/3/library/unittest.html#unittest.TestLoader.discover" rel="n...
<python><import><python-unittest>
2023-01-24 17:56:03
0
1,559
isakbob
75,225,371
898,042
how to rename python script to be used in lambda - lambda_handler vs main() function name?
<p>initially this was python script on ec2 but now i want it become aws lambda - generated from terraform! Since aws lambda needs lambda_handler function vs &quot;__ main __&quot;.</p> <p>I wonder what to put in my tf code for handler arg.</p> <p>The python script(it gets zipped by terraform then loaded up to aws lambd...
<python><amazon-web-services><aws-lambda><terraform>
2023-01-24 17:51:53
1
24,573
ERJAN
75,225,115
5,763,413
Get N Smallest values from numpy array with array size potentially less than N
<p>I am trying to use <code>numpy.argpartition</code> to get the <code>n</code> smallest values from an array. However, I cannot guarantee that there will be at least <code>n</code> values in the array. If there are fewer than <code>n</code> values, I just need the entire array.</p> <p>Currently I am handling this with...
<python><numpy>
2023-01-24 17:27:46
2
2,125
blackbrandt
75,224,935
7,053,813
Matrix Multiplication with Multindex columns using broadcast
<p>I want to multiply two matrices (<code>.dot</code> not <code>.mul</code>), one of which may or may not have 2-D mutli-index columns. I have solved this for the 1-D case and the 2-D case, I feel like there should be a generalization between the two, but I can't figure it out.</p> <h3>Sample Data</h3> <pre><code>&gt;&...
<python><pandas>
2023-01-24 17:11:40
1
759
Collin Cunningham
75,224,811
11,462,274
Even defining object before calling query for a DataFrame, returns the error name is not defined
<pre><code>def fl_base(df,file_name): columns = ['historic_odds_1','historic_odds_2','historic_odds_3','historic_odds_4','odds'] mean_cols = df[columns].mean(axis=1) df = df.query( f&quot;\ (mean_cols &gt; 0) and \ ((@df['minute_traded']/mean_cols)*100 &gt;= 1000) and \ ...
<python><pandas><dataframe>
2023-01-24 17:01:36
1
2,222
Digital Farmer
75,224,524
3,595,907
Pairwise combinations of two image stacks
<p>I have 2 RGB image stacks containing 200 images each. Each image is (300, 300, 3) so each stack is (200, 300, 300, 3).</p> <p>So we have:</p> <pre><code>a_stack[200, 300, 300, 3] b_stack[200, 300, 300, 3] </code></pre> <p>My aim is to calculate the Euclidean distance between every pairwise combination of images in e...
<python><combinations><numpy-ndarray><combinatorics>
2023-01-24 16:36:25
0
3,687
DrBwts
75,224,455
15,080,473
error while receiving data and converting it into f64
<p>I am trying to send data over a TCP connection from rust to python, however while receiving the data in python I am getting the following error when trying to convert it from bytes to f64.</p> <pre><code>Traceback (most recent call last): File &quot;server.py&quot;, line 36, in &lt;module&gt; [x] = struct.unpa...
<python><tcp><byte>
2023-01-24 16:30:50
1
524
Ankit Kumar
75,224,450
5,684,405
How to refer to subclass property in abstract shared implementation in abstract class method
<p>For classes:</p> <pre><code>class Base(ABC): def __init__(self, param1): self.param1 = param1 @abstractmethod def some_method1(self): pass # @abstractmethod # def potentially_shared_method(self): # ???? class Child(Base): def __init__(self, param2): ...
<python><python-3.x>
2023-01-24 16:30:39
1
2,969
mCs
75,224,346
9,749,124
Visualise topics from BERTopic
<p>I am using <code>TOPIC_MODEL.visualize_topics()</code> for visualising my topics on the graph. This is the example:</p> <p><a href="https://i.sstatic.net/E3Dym.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/E3Dym.png" alt="enter image description here" /></a></p> <p>My question is, how to see more th...
<python><machine-learning><bert-language-model>
2023-01-24 16:21:54
2
3,923
taga
75,224,332
2,662,901
Why does indexing DataFrame by date string affect column return type?
<p>While investigating <a href="https://stackoverflow.com/q/75178105/2662901">why int columns are sometimes returned as floats</a> we found the following surprising behavior:</p> <pre><code>import pandas as pd import numpy as np import datetime df = pd.DataFrame(data=list(zip(*[np.random.randint(1,3,5), np.random.rand...
<python><pandas><dataframe>
2023-01-24 16:21:00
1
3,497
feetwet
75,224,203
5,040,775
How to separate dataframe by consecutive months in column?
<pre><code> Ticker Month Price 0 ABC US EQUITY 1/1/2020 20 1 ABC US EQUITY 2/1/2020 20 2 ABC US EQUITY 3/1/2020 20 3 ABC US EQUITY 4/1/2020 20 4 ABC US EQUITY 5/1/2020 20 5 ABC US EQUITY 6/1/2020 20 6 ABC US EQUITY 7/1/2020 20 7 ABC US EQUITY 8...
<python><pandas><dataframe>
2023-01-24 16:09:41
1
3,525
JungleDiff
75,224,099
10,689,857
Merge two lists of dictionaries ignoring None entries
<p>I have the below two lists:</p> <pre><code>a = [{'a1': 1, 'a2': 2}, {'a3': 3}] b = [{'b1': 1, 'b2': 2}, None] </code></pre> <p>I would like to merge them creating an output like the below, ignoring the None elements.</p> <pre><code>desired_output = [{'a1': 1, 'a2': 2, 'b1': 1, 'b2': 2}, {'a3': 3}] </code></pre>
<python>
2023-01-24 16:02:29
2
854
Javi Torre
75,224,063
1,230,694
Convert Time Series Data By Column Into Rows
<p>I have output from a system which has multiple readings for a date range, date is one column and then each reading is a column of its own, an example data frame looks like this:</p> <pre><code> Date/Time DEVICE_1 DEVICE_2 01/01 01:00:00 10.141667 8.807851 </code></pre> <p>I would like to convert this ...
<python><pandas><time-series>
2023-01-24 15:59:02
1
3,899
berimbolo
75,224,020
3,128,109
Can I use scipy to check the jacobian of a function?
<p>I have a function for which I know the explicit expression of the jacobian. I would like to check the correctness of this jacobian by comparing it against a finite-element approximation. Scipy has a <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.check_grad.html" rel="nofollow noreferrer...
<python><numpy><scipy><derivative>
2023-01-24 15:55:19
1
2,245
usernumber
75,223,860
5,522,007
Connect to SQL Server db with Azure AD MFA using Python in Docker
<p>I am trying to set up a Python Docker container from which I can connect to several SQL Server databases using Azure Active Directory MFA.</p> <p>I've created the Docker file as shown below. This builds ok and I am using it in a VSCode devcontainer but not certain I have got all the sql server/odbc stuff correct as ...
<python><sql-server><docker><azure-active-directory><kerberos>
2023-01-24 15:44:10
1
371
Violet
75,223,845
381,281
How to fill a contingency table from the marginal distributions given some optimization constraints?
<p>I need to find the cells of a contingency table given the marginal distributions.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>2574</th> <th>2572</th> <th>3393</th> <th>3768</th> <th>3822</th> <th><em><strong>b</strong></em></th> <th><em><strong>e</strong></em></th> </tr> </thead> <tb...
<python><mathematical-optimization><cvxpy><mixed-integer-programming><cvxopt>
2023-01-24 15:43:10
1
2,613
hfs
75,223,799
14,599,244
Is there any way to call a Python script from an Ansible playbook and pass the output as variable to an Ansible playbook back again for the next task?
<p>We are trying to pass return output (JSON) from Firewall Facts (containing 1000+ Policies) to a Python script, then Python Script will process that output (like getting right firewall policy to modify) and pass the output as variable to Ansible playbook back again for next task execution.</p> <p>We have tested this ...
<python><ansible>
2023-01-24 15:40:21
2
347
UME
75,223,777
2,439,905
Extraction of the text content of mixed text/json list of strings using python3
<p>I have a corpus of texts packaged into JSON. I have already stripped of some outer JSON layers and I have now lists like the following one</p> <pre><code>data = [ '“Ми підписали угоду, яка дозволяє громадянам України подорожувати без віз до Монголії. Це означає, що громадяни України можуть в’їжджати до Монголії ...
<python><json><list><text-processing>
2023-01-24 15:38:19
1
665
Sir Cornflakes
75,223,687
12,906,445
Can not convert Pytorch ml model to TorchScript Version
<p>I'm trying to convert <code>PyTorch ml model</code> into <code>TorchScript Version</code> and then convert it to <code>Core ML</code> using <code>coremltools</code>.</p> <p><strong>While trying to convert <code>PyTorch ml model</code> into <code>TorchScript Version</code> my code below keep getting following error:<...
<python><machine-learning><pytorch><coremltools>
2023-01-24 15:30:32
1
1,002
Seungjun
75,223,644
13,762,083
How to plot a rectangle facing in a particuliar direction in matplotlib?
<p>I would like to plot a rectangle centered at the position <code>(x, y, z)</code>, with length <code>a</code> along the <code>(n1x, n1y, n1z)</code> direction and width <code>b</code> along the <code>(n2x, n2y, n2z)</code> direction. I also want the surface of the rectangle to face a certain direction, the direction ...
<python><matplotlib><plot>
2023-01-24 15:28:23
1
409
ranky123
75,223,506
5,288,867
Access blob in storage container from function triggered by Event Grid
<p>Just for reference I am coming from AWS so any comparisons would be welcome.</p> <p>I need to create a function which detects when a blob is placed into a storage container and then downloads the blob to perform some actions on the data in it.</p> <p>I have created a storage account with a container in, and a functi...
<python><amazon-web-services><azure><azure-functions><azure-blob-storage>
2023-01-24 15:15:44
2
3,540
dangee1705
75,223,419
4,047,472
Python import function from another file via argparse
<p>I'm writing a small utility function which takes in input arguments of the location of a Python file, and also a function to call within the Python file</p> <p>For example <code>src/path/to/file_a.py</code></p> <pre><code>def foo(): ... </code></pre> <p>In the utility function, I'm parsing the arguments like so:</...
<python><python-3.x><argparse>
2023-01-24 15:07:31
1
7,592
Rekovni
75,223,415
7,031,021
python-docx trailing trilling whitepsaces not showing correctly
<p><strong>Goal</strong></p> <p>I am trying to add a text to a table cell where the text is a combination of 2 strings and the space between the strings of variable size so that the final text has the same length and it appears as if the second string is right aligned.</p> <p>I can either use format or ljust to combine...
<python><python-docx>
2023-01-24 15:07:26
1
510
RSale
75,223,400
5,956,459
Import a module in python as a command line option
<p>Is there a way to import a module through the command line, that gets exposed to the running script (or ideally through all execution)? My use case is to debug: I have a set of debugging utils (to display images, histograms...) that I only want to import while debugging (and that other people on my team do not need ...
<python><debugging><command-line-interface>
2023-01-24 15:06:26
1
313
Manel B
75,223,246
1,564,070
Selenium blocking downloads with Edge?
<p>I have a web automation tool developed with Python and Selenium and using the MS Edge driver. All is working well except when downloading a file. The message &quot;Couldn't download - blocked&quot; appears in the Downloads window.</p> <p>I've tested this same case with a user-launched instance of Edge and it works...
<python><selenium-webdriver><microsoft-edge>
2023-01-24 14:54:00
1
401
WV_Mapper
75,223,206
5,597,037
Python YFinance - Earnings Calendar no longer works
<p>I am trying to get the next earnings date using python. Up until now, I've been using:</p> <pre><code>obj = yf.Ticker('TSLA') cal = obj.calendar next_earnings_date = cal.iloc[0][0] </code></pre> <p>I think the API has recently broken. I have also tried:</p> <pre><code>import pandas_datareader as web import pandas as...
<python><yfinance>
2023-01-24 14:50:30
1
1,951
Mike C.
75,223,099
11,564,487
NA_character_ not identidied as NaN after importing it into Python with rpy2
<p>I am using the following code inside a R magic cell:</p> <pre><code>%%R -o df library(tibble) df &lt;- tibble(x = c(&quot;a&quot;, &quot;b&quot;, NA)) </code></pre> <p>However, when I run in another cell (a Python one):</p> <pre><code>df.isna() </code></pre> <p>I get</p> <pre><code> x 1 False 2 False 3 Fa...
<python><r><rpy2>
2023-01-24 14:41:33
1
27,045
PaulS
75,222,998
9,377,539
Why not able to scrape all pages from a website with BeautifulSoup?
<p>I'm trying to get all the data from all pages, i used a counter and cast it to take the page number in the url then looped using this counter but always the same result This is my code :</p> <pre><code> # Scrapping job offers from hello work website #import libraries import random import requests import csv from...
<python><web-scraping><beautifulsoup><python-requests>
2023-01-24 14:33:49
1
711
K_mns
75,222,929
6,435,921
Remove rows of dataframe contained in list (without using a loop)
<h1>Problem Explanation</h1> <p>I have a dataframe with two columns <code>'A'</code> and <code>'B'</code>. I also have a list of tuples where the first element of the tuple is an element in the column <code>'A'</code>, and the second is in the column <code>'B'</code>. I would like to remove all rows of the dataframe co...
<python><pandas><numpy>
2023-01-24 14:27:50
5
3,601
Euler_Salter
75,222,897
6,282,032
Sort dataframe based on minimum value of two columns
<p>Let's assume I have the following dataframe:</p> <pre><code>import pandas as pd d = {'col1': [1, 2,3,4], 'col2': [4, 2, 1, 3], 'col3': [1,0,1,1], 'outcome': [1,0,1,0]} df = pd.DataFrame(data=d) </code></pre> <p>I want this dataframe sorted by col1 and col2 on the minimum value. The order of the indexes should be 2, ...
<python><pandas>
2023-01-24 14:24:51
4
854
Tox
75,222,562
7,713,770
How to merge two models into one model with django for admin?
<p>I have to identical models:</p> <pre><code>class AnimalGroup(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField(max_length=1000, blank=True) images = models.ImageField(upload_to=&quot;photos/groups&quot;) class AnimalSubGroup(models.Model): name = m...
<python><django>
2023-01-24 13:59:06
2
3,991
mightycode Newton
75,222,540
5,896,319
How to solve libmagic.dylib - incompatible architecture error?
<p>I'm trying to install my Django project to my M1 Mac laptop but it is giving errors.</p> <pre><code>..OSError: dlopen(/Users/e.celik/Library/Python/3.8/lib/python/site-packages/magic/libmagic/libmagic.dylib, 0x0006): tried: '/Users/e.celik/Library/Python/3.8/lib/python/site-packages/magic/libmagic/libmagic.dylib' (...
<python><django>
2023-01-24 13:57:16
1
680
edche
75,222,273
618,579
Grabbing the octet stream data from a Graph API response
<p>I have been working on some code to download a days worth of Teams usage data from the Graph API. I can successfully send the token and receive the response. The response apparently contains the URL in the head to download the csv file. I can't see to find the code to grab it though.</p> <p>My code as the moment is ...
<python><microsoft-graph-api>
2023-01-24 13:37:07
1
2,513
Nathan
75,222,252
9,919,423
ValueError: Can't convert Python sequence with a value out of range for a double-precision float
<p>when I use TensorBoard to record the <code>adaptive learning rate</code> of a neural network, I use this code:</p> <pre><code>summary_writer = tf.summary.create_file_writer(log_dir) with summary_writer.as_default(): tf.summary.scalar('metrics/learning rate', data=float(model.optimizer._hyper['learning_rate']), s...
<python><tensorflow><deep-learning><neural-network><tensorboard>
2023-01-24 13:35:24
0
412
David H. J.
75,222,239
4,342,608
How to set operation id for custom application insight events?
<p>We have running on Azure a Python Web App (flask). It processes requests and also logs some results in the end via a custom event to Application Insights.</p> <p>However inside Application Insights our end-to-end transaction Operation ID for our Custom Events is 0.</p> <p><a href="https://i.sstatic.net/NaYd2.png" re...
<python><flask><azure-application-insights><azure-webapps>
2023-01-24 13:34:03
1
489
Swifting
75,222,111
11,222,963
How to create a fake but realistic scatter plot showing a relationship?
<p>I would like to generate some dummy data to show a positive relationship in a scatterplot.</p> <p>I have some code below but the output looks too &quot;perfect&quot;:</p> <pre><code>import random import pandas as pd # num_obs = number of observations def x_and_y(num_obs): x_list = [] y_list = [] f...
<python><numpy><random>
2023-01-24 13:22:55
1
3,416
SCool
75,222,110
14,843,373
Built in way to convert this data to dict or json in python
<p>So I have an input of</p> <pre><code>s = &quot;['some.dot.seperated.words.here[id=123,rapidId=76,state=CLOSED,name=james_simpson,startDate=2021-10-30T11:16:00.000Z,endDate=2022-12-23T11:16:00.000Z,completeDate=2023-01-02T11:07:43.518Z,activatedDate=2022-10-30T11:20:03.627Z,sequence=33643,goal=do something\nfun\nwith...
<python>
2023-01-24 13:22:54
1
361
beautysleep
75,222,091
11,251,373
Python: partially initialize instance
<p>Not sure wether it is possible or not in general but i have a following question:</p> <p>for example we have class Foo</p> <pre class="lang-py prettyprint-override"><code>class Foo: def __init__(a, b, c): self.a = a self.b = b self.c = c def sum(self): return self.a + self.b + self...
<python>
2023-01-24 13:21:04
0
2,235
Aleksei Khatkevich
75,222,031
14,125,436
How to highlight area between 3D lines with texture in Python
<p>I want to fill between two curves in a 3D plot in matplotlib. I used <a href="https://stackoverflow.com/questions/36737053/mplot3d-fill-between-extends-over-axis-limits">this answer</a> to do that. But I want to use a texture for filling rather than a single color. I very much appreciate any help. I used the followi...
<python><matplotlib>
2023-01-24 13:16:02
1
1,081
Link_tester
75,221,888
5,561,875
Fast Savgol Filter on 3D Tensor
<p>I have a tensor of example shape <code>(543, 133, 3)</code>, meaning 543 frames, with 133 points of X,Y,Z</p> <p>I would like to run a <code>savgol_filter</code> on every point in every dimension, however, naively, this is quite slow:</p> <pre class="lang-py prettyprint-override"><code>points, frames, dims = tensor....
<python><numpy><scipy>
2023-01-24 13:03:10
1
6,344
Amit
75,221,879
16,978,074
create an edge list on films that share a genre
<p>hello everyone I'm doing a project to analyze a website and build a network graph with python. I chose the themovieb.org website. The nodes are the ids of the movies and the links between the nodes are the genres that two movies depend on. For example node_A and node_B have a link if they have the same genres in com...
<python><arrays><dictionary><themoviedb-api><edge-list>
2023-01-24 13:02:19
1
337
Elly
75,221,728
4,763,333
pipenv install cannot find any packages
<p>I cannot build a virutal environment using pipenv install, I always get the error No matching distribution found for aws-lambda-powertools if I remove that package I will get the same error for another package I have in there.</p> <p>Stack trace (displayed when I try to build throgh pycharm)</p> <pre><code> Pipfi...
<python><pip><pipenv>
2023-01-24 12:48:07
0
1,425
AnonymousAlias
75,221,726
5,884,126
Reusing a variable from an if clause
<p>Let's say we have the following code:</p> <pre><code>if re.search(r&quot;b.&quot;, &quot;foobar&quot;): return re.search(r&quot;b.&quot;, &quot;foobar&quot;).group(0) </code></pre> <p>This is obviously a redundant call, which can be avoided by assigning the condition to a variable before the if block:</p> <pre><co...
<python><if-statement><optimization>
2023-01-24 12:47:55
0
964
PixelMaster
75,221,713
10,192,593
For loop through list of strings
<p>I am trying to save certain information out of xarray in a loop. I keep getting an error msg. Here is an example:</p> <pre><code>import numpy as np import pandas as pd import xarray as xr samples = {} samples['first'] = [1,2] samples['second'] = [3,4] samples categories = list(samples.keys()) categories dta = ...
<python>
2023-01-24 12:47:26
3
564
Stata_user
75,221,654
2,163,392
How to slice and calculate the pearson correlation coefficient between one big and small array with "overlapping" windows arrays
<p>Suppose I have two very simple arrays with numpy:</p> <pre><code>import numpy as np reference=np.array([0,1,2,3,0,0,0,7,8,9,10]) probe=np.zeros(3) </code></pre> <p>I would like to find which slice of array <code>reference</code> has the highest pearson's correlation coefficient with array <code>probe</code>. To do t...
<python><arrays><numpy><pearson-correlation><pearson>
2023-01-24 12:42:41
1
2,799
mad
75,221,639
8,771,201
Python mysql get value from table before insert in the same table
<p>I have a table with different type of article numbers:</p> <pre><code>Date - Artsup - ArtTest - ArtCombo ------------------------------- 01-01-23 - S1 - T1 - S1T1 01-01-23 - S2 - T2 - S2T2 </code></pre> <p>Now I want to insert a new record in the same table but first I want to check if I ...
<python><mysql>
2023-01-24 12:41:09
1
1,191
hacking_mike
75,221,569
9,102,437
How to monkeypatch a python library class method?
<p>I am trying to modify a <code>better_profanity</code> library to include an additional argument to <code>get_replacement_for_swear_word</code> function. To do so I first import the necessary parts of the library and test its functionality before:</p> <pre class="lang-py prettyprint-override"><code>from better_profan...
<python><python-3.x><monkeypatching>
2023-01-24 12:34:10
1
772
user9102437
75,221,387
4,654,120
Python - How to run a huggingface pipeline offline for the first time?
<p>I have a python code that uses a Huggingface pipeline.</p> <pre><code>from transformers import pipeline import pandas as pd tqa = pipeline(task=&quot;table-question-answering&quot;, model=&quot;google/tapas-base-finetuned-wtq&quot;) table = pd.read.csv(&quot;table.csv&quot;) table = table.astype(str) query = [&qu...
<python><machine-learning><huggingface-transformers>
2023-01-24 12:18:45
1
2,099
Bluemarble
75,221,290
9,196,760
Send scheduled message everyday to all users using the slack bot
<p>I am creating a slack bot project using Django. Here I would like to send a scheduled message to every user of the workspace. Every day, the bot will ask specific questions to all users, but personally. In that case, how can I post questions every day within a specific schedule?</p> <p>Which tool or django-package w...
<python><django><slack><slack-api>
2023-01-24 12:11:20
0
452
Barun Bhattacharjee