QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
74,796,726
9,869,260
Pandas Dataframe create new column with grouppy count with condition on count
<p>I have this Dataframe</p> <pre><code> df = pd.DataFrame({&quot;A&quot;: [1, 1, 1, 1, 1, 2, 2, 2, 3], &quot;B&quot;: [1, 4, 5, 6, 10, 7, 8, 9, 3], &quot;C&quot;: [&quot;Hello&quot;, &quot;World&quot;, &quot;How&quot;, &quot;are&quot;, &quot;you&quot;, &quot;today&quot;, &quot;miss&quot;, &quot;?&quot;, &quot;!&quot;]...
<python><pandas>
2022-12-14 10:21:22
1
437
Chjul
74,796,555
5,346,843
Error locating Pandas index using Timestamp
<p>I have a <code>Pandas</code> <code>dataframe</code> that looks something like this:</p> <pre><code> a b c ... x y z date ... 2043-10-01 10230.413086 846.184082 0.267180 .....
<python><pandas>
2022-12-14 10:08:06
1
545
PetGriffin
74,796,509
1,150,683
number() not supported in LXML XPath parsing?
<p>I am running into some unexpected issues with XPath. I have a query that runs fine when using a database system like BaseX, but in Python with <code>lxml</code> it throws an error.</p> <p>Here is an example:</p> <pre class="lang-py prettyprint-override"><code>import lxml.etree as ET xml = &quot;&quot;&quot;&lt;tre...
<python><xml><lxml><basex><xpath-1.0>
2022-12-14 10:04:28
1
28,776
Bram Vanroy
74,796,337
1,939,730
How to count how many times an event occurred in the last 24 hour of a given date?
<p>Given a dataframe representing orders with columns: <code>ID, order_date, expedition_date, ...</code> I want to assign a new column to the dataframe that contains, for each row, how many orders were placed (i.e., order_date) in the last 24h with respect to the row's expedition_date.</p> <p>For example: for a row wit...
<python><pandas><window><rolling-computation>
2022-12-14 09:51:42
1
567
Carlos Navarro Astiasarán
74,796,191
1,184,899
Get element text behind shadow DOM element using Playwright
<p>I am trying to use Playwright to get contents of the open shadow root element which looks like this.</p> <pre><code>&lt;some-element&gt; #shadow-root ABC &lt;/some-element&gt; </code></pre> <p>Here <code>#shadow-root</code> contains text <code>ABC</code> without any additional tags.</p> <p>I am able to locate <c...
<python><playwright><playwright-python>
2022-12-14 09:38:56
2
704
Termos
74,796,189
11,167,163
How to remove white space in the middle of a pie chart?
<p>Below is the example code I made to have a reproducible example.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() size = 0.3 vals = np.array([[60., 32.], [37., 40.], [29., 10.]]) cmap = plt.get_cmap(&quot;tab20c&quot;) outer_colors = cmap(np.arange(3)*4) inner_colors ...
<python><matplotlib>
2022-12-14 09:38:36
1
4,464
TourEiffel
74,796,120
2,528,453
Saving matplotlib figure from tkinter application without using pyplot
<p>I am using multiple <code>matplotlib</code> figures to visualize data in a <code>tkinter</code> application and so far that has been going great by using the <a href="https://matplotlib.org/stable/users/explain/api_interfaces.html" rel="nofollow noreferrer">explicit interface</a>, i.e. by working on the axis objects...
<python><matplotlib><tkinter>
2022-12-14 09:32:43
0
1,061
obachtos
74,795,811
11,729,954
Get version of Python poetry project from inside the project
<p>I have a python library packaged using poetry. I have the following requirements</p> <p>Inside the poetry project</p> <pre class="lang-py prettyprint-override"><code># example_library.py def get_version() -&gt; str: # return the project version dynamically. Only used within the library def get_some_dict() -&gt;...
<python><python-packaging><python-poetry>
2022-12-14 09:05:38
2
457
Beast
74,795,728
7,766,024
Getting a ModuleNotFoundError when trying to import from a particular module
<p>The directory I have looks like this:</p> <pre><code>repository /src /main.py /a.py /b.py /c.py </code></pre> <p>I run my program via <code>python ./main.py</code> and within <code>main.py</code> there's an important statement <code>from a import some_func</code>. I'm getting a <code>ModuleNotFound...
<python><python-import>
2022-12-14 08:58:31
2
3,460
Sean
74,795,650
1,231,714
Plotting variable number of columns in pandas
<p>I have CSV file that has a date column and measurements column. Sometimes there are 4 or more measurement columns. Regardless of the number of columns, I would like to plot all columns on the same plot (same axis, not as subplots). Right now I have the following syntax for plotting all 4 data - how do I generalize p...
<python><pandas><matplotlib>
2022-12-14 08:52:30
0
1,390
SEU
74,795,598
10,035,190
how to do pandas groupby?
<p>i have a excel sheet</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Animal</th> <th>max Speed</th> </tr> </thead> <tbody> <tr> <td>Falcon</td> <td>34</td> </tr> <tr> <td>Falcon</td> <td>42</td> </tr> <tr> <td>Parrot</td> <td>18</td> </tr> <tr> <td>Parrot</td> <td>29</td> </tr> </tbody> ...
<python><pandas><group-by>
2022-12-14 08:46:49
2
930
zircon
74,795,541
4,128,957
How to find all leaf and non leafe records and update them on each non leaf records in odoo 13
<p>In the employee profile, I added a <code>Many2one</code> field which relates to the employee table itself (known as Reporting of the current employee) and another field is a <code>Many2one</code> with a foreign key of Reporting manager field.</p> <p>And I have another field <code>Many2many</code> related to the empl...
<python><python-3.x><odoo><odoo-13>
2022-12-14 08:41:19
1
4,224
KbiR
74,795,465
20,732,098
Check if a row in column is unique python Dataframe
<p>I have the following Dataframe:</p> <pre class="lang-py prettyprint-override"><code> | id1 | result | | -------- | -------------- | | 2 | 0.5 | | 3 | 1.4 | | 4 | 1.4 | | 7 | 3.4 | | 2 | 1.4 | </code></pre> <p>I wan...
<python><pandas><dataframe>
2022-12-14 08:33:25
3
336
ranqnova
74,795,315
5,856,119
Processing large number of JSONs (~12TB) with Databricks
<p>I am looking for guidance/best practice to approach a task. I want to use Azure-Databricks and PySpark.</p> <p><strong>Task:</strong> Load and prepare data so that it can be efficiently/quickly analyzed in the future. The analysis will involve summary statistics, exploratory data analysis and maybe simple ML (regres...
<python><azure><pyspark><databricks><azure-databricks>
2022-12-14 08:19:23
1
1,311
An economist
74,795,034
4,845,935
Single-line conditional mocking return values in pytest
<p>I have some method in a Python module db_access called read_all_rows that takes 2 strings as parameters and returns a list:</p> <pre><code>def read_all_rows(table_name='', mode=''): return [] # just an example </code></pre> <p>I can mock this method non-conditionally using pytest like:</p> <pre><code>mocker.patc...
<python><mocking><pytest>
2022-12-14 07:50:15
1
874
dimnnv
74,794,792
4,451,521
Selecting rows from a list or other iterable but in order
<p>I have a dataframe that has a column named &quot;ID&quot; I also have another dataframe with a list of ID values that I want to use.I can select a sub dataframe with the rows corresponding to the IDs in the list</p> <p>For example</p> <pre><code>IDlist_df=pd.DataFrame({&quot;v&quot;:[3,4,6,9]}) df=pd.DataFrame({&quo...
<python><pandas>
2022-12-14 07:21:48
2
10,576
KansaiRobot
74,794,744
11,419,494
Keras' model.summary() not reflecting the size of the input layer?
<p>In the example from 3b1b's video about Neural Network (<a href="https://youtu.be/aircAruvnKk?t=746" rel="nofollow noreferrer">the video</a>), the model has 784 &quot;neurons&quot; in the input layer, followed by two 16-neuron dense layers, and a 10-neuron dense layer. (Please refer to the screenshot of the video pro...
<python><tensorflow><keras>
2022-12-14 07:16:21
1
316
jshji
74,794,708
13,954,738
How to sort a list of dictionaries alphabetically in Jinja2
<p>My sample list of dictionaries is shown below:</p> <pre class="lang-py prettyprint-override"><code>mydata = [{'data': [27, 3, 30, None, None], 'name': 'S1'}, {'data': [57.33, 6.37, 63.7, None, None], 'name': 'A2'}, {'data': [2349.62, 261.09, 2610.71, 0, 0], 'name': 'Total'}] </code></pre> <p>I want to sort the whole...
<python><html><python-3.x><flask><jinja2>
2022-12-14 07:12:38
1
336
ninjacode
74,794,636
17,782,348
Convert array of dicts to timestamp-indexed DataFrame
<p><code>ts</code> should be index (Unix time in milliseconds), column name is random string.</p> <pre><code>[ {'ts': 1669246574000, 'value': '6.06'}, {'ts': 1669242973000, 'value': '6.5'} ] </code></pre> <p>I would like to have the following output</p> <pre><code>DT index SomeParam 1669242973000 6....
<python><pandas><dataframe><time-series>
2022-12-14 07:03:46
0
559
devaskim
74,794,574
8,208,804
Pytest parametrized django_db mark required
<p>I am writing unit tests for a function. In parameterize, I am generating tests cases by making some DB calls when required.</p> <pre class="lang-py prettyprint-override"><code>def my_function(tokens): pass def generate_tokens_helper(**filters): tokens = list(MyTable.objects.values(**filters)) return tok...
<python><django><pytest><pytest-django>
2022-12-14 06:57:23
1
1,462
Sreekar Mouli
74,794,392
7,806,720
FastAPI: Every new request to the API is taking twice the time, if a prior request hasn't completed yet
<p>I am trying to execute a longer task (<code>the_longer_function</code>) in the background, and return the response immediately without waiting for the execution of primary function to complete.</p> <p>Here's the basic code line that I have created:</p> <pre><code>@app.post(&quot;/something/something_test&quot;, resp...
<python><python-3.x><python-asyncio><fastapi><background-process>
2022-12-14 06:33:50
0
901
SalGorithm
74,794,157
5,329,243
Kivy / Python: How to convert float color list to web rgb?
<p>How can I convert Kivy's <code>[0.5019607843137255, 0.796078431372549, 0.7686274509803922, 1.0]</code> float color list to web rgb (i.e. <code>#AABBCCDD</code>) in Python?</p> <p>The list consist of RGBA colors in float format where <code>0..255</code> is represented as <code>0..1</code> and each color is the list ...
<python><web><colors><kivy><converters>
2022-12-14 06:04:12
1
648
CeDeROM
74,794,064
2,975,438
Pandas: how to add column with Booleans (True/False) based on duplicates in one column and group index in another column
<p>I have the following dataframe:</p> <pre><code>d_test = { 'name' : ['bob', 'rob', 'dan', 'steeve', 'carl', 'steeve', 'dan', 'carl', 'bob'], 'group': [1, 4, 3, 3, 2, 3, 2, 1, 5] } df_test = pd.DataFrame(d_test) </code></pre> <p>I am looking for a way to add column <code>duplicate</code> with <code>True</code>...
<python><pandas>
2022-12-14 05:48:49
1
1,298
illuminato
74,793,930
4,793,216
Why is path parameter shown as query parameter in FastAPI docs?
<p>I am developing APIs using FastAPI.</p> <p>I have set the router as the following:</p> <pre><code>router = APIRouter( prefix=&quot;/customer-profiles&quot;, tags=[&quot;customer-profiles&quot;], responses={ 404: { &quot;description&quot;: &quot;Not found&quot; } }, ) @rou...
<python><fastapi><pydantic>
2022-12-14 05:27:59
1
331
Aadarsha
74,793,690
5,653,423
Convert images to numpy array with RGB values
<p>I have written following code to read set of images in a directory and convert it into NumPy array.</p> <pre><code> import PIL import torch from torch.utils.data import DataLoader import numpy as np import os import PIL.Image # Directory containing the images image_dir = &quot;dir...
<python><machine-learning><image-processing><pytorch><python-imaging-library>
2022-12-14 04:47:41
1
1,402
shome
74,793,663
11,229,812
How to show sensor reading in tkinter?
<p>I am trying to capture readings from the sensor into tkniter and am stuck on a small problem. To simulate sensor reading I created a small function that increments the number for 1 every second. And in this example, I am trying to present that counter within tkniter label.</p> <p>Here is the code:</p> <pre><code>imp...
<python><python-3.x><tkinter>
2022-12-14 04:43:09
2
767
Slavisha84
74,793,652
10,534,633
What is the usage of defining many elements types in list type as for tuple type?
<p>Since <em>Python 3.9</em>, there are type hints built-in and for a <code>list</code> type, there's a possibility to define also type of its elements.</p> <p>When all the list's elements have the same type, it's simple: <code>list[str]</code>.<br /> When the elements' types are different, we can define a type hint li...
<python><list><type-hinting>
2022-12-14 04:41:30
1
1,230
maciejwww
74,793,562
2,368,545
Regular express to find all lower case string with dot with Python
<p>Trying with python to find all strings inside a double quote, and with domain name like format, such as <code>&quot;abc.def.ghi&quot;</code>.</p> <p>I am currently using <code>re.findall('\&quot;([a-z\\.]+[a-z]*)\&quot;', input_string)</code>,</p> <p><code>[a-z\\.]+</code> is for <code>abc.</code>, <code>def.</code>...
<python><regex>
2022-12-14 04:24:32
2
696
Frank
74,793,392
15,542,245
Numerical reference for backreference not working out in Python
<p>I was trying to deal with difflib matches that return double word place names when only one of the words has been used to make the match. That is: when I do the difflib regex substitution I get a double up of the second word.</p> <p>Approach:</p> <ul> <li>capture substrings so repeated word is last/first of substrin...
<python><regex><backreference><capture-group>
2022-12-14 03:52:42
1
903
Dave
74,793,352
8,321,207
matplotlib pyplot display ticks and values which are in scientific form
<p>I have a plot which looks like this:</p> <p><a href="https://i.sstatic.net/MS7Qw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/MS7Qw.png" alt="enter image description here" /></a> The values displayed on the blue line are the cost ratio.</p> <p>The corresponding code looks like this:</p> <pre><code>...
<python><matplotlib><plot><linegraph>
2022-12-14 03:44:42
1
375
Kathan Vyas
74,793,240
11,918,314
Python Loop Function to Create New Columns based on Groupby of multiple columns
<p>I have a dataframe with the following columns</p> <pre><code>rater_id being_rated_id combine_id avg_jump avg_run avg_swim category 100 200 100200 3 3 2 heats 100 200 100200 4 4 1 heats 101 200 ...
<python><pandas><dataframe><for-loop>
2022-12-14 03:22:25
1
445
wjie08
74,793,228
7,585,973
How to avoid unique key appear twice in PySpark left join
<p><code>df_1</code> column -&gt; <code>|id|pym_cat|sub_status|year|month|day|</code></p> <p><code>df_2</code> column -&gt; <code>|id|loc_provinsi|loc_kabupaten|loc_kecamatan|</code></p> <p>Here's my code</p> <p><code>df_join = df_1.join(df_2, df_1.id == df_2.id, &quot;left&quot;)</code></p> <p>the error message</p> <p...
<python><join><pyspark>
2022-12-14 03:20:49
2
7,445
Nabih Bawazir
74,793,150
17,620,776
AttributeError: 'float' object has no attribute 'ids' when running kivy app
<p>I am trying to make a app that captures 30 images a second from the webcam in kivy.</p> <p>But when I run it, it give me this error:</p> <pre><code>AttributeError: 'float' object has no attribute 'ids' </code></pre> <p>Here is the code to reproduce the problem:</p> <pre><code>from kivy.app import App from kivy.lang ...
<python><kivy>
2022-12-14 03:05:44
2
357
JoraSN
74,792,952
19,425,874
Adding Current Date column next to current Data Frame using Python
<p>I'm not fully understanding data frames &amp; am in the process of taking a course on them. This one feels like it should be so easy, but I could really use an explanation.</p> <p>All I want to do is ADD a column next to my current output that has the CURRENT date in the cells.</p> <p>I'm getting a timestamp using<...
<python><pandas><dataframe><python-requests><timestamp>
2022-12-14 02:24:22
1
393
Anthony Madle
74,792,951
4,373,372
Convert RGBA image to array in specific range in python
<p>I have an array of values in range of 1500 to 4500. I managed to convert the data using matplotlib function. The code as follows:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np norm = plt.Normalize(vmin=1500, vmax=4500) jet = plt.cm.jet # generate 100x100 with ...
<python><numpy><matplotlib>
2022-12-14 02:24:21
1
518
Alif Jamaluddin
74,792,731
4,451,521
How do I add a column to a dataframe based on values from other columns?
<p>I have a dataframe and I would like to add a column based on the values of the other columns</p> <p>If the problem were only that, I think a good solution would be <a href="https://stackoverflow.com/a/46684122/4451521">this answer</a> However my problem is a bit more complicated</p> <p>Say I have</p> <pre><code>impo...
<python><pandas>
2022-12-14 01:38:24
2
10,576
KansaiRobot
74,792,714
7,658,985
Find all JSON files within S3 Bucket
<p>is it possible to find all <code>.json</code> files within S3 <code>bucket</code> where the bucket itself can have multiple sub-directories ?</p> <p>Actually my bucket includes multiple sub-directories where i would like to collect all JSON files inside it in order to iterate over them and parse specific key/values....
<python><json><amazon-web-services><amazon-s3><boto3>
2022-12-14 01:35:36
1
11,557
αԋɱҽԃ αмєяιcαη
74,792,690
2,160,616
Calculating difference between two rows, based on another column match condition, in Python / Pandas
<p>I have seen questions like <a href="https://stackoverflow.com/questions/13114512/">calculate the difference between rows in DataFrame</a> &amp; i understand Pandas provides <code>df.diff()</code> API but my question context is slightly different. DataFrame will consist thousands of rows with volume data till that ti...
<python><pandas><dataframe>
2022-12-14 01:31:00
1
3,343
BeingSuman
74,792,607
11,122,879
Poor Result in Detecting Meter Reading Using Pytesseract
<p>I am trying to develop a meter reading detection system. This is the picture <a href="https://i.sstatic.net/qVPcW.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qVPcW.jpg" alt="enter image description here" /></a></p> <p>I need to get the meter reading 27599 as the output. I used this code:</p> <pre>...
<python><opencv><ocr><python-tesseract><meter>
2022-12-14 01:13:01
1
501
Rashida
74,792,454
7,211,014
python change a files creation and modification time without having to use a subcommand?
<p>I want to change the modification and creation time of any file with python. This would be the command I use in Linux:</p> <pre><code>touch -a -m -t 201512180130.09 ./file.jpg </code></pre> <p>Then I check the following I can see the date is changed correctly:</p> <pre><code>$ls -l --time-style=full-iso -rw-rw-r-- ...
<python><date><time><touch><concurrentmodification>
2022-12-14 00:43:48
0
1,338
Dave
74,792,378
7,148,668
zipfile.BadZipFile: Bad offset for central directory
<p>I have designed a webpage that allows the user to upload a zip file. What I want to do is store this zip file directly into my sqlite database as a large binary object, then be able to read this binary object as a zipfile using the <code>zipfile</code> package. Unfortunately this doesn't work because attempting to p...
<python><flask><zip>
2022-12-14 00:30:05
1
345
Kookie
74,792,243
315,168
Truncating by time in (name, timestamp) Pandas MultiIndex
<p>I have the following <code>MultiIndex</code> created with <code>df.groupby(...).resample()</code>. It is stock market-like OHLC data grouped by an asset and then having OHLC candle time-series for this asset.</p> <pre><code> high low close ... avg_trade buys sells pair timestamp ...
<python><pandas>
2022-12-14 00:04:26
1
84,872
Mikko Ohtamaa
74,792,053
4,561,887
Python: obtain the path to the home directory of the user in whose directory the script being run is located
<p>I don't consider this question (<a href="https://stackoverflow.com/q/50499/4561887">How do I get the path and name of the file that is currently executing?</a>) nor <a href="https://stackoverflow.com/q/3718657/4561887">this one</a> to be a duplicate of mine, because the answer to them is simply <code>__file__</code>...
<python><linux><path>
2022-12-13 23:35:46
1
55,879
Gabriel Staples
74,792,048
7,984,318
How to check pandas dataframe column value float nan
<p>I have a pandas dataframe column which value is nan and is a float:</p> <pre><code>df['column'] </code></pre> <p>I want to add a logic there,if df['column'] equal float nan then do something,the problem is I have no idea how to check if it is float nan ,is there anyway like:</p> <pre><code>if df['column'] == 'nan': ...
<python><pandas><dataframe>
2022-12-13 23:34:53
1
4,094
William
74,791,962
7,903,749
How to implement `left outer join` with additional matching condition, with `annotate()` or something else?
<p>The <code>transaction</code> (entity) records have customized attributes in EAV format, so we are implementing a design pattern that assembles EAV data with the entities by a series of <code>left outer join</code> operations in SQL query, briefly as the following:</p> <ul> <li>First, we have retrieved the metadata, ...
<python><django><entity-attribute-value>
2022-12-13 23:22:08
1
2,243
James
74,791,868
8,816,642
How to create a frequency / value count table from multiple dataframes
<p>I have two dataframes,</p> <pre><code>df1 df2 country country US AR US AD CA AO CN AU AR US </code></pre> <p>How do I group by them by combining the country list ...
<python><pandas><dataframe>
2022-12-13 23:09:22
3
719
Jiayu Zhang
74,791,859
8,925,864
How to generate all configurations of a given length in Python
<p>I am trying to generate a list of all configurations where in each configuration is as follows. Each configuration is a list of length <code>n</code> whose entry can take on values <code>0-q</code> where <code>q</code> is a positive integer. For example if <code>q=1</code> then I am trying to generate a list of all ...
<python><recursion>
2022-12-13 23:08:21
1
305
q2w3e4
74,791,850
11,462,274
How to do a cumulative sum in a DataFrame analyzing all possible combination columns instead of analyzing only all columns together?
<p>If we want to know if the cumulative sums are profitable in the <code>['Col 1','Col 2','Col 3']</code> columns for the long term, we do it this way:</p> <pre class="lang-python prettyprint-override"><code>import pandas as pd import io ex_csv = &quot;&quot;&quot; Col 1,Col 2,Col 3,return a,b,c,1 d,e,f,1 a,e,c,-1 a,e...
<python><pandas><dataframe><cumsum>
2022-12-13 23:07:12
1
2,222
Digital Farmer
74,791,822
12,821,675
SQLAlchemy - Default PKs and Bulk Save
<p>I have a model with a uuid as the pk with a default value like so:</p> <pre class="lang-py prettyprint-override"><code>class Car(...): ... uuid = Column( String, primary_key=True, default=lambda x: str(uuid4()), ) </code></pre> <p>At somepoint in my application I bulk add a bunc...
<python><python-3.x><sqlalchemy>
2022-12-13 23:03:05
1
3,537
Daniel
74,791,817
9,749,124
Changing labels for Pandas rows that have the same value
<p>I want to change labels in the Pandas dataframe for the row that have the same value but different label:</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;text&quot;: [&quot;bannana&quot;, &quot;tomato&quot;, &quot;potato&quot;, &quot;potato&quot;, &quot;lemon&quot;, &quot;cucamber&quot;], ...
<python><pandas>
2022-12-13 23:02:40
2
3,923
taga
74,791,708
2,142,728
How to call function with dict, while ignoring unexpected keyword arguments?
<p>Something of the following sort. Imagine this case:</p> <pre class="lang-py prettyprint-override"><code>def some_function(a, b): return a + b some_magical_workaround({&quot;a&quot;: 1, &quot;b&quot;: 2, &quot;c&quot;: 3}) # returns 3 </code></pre> <p>I can't modify <code>some_function</code> to add a <code>*...
<python><keyword-argument>
2022-12-13 22:49:42
4
3,774
caeus
74,791,672
13,530,377
Datetime string needs to be converted to datetime object before matching on pandas column
<p>Looking for clarification. I've seen several comments in SO posts saying emphatically that you can do a greater than less than comparison with a datetime column and a string formatted like a datetime object. I am finding this to be false so I was wondering if anyone could indeed confirm that this is not possible.</p...
<python><pandas><datetime>
2022-12-13 22:43:48
1
483
Justin Benfit
74,791,436
19,675,781
How to sort dataframe columns baed on 2 indexes?
<p>I have a data frame like this</p> <pre><code>df: Index C-1 C-2 C-3 C-4 ........ Ind-1 3 9 5 4 Ind-2 5 2 8 3 Ind-3 0 1 1 0 . . </code></pre> <p>The data frame has more than a hundred columns and rows with whole numbers(0-60) as values.<br /> The first two rows(indexes) hav...
<python><python-3.x><pandas><dataframe>
2022-12-13 22:12:17
1
357
Yash
74,791,215
1,134,241
How to train an LSTM with multiple simultaneous time-series. Radon values over a year in 100 houses with 4 rooms
<p>I have trained an LSTM neural network on 1 year's worth of radon measurement time-series data for one room in one house. I have 100 houses with 4 rooms each. How could I create a for loop to train on 70 houses (4 rooms each) to keep training the network with data rather than having 70 different LSTMs?</p> <pre><code...
<python><tensorflow><keras>
2022-12-13 21:45:38
1
2,263
HCAI
74,791,202
3,246,693
Match nearest timestamp without set_index
<p>I have 2 dataframes that contain event activities from various applications.</p> <p>I want to merge them together and match up the events from the 2nd dataframe where the date field is less than(before) the date in the 1st dataframe wherever the user and system are the same. Also, if there is no event in Data2 or t...
<python><python-3.x><pandas><dataframe>
2022-12-13 21:44:08
0
803
user3246693
74,791,141
12,574,341
Iterating through one dict of size n vs two dicts of size n/2
<p>Implementing a bijective map. Internally representing it using dictionary(s).</p> <p>Is there a performance difference between iterating through a dictionary of size n and iterating through two dictionaries of size n/2?</p> <p>Option 1:</p> <pre class="lang-py prettyprint-override"><code>d = {'A': 1, 'B': 2, 1: 'A',...
<python><performance><hashmap><big-o>
2022-12-13 21:37:20
1
1,459
Michael Moreno
74,791,092
2,601,293
pydantic dataclass allowing None parameter
<p>When using <code>pydantic.dataclass</code> I'm specifying that a type must be an <code>int</code>. When the constructor is called with a <code>None</code> parameter, the validator <strong>doesn't</strong> raise a <code>ValidationError</code>. How can I make the <code>pydantic.dataclass</code> raise when None is pas...
<python><pydantic>
2022-12-13 21:31:02
1
3,876
J'e
74,791,087
4,613,465
Python opencv error (-215:Assertion failed) 0 <= scaleIdx && scaleIdx < (int)scaleData->size() in CascadeClassifier.detectMultiScale
<p>I'm using the CascadeClassifier of the opencv-python package to perform face detection with the haarcascade_frontalface_default.xml with this code:</p> <pre><code>self.face_cascade = cv2.CascadeClassifier(haar_cascade_path) ... gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) faces = self.face_cascade.detectMul...
<python><opencv><face-detection><assertion>
2022-12-13 21:30:48
1
772
Fatorice
74,791,018
7,168,098
python ziping lists of single element or tuples into list of tuples
<p>Assuming I have a colection of lists of the same size (same number of elements), where the elements are single elements (strings, numbers) or tuples:</p> <pre><code>a = ['AA', 'BB', 'CC'] b = [7,8,9] d = [('TT', 'ZZ'),('UU', 'VV'),('JJ','KK')] e = [('mm', 'nn'), ('bb', 'vv'), ('uu', 'oo')] </code></pre> <p>I would l...
<python><list><dictionary><tuples><zip>
2022-12-13 21:23:31
4
3,553
JFerro
74,790,952
11,229,812
How to create function that can be used with switch button in Tkniter GUI?
<p>I am trying to build a GUI with Tkinter and use it to control my Raspberry Pi robot. With some help, I managed to get the functionality of the buttons when being pressed and held down but I am struggling with the function that will allow me to do things with the switch button. <a href="https://i.sstatic.net/HSWcT.pn...
<python><python-3.x><tkinter>
2022-12-13 21:17:39
1
767
Slavisha84
74,790,924
2,194,805
Python unittests one by one works well but not together under Flask
<p>I've a test file containing some unittests. All of them looks like:</p> <pre><code>def test_something_222(self): with app.test_client() as c: response = c.get(URL) assert response.status_code == some_value </code></pre> <p>. When I run them one by one, everything works well, however using <strong...
<python><unit-testing><flask>
2022-12-13 21:14:13
0
1,389
user2194805
74,790,814
5,103,969
Is there any way to cimport cv2 in cython?
<p>I am trying to cimport cv2 in Cython Code.</p> <p><code>cimport cv2</code></p> <p>I have installed the Python OpenCV module and the Cython wrapper for OpenCV, but I'm unsure how to cimport the cv2 module in my Cython code.</p> <p>To get the best performance, if not cimport, how should the cv2 C++ code be imported an...
<python><opencv><cython>
2022-12-13 21:00:46
1
975
Abhik Sarkar
74,790,809
12,199,326
Remove data of type category from plot
<p>Say we have a df with a column defined as a category:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Color': ['Yellow', 'Blue', 'Red', 'Red']}, dtype='category') # data type is category </code></pre> <p>Now say we want to plot these data while removing one of the categorical levels:</p> <pre><code># Exclude ...
<python><pandas><plot><dtype>
2022-12-13 21:00:13
2
892
johnjohn
74,790,773
2,526,128
Is an attribute protected if initialized as public but setters & getters treat it as protected?
<p>While learning the basics of object oriented programming in Python, I came across something I cannot search effectively to find matching keywords:</p> <p>I wrote validation checks for a basic class <code>Course</code>, which has a protected attribute <code>_level</code>. The getters and setters treat this as a prote...
<python><oop>
2022-12-13 20:55:21
1
718
batlike
74,790,739
7,882,846
Pandas Mixed Date Format Values in One Column
<pre><code>df = pd.Series('''18-04-2022 2016-10-05'''.split('\n') , name='date' ).to_frame() df['post_date'] = pd.to_datetime(df['date']) print (df) date post_date 0 18-04-2022 2022-04-18 1 2016-10-05 2016-10-05 </code></pre> <p>When trying to align the date column into one consistent format, I get an err...
<python><pandas><datetime>
2022-12-13 20:51:18
1
439
Todd
74,790,649
311,130
How to repeatedly attach object A for every object B in python?
<pre><code>raw_data_row = { &quot;account_level_data&quot; : {&quot;account_name&quot;: &quot;A&quot;, &quot;currency&quot; :&quot;USD&quot;} &quot;store_level_data&quot; : {&quot;store_name&quot;: &quot;MySotre&quot;, &quot;address&quot; :&quot;MyStreet&quot;}, item_values : [{&quot;name&quot;: &quot;a&quot;, &quot;pr...
<python>
2022-12-13 20:42:53
1
36,892
Elad Benda
74,790,598
3,937,811
How to process a response from the Twilio REST API
<p>I am developing a program to help treat depression. I do not have a deep understanding of Twilio. I would like to collect the responses to this message:</p> <pre><code>Sent from your Twilio trial account - What are the positive results or outcomes you have achieved lately? What are the strengths and resources you ha...
<python><twilio>
2022-12-13 20:37:31
2
2,066
Evan Gertis
74,790,568
16,962,446
difference between autobegin and Session.begin
<p>In the following code snippet a commit is executed once the with block is exited.</p> <pre><code>from sqlalchemy import create_engine, Column, String from sqlalchemy.orm import declarative_base, Session Base = declarative_base() class Foo(Base): __tablename__ = 'Foo' id = Column(String, primary_key=True) ...
<python><sql><sqlalchemy><transactions>
2022-12-13 20:32:59
1
557
Jake
74,790,288
3,937,811
How to process words from a csv list
<p>I am running into an issue based on the following program.</p> <h3>Code</h3> <pre><code># Download the helper library from https://www.twilio.com/docs/python/install import os from twilio.rest import Client import logging import csv logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(mes...
<python><typeerror>
2022-12-13 20:01:44
2
2,066
Evan Gertis
74,790,072
5,666,203
NaN values arise after writing and reading a .sigmf-data file in Python
<p>I have a Numpy array of complex values that I am preparing to write out to a .sigmf-data file:</p> <pre><code># ISTFT t_recon, x_recon = signal.istft(Zxx_unflip, fs=sample_rate, nperseg=NFFT, nfft=NFFT, ...
<python><arrays><numpy>
2022-12-13 19:36:03
1
1,144
AaronJPung
74,790,067
8,094,926
Which variables are allowed in a __str__ implementation?
<p>I'm learning python <code>@property</code> annotation using <a href="https://www.online-python.com/online_python_compiler" rel="nofollow noreferrer">this</a>. My understanding is that it is a built-in property to facilitate accessing and modifying class properties. I created a class using this annotation on some pro...
<python><python-3.x>
2022-12-13 19:35:23
1
468
chocalaca
74,790,062
12,076,197
How to Multi-Index an existing DataFrame
<p>&quot;Multi-Index&quot; might be the incorrect term of what I'm looking to do, but below is an example of what I'm trying to accomplish.</p> <p>Original DF:</p> <pre><code> HOD site1_units site1_orders site2_units site2_orders hour1 6 3 20 16 hour2 ...
<python><pandas><dataframe>
2022-12-13 19:35:00
2
641
dmd7
74,790,060
7,158,458
View takes 1 positional argument but 2 were given
<p>Trying to make a POST request to openAI with the input:</p> <pre><code>{&quot;write hello world&quot;} </code></pre> <p>but getting the error:</p> <pre><code>TypeError: View.__init__() takes 1 positional argument but 2 were given </code></pre> <p>Here is my view:</p> <pre><code>def get_help(user_input): response...
<python><django><openai-api>
2022-12-13 19:34:55
1
2,515
Emm
74,789,903
10,328,083
How to write arrays to .bson file using bson package from pymongo
<p>I have a dictionary <code>my_dict</code> of the following form. It has two keys, <code>'0'</code> and <code>'1'</code>. For either of these keys, <code>my_dict['0']</code> is an <code>np.array</code> with <code>np.shape(my_dict['0']) = (10, 400000)</code>.</p> <p>I am trying to use the <code>bson</code> package from...
<python><arrays><file-io><pymongo><bson>
2022-12-13 19:17:56
0
547
seeker_after_truth
74,789,640
17,696,880
How to perform replacement with re.sub() if and only if there is a ; or \n. in the middle of the capture groups?
<pre class="lang-py prettyprint-override"><code>import re, datetime #Ejemplos en donde si se debe hacer uno o mas reemplazos input_text = &quot;Decian muchas cosas; Seguro eso ocurrira despues de 3 dias&quot; input_text = &quot;seguro eso ocurrira despues de 3 dias.\n empieza el 2021-11-12&quot; input_text = &quot;Re...
<python><python-3.x><regex><regex-group><regexp-replace>
2022-12-13 18:52:14
0
875
Matt095
74,789,548
1,914,781
plotly express plot with filled rect in background
<p>How to move below fill rect in background layer?</p> <pre><code>import numpy as np import plotly.express as px def plot(x,y): fig = px.scatter( x=x, y=y, error_y=[0] * len(y), error_y_minus=y ) fig.add_vrect(x0=0, x1=np.pi, line_width=0, fillcolor=&quot;pink&quot;) t...
<python><plotly>
2022-12-13 18:41:20
1
9,011
lucky1928
74,789,349
15,781,591
Why does first plot in for loop not get formatted, while the rest are?
<p>I have the following code that iterates through a data frame row and grabs a start timestamp and an end timestamp from two columns, creating a &quot;time series range&quot;, and then plots that time series range from another dataframe of timeseries data. And so, I iterate through each time series range and create th...
<python><pandas><matplotlib><plot>
2022-12-13 18:22:07
1
641
LostinSpatialAnalysis
74,789,249
12,752,172
How to extract data from a dynamic table with selenium python?
<p>I'm trying to extract data from a website. I need to enter the value in the search box and then find the details. it will generate a table. After generating the table, need to write the details to the text file or insert them into a database. I'm trying the following things.</p> <p>Website: <a href="https://commtech...
<python><selenium><selenium-webdriver><beautifulsoup><webdriverwait>
2022-12-13 18:12:47
2
469
Sidath
74,789,171
11,734,835
what is use_develop in tox and development mode
<p>I was trying to understand the purpose of <code>use_develop</code> and from the docs, I found this:</p> <blockquote> <p>Install the current package in development mode with develop mode. For pip this uses -e option, so should be avoided if you’ve specified a custom install_command that does not support -e.</p> </blo...
<python><tox>
2022-12-13 18:04:29
1
356
james pow
74,789,116
19,838,568
ast.literal_eval not working as part of list comprehension (when reading a file)
<p>I am trying to parse a file which has pairs of lines, each of them representing a list of integers or other lists. Example data from the file:</p> <pre><code>[[[6,10],[4,3,[4]]]] [[4,3,[[4,9,9,7]]]] [[6,[[3,10],[],[],2,10],[[6,8,4,2]]],[]] [[6,[],[2,[6,2],5]]] </code></pre> <p>I am trying to read the file into a li...
<python><abstract-syntax-tree>
2022-12-13 17:59:19
3
2,406
treuss
74,788,974
12,574,341
Python annotate type as regex pattern
<p>I have a dictionary annotation</p> <pre class="lang-py prettyprint-override"><code>class OrderDict(TypedDict): name: str price: float time: str </code></pre> <p>The value of <code>time:</code> will always be formatted like <code>2022-01-01 00:00:00</code>, or <code>&quot;%Y-%m-%d %H:%M:%S&quot;</code>. I...
<python><mypy><python-typing><pyright>
2022-12-13 17:47:59
2
1,459
Michael Moreno
74,788,890
4,602,248
Programmatically check when google sheets spreadsheet was last updated
<p>I am starting to pull data from multiple shared spreadsheets on google sheets and this works fine. Currently I have to read in the whole spreadsheet and process the data to see if any updates have been made to it. How can I programmatically (in Python 3.9) get a timestamp of the last update to a google sheet?</p>
<python><io><version-control><timestamp><google-sheets-api>
2022-12-13 17:41:29
1
2,529
Alex
74,788,877
17,889,840
how to create hdf5 file from numpy dataset files
<p>I have 1970 <code>.npy</code> files as features for MSVD dataset. I want to create one <code>.hdf5</code> file from these numpy files.</p> <pre><code>import os import numpy as np import hdf5 TRAIN_FEATURE_DIR = &quot;MSVD&quot; for filename in os.listdir(TRAIN_FEATURE_DIR): f = np.load(os.path.join(TRAIN_...
<python><numpy><hdf5>
2022-12-13 17:40:18
1
472
A_B_Y
74,788,743
4,329,348
Python logging perforamnce when level is higher
<p>One advantage of using logging in Python instead of print is that you can set the level of the logging. When debugging you could set the level to DEBUG and everything below will get printed. If you set the level to ERROR then only error messages will get printed.</p> <p>In a high-performance application this propert...
<python><logging><python-logging>
2022-12-13 17:29:10
1
1,219
Phrixus
74,788,740
3,161,120
How to use multithreading.Value in dataclass?
<p>Would anyone of you know if it's possible to use <code>multiprocessing.Value</code> field in <code>dataclass</code>?</p> <p>For the following dataclass definition, I am getting <code>TypeError: this type has no size</code> exception.</p> <pre><code>import multiprocessing from dataclasses import dataclass @dataclass...
<python><python-3.x><multiprocessing><python-dataclasses>
2022-12-13 17:28:57
1
1,830
gbajson
74,788,656
8,869,570
What is the "+01:00" in "2006-04-03 08:00:00+01:00" datetime timestamp object?
<p>I printed out a <code>&lt;class 'pandas._libs.tslibs.timestamps.Timestamp'&gt;</code> <code>time</code> variable, and it displays as</p> <pre><code>2006-04-03 08:00:00+01:00 </code></pre> <p>I am wondering what is the <code>+01:00</code> at the end? Seems this is related to daylight savings?</p> <p>When I did</p> <p...
<python><datetime><timestamp><timezone>
2022-12-13 17:22:08
2
2,328
24n8
74,788,564
7,576,002
How do you connect use pyodbc to connect to MS SQL server when password has escape characters
<p>I'm writing a connection string in Python that connects to a MS SQL Server database. I am using pyodbc. Previously, I had used SqlAlchemy and that worked fine. However, I'd like to NOT use SQLAlchemy because I'd like to keep things simple.</p> <p>The problem is, when I try to create a connect string and the passw...
<python><sql-server><pyodbc>
2022-12-13 17:14:06
0
1,129
KSS
74,788,554
9,786,534
How can I change the dimensions of a xarray variable?
<p>I have a gridded xarray dataset that looks like this:</p> <pre><code>print(ds) &lt;xarray.Dataset&gt; Dimensions: (month: 12, isobaricInhPa: 37, latitude: 721, longitude: 1440) Coordinates: * isobaricInhPa (isobaricInhPa) float64 1e+03 975.0 950.0 ... 3.0 2.0 1.0 * latitude (latitude) float64 90.0 ...
<python><python-3.x><python-xarray>
2022-12-13 17:13:40
1
324
e5k
74,788,423
12,337,118
Can't pass header in Python client generated by OpenAPI Generator
<p>With the help of <a href="https://openapi-generator.tech/" rel="nofollow noreferrer">OpenAPI Generator</a> I generated a Python client for the Amadeus <a href="https://github.com/tsolakoua/amadeus-open-api-example/blob/master/TravelRestrictions_v2_swagger_specification.json" rel="nofollow noreferrer">Travel Restrict...
<python><openapi><openapi-generator><amadeus>
2022-12-13 17:03:00
0
731
anna_ts
74,788,390
16,267,101
how to get a column value of foreign key in the form of object?
<p>There is 2 models <code>Registration</code> and <code>RegistrationCompletedByUser</code>, I want <code>Registration</code> queryset from <code>RegistrationCompletedByUser</code> with <code>filters(user=request.user, registration__in=some_value, is_completed=True)</code> over <code>RegistrationCompletedByUser</code>....
<python><django><django-models>
2022-12-13 16:59:57
2
335
shraysalvi
74,788,356
13,279,198
Quicksort with median-of-three not sorting properly?
<p>Please explain to me what I am doing wrong in my Quicksort code because the output array is not correctly sorted. It is using the median of three partitioning to select the pivot.</p> <p>Here is the code:</p> <pre><code>def medianof3(arr, low, high): center = (low + high) // 2 if arr[low] &lt; arr[center]: a...
<python><sorting><data-structures><quicksort>
2022-12-13 16:56:57
1
359
Ah_bb
74,788,241
3,030,875
How to quickly instantiate a pyspark SparkContext for unit testing?
<p>In my Python 3.8 unit test code, I need to instantiate a SparkContext to test some functions manipulating a <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.RDD.html#pyspark.RDD" rel="nofollow noreferrer">RDD</a>.</p> <p>The problem is that instantiating a SparkContext takes a few secon...
<python><pyspark><rdd><python-unittest>
2022-12-13 16:47:44
0
1,778
Brainless
74,788,118
9,720,696
How to upload the a folder into Azure blob storage while preserving the structure in Python?
<p>I've wrote the following code to upload a file into blob storage using Python:</p> <pre><code>blob_service_client = ContainerClient(account_url=&quot;https://{}.blob.core.windows.net&quot;.format(ACCOUNT_NAME), credential=ACCOUNT_KEY, ...
<python><azure><azure-blob-storage><azure-python-sdk>
2022-12-13 16:38:13
1
1,098
Wiliam
74,788,097
3,067,276
Why does TypeVar and TypedDict require repeating the variable name as a string?
<p>In Python typing, why do I have to write <code>T = TypeVar(&quot;T&quot;)</code> instead of just <code>T = TypeVar()</code>? Any static analyzer is able to read the variable name without requiring the string parameter. The string parameter only matters for getting the name of the type variable in runtime. As far as ...
<python><python-typing>
2022-12-13 16:36:54
1
3,439
fonini
74,788,083
11,170,350
compare two list of unequal length and fill third list by unmatched index
<p>I have two list of unequal size.</p> <pre><code>large_list=['A','B','C','D','E','F','G','H','I'] small_list=['A','D','E'] </code></pre> <p>I have another list.</p> <pre><code>tag_list=['1','3','5'] </code></pre> <p>I want to compare large_list against small_list. Where the elements are equal, at that point take the ...
<python>
2022-12-13 16:35:45
5
2,979
Talha Anwar
74,788,070
5,110,870
VS Code: why is Python dataclass not inheriting the parent's attributes?
<p>I am new to OOP, often a big pain as things aren't explained clearly and have weird behaviours.</p> <p>One frustrating example in Python 3.9.13:</p> <pre><code>@dataclass class Person: name: str city: str age: int @dataclass class Student(Person): grade: int subjects: list </code></pre...
<python><oop><inheritance><python-dataclasses>
2022-12-13 16:34:48
0
7,979
FaCoffee
74,787,906
2,970,705
Elasticsearch: mapper_parsing_exception: Get detailed error message
<p>I am inserting a Pandas dataframe into Elasticsearch, using the <code>elasticsearch</code> Python package.</p> <p>I have created an index specifying an explicit mapping:</p> <pre><code>mappings = { 'properties': { 'PLZ': {'type': 'integer'}, 'ORT': {'type': 'text'}, 'STRASSE': {'type': 't...
<python><pandas><elasticsearch>
2022-12-13 16:22:05
0
6,044
JavAlex
74,787,831
6,156,353
Easiest way to fill in jinja template
<p>I have a jinja templates (python files) with several variables like this <code>{{ some_variable }}</code>. Then I have a <code>yml</code> files with the defined variable values.</p> <p>python/jinja template:</p> <pre class="lang-py prettyprint-override"><code>import datetime some_variable = '{{ some_variable }}' </...
<python><jinja2>
2022-12-13 16:15:55
1
1,371
romanzdk
74,787,746
7,949,129
How to update only a part of a json which is stored in a database with a "json path" list?
<p>Let´s say we have a database and there is a json stored as a string which contains configurations. In the application we want to update only a specific value and write then back the json as a string to the database.</p> <p>The HTTP request provides a &quot;jsonPath&quot; which reflects a path in the json file to na...
<python><json><django>
2022-12-13 16:09:14
2
359
A. L
74,787,600
11,002,498
Errors trying to switch to new version of Python in Visual Studio Code
<p>I am using visual studio code to run a program in python. I wrote my program in python 3.7 and everything was fine. I tried to install jupyterlab but it needed a new version. So I switched to Python 3.11 (3.11.0 64-bit to be more precise).</p> <p>When I run my code in the newer Python version it says:</p> <blockquot...
<python><visual-studio-code>
2022-12-13 15:56:38
1
464
Skapis9999