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,806,634
2,626,865
twilio sms webhook api
<p>I'm would like to programmatically change the webhook for a given number (and possibly enumerate available numbers) or messaging service, but I can't find the API documentation. From <a href="https://www.twilio.com/docs/messaging/guides/webhook-request" rel="nofollow noreferrer">Our Request to your Webhook URL</a>:<...
<python><rest><twilio><twilio-api>
2023-03-21 21:50:03
1
2,131
user19087
75,806,623
8,068,825
Parallelize operation on Pandas DataFrame
<p>So I have this Python class below. It's job is to take a Pandas Dataframe and create classes based on the contents of the Dataframe. This creation operation can take a while so I want to parallelize it. Below I have the code that I have parallelized it. I take number of cores and split the Dataframe then pass it to ...
<python><pandas>
2023-03-21 21:48:47
1
733
Gooby
75,806,560
14,173,197
Capping outliers of a dataframe
<p>I have a dataframe with a 'tot_dl_vol' column. I want to cap the values of that column that have higher than 80% Year over Year or lower than 10% Year over Year percentage. How do I achieve this? I have written this code so far.</p> <pre><code>df['YoY_dl'] = (df['tot_dl_vol'].pct_change(12)) * 100 upper = 80 lower =...
<python><pandas><dataframe><outliers>
2023-03-21 21:40:33
1
323
sherin_a27
75,806,509
444,561
Pandas truncates strings in numpy list
<p>Consider the following minimal example:</p> <pre class="lang-py prettyprint-override"><code>@dataclass class ExportEngine: def __post_init__(self): self.list = pandas.DataFrame(columns=list(MyObject.CSVHeaders())) def export(self): self.prepare() self.list.to_csv(&quot;~/Desktop/tes...
<python><pandas><list><numpy><truncation>
2023-03-21 21:31:30
2
1,114
GarethPrice
75,806,497
967,621
Select and read a file from user's filesystem
<p>I need to:</p> <ul> <li>Enable the user to select a plain text file from the user's filesystem.</li> <li>Make it available to Pyodide.</li> <li>Read its contents line-by-line in Pyodide (in the Python code).</li> </ul> <p>The code to read currently replaced by dummy code: <code>inp_str = 'ACGTACGT'</code>. The actua...
<javascript><python><webassembly><pyodide>
2023-03-21 21:29:30
3
12,712
Timur Shtatland
75,806,484
11,141,816
Sympy package could not inport the number obtained from the calculation
<p>I wrote a function to optimize the number from sympy package.</p> <pre><code>Optimize_function() </code></pre> <p>It optimize a list of values</p> <pre><code> Optimize_function(list_1) </code></pre> <p>where in jupyter notebook, I typed</p> <pre><code>list_1 </code></pre> <p>and obtained the following output (they w...
<python><sympy>
2023-03-21 21:27:06
0
593
ShoutOutAndCalculate
75,806,473
5,212,614
How can we pick out features form a JSON string and structure everything in rows and columns?
<p>I have a small python script that iterates through a bunch of JSON strings and appends everything into a list, liek this.</p> <pre><code>my_list.append(response) </code></pre> <p>Now, I am trying to normalize the list, liek this</p> <pre><code>df_vehicles = json_normalize(my_list) </code></pre> <p>Then, I normalize ...
<python><json><python-3.x>
2023-03-21 21:25:32
0
20,492
ASH
75,806,451
9,727,763
Evaluating huggingface transformer with trainer gives different results
<p>I am using a pre-trained Transformer for sequence classification which I fine-tuned on my dataset with the Trainer class. When I evaluate the model using the Trainer class I get an accuracy of 94%</p> <pre class="lang-py prettyprint-override"><code>trainer = Trainer(model=model) preds = trainer.predict(validation_da...
<python><machine-learning><huggingface-transformers>
2023-03-21 21:20:55
0
345
Jan Koci
75,806,404
5,116,032
Scipy Chi2 Probability Density Function Exploding
<p>I am trying to plot a chi squared probability density function trained on some experimental data at different conditions in python. My code is shown below.</p> <pre><code> import numpy as np import matplotlib.pyplot as plt import scipy.stats as ss data= [] #read from CSV file. chi...
<python><scipy><statistics><chi-squared><scipy.stats>
2023-03-21 21:13:26
0
434
iato
75,806,292
4,966,886
pyqt5 central widget with QTableWidgets in a MainWindow not correctly resized
<p>I use as the central widget in a QMainWindow a QDialog with a bunch of QTableWidget in it.</p> <pre><code>import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(pa...
<python><qt><pyqt5>
2023-03-21 21:01:15
1
306
user11634
75,806,255
3,965,828
Functions Framework giving "Provided code is not a loadable module. Could not load the function, shutting down."
<p>I have a Google Cloud Function I've developed. The main.py and requirements.txt file are both in a folder called &quot;hello&quot;. Here's the entirety of my main.py file:</p> <pre><code>import functions_framework import logging logging.basicConfig(level=logging.INFO) @functions_framework.http def hello(request): ...
<python><google-cloud-functions><functions-framework>
2023-03-21 20:55:14
0
2,631
Jeffrey Van Laethem
75,806,091
6,197,439
How to display required amount of leading zeroes with Python3 f-string?
<p>I just want to format a number as hex, with four characters in all - so up to three leading zeroes. I'm trying this:</p> <pre class="lang-none prettyprint-override"><code>$ python3 --version Python 3.10.10 $ python3 -c 'TVAR=0x000a; print(f&quot;{TVAR:#04x}&quot;)' 0x0a </code></pre> <p>So, I thought that with <cod...
<python><python-3.x><hex><string-formatting><f-string>
2023-03-21 20:32:44
1
5,938
sdbbs
75,805,981
5,255,581
How to find most connected nodes after spectral clustering on networkx?
<p>I've done spectral clustering on G and created a partition matrix to form subgraphs for each cluster:</p> <pre><code>clusters = SpectralClustering(affinity = 'precomputed', assign_labels=&quot;discretize&quot;,random_state=0,n_clusters=n_clusters).fit_predict(adj_matrix) partMatrix = [[] for x in range(n_clusters)] ...
<python><graph><networkx>
2023-03-21 20:16:17
0
865
mleafer
75,805,947
12,760,550
Create column that orders ID by first Start Date
<p>Imagine I have the following dataframe:</p> <pre><code>ID Start Date 1 1990-01-01 1 1990-01-01 1 1991-01-01 2 1991-01-01 2 1990-01-01 3 2002-01-01 3 2000-01-01 4 1991-01-01 </code></pre> <p>What would be the best way to create a column named Order that, for each unique ID in the ID column, starting ...
<python><pandas><list><filter><sequence>
2023-03-21 20:11:33
1
619
Paulo Cortez
75,805,772
11,279,970
Call OpenAI API async with Python, asyncio and aiohttp
<p>I am trying to make asynchronous calls to openai API completions using aiohttp and asyncio. See below where I create a dataframe of elements (Door, Window, etc.) I want information from regarding the given context (description of a room)</p> <pre><code>#imports import pandas as pd # Make a dataframe import aiohttp ...
<python><pandas><python-asyncio><aiohttp><openai-api>
2023-03-21 19:49:29
2
508
Simon Palmer
75,805,468
12,458,212
Filter nested numpy array
<p>Hi I'm trying to filter the following numpy array but running into issues. I'd like to filter for all arrays equal to [('a','b','c'),1]. The problem is I can't figure out how to either combine the elements in each array so instead of [('a','b','c'),1], I would have [('a','b','c',1)], OR simply filter given the origi...
<python><numpy>
2023-03-21 19:11:21
2
695
chicagobeast12
75,805,411
2,209,313
What are the `y` and `x` params to the python curses `window.getch()` method?
<p>I may be missing something very obvious, but I am confused by the optional <code>[y, x]</code> parameters to the <code>window.getch( [y, x] )</code> method <a href="https://docs.python.org/3/library/curses.html#curses.window.getch" rel="nofollow noreferrer">described in the Python documentation</a>. What are these ...
<python><coordinates><curses><coordinate-systems><python-curses>
2023-03-21 19:03:40
3
3,423
Wandering Logic
75,805,235
1,451,531
How to pass bash argument array to single-quoted python call
<p>I have a script that looks something like this:</p> <pre class="lang-bash prettyprint-override"><code>#!/bin/bash /usr/local/bin/myproc --tags='env:dev' 'python myscript.py --my-argument VAL1 --my-argument VAL2 &gt; /some/redirect' </code></pre> <p>Now I need to add additional logic that conditionally changes the a...
<python><bash>
2023-03-21 18:42:20
1
1,416
Splendor
75,805,054
814,438
Python Process.join is Released in Linux but Not Windows
<p>I have observed different behavior in how Windows 10 and Ubuntu 18.04 handle the <code>Process.join()</code> function. What accounts for the difference in behavior?</p> <p>I am running Python 3.6.</p> <p>In this code, the main process starts a subprocess and then calls <code>join</code>. The subprocess runs a thread...
<python><linux><windows><multithreading><multiprocessing>
2023-03-21 18:24:54
1
1,199
Jacob Quisenberry
75,804,965
17,896,651
Peewee value returns to its default after few seconds (BUG?)
<p>This used to be my model:</p> <pre><code>db = SqliteDatabase(Settings.stats_conf_database_location) class ActivityTracker(Model): date = DateField(unique=True) activity_time_curr = IntegerField(default=0) # active seconds today activity_time_max = IntegerField() # max active seconds today class ...
<python><peewee>
2023-03-21 18:13:55
1
356
Si si
75,804,936
6,321,559
Pytest Caplog for Testing Logging Formatter
<p>I'm using a logging formatter to redact passwords. I want to write a test to confirm that the logging redactor is effective. In this example I simplified the code to redact &quot;foo&quot;.</p> <p>With this redactor code in the my <code>my_logger.py</code> module (simplified redaction of a specific word):</p> <pre><...
<python><pytest>
2023-03-21 18:11:37
1
2,046
it's-yer-boy-chet
75,804,905
19,980,284
Specify NaN encoding in np.where() logic
<p>I have data that looks like this:</p> <pre><code> id case2_q6 0 300 3.0 1 304 4.0 2 306 3.0 3 309 1.0 4 311 3.0 5 312 4.0 6 314 NaN 7 315 2.0 8 316 3.0 9 317 3.0 </code></pre> <p>And using this <code>np.where()</code> function call to generate new variables:</p> <pre><co...
<python><pandas><dataframe><numpy><conditional-statements>
2023-03-21 18:07:49
2
671
hulio_entredas
75,804,827
18,108,767
The z-axis label is not showing in a 3D plot
<p>I have an issue with a 3d plot, at the moment of visualizing it. It appears without the z-axis label,</p> <p><a href="https://i.sstatic.net/N1Xp0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/N1Xp0.png" alt="enter image description here" /></a></p> <p>but when I set a longer title, it appears:</p> <...
<python><matplotlib><matplotlib-3d>
2023-03-21 17:58:36
1
351
John
75,804,781
1,440,349
How to create pyspark dataframes from pandas dataframes with pandas 2.0.0?
<p>I normally use <code>spark.createDataFrame()</code> which used to throw me deprecated warnings about iteritems() call in earlier version of Pandas. With pandas 2.0.0 it doesn't work at all, resulting in an error below:</p> <pre><code>AttributeError Traceback (most recent call last) File &l...
<python><pandas><dataframe><apache-spark><pyspark>
2023-03-21 17:53:25
3
465
shiftyscales
75,804,599
4,505,301
OpenAI API: How do I count tokens before(!) I send an API request?
<p>OpenAI's text models have a context length, e.g.: Curie has a context length of 2049 tokens.</p> <p>They provide <code>max_tokens</code> and <code>stop</code> parameters to control the length of the generated sequence. Therefore the generation stops either when stop token is obtained, or <code>max_tokens</code> is r...
<python><openai-api><chatgpt-api><gpt-3><gpt-4>
2023-03-21 17:35:10
4
1,562
meliksahturker
75,804,409
21,420,742
How to check for Previous managers in Employee History (Python)
<p>I have a dataset with all employees records and need to find the most recent(which I have) and the previous manager before. I wanted to use the shift function but unfortunately not all employees have the same history layout. Here is a small example:</p> <pre><code> ID Job_Title Mananger 1 Sales ...
<python>
2023-03-21 17:15:46
1
473
Coding_Nubie
75,804,367
7,657,180
Delete list of files in python
<p>I am trying to clean USB drive and I have specified most of the unnecessary folders and files. the following code is very good</p> <pre><code>import os import shutil import hashlib def delete_files_and_folders_on_usb_drive(usb_drive_path, filenames_to_delete, folder_prefixes, target_hash): for root, dirs, files...
<python><shutil>
2023-03-21 17:12:13
1
9,608
YasserKhalil
75,804,346
3,087,409
Opposite of Pandas "to_flat_index()"
<p>I have a pandas dataframe with MultiIndex columns, which I'm writing to an SQL database. To write to the database nicely I have to flatten the MultiIndex (see <a href="https://stackoverflow.com/a/60406162/3087409">this answer</a>), but this means when I read from the database I want to reconstruct the MultiIndex.</p...
<python><pandas><dataframe>
2023-03-21 17:10:42
1
2,811
thosphor
75,804,182
13,686,796
ValueError: object has no field when using monkeypatch.setattr on a pydantic.BaseModel's method
<p>I usually can patch methods of normal objects using pytest monkeypatch. However when I try with a <code>pydantic.BaseModel</code> it fails.</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel class Person(BaseModel): name: str age: int def intro(self) -&gt; str: ...
<python><pytest><pydantic><monkeypatching>
2023-03-21 16:56:07
2
491
valcapp
75,804,180
1,609,428
how to do a qcut by group in polars?
<p>Consider the following example</p> <pre><code>zz = pl.DataFrame({'group' : ['a','a','a','a','b','b','b'], 'col' : [1,2,3,4,1,3,2]}) zz Out[16]: shape: (7, 2) ┌───────┬─────┐ │ group ┆ col │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═══════╪═════╡ │ a ┆ 1 │ │ a ┆ 2 │ │ a ┆ 3 │ │ a ┆ 4 ...
<python><pandas><python-polars>
2023-03-21 16:55:42
1
19,485
ℕʘʘḆḽḘ
75,804,160
3,764,619
Installing environment for https://github.com/igorshubovych/markdownlint-cli fails with AttributeError: 'bytes' object has no attribute 'tell' #328
<p>I am using</p> <pre><code>- repo: https://github.com/igorshubovych/markdownlint-cli rev: v0.32.2 hooks: - id: markdownlint </code></pre> <p>Sometimes, pre-commit fails with the following error.</p> <pre><code>[INFO] Installing environment for https://github.com/igorshubovych/markdownlint-cli. [INFO] On...
<python><pre-commit-hook><pre-commit><pre-commit.com><nodeenv>
2023-03-21 16:53:43
0
680
Casper Lindberg
75,803,969
3,215,940
QFileDialog not closing after file selection
<p>I have a simple function that opens a file dialog using pyqt6 to select a file. The function works, but the dialog hangs after being called and I'm not sure why it's not getting automatically closed when the file is selected.</p> <pre><code>def ui_find_file(title=None, initialdir=None, file_type=None): import os ...
<python><pyqt6>
2023-03-21 16:37:55
2
4,270
Matias Andina
75,803,710
5,858,752
How to prepend a string to the name of many columns in a dataframe?
<p>I have a dataframe with numerous columns, and I need to prepend the same string to the name of each of these columns.</p> <p>Rather than doing</p> <pre><code>df.rename({&quot;col1&quot;: &quot;prepended_str_col1&quot;, ....., }) </code></pre> <p>I was wondering if there is an easier way to do this?</p>
<python><pandas><dataframe>
2023-03-21 16:13:30
3
699
h8n2
75,803,534
11,267,783
Include live figures Matplotlib on PDF
<p>I wanted to know if it is possible to include interactive figures in PDF.</p> <p>For example, I wanted to generate figures with Matplotlib, create a PDF with Latex and be able to zoom or pan inside the figures on the PDF. (The same behavior that we have for example when we plot with Matplotlib)</p> <p>Maybe there is...
<python><matplotlib><pdf><latex>
2023-03-21 15:58:48
1
322
Mo0nKizz
75,803,379
3,834,415
How does one export classmethods to a module as module methods in a dynamic fashion in python?
<p>Assuming <code>python3.10</code>, suppose I have a class in some file:</p> <pre><code>class Foo(metaclass=ABCMeta): @classmethod @abstractmethod def do_fn(cls, yada, yada_): pass @classmethod @abstractmethod def that_fn(cls, this, that): pass SpecializedFoo(Foo): @classmethod def do_fn(cl...
<python><oop><functional-programming>
2023-03-21 15:43:08
1
31,690
Chris
75,803,374
1,317,323
How to use miniconda as a linux system user
<p>I'd like to run a Django app on a linux machine using miniconda as a tool for managing packages and virtual environment.</p> <p>Systemctl will launch gunicorn as a dedicated system user, say my_app_user. Sources will be on /opt/my_app with permission only for my_app_user.</p> <p>What is the correct / secured way to ...
<python><django><miniconda>
2023-03-21 15:42:32
1
1,002
Yvain
75,803,316
5,575,597
How can I make a bar chart in Bokeh were positive/negative values have different colours?
<p>In the below simple example code I have a bar chart with pos/neg values, how can I ammend the code to show green/red for pos/neg value bars?</p> <pre><code>from bokeh.io import show from bokeh.plotting import figure fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] counts = [-5, 3, 4...
<python><bokeh>
2023-03-21 15:37:47
1
863
cJc
75,803,123
7,656,767
How to pass double quoted parameter to Python requests.get()
<p>An API I'm using requires one of the parameters to be passed in in double quotes like so: <code>https://example.com/api?country=&quot;US&quot;</code>. It seems no matter how I try to pass this in, I get a 500 response using Python's <code>requests</code> library. I've tried the following:</p> <ul> <li>`params = {&qu...
<python><string><https><python-requests><urlencode>
2023-03-21 15:22:28
1
710
Eric Hasegawa
75,803,086
2,516,789
Countdown clock not updating in a multi-frame tkinter app
<p>I'm in the progress of writing a python app to show a countdown clock in one window, and a video in another (haven't started integrating the video part yet).</p> <p>However, the countdown clock I have written doesn't update, and only shows the initial countdown time when the app was launched. I need it to update aro...
<python><python-3.x><tkinter><raspberry-pi>
2023-03-21 15:18:13
1
1,190
Newbie
75,803,030
710,955
Loguru - how to change the logs 'filename'
<p>With the python log library 'loguru', is there a way to change the log file name after declaring it?</p> <p>Thanks!</p> <pre><code>from loguru import logger logger.add('dummy.log', format=&quot;{time:YYYY-MM-DD HH:mm:ss} {level} {message}&quot;) ..... # How to change log filename? logger.debug('my message') </code>...
<python><loguru>
2023-03-21 15:14:00
1
5,809
LeMoussel
75,802,977
12,436,050
Adding a string to a dataframe column and create a new column in Python 3.7
<p>I have following pandas dataframe</p> <pre><code> col1 col2 0 ORG-1 LOC-100052061, LOC-100032442, LOC-100042003 1 ORG-2 LOC-100005615, LOC-100000912, LOC-100043831 </code></pre> <p>I would like to explode col2 and add a url to each value.</p> <p>The expected output is:</p> <pre><code> col1 col2 ...
<python><pandas>
2023-03-21 15:09:34
2
1,495
rshar
75,802,971
8,613,945
How to use python and telnetlib3 to send commands and provide an interactive session
<p>I would like to use python to connect to a telnet server and do the following steps:</p> <ul> <li>send some commands to get the server in an initial state</li> <li>start an interactive session with stdin and stdout so a user can interact with the server's cli</li> <li>potentially send some commands after the user fi...
<python><telnet>
2023-03-21 15:09:01
1
605
Giles Knap
75,802,870
12,769,783
Type hint that indicates that class contains method with signature
<p>Is it possible to write a type hint which checks if a passed type defines a function with a specific name and signature, if the name of the function and its signature are derived from another argument?</p> <p>In the following scenario I try to show what I intend to do: I want to write a type hint for the function <c...
<python><python-typing>
2023-03-21 15:01:56
1
1,596
mutableVoid
75,802,832
8,849,755
Rename specific index level in multiindex data frame
<p>What I want to do can perfectly be done in this way:</p> <pre class="lang-py prettyprint-override"><code>df.reset_index('level_x', inplace=True, drop=False) df.rename(columns={'level_x': 'level_y', inplace=True) df.set_index('level_y', append=True) </code></pre> <p>but I am very sure there is a one liner (and better...
<python><pandas><rename><multi-index>
2023-03-21 14:58:12
1
3,245
user171780
75,802,773
5,881,882
Python: Object not callable - runs in Notebook but not in PyCharm
<p>EDIT: I could solve it (hopefully it does what I want). But I don't understand why it works now. I put my workaround at the bottom. Would be great, if somebody could enlighten me, why it works (or why notebook worked without it).</p> <hr /> <p>I use the code from this tutorial:</p> <p><a href="https://amaarora.githu...
<python><pytorch><callable>
2023-03-21 14:53:20
1
388
Alex
75,802,689
10,251,146
polars - Fill null over Groups
<p>I am trying to fill null timestamps over groups, my dataframe looks like this</p> <pre class="lang-py prettyprint-override"><code>df = pl.from_repr(&quot;&quot;&quot; ┌───────────────────────────────────┬──────────────────────────────────┬───────┐ │ start ┆ stop ...
<python><dataframe><python-polars>
2023-03-21 14:46:26
1
459
linus heinz
75,802,643
271,388
Is double close in strace necessarily bad?
<p>I am training a neural network. Somewhere in my code base, I have a code snippet like the following:</p> <pre class="lang-py prettyprint-override"><code>def foo(): d = {} with PIL.Image.open(img_path) as img: d[&quot;img&quot;] = torchvision.transforms.functional.to_tensor(img) return d </code></...
<python><python-imaging-library><system-calls>
2023-03-21 14:43:33
1
1,808
CrabMan
75,802,629
6,137,103
Deny overriding specific fields of a Pydantic model
<p>What is the proper way to restrict child classes to override parent's fields?</p> <p><strong>Example</strong>. I want this to fail:</p> <pre class="lang-py prettyprint-override"><code>class TechData(BaseModel): id: Optional[int] = Field(default=None, alias='_id') class Child(TechData): id: Optional[int] # ...
<python><python-3.x><pydantic>
2023-03-21 14:42:38
2
508
kupihleba
75,802,509
10,714,156
Python: Best way to define and re-use an object for subsequent tests using `pytest`
<p>I have some tests running on my Python package using <code>pytest</code>. However, I am noticing that I am re-writing a lot of times an object that is necessary for the function I am testing.</p> <p>For the sake of the example, consider the following function <code>foo()</code>.</p> <pre><code>def foo(dictionary:dic...
<python><unit-testing><testing><automated-tests><pytest>
2023-03-21 14:29:31
2
1,966
Álvaro A. Gutiérrez-Vargas
75,802,506
2,826,011
Populate pandas dataframe after index values
<p>I have a DataFrame that looks like the one on the left below and I need to re-arrange so it looks like the one on the right:</p> <pre><code> XYZ year month values A B C D 0 A 2006 8 35601 2005-01 NaN NaN NaN NaN 1 A 2005 3 13164 ...
<python><pandas><dataframe>
2023-03-21 14:29:17
1
2,560
Thanos
75,802,453
1,656,343
Generate SQLAlchemy models from Pydantic models
<p>So I have this large JSON dataset with a huge number of properties (as well as nested objects). I have used <code>datamodel-code-generator</code> to build pydantic models. The JSON data has been imported into pydantic models (with nested models).</p> <p>Now I need to push them into the database.</p> <p>How can I aut...
<python><json><sqlalchemy><pydantic><sqlmodel>
2023-03-21 14:23:54
1
10,192
masroore
75,802,370
10,535,123
Is pandas groupby() function always produce a DataFrame with the same order respect to the column we group by?
<p>Given <code>pd.DataFrame</code> <code>X</code> with column <code>id</code>, is the call to <code>groupby()</code> always return a DataFrame with the same order with respect to the column <code>id</code>?</p> <p><code>X.groupby('id')[col_name].first()</code></p>
<python><pandas>
2023-03-21 14:16:28
1
829
nirkov
75,802,259
231,670
How to keep linters from complaining about type hints that don't match on a technicality?
<p>Considering the toy example:</p> <pre class="lang-py prettyprint-override"><code>def get_dimensions(the_string: str) -&gt; tuple[int, int]: return tuple([int(_) for _ in the_string.split(&quot;x&quot;)]) </code></pre> <p>I <em>know</em> that <code>the_string</code> will only ever contain on <code>x</code> (it's ...
<python><type-hinting>
2023-03-21 14:06:43
1
6,468
Daniel Quinn
75,802,200
7,822,387
Best way to create 3d matrix of variables in PULP
<p>I want to create a list of variables in PULP that will follow the following structure. There can be any number of types, and each type can have any number of subcat, however each type/subcat must have exactly 2 numbers.</p> <pre><code>type subcat number 1 A 1 1 A 2 1 B 1 1 B 2 2 A ...
<python><pulp>
2023-03-21 14:00:57
1
311
J. Doe
75,802,162
8,721,169
Set a custom requirements.txt for a Cloud Function
<p>I have several functions in <strong>the same <code>main.py</code> of a unique repo</strong>, each of them being deployed on GCP Cloud Function like that:</p> <ul> <li><code>gcloud functions deploy func1 --entry-point=my_function_1</code></li> <li><code>gcloud functions deploy func2 --entry-point=my_function_2</code>...
<python><google-cloud-functions>
2023-03-21 13:58:12
1
447
XGeffrier
75,802,128
50,065
Adding --find-links URLs to dependencies in pyproject.toml
<p>You can install the python package <a href="https://github.com/google/jax/blob/main/setup.py" rel="noreferrer">Jax</a> with some extra packages depending on your environment.</p> <p>For GPU:</p> <pre><code>pip install jax[cuda] --find-links https://storage.googleapis.com/jax-releases/jax_cuda_releases.html </code></...
<python><dependency-management><jax><pyproject.toml>
2023-03-21 13:54:55
0
23,037
BioGeek
75,802,111
1,314,503
groupby and count of values in dataframe
<p>I am having following values in excel/dataframe.</p> <p><a href="https://i.sstatic.net/t9Fpx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/t9Fpx.png" alt="enter image description here" /></a></p> <p>here I need to group by the values by 'Date' column and respectively need to put count of the other 2...
<python><python-3.x><pandas><dataframe>
2023-03-21 13:53:39
4
5,746
KarSho
75,802,099
6,151,828
Change which axis is used as radial/angular position with matplotlib polar=True (Creating circular phylogenetic tree with Bio.Phylo)
<p>If I create a phylogenetic tree using Biopython Phylo module, it is oriented from left to right, e.g.:</p> <pre><code>import matplotlib.pyplot as plt from Bio import Phylo from io import StringIO handle = StringIO(&quot;(((A,B),(C,D)),(E,F,G));&quot;) tree = Phylo.read(handle, &quot;newick&quot;) fig, ax = plt.sub...
<python><matplotlib><bioinformatics><biopython><phylogeny>
2023-03-21 13:52:14
1
803
Roger V.
75,802,082
7,012,917
Minor ticks not evenly spaced/aligned with major ticks when setting xlim
<p>I am plotting some timeseries data. I noticed that when plotting the whole timeseries the minor ticks (for the x-axis) are perfectly evenly spaced. But when I set the x-axis limits (<code>xlim</code>), suddenly the minor ticks start getting more and more off-sync.</p> <p>As you can see the minor ticks are perfectly ...
<python><matplotlib>
2023-03-21 13:50:45
3
1,080
Nermin
75,801,932
1,675,615
How to recursively enrich json object with custom field using python jsons
<p>I'm using <a href="https://jsons.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">jsons</a> library and would like to add a custom serializer that for a given type adds a certain field.</p> <p>Naive example:</p> <pre><code>def adjust(obj): if isinstance(obj, MyFoo): json = jsons.dump(obj) ...
<python><python-jsons>
2023-03-21 13:35:37
1
1,467
Krever
75,801,738
9,769,953
importlib.metadata doesn't appear to handle the authors field from a pyproject.toml file correctly
<p>I'm having a problem retrieving the author metadata information of a package through <a href="https://docs.python.org/3.11/library/importlib.metadata.html" rel="nofollow noreferrer"><code>importlib.metadata</code></a>.</p> <p>My package setup is as follows:</p> <p>I'm using Python's <code>setuptools</code> with a mi...
<python><setuptools><packaging><python-importlib>
2023-03-21 13:17:08
1
12,459
9769953
75,801,619
10,192,593
Slicing numpy arrays in a for loop
<p>I have a multidimentional numpy array of elasticities with one of the dimensions being &quot;age-groups&quot; (0-92 years) and the other &quot;income-groups&quot; (low/high income).</p> <p>I would like to create a table with the mean elasticities for each combination of subgroups using a for loop.</p> <p>My code is ...
<python><numpy><numpy-slicing>
2023-03-21 13:05:48
1
564
Stata_user
75,801,560
7,596,102
Use BytesIO instead of NamedTemporaryFile with openpyxl
<p>I understand that with <code>openpyxl&gt;=3.1</code> function <code>save_virtual_workbook</code> is gone and preferred solution is using <code>NamedTemporaryFile</code>.</p> <p>I want it to be done without writing to filesystem, only in memory, just like <code>BytesIO</code> did.</p> <p>Before update I had:</p> <pre...
<python><django><openpyxl>
2023-03-21 12:58:20
2
405
qocu
75,801,556
19,155,645
how to access folder in 'shared with me' drive from colab notebook
<p>I have a Jupyter notebook that needs access to a .csv data file. I intend to make these accessible for other people in my group, and I want it to work directly for them too, without the need to change the directory, or manually import data, or even 'save shortcut in drive'.</p> <p>At the moment both files (.ipynb an...
<python><jupyter-notebook><google-drive-api><google-colaboratory>
2023-03-21 12:57:55
1
512
ArieAI
75,801,520
2,016,632
I'm unable to build CPython from scratch on Linux because of inability to find encodings Module. What am I missing?
<p>I have an old Centos 7 system. It has one user [plus root] and has python2.7 and python3.6.8 installed. The latter has binary <code>/bin/python3</code> Neither PYTHONHOME nor PYTHONPATH are defined. Python3 runs fine, for example, <code>print(encodings.__file__) </code> gives <code>usr/lib64/python3.6/encodings/__in...
<python><centos7>
2023-03-21 12:54:59
2
619
Tunneller
75,801,389
4,436,572
Polars replace_time_zone and convert_time_zone show different string representation for same timezone conversion
<p>Test Data:</p> <pre><code>import polars as pl import pandas as pd from datetime import date, time, datetime # polars df for Jan to 12th, March 2022 before DST transition. tdf = pl.DataFrame( pl.date_range( low=date(2022, 1, 3), high=date(2022, 3, 12), interval=&quot;5m&quot;, tim...
<python><date><datetime><time><python-polars>
2023-03-21 12:43:42
1
1,288
stucash
75,801,279
11,143,347
The passed model is not callable and cannot be analyzed directly with the given masker! Model: Pipeline()
<p>I have trained a model then have saved its pickle, I want to perform a shap analysis on the validation set &quot;X_val&quot;, I've set the code as follows:</p> <pre><code>import joblib import shap from lightgbm import LGBMClassifier # Load the model from the pickle file model = joblib.load(&quot;model.pkl&quot;) ...
<python><pandas><machine-learning><lightgbm><shap>
2023-03-21 12:33:46
0
452
Sara
75,801,123
239,923
How do I assign a new column to polars dataframe?
<p>In polars, I am trying to create a new column I already know the values of the columns and I just want to add a column with those values. Below is the code</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({&quot;a&quot;: [1, 2], &quot;b&quot;: [4, 5]}) english_titles = [&qu...
<python><dataframe><python-polars>
2023-03-21 12:19:20
1
16,264
xiaodai
75,801,049
8,279,555
Use CSV data downloaded from ftp with csv.reader
<p>I'm working on a little script that downloads a csv file from a ftp server, and when downloaded i want to do some calulations on each row before i write it to a new file.</p> <p>i have the ftp part working, but i cant figure out how to use the BytesIO data as csv data.</p> <p>Im using the code below but that prints ...
<python><csv><ftp>
2023-03-21 12:11:47
1
484
VA79
75,801,017
3,832,272
Glue in JupyterNotebook
<p>A while ago I was successfully able to insert variables/strings from a code into the markdown of JupyterNotebook. I followed these steps:</p> <pre><code>from myst_nb import glue a = 5*5 glue(&quot;results&quot;, a) </code></pre> <p>And then I inserted the variable in the markdown section:</p> <p><code> My calculat...
<python><jupyter-notebook><module><markdown>
2023-03-21 12:08:10
1
315
Jo-Achna
75,800,972
1,581,090
How to use subprocess.run with correct path on windows?
<p>On windows 10 using python 3.10.10 I am trying to run a windows executable, but there is some issue with the path to the folder of the executable. I am trying to run the following code</p> <pre><code>path = r&quot;C:/Program Files (x86)/STMicroelectronics/STM32Cube/STM32CubeProgrammer/bin&quot; result = subprocess....
<python><windows>
2023-03-21 12:04:16
1
45,023
Alex
75,800,935
7,603,109
urllib: TypeError: expected string or bytes-like object
<p>I am trying to make an API call where I pass a file in the header</p> <pre><code>import urllib.request headers = {'files[]': open('File.sql','rb')} datagen ={} request = urllib.request.Request('https://www.rebasedata.com/api/v1/convert', datagen, headers) response1 = urllib.request.urlopen(request) # Error : Typ...
<python><urllib><urllib3>
2023-03-21 12:02:08
1
22,283
Adrita Sharma
75,800,926
55,934
How can I improve the accuracy of OpenCV checkerboard detection in this case?
<p>I would like to track the location of checkerboard corners in this stereo fisheye camera, using OpenCV in Python.</p> <p><a href="https://i.sstatic.net/2STMl.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2STMl.png" alt="Stereo fisheye checkerboard" /></a></p> <p>To help the algorithm, I am only runn...
<python><algorithm><opencv>
2023-03-21 12:01:16
1
5,950
Rocketmagnet
75,800,905
2,300,369
Implement order definition by multiple attributes
<p>I'd like to know how to efficiently sort by object's multiple attributes. For instance, given</p> <pre><code>class A: def __init__(self, a, b): self.a = a self.b = b def __lt__(self, other): if self.a == other.a: return self.b &lt; other.b return self.a &lt; other...
<python><sorting><oop>
2023-03-21 11:58:53
3
308
user2300369
75,800,672
8,506,921
Accessing model when creating new python package
<p>I'm making a python package where the main functionality is using a model that I've trained. I want it to be as easy as possible to access the model for end users so they can just use the main functions without needing to actively go find and download the model separately.</p> <p>I initially thought I would just inc...
<python><python-packaging>
2023-03-21 11:35:55
1
1,874
Jaccar
75,800,636
9,418,052
Google Ads API "RefreshError: ('unauthorized_client: Unauthorized', {'error': 'unauthorized_client', 'error_description': 'Unauthorized'})"
<p>I am trying to make a call to Google Ads API to access campaign data in python. I have completed the following steps:</p> <ol> <li>Created a web app and enabled Google-Ads API</li> <li>Saved JSON file that contains client id and secret information</li> <li>Generated refresh token</li> <li>Updated google-ads yaml fil...
<python><google-ads-api>
2023-03-21 11:32:06
3
404
Ankit Tripathi
75,800,596
17,194,313
How to you write polars data frames to Azure blob storage?
<p>Given a parquet file in Azure blob storage, this can be read into a polars dataframe using</p> <pre class="lang-py prettyprint-override"><code>pl.read_parquet('az://{container-name}/{filename}', storage_options={'account_name': ..., 'account_key': ...}) </code></pre> <p>(the above works via the optional dependency o...
<python><azure-blob-storage><python-polars>
2023-03-21 11:28:10
2
3,075
MYK
75,800,587
1,747,029
Use SI units in sympy rather than Hartree units
<p>I am trying to use <code>sympy</code> to calculate wave functions for the hydrogen atom, and would like to use SI units rather than Hartree units. The documentation gives lots of examples, but all using Hartree units. Is there a way of switching to SI units?</p>
<python><sympy><physics>
2023-03-21 11:27:02
1
594
Graham G
75,800,558
860,202
Find all possible sums of the combinations of integers from a set, efficiently
<p>Given an integer n, and an array a of x random positive integers, I would like to find all possible sums of the combinations with replacement (n out of x) that can be drawn from this array.</p> <p>For example:</p> <pre><code>n = 2, a = [2, 3, 4, 6] all combinations = [2+2, 2+3, 2+4, 2+6, 3+3, 3+4, 3+6, 4+4, 4+6, 6+6...
<python><algorithm><math><optimization>
2023-03-21 11:24:07
1
684
jonas87
75,800,493
14,786,813
Official Flax Example "Imagenet" is Bugged
<p>I have tried to use run the official <a href="https://colab.research.google.com/github/google/flax/blob/main/examples/imagenet/imagenet.ipynb" rel="nofollow noreferrer">Flax/ImageNet</a> code. Due to the difference in jax version, I have tried two methods. The <a href="https://colab.research.google.com/gist/rwbfd/40...
<python><jax>
2023-03-21 11:17:58
1
320
RanWang
75,800,304
3,370,495
Can't open web browser with webbrowser module
<p>I'm trying to open an url using python <code>webbrowser</code> module. When the code below runs nothing happens.</p> <pre><code>import webbrowser webbrowser.open_new('http://www.python.org') </code></pre> <p>But when a <code>sleep</code> time is given, the browser opens and closes after the sleep time is over.</p> ...
<python><url><window><python-webbrowser>
2023-03-21 10:57:24
0
509
Shyam3089
75,800,290
13,180,235
Django admin integer field with '+' '-' on either side to increment/decrement value
<p>Im stuck in a client's requirement. He wants to have a field in django admin panel like the screenshot I have attached <a href="https://i.sstatic.net/kDpRs.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kDpRs.png" alt="screenshot" /></a></p> <p>I have a field in my model landing_page_btn_text_size = ...
<python><django><django-models><django-admin>
2023-03-21 10:55:59
1
335
Fahad Hussain
75,800,252
10,687,907
Get next row after groupby
<p>My question is similar to this one : <a href="https://stackoverflow.com/questions/68479601/get-next-row-besides-the-previous-row-after-groupby">Get next row besides the previous row after groupby</a> but not quite the same. I'd like to get the first row appearing after a group concatenated to each row of the group.<...
<python><pandas>
2023-03-21 10:51:54
1
807
Achille G
75,800,240
9,021,547
How to add intervals to a date in numpy
<p>I need to subtract x months from a specific date in python and tried several ways, but get the following errors:</p> <pre><code> dates = np.array(['2023-02-28T00:00:00.000000000','2022-12-31T00:00:00.000000000','2019-01-01T00:00:00.000000000'], dtype=np.datetime64) dates + np.timedelta64(-5,'M') numpy.core._excepti...
<python><numpy><datetime>
2023-03-21 10:50:48
1
421
Serge Kashlik
75,799,998
10,391,157
App doesn't comply with Google OAuth policy
<p>I want basic user authentication using Google OAuth2 sign in. I open a browser in my app to <code>https://accounts.google.com/o/oauth2/v2/auth</code>, and receive the authentication token at my python server. But if I try to exchange this with an access token, google complains about not complying with the policy, wi...
<python><google-oauth>
2023-03-21 10:28:42
0
1,538
Luke100000
75,799,966
12,967,353
Using default tool values for reusable noxfile
<p>I am implementing a reusable noxfile, my goal is that the different Python components of my project can have the same workflow for testing, linting, etc.</p> <p>To do this, I created a <code>nox_plugin</code> module containing this generic <code>noxfile.py</code> (this is a sample):</p> <pre><code>import nox @nox.s...
<python><continuous-integration><coverage.py><pyproject.toml><nox>
2023-03-21 10:25:26
0
809
Kins
75,799,955
13,123,667
How to do inference with YOLOv5 and ONNX
<p>I've trained a YOLOv5 model and it works well on new images with yolo detect.py</p> <p>I've exported the model to ONNX and now <strong>i'm trying to load the ONNX model and do inference</strong> on a new image. My code works but I don't get the correct bounding boxes.</p> <p>I need to get the area of the bounding bo...
<python><yolo><onnx><yolov5><onnxruntime>
2023-03-21 10:24:21
3
896
Timothee W
75,799,800
6,621,137
How to implement same customized log through differents files via logging module
<p>I believe from other questions I have read that logging has a singleton pattern but I did not succeed to implement it right.</p> <p>I have a <code>logger.py</code> file like this :</p> <pre><code>import logging import os from concurrent_log_handler import ConcurrentRotatingFileHandler def create_file_handler(path,...
<python><python-3.x><logging><singleton><python-logging>
2023-03-21 10:09:27
1
452
TmSmth
75,799,722
10,003,538
How to deal with stack expects each tensor to be equal size eror while fine tuning GPT-2 model?
<p>I tried to fine tune a model with my personal information. So I can create a chat box where people can learn about me via chat gpt.</p> <p>However, I got the error of</p> <blockquote> <p>RuntimeError: stack expects each tensor to be equal size, but got [47] at entry 0 and [36] at entry 1</p> </blockquote> <p>Because...
<python><tensorflow><artificial-intelligence><huggingface-transformers><gpt-2>
2023-03-21 10:01:28
2
1,225
Chau Loi
75,799,294
16,971,617
Generate random 2D polygons
<p>I would like to generate some random shapes that are regular polygons with right angled (Like a floor plan) only.</p> <p>I'm not sure how to approach this problem. One approach is to train a GAN model to do it but is there a algorithm to do that? I was thinking to generate as follows</p> <p><a href="https://i.sstati...
<python><random><computer-vision><computational-geometry>
2023-03-21 09:20:48
2
539
user16971617
75,799,074
13,158,157
pyspark export parquet not in snappy compression
<p>Reading documentation for <a href="https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrameWriter.parquet.html" rel="nofollow noreferrer">spark.write.parquet</a> does not show me options to change compression for the exported parquet. To go around the default exported parquet f...
<python><pandas><apache-spark><pyspark><databricks>
2023-03-21 08:58:13
1
525
euh
75,798,705
14,912,118
Getting Data must be padded to 16 byte boundary in CBC mode when decrypting the file
<p>I am trying to decrypt the file which I have encrypted using following link(python encryption code) <a href="https://stackoverflow.com/questions/75665392/getting-bad-magic-number-while-decrypting-the-file/">Getting Bad Magic Number while Decrypting the file</a></p> <p>But when i am trying to decrypt the code getting...
<python><encryption><openssl><aes>
2023-03-21 08:15:04
1
427
Sharma
75,798,605
6,761,328
Show non-numerical variables / columns in hover text
<p>I have this code to create a plot and this dataframe</p> <pre><code>df2.dtypes Out[464]: Device category time datetime64[ns] Path category variable object value float64 path category dtype: object df3 = df2.query('variable==@signals').groupby('p...
<python><plotly><plotly-dash>
2023-03-21 08:03:48
1
1,562
Ben
75,798,212
4,792,660
Get vertex list and face list in maya
<p>I am new to maya scripting. I have a .fbx being loaded and for each shape node I need to convert such shape into a .obj file.</p> <p>Now I've found a way to exctract the vertex coordinates by doing something like</p> <pre><code>node_name = &quot;testnodeshape&quot; vtxIndexList = cmds.getAttr(node_name +&quot;.vrts&...
<python><maya><wavefront>
2023-03-21 07:11:04
0
2,948
user8469759
75,798,012
6,760,948
Modify flag status if a condition is met
<p>Below is a JSON output from an API microservice.</p> <pre><code>{ &quot;case&quot;: &quot;2nmi&quot;, &quot;id&quot;: &quot;6.00c&quot;, &quot;key&quot;: &quot;subN&quot;, &quot;Brand&quot;:[ { &quot;state&quot;: &quot;Active&quot;, &quot;name&quot;: &qu...
<python><python-3.x>
2023-03-21 06:42:52
2
563
voltas
75,797,700
6,505,146
How to make kdeplot robust to negative/zero values
<p>I have two real/float variables stored in native python lists:</p> <pre><code>x = [2.232, 2.331, 2.112...] y = [-3.431, 2.213, -1.232...] </code></pre> <p>Notice that there are negative values. This seems to be giving the <code>kde</code> call some problems. I have gotten this error:</p> <blockquote> <p>ZeroDivision...
<python><seaborn><kdeplot>
2023-03-21 05:51:42
0
2,627
Arash Howaida
75,797,640
1,645,131
How to specify column types with Polars read_csv
<p>While reading a csv file in pandas, we have option of dtype in read_csv(). Do we have similar option in polars?</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import polars as pl data_pd = pd.read_csv('file.csv',dtype={'col1':str, 'col2':str}) data_pl = pl.read_csv('file.csv',dtype={'col1':...
<python><dataframe><csv><python-polars>
2023-03-21 05:38:07
1
1,032
Kuber
75,797,591
4,107,349
Adding column to a Pandas df checking whether date range ever falls on a given month in any year
<p>We have a dataframe of entries where we want to know which entries have ever existed within a given month of any year. Simplified eg:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import datetime as dt df = pd.DataFrame( { &quot;start&quot;: [dt.datetime(2020,1,1), dt.datetime...
<python><pandas><dataframe>
2023-03-21 05:27:31
2
1,148
Chris Dixon
75,797,278
610,569
Playing a video with captions in Jupyter notebook
<h1>How to play a video with captions in Jupyter notebook?</h1> <p>With code snippets from these post, I've tried to play a video inside jupyter notebook:</p> <ul> <li><a href="https://stackoverflow.com/questions/18019477/how-can-i-play-a-local-video-in-my-ipython-notebook">How can I play a local video in my IPython no...
<python><video><jupyter-notebook><html5-video><webvtt>
2023-03-21 04:15:50
2
123,325
alvas
75,797,194
5,029,589
Combine two rows in data frame in python
<p>I have a data frame which has two columns and one column has a duplicate values .I want to combine the rows into one . But I dont want to run any aggregation function . My data frame is</p> <p>My data frame df</p> <pre><code> CP CL 0 45538 [757, 1] 1 5548 [712515, 1] 2...
<python><pandas><dataframe>
2023-03-21 03:57:19
1
2,174
arpit joshi