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,141,428
2,100,039
Python "checknull() takes no keyword arguments" error
<p>I have tried to research this error and I cannot seem to find an answer. I've never seen this and this code worked fine last month and now I receive this error with the same code. Please advise and thank you. I've included my code and the error message below. The program is designed to read data from a URL and inges...
<python><error-handling><null><runtime-error>
2023-01-17 02:19:47
0
1,366
user2100039
75,141,364
17,823,260
How to convert two columns of dataframe into an orderedDict in Python?
<p>I have a table named <code>tableTest</code> like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>startDate</th> <th>endDate</th> </tr> </thead> <tbody> <tr> <td>2022-12-15</td> <td>2022-12-18</td> </tr> <tr> <td>2022-12-19</td> <td>2022-12-21</td> </tr> <tr> <td>2022-12-22</td> <td...
<python><pandas><pyspark>
2023-01-17 02:04:48
2
339
Guoran Yun
75,141,277
10,200,497
get the first row of mask that meets conditions and create a new column
<p>This is my pandas dataframe:</p> <pre><code>df = pd.DataFrame({'a': [20, 21, 333, 444], 'b': [20, 20, 20, 20]}) </code></pre> <p>I want to create column <code>c</code> by using this <code>mask</code>:</p> <pre><code>mask = (df.a &gt;= df.b) </code></pre> <p>and I want to get the second row that meets this condition ...
<python><pandas>
2023-01-17 01:44:53
1
2,679
AmirX
75,141,238
4,334,110
exhaustive search over a list of complex strings without modifying original input
<p>I am attempting to create a minimal algorithm to exhaustively search for duplicates over a list of strings and remove duplicates using an index to avoid changing cases of words and their meanings.</p> <p>The caveat is the list has such words Blood, blood, DNA, ACTN4, 34-methyl-O-carboxy, Brain, brain-facing-mouse, ...
<python><list><algorithm><search><duplicates>
2023-01-17 01:36:49
2
1,136
Paritosh Kulkarni
75,141,237
558,619
General function to turn string into **kwargs
<p>I'm trying to find a way to pass a string (coming from outside the python world!) that can be interpreted as <code>**kwargs</code> once it gets to the Python side.</p> <p>I have been trying to use <a href="https://stackoverflow.com/questions/38799223/parse-string-to-identify-kwargs-and-args">this pyparsing example</...
<python><parsing>
2023-01-17 01:36:29
4
3,541
keynesiancross
75,141,191
19,826,650
Change List format in Python
<p>I have an List like down below</p> <pre><code>[['-6.167665', '106.904251'], ['-6.167665', '106.904251']] </code></pre> <p>How to make it like this?</p> <pre><code>[[-6.167665, 106.904251], [-6.167665, 106.904251]] </code></pre> <p>Any suggestions how to do it?</p>
<python>
2023-01-17 01:25:49
5
377
Jessen Jie
75,141,188
4,195,053
How to record code execution timings for multiple functions as a pandas dataframe in Python
<p>I have multiple functions, where each function is designed to perform a particular task. For the sake of an example, suppose I want to prepare lunch. Possible functions for this task can be, <code>collect_vege_images()</code> <code>remove_duplicates()</code> and <code>count_veges_in_multiple_plates()</code>.</p> <p>...
<python><python-3.x><pandas><dataframe>
2023-01-17 01:25:14
1
2,022
mnm
75,141,149
558,639
numpy: limiting min value of a scalar, 1D or nD array
<p>Given a scalar, a 1D or an N-D numpy (numeric) array, I'd like to replace all values less than <code>threshold</code> with <code>threshold</code>. So, for example:</p> <pre><code>def fn(a, threshold): return ??? fn(2, 2.5) =&gt; 2.5 # scalar fn([1, 2, 3...
<python><numpy><array-broadcasting>
2023-01-17 01:13:59
1
35,607
fearless_fool
75,141,134
4,420,797
cifar100: spikes in accuracy and loss
<p>I am training a <code>preactresnet18</code> network on the cifar100 dataset. I have adjusted all training settings but still, I can see spikes in my training loss and accuracy. I have no idea why it's happening. I have changed the learning rate batch size but still i cannot solve it.</p> <p><strong>Code</strong></p>...
<python><pytorch><dataset><torch><resnet>
2023-01-17 01:10:38
0
2,984
Khawar Islam
75,141,095
4,755,954
Streamlit + Spacy causing "AttributeError: 'PathDistribution' object has no attribute '_normalized_name'"
<blockquote> <p><strong>Note:</strong> This is not a duplicate question as I have gone through <a href="https://stackoverflow.com/questions/67212594/attributeerror-pathdistribution-object-has-no-attribute-name">this answer</a> and made the necessary package downgrade but it still results in the same error. Details belo...
<python><python-3.x><spacy><apple-m1><streamlit>
2023-01-17 01:00:02
1
19,377
Akshay Sehgal
75,140,968
1,689,987
Python error "Parameters to generic types must be types. Got <module "
<p>When trying to use my own class as a type hint :</p> <pre><code>from mycode.ltm import MyClass def DoSomething(self, values: List[MyClass]) -&gt; None: </code></pre> <p>I get:</p> <blockquote> <p>Parameters to generic types must be types. Got &lt;module '...' from '...'&gt;.</p> </blockquote> <p>How to fix this?</p...
<python><python-typing>
2023-01-17 00:27:34
1
1,666
user1689987
75,140,730
3,666,612
Enable Visual Studio Intellisense for .pyd python modules generated with pybind11
<p><strong>Background</strong>: I've successfully used pybind11 in a Visual Studio 2022 MSBuild project to create a .pyd library of C/C++ functions which can be imported into python code directly using the instructions here: <a href="https://learn.microsoft.com/en-us/visualstudio/python/working-with-c-cpp-python-in-v...
<python><c++><visual-studio><intellisense><pybind11>
2023-01-16 23:39:14
0
519
NKatUT
75,140,727
8,869,570
How to create a dataframe from a single row of another dataframe?
<p>I'd like to create a dataframe from a select row of another dataframe, e.g.,</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;col1&quot;: [1, 2], &quot;col2&quot;: [0, 1]}) # I want to create df1 such that df1 is a dataframe from the first row of df df1 = df.iloc[0] # produces a pandas Series which is no...
<python><pandas><dataframe>
2023-01-16 23:38:52
0
2,328
24n8
75,140,680
6,611,818
Python3 slack_bolt is there easy way to format attachment responses?
<p>Currently my responses to a command given come back to Slack in a very hard format to read. I am hoping there is a way to format the out so it's easier on the eyes.</p> <pre><code>Console APP 11:26 [{'imageCL': '1838900-unix64-clang-debug'}, {'imageCL': '1838872-unix64-clang-debug'}, {'imageCL': '1838851-unix64-cla...
<python><slack><slack-bolt>
2023-01-16 23:32:05
0
425
New2Python
75,140,645
21,115
Python typing for class that having methods from decorator
<p>The <a href="https://lidatong.github.io/dataclasses-json/#usage" rel="nofollow noreferrer"><code>dataclasses-json</code></a> allows code such as:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass from dataclasses_json import dataclass_json @dataclass_json @dataclass class Person:...
<python><python-typing><python-dataclasses>
2023-01-16 23:23:29
1
18,140
davetapley
75,140,592
5,019,169
How to handle a global context object in the following scenario?
<p>I have these two classes:</p> <pre><code>class TestSuite(object): def __init__(self, context): self._tests = [ Test(test_data) for test_data in context[&quot;tests&quot;] ] self.context = context @property def runtime(self): try: return RuntimeFac...
<python><class><oop><design-patterns>
2023-01-16 23:13:54
0
11,224
Ahasanul Haque
75,140,464
14,673,832
Unexpected output for a class methods in Python
<p>Which of the following correctly describe the complete output of executing the Python Polymorphic functions below? I got this question online which I think the output is unexpected. Primary class has object inside it, shouldnt it matter? Also can we write classmethod inside a function as an argument?</p> <pre><code...
<python><polymorphism><class-method>
2023-01-16 22:54:56
0
1,074
Reactoo
75,140,280
7,668,467
Polars Aggregate Multiple Rows into One Row
<p>I have a df created like this:</p> <pre class="lang-py prettyprint-override"><code>df = pl.from_repr(&quot;&quot;&quot; ┌───────────────┬──────────────┬───────────────┐ │ schema_name ┆ table_name ┆ column_name │ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str │ ╞...
<python><python-polars>
2023-01-16 22:27:20
1
2,434
OverflowingTheGlass
75,140,194
683,741
Output linux CLI output to a datatable in python
<p>In Python, what is the best way to take the output from a CLI command and add it into a datatable?</p> <p>I've been using <code>pandas</code> for the datatable, but I can't get the right result. I'd like to take the results of the command and manipulate the data in python in a datatable of some type and then add fu...
<python><pandas><linux>
2023-01-16 22:13:37
0
1,615
e-on
75,140,078
5,924,264
TypeError: cannot subtract DatetimeArray from ndarray when prepending a row to dataframe
<pre><code>import pandas as pd import numpy as np df = pd.DataFrame({&quot;start&quot;: [pd.to_datetime(&quot;2001-01-01 08:00:00+00:00&quot;)]}) df1 = pd.DataFrame([np.nan], columns=df.columns) df1[[&quot;start&quot;]] = [ df[&quot;start&quot;].iloc[0], ] df = df1.append(df, ignore_index=True) df[&quot;start&qu...
<python><pandas><dataframe>
2023-01-16 21:57:44
0
2,502
roulette01
75,140,072
8,277,512
Matplotlib pick_event not working with geopandas dataframe
<p>Here is my <a href="https://github.com/leej11/parkrun_stat_mapper/blob/main/map_of_my_parkruns.ipynb" rel="nofollow noreferrer">Jupyer Notebook source code</a>.</p> <p>But a hard-coded reproducible example is below. (You will need access to the UK.geojson file from my Github or the true source: <a href="http://geopo...
<python><matplotlib><jupyter-notebook><geopandas><matplotlib-widget>
2023-01-16 21:57:06
1
324
Liam Gower
75,140,070
2,441,615
Algorithm for grouping millions of names into groups of similar names
<p>I want to group the names in a list of a few million names into groups of similar names. For example, if the names &quot;John&quot;, &quot;John12&quot; and &quot;azJohn&quot; appear in the list, they should all go into the same grouo. A naive approach could be to use an algorithm like this:</p> <pre class="lang-py p...
<python><algorithm><grouping>
2023-01-16 21:56:50
1
659
K. Claesson
75,139,914
20,895,654
Sort dictionary by multiple values, where amount of values can vary
<p>To come straight to the point:</p> <pre><code>def sortBy(dict, byWhat): # byWhat is a list of 1 - 10 strings, which can include any of allAttributes # allAttributes = ['name', 'kingdom', 'diff', 'tier', 'type', 'founder', 'prover', 'server', 'extra', 'link'] # the lower the index, the higher the sorting prior...
<python><dictionary><sorting><lambda>
2023-01-16 21:34:05
2
346
JoniKauf
75,139,852
558,639
Python file organization for chainable functions
<p>I'm writing a Python3.x framework that has <em>generators</em> and <em>filters</em>. I have a compact syntax for chaining the output of generators and filters into filters, but file organization feels inelegant. Here's what I mean.</p> <p>Assume Renderer is the super class for both generators and filters:</p> <pre...
<python><python-3.x><import><dependencies>
2023-01-16 21:26:48
0
35,607
fearless_fool
75,139,782
5,961,077
How can I sort out an object is datetime or date in python?
<p>I am trying to develop a logic that depends on the type of the input being date or datetime. To achieve this goal, I used <code>isinstance</code> with <code>datetime.date</code> and <code>datetime.datetime</code>. Unfortunately, it seems like that a <code>datetime.datetime</code> object is considered an instance of ...
<python><python-3.x>
2023-01-16 21:17:19
2
1,411
Mehdi Zare
75,139,755
3,875,372
New scrape table data from a hover popup with Selenium and Python
<p>I had this Selenium hover scrape working a few years ago, and I remember it was a challenge to select the correct hover table element, which only shows on hover. The website has undergone a complete style overhaul (seems like Tailwind CSS), and even though I've used the inspector w/a forced hover state, now Selenium...
<python><html><selenium><screen-scraping>
2023-01-16 21:13:05
1
367
DNburtonguster
75,139,369
8,925,864
Plotting probability of a list of floating point values in Python
<p>I am creating a list <code>ans</code> using the following code and have tried to create histogram plots of <code>ans</code> using both matplotlib and seaborn using <code>density=True</code> but I still don't get a probability density of the list of the values in <code>ans</code>. Here is the code.</p> <pre><code>num...
<python><matplotlib>
2023-01-16 20:29:39
0
305
q2w3e4
75,139,276
9,428,990
Reduce size of authorization python AWS Lambda@Edge
<p>I'm trying to implement authorization in my cloudfront distribution. It has worked so far until I ran into size limitation. I'm now running into the cloudfront error message <code>Max allowed: 1048576</code>, which is roughly ~1MB. But after installing the <code>authlib</code> package the total size is around 6MB. M...
<python><python-3.x><aws-lambda><amazon-cloudfront><aws-lambda-edge>
2023-01-16 20:17:28
2
719
Frankster
75,139,201
2,023,745
How to recursively traverse a nested dictionary given a path?
<p>Give an n-level nested dictionary, and a path (e.g. <code>['a', 'b', 'c', 'd']</code>, how can I traverse a nested dictionary to see if the path completely exists in the dictionary or not?</p> <p>If the path doesn't exist, I want to return <code>None</code>, otherwise I want to return the value associated with the f...
<python><recursion>
2023-01-16 20:07:55
1
8,311
TheRealFakeNews
75,139,126
10,299,633
error when using SKforecast: UserWarning: `y` has DatetimeIndex index but no frequency. Index is overwritten with a RangeIndex of step 1
<p>I am trying to use <code>skforecast</code> for time series analysis however I am getting warning telling me that the df has no frequency because the index is not <code>DateTimeIndex</code> but in fact it is.</p> <p>Here is the code:</p> <pre><code>import yfinance as yf import datetime as dt spxl = yf.Ticker(&quot;S...
<python><pandas><datetime><time-series><yfinance>
2023-01-16 19:57:56
1
327
Sam.H
75,139,027
7,318,120
how to resolve google sheets API error with python
<p>I am trying to read / write to google sheets using python.</p> <p>I run this boilerplate code, but get the following error:</p> <pre><code>APIError: {'code': 403, 'message': 'Request had insufficient authentication scopes.', 'errors': [{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficien...
<python><google-sheets><google-sheets-api>
2023-01-16 19:45:21
1
6,075
darren
75,138,791
17,487,457
find the median frequency of the resultant fft magnitude
<p>I am having my head confused around computing the median frequency from the fft I computed over my data, using the following function:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from scipy.fft import fft, fftfreq def fft_transfrom(data): # data has a 4D shape fourier = fft(data, axi...
<python><arrays><numpy><fft>
2023-01-16 19:20:27
0
305
Amina Umar
75,138,769
11,462,274
Using sklearn and keras to check how reliable a cumulative sum is for the long term
<p>Part of my CSV file:</p> <pre class="lang-none prettyprint-override"><code>cumulative_sum 0.2244 0.75735 1.74845 1.93545 2.15985 2.8611 1.8611 2.2538 2.88025 3.83395 2.83395 5.0312 5.4426000000000005 5.5735 4.5735 3.5735 2.5735 3.38695 2.38695 1.3869500000000001 1.7048500000000002 2.47155 3.6309500000000003 4.1078 4...
<python><tensorflow><keras><sklearn-pandas>
2023-01-16 19:18:30
0
2,222
Digital Farmer
75,138,558
11,780,316
How can I SHA1-HMAC a string in Python
<p>I've been trying to figure out how to use HMAC to hash a string in Python for a TOTP generator I've already made in PHP. In PHP, I use the command <code>echo -n &quot;0x00000000035362f9&quot; | xxd -r -p | openssl dgst -sha1 -mac HMAC -macopt hexkey:0080700040024c8581c2</code> which returns the desired value <code>7...
<python><hash><sha1><hmac>
2023-01-16 18:56:04
1
367
lwashington27
75,138,435
15,724,084
yield scrapy.Request does not invoke parse function on each iteration
<p>in my code i have to functions inside scrapy class. start_request takes data from excel workbook and assigns value to <code>plate_num_xlsx</code> variable.</p> <pre><code>def start_requests(self): df=pd.read_excel('data.xlsx') columnA_values=df['PLATE'] for row in columnA_values: global plate_nu...
<python><scrapy>
2023-01-16 18:43:25
1
741
xlmaster
75,138,423
2,529,619
Fast vector addition of multiple columns in pandas
<p>I need to add up multiple columns of large DataFrames in a loop. It's taking very long. The bottleneck is in creating copies of the DataFrame.</p> <p>Here is a simplified code sample of what I am trying to do:</p> <pre><code>import itertools as it import numpy as np import pandas as pd def sum_combo_ranks(df, com...
<python><pandas><python-itertools>
2023-01-16 18:42:32
2
7,582
ChaimG
75,138,404
14,742,509
replace values in a category column based on the order they appear
<p>I have a DataFrame with 1k records similar to the below one. Column B is a group column in sorted order.</p> <pre><code>import pandas as pd df = pd.DataFrame([['red', 0], ['green', 0], ['blue', 16],['white', 58],['yellow', 59], ['purple', 71], ['violet', 82],['grey', 82]], columns=['A','B']) df A B 0 red...
<python><pandas><dataframe>
2023-01-16 18:40:20
1
329
DOT
75,138,362
7,190,950
Python Django nginx uWsgi getting failed on specific callback endpoints
<p>I'm running Django web app on a docker container where I use Nginx with uwsgi. Overall the web works just fine it fails only on specific callback endpoints during the social app (Google, Facebook) registration.</p> <p>Below is the command I use to run the uswgi</p> <pre><code>uwsgi --socket :8080 --master --strict -...
<python><django><docker><uwsgi><django-allauth>
2023-01-16 18:35:39
0
421
Arman Avetisyan
75,138,334
4,418,481
Dash Leaflet popup to show multiline with links
<p>I have make a simple map using dash-leaflet and I wanted to add a popup based on some data that I have.</p> <p>This data contains names, prices and links which I would like to show in the popup.</p> <p>I tried to do the following but it gave this result:</p> <pre><code> for index, row in data.iterrows(): ...
<python><plotly-dash><dash-leaflet>
2023-01-16 18:33:31
1
1,859
Ben
75,138,131
443,908
pythonic way of expressing set with infinite number
<p>I'm leading a python study group in a couple of weekends and thought I would go over some simple discrete math ideas, starting with sets. Is there pythonic way of expressing a set like</p> <p>A = {x| -inf &lt; x &lt; 6}</p> <p>a simple boolean val of <code>n &lt; 6</code> will obviously work, but wondering if there ...
<python><set>
2023-01-16 18:14:18
0
1,654
badperson
75,138,086
3,312,636
Unable to read file from DBFS mount
<p>I am using Python code in Databricks to read a JSON using the below code.</p> <pre><code>my_json = '' with open('/dbfs/mnt/my_mount/my_json.json', 'r') as fp: my_json = json.load(fp) </code></pre> <p>But I am getting the below error</p> <pre><code>FileNotFoundError: [Errno 2] No such file or directory: '/dbfs/mn...
<python><json><pyspark><databricks>
2023-01-16 18:08:22
0
21,579
Sarath Subramanian
75,137,717
7,427,859
Eventlet + DNS Python Attribute Error: module "dns.rdtypes" has no attribute ANY
<p>I know that someone will face this problem. I had this problem today, but I could fix it promptly, and I want to share my solution:</p> <p>Problem:</p> <pre><code>from flask_socketio import SocketIO </code></pre> <p>You will receive an output error with something like:</p> <blockquote> <p>Attribute Error: module &qu...
<python><flask-socketio><eventlet><dnspython>
2023-01-16 17:32:09
2
496
Indesejavel Coisa
75,137,677
2,912,349
How to compute the Jacobian of a pairwise distance function (`scipy.spatial.pdist`)
<h2>Context</h2> <p>I am the author and maintainer of <a href="https://github.com/paulbrodersen/netgraph" rel="nofollow noreferrer">netgraph</a>, a python library for creating network visualisations. I am currently trying to optimise a routine that computes a set of <code>N</code> node positions for networks in which e...
<python><optimization><scipy><scipy-optimize>
2023-01-16 17:27:22
2
12,703
Paul Brodersen
75,137,576
1,444,043
Problems with logging handler propagation - messages repeated
<p>I'm trying to setup logging for a modules and have the following minimal reproducible example...</p> <pre class="lang-py prettyprint-override"><code>import sys from pathlib import Path from datetime import datetime import logging start = datetime.now() LOG_CONFIG = logging.basicConfig( filename=Path().cwd().stem...
<python><logging>
2023-01-16 17:19:02
1
2,447
slackline
75,137,538
8,967,422
Python How to run scripts from a subdirectory?
<p>I have such structure of project:</p> <pre><code>lib/ ... scripts/ ... </code></pre> <p>I have many Python scripts in the <code>scripts/</code> directory. All of them contains relative imports: <code>from lib import ...</code></p> <p>So, how can I easy run scripts from the root of project <code>/</code>, wit...
<python><directory><python-import><relative-import>
2023-01-16 17:15:09
3
486
Alex Poloz
75,137,516
12,621,824
Python: Call function that returns two strings inside map function
<p>Hello I am trying to create a function that is called inside a map function, splits the string that have been passed as input and returns two processed strings. To be more understood here is my code (it doesn't seem to return anything).</p> <pre><code>def prepare_data(data): x1, x2 = data.split(&quot; &quot;, 1)...
<python><map-function>
2023-01-16 17:13:05
2
529
C96
75,137,492
14,091,382
AttributeError: 'Kernel' object has no attribute 'masker' during training of SVC with rbf kernel
<p>I am training my SVC model and I am getting this error with the Shap Library. Have tried some methods including shap.maskers.Independent but the same error keeps appearing. Am I missing out something?</p> <p>Codes</p> <pre><code>model = SVC (C = 10.0, gamma = 0.01, kernel = 'rbf', probability=True) model.fit(X_resa...
<python><machine-learning><scikit-learn><shap><svc>
2023-01-16 17:10:23
1
333
DDM
75,137,474
11,261,546
eigenvalues of a simple RGB image
<p>I'm trying to replicate the results of an image treatment algorithm I saw in a paper.</p> <p>An important step is to calculate the eigenvalues of an squared <strong>image</strong></p> <p>When reading this I thought they may mean the eigenvalues of each channel (i.e R G and B) as they are using colored images.</p> <p...
<python><numpy><opencv><image-processing>
2023-01-16 17:08:50
0
1,551
Ivan
75,137,470
6,156,353
Can I attach migrations to a corresponding data warehouse model using SQLAlchemy and Alembic?
<p>Let's say I want to build a data warehouse using these two tools. I was thinking of something like</p> <pre><code>root - database_schema -- table1.py (SQLAlchemy model) -- table2.py ... - database_schema2 -- table1.py ... - alembic </code></pre> <p>However, alembic is creating all migrations in one folder (versions)...
<python><sqlalchemy><data-warehouse><alembic>
2023-01-16 17:08:32
1
1,371
romanzdk
75,137,319
3,507,584
Plotly Scatterpolar change fill, line and hover color
<p>I have the following example. I can change the fill color to 'green' following the <a href="https://plotly.github.io/plotly.py-docs/generated/plotly.graph_objects.Scatterpolar.html?highlight=scatterpolar#plotly.graph_objects.Scatterpolar" rel="nofollow noreferrer">documentation</a> but I cannot find how to change th...
<python><charts><scatter-plot><plotly>
2023-01-16 16:54:18
1
3,689
User981636
75,137,238
4,397,312
Can I pass 'wandb' object to another class in python?
<p>I have written a modular code and I wanted to pass a wandb object to a class which has been written in another .py file. I instantiated a wandb object using:</p> <pre><code>import wandb exp_name = &quot;expriment name&quot; run = wandb.init(config = wandb.config, project= exp_name, entity=&quot;username&quot;) </co...
<python><logging><wandb>
2023-01-16 16:46:14
1
717
Milad Sikaroudi
75,137,217
10,658,339
How to get values outside an interval pandas DataFrame
<p>I'm trying to get the values outside an interval in pandas dataframe, and I was trying to avoid iterating over the rows. is there any way to do that?</p> <p>This is what I was trying, but it gives the error</p> <blockquote> <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.a...
<python><pandas><dataframe><filtering><apply>
2023-01-16 16:44:17
3
527
JCV
75,137,163
17,103,465
How to reset index for pandas.core.series
<p>My dataframe contains a string column 'code_desc' which contains with codes in it.</p> <p>I have a pandas.core.series generated by the code below:</p> <pre><code>d = {'R438': 'The person is a Ninja', 'R727': 'The person is a Pirate', .....} pat = r'\b(%s)\b' % '|'.join(d) codes = df['codes_desc'].str.extract...
<python><pandas>
2023-01-16 16:38:22
0
349
Ash
75,137,090
6,464,525
pyflink AttributeError: type object 'EnvironmentSettings' has no attribute 'in_streaming_mode'
<pre class="lang-py prettyprint-override"><code>%pyflink from pyflink.table import EnvironmentSettings, StreamTableEnvironment env_settings = EnvironmentSettings.in_streaming_mode() table_env = StreamTableEnvironment.create(environment_settings=env_settings) </code></pre> <p>Will fail with the following context:</p> <...
<python><apache-flink><amazon-kinesis><pyflink>
2023-01-16 16:31:48
1
344
hi im Bacon
75,136,991
3,004,472
Reading multiple files from different aws S3 in Spark parallelly
<p>I have a scenario where I would need to read many files (in csv or parquet) from s3 bucket located different locations and with different schema.</p> <p>My purpose of this is to extract all metadata information from different s3 locations and keep it as a Dataframe and save it as csv file in s3 itself. The problem h...
<python><apache-spark><pyspark><apache-spark-sql><boto3>
2023-01-16 16:23:22
1
880
BigD
75,136,853
2,423,198
Use shift in pd.NamedAgg groupby in pandas
<p>I find it very convenient to use <code>pd.NamedAgg</code> in order to give names to columns after aggregation, but I don't know how to do other aggregate functions like <code>shift</code>. The code bellow doesn't work because of the 3rd aggregation.</p> <pre><code>df.groupby([&quot;ID&quot;, &quot;Day&quot;, &quot;h...
<python><pandas><group-by>
2023-01-16 16:11:39
0
3,400
deltascience
75,136,745
16,521,194
subprocess.Popen raises error while command works in shell
<h2>Issue</h2> <p>I have this command, which works in the shell:</p> <pre class="lang-bash prettyprint-override"><code>&lt;ABS_PATH&gt;/odbc2parquet query --connection-string &quot;Driver={&lt;DRIVER_NAME&gt;};SERVER=&lt;SERVER_IP&gt;,&lt;SERVER_PORT&gt;;DATABASE=&lt;DB_NAME&gt;;UID=&lt;UID&gt;;PWD=&lt;PWD&gt;&quot; &l...
<python><subprocess>
2023-01-16 16:01:52
0
1,183
GregoirePelegrin
75,136,588
12,957,790
Storing and displaying emojis with mysqldb and Python Flask
<p>I have a database with a table called <code>posts</code> and I have two fields called <code>title</code> and <code>description</code>. Both <code>title</code> and <code>description</code> can contain emoji characters.</p> <p>The solutions to similar problems told me to <code>convert the character set to utf8mb4</cod...
<python><mysql><flask><encoding><emoji>
2023-01-16 15:47:50
1
575
Bob
75,136,584
10,967,961
Creating a dummy out of a list variable python
<p>I have a pandas dataframe looking like this:</p> <pre><code>docdb tech_classes 1187498 ['Y02P 20/10'] 1236571 ['Y02B 30/13' 'Y02B 30/12' 'Y02P 20/10'] 1239098 ['Y10S 426/805' 'Y02A 40/81'] ... </code></pre> <p>What I would like to do is to create N dummy variables where N is the total number of names ...
<python><pandas><dummy-variable>
2023-01-16 15:47:35
2
653
Lusian
75,136,484
15,724,084
pandas getting lastrow index of excel file and appending data to it, needs some fix
<p>i am trying to get last row of column <code>plate</code> and append data to it. But it gives corrupt file error even though scrapy is working properly.</p> <p>I guess error is due to lines below. Where I firstly, use pandas <code>ExcelWriter</code> object, then for getting last row I use dataframe.</p> <pre><code> ...
<python><pandas><scrapy>
2023-01-16 15:38:58
1
741
xlmaster
75,136,404
17,561,414
explode function spark python
<p>I have the following data structure in JSON file and would like to flatten the data.</p> <pre><code> root |-- _embedded: struct (nullable = true) | |-- items: array (nullable = true) | | |-- element: struct (containsNull = true) | | | |-- _links: struct (nullable = true) | | | | ...
<python><apache-spark><apache-spark-sql><azure-databricks><flatten>
2023-01-16 15:32:24
1
735
Greencolor
75,136,383
5,224,236
pip install fails when Installing build dependencies
<p>Installing packages in my lovely locked-down IT environment</p> <pre><code>python -m pip --default-timeout=1000 install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org pyautogui </code></pre> <p>Using this I am able to install packages such as <code>matplotlib</code> with...
<python><pip><pyautogui>
2023-01-16 15:30:28
1
6,028
gaut
75,136,353
5,448,626
Problem uploading excel file to SharePoint with LDAP
<p>I am trying to upload an Excel file to SharePoint, using the code I found <a href="https://learn.microsoft.com/en-us/answers/questions/142065/ways-to-access-upload-documents-to-sharepoint-site" rel="nofollow noreferrer">here</a>, but so far, I cannot manage to make it work with my LDAP account. Getting this error:</...
<python><authentication><sharepoint><upload><ldap>
2023-01-16 15:27:35
0
43,725
Vityata
75,136,212
5,522,036
Why pandas prefers float64 over Int64?
<p>I have a pandas dataframe with a column, with 3 unique values: <code>[0, None, 1]</code> When I run this line:</p> <pre><code>test_data = test_data.apply(pd.to_numeric, errors='ignore') </code></pre> <p>the above mentioned column data type is converted to <code>float64</code></p> <p>Why not <code>int64</code>? Techn...
<python><pandas><dataframe>
2023-01-16 15:14:27
1
2,470
Ish Thomas
75,136,052
14,578,331
Reducing file size of animated Plotly Express Choropleth plot
<p>I am plotting numerical data using <code>plotly</code> Express <code>Choropleth</code> and that data has changing values over time, which makes an animation sensible to use. The resulting file size is, however, quite large and I would like to reduce it for web applications.</p> <p>The problem seems to be that Plotly...
<python><plotly><choropleth>
2023-01-16 15:01:11
0
1,016
C Hecht
75,135,947
6,803,924
How to implement an n-gram inverted index from a paper (Python)?
<p>I am trying to implement an <strong>n-Gram/2L-approximation index</strong> from a paper by Min-Soo Kim, Kyu-Young Whang and Jae-Gil Lee, found here: <a href="http://infolab.dgist.ac.kr/%7Emskim/papers/CSSE07.pdf" rel="nofollow noreferrer">http://infolab.dgist.ac.kr/~mskim/papers/CSSE07.pdf</a></p> <p>Building the In...
<python><indexing><string-matching><n-gram><inverted-index>
2023-01-16 14:52:41
0
329
Lukáš Moravec
75,135,847
4,700,367
mypy: error: Module "multiprocessing.managers" has no attribute "EventProxy" [attr-defined]
<p>I have a method which takes a <code>multiprocessing.Manager().Event()</code>, for the purposes of gracefully stopping my app.</p> <p>When I run mypy against it, it complains that it's not a valid type:</p> <pre class="lang-none prettyprint-override"><code>error: Module &quot;multiprocessing.managers&quot; has no att...
<python><python-3.x><mypy><python-typing>
2023-01-16 14:43:46
1
438
Sam Wood
75,135,830
4,152,567
Tensorboard error: An op outside of the function building code is being passed a "Graph" tensor
<p>The following code replicates a Tensorboard error I keep getting. <strong>Complete error:</strong></p> <pre><code> TypeError: An op outside of the function building code is being passed a &quot;Graph&quot; tensor. </code></pre> <p>It is possible to have Graph tensors leak out of the function building context by i...
<python><tensorflow><keras><tensorboard>
2023-01-16 14:42:14
1
512
Mihai.Mehe
75,135,759
1,574,551
Detect language in pandas column in python
<p>I would like to detect language in pandas column in python. After detecting it I want to write the language code as a column in pandas dataframe. Below is my code and what I tried. But I got an error please help.</p> <p>Thank you.</p> <pre><code> data = {'text': [&quot;It is a good option&quot;,&quot;Better to ha...
<python><pandas><textblob>
2023-01-16 14:37:26
2
1,332
melik
75,135,721
9,625,038
Standard application for a filetype not available inside service
<p>I've created a service which accepts PDF files from other computers using a socket, and then prints it to a connected printer. The code for this is written in Python.</p> <p>I've tested this application by running the Python script manually, and everything works as expected. The script creates a socket, accepts a PD...
<python><powershell><windows-services>
2023-01-16 14:33:46
1
591
Alexander Schillemans
75,135,634
943,524
Is that a valid BFS?
<p>I recently wrote a function to traverse a graph, along those lines:</p> <pre><code>def traverse(batch: list[str], seen: set[str]): if not batch: return new_batch = [] for node in batch: print(node) new_batch.extend(n for n in neighbours(node) if n not in seen) traverse(new_bat...
<python><graph-theory><breadth-first-search><graph-traversal>
2023-01-16 14:26:23
1
1,439
Weier
75,135,628
14,667,788
how to insert string into query in python pymysql
<p>I have a following query:</p> <pre class="lang-py prettyprint-override"><code>cursor = connection.cursor() query = &quot;&quot;&quot; SELECT * FROM `my_database`.table_a &quot;&quot;&quot; result = cursor.execute(query) </code></pre> <p>which works as expected. But I need to change <code>my...
<python><mysql><pymysql>
2023-01-16 14:25:55
1
1,265
vojtam
75,135,608
15,376,262
How to select multiple children from HTML tag with Python/BeautifulSoup if exists?
<p>I'm currently scraping elements from a webpage. Let's say i'm iterating over a HTML reponse and a part of that response looks like this:</p> <pre><code>&lt;div class=&quot;col-sm-12 col-md-5&quot;&gt; &lt;div class=&quot;material&quot;&gt; &lt;div class=&quot;material-parts&quot;&gt; &lt;span class=&quot;material-pa...
<python><html><css><web-scraping><beautifulsoup>
2023-01-16 14:24:48
2
479
sampeterson
75,135,540
10,197,418
Python polars: modify every nth row
<p>Given a polars DataFrame in Python, how can I modify every nth element in a series?</p> <pre class="lang-py prettyprint-override"><code># have df = pl.DataFrame(pl.Series(&quot;a&quot;, [1, -1, 1, -1, 1])) # want # [1, 1, 1, 1, 1] # selecting works fine: df[&quot;a&quot;, 1::2] shape: (2,) Series: 'a' [i64] [ -...
<python><indexing><slice><python-polars>
2023-01-16 14:20:03
1
26,076
FObersteiner
75,135,532
11,945,144
Best parameters for UMAP + HistGradientBoostingClassifier
<p>I'm trying to find the best parameters for the UMAP (dimensionality reduction) model together with HistGradientBoostingClassifier.</p> <p>The loop I have created is:</p> <pre><code>vectorizer = TfidfVectorizer(use_idf=True, max_features = 6000) corpus = list(df['comment']) x = vectorizer.fit_transform(corpus) y = df...
<python><for-loop><hyperparameters><boosting><runumap>
2023-01-16 14:19:19
1
343
Maite89
75,135,519
9,794,068
Iteration count in recursive function
<p>I am writing a recursive function to make permutations of digits from <code>0</code> to <code>n</code>. The program will return the <code>th</code> permutation that is obtained. It all works well but I had to use the cheap trick of defining <code>count</code> as a list, that is <code>count=[0]</code>. In this way I ...
<python><recursion><global-variables>
2023-01-16 14:18:35
2
530
3sm1r
75,135,495
6,290,062
pythonic equivalent of R double pivot and filter
<p>A task I come up against reasonable often is something like the following transformation:</p> <p>from:</p> <pre><code> home_team_id away_team_id home_team away_team 1 1 2 Arsenal Tottenham 2 2 3 Tottenham Chelsea </code></pre> <p>to</p> <pre><code> team value 1...
<python><r><filter><pivot>
2023-01-16 14:16:41
1
917
Robert Hickman
75,135,415
1,711,088
Selenium. Python. Interact with extensions
<p>I'm using Selenium, Chrome and Python 3.10. I'm trying to automate login to &quot;opensea.io&quot; site. Site doesn't have a classic login page. It's login only through installed MetaMask wallet extension. When i click &quot;Login&quot; extension is open a popup and wait my actions (click to buttons and enter a pass...
<python><selenium><google-chrome-extension><automation><findelement>
2023-01-16 14:10:44
1
976
Massimo
75,135,100
10,437,727
What Python unittest command to run here?
<p>Here's my project structure:</p> <pre><code>├── compute_completeness_service │ ├── __init__.py │ ├── app.py │ ├── tests │ │ ├── integration │ │ │ ├── __init__.py │ │ │ └── test__init__.py │ │ └── unit │ │ ├── __init__.py │ │ ├── __pycache__ │ │ └── test_utils.py │ ...
<python><python-3.x><python-unittest>
2023-01-16 13:45:39
1
1,760
Fares
75,134,954
15,229,310
Decorate all functions of a class in Python 3
<p>This has been asked, but all solutions seems to be from around 2011 for early python 2.x, unusable for recent (3.6+) versions.</p> <p>Having</p> <pre class="lang-py prettyprint-override"><code>def function_decorator(fn): def wrapper(*args, **kwargs): print('decorated') return fn(*args, **kwargs) ...
<python><python-3.x><python-decorators>
2023-01-16 13:33:59
1
349
stam
75,134,930
15,724,084
pandas appending data works online for few rows
<p>my script writes on each iteration to excel file from row 2. But I need it to append data each time under the last row.</p> <p>code need to write new data in a bulk from the last row</p> <p>code is below</p> <pre><code>import scrapy from scrapy.crawler import CrawlerProcess import pandas as pd class plateScraper(sc...
<python><pandas><scrapy>
2023-01-16 13:31:21
1
741
xlmaster
75,134,922
859,227
Removing extra spaces in print()
<p>I want to show a progress like</p> <pre><code>[500/5000] [1000/5000] [1500/5000] ... </code></pre> <p>With the following print line</p> <pre><code>print(&quot;[&quot;,str(c),&quot;/&quot;,str(len(my_list)),&quot;] &quot;, end='') </code></pre> <p>I see extra spaces like <code>[ 1000 / 55707 ] [ 2000 / 55707 ]</code>...
<python><python-3.x>
2023-01-16 13:30:28
1
25,175
mahmood
75,134,906
2,710,058
Python async, future behaviour
<pre><code>from asyncio import Future import asyncio async def plan_fut(future_obj): print('future started') await asyncio.sleep(1) future_obj.set_result('Future completes') def create() -&gt; Future: future_obj = Future() asyncio.create_task(plan_fut(future_obj)) return future_obj async def ...
<python><python-asyncio>
2023-01-16 13:29:14
0
391
Pramod
75,134,878
710,955
Python: NLTK and Spacy, don't get same result when tokenize sentence in French
<p>I want to split french text into sentences.</p> <p>With <a href="https://www.nltk.org/_modules/nltk/tokenize.html#sent_tokenize" rel="nofollow noreferrer">NLTK</a>, I use the sentence tokenizer directly as follows:</p> <pre><code>import nltk.data tokenizer = nltk.data.load('tokenizers/punkt/french.pickle') tokens = ...
<python><nlp><nltk><spacy>
2023-01-16 13:26:39
1
5,809
LeMoussel
75,134,626
991,710
Propertly form JSON with df.to_json with dataframe containing nested json
<p>I have the following situation:</p> <pre><code>id items 3b68b7b2-f42c-418b-aa88-02450d66b616 [{quantity=3.0, item_id=210defdb-de69-4d03-bddd-7db626cd501b, description=Abc}, {quantity=1.0, item_id=ff457660-5f30-4432-a5af-564a9dee0029, description=xyz . 23}, {quantity=10.0, item_id=8d...
<python><json><pandas>
2023-01-16 13:04:35
1
3,744
filpa
75,134,616
15,368,670
Simple check for projected crs
<p>How can I easily check if a crs is a projected one for geopandas ?</p> <p>Basically a function:</p> <pre><code>is_projected_crs(crs) </code></pre> <p>returning True or False.</p> <p>I need that because I am writing some code to avoid the warning from geopandas :</p> <pre><code>Geometry is in a geographic CRS. Result...
<python><geopandas><coordinate-systems>
2023-01-16 13:03:47
1
719
Oily
75,134,553
13,058,538
Installation of Couchbase Python SDK 3.0.10 failing on python 3.8.5
<p>I am unable to install Couchbase Python SDK of version 3.0.10 (I specifically need this version). I am using Ubuntu 22.04 and with pyenv set global python to 3.8.5. I am also using poetry with venv. (Installation fails both in venv and globally). It seems that I tried out everything - using different python versions...
<python><couchbase>
2023-01-16 12:56:54
0
523
Dave
75,134,485
6,209,004
Quarto batch processing in python
<p>Doing batch rendering with quarto using the following script From vscode</p> <pre class="lang-py prettyprint-override"><code>import os import glob from pathlib import Path PHASE = [0, 0.1, 0.2] for f in PHASE: os.system( f&quot;quarto render individual_reference_template_copy.qmd --output phase_{f}.html...
<python><quarto>
2023-01-16 12:51:06
1
1,908
Kresten
75,134,424
12,877,988
How to encrypt decrypted text by django-fernet-fields?
<p>I am using django-fernet-fields, and documentation says By default, django-fernet-fields uses your SECRET_KEY setting as the encryption key. my SECRET_KEY in django is the one created by django let say it is &quot;XXXX&quot;.</p> <p>my dectypted text is &quot;gAAAAABfIrFwizr11ppteAXE3MOMItPDNfNkr5a4HcS3oiT7ih4Ln7y6...
<python><django><fernet>
2023-01-16 12:45:33
0
1,497
Elvin Jafarov
75,134,415
11,662,972
How to set the format of the marginal graph in dash plotly?
<p>I have a scatterplot with a <code>marginal_y</code> subgraph made with:</p> <pre class="lang-py prettyprint-override"><code>fig = px.scatter(df_filtrada, x=df_filtrada.index, y=pto, marginal_y = &quot;violin&quot;) </code></pre> <p>When I update some properties o...
<python><plotly-dash><plotly>
2023-01-16 12:44:54
1
385
Adrian Fischer
75,134,342
9,884,812
Django CaptureQueriesContext can't see my objects filter query in captures_queries
<p>I want to log the raw SQL statements in my Django testcases.<br /> I can see the INSERT sql statements, but I can't see the SELECT sql statements in the log.</p> <p>I want to see every SQL statement in the log, whether it is CREATE, SELECT, UPDATE or something else.</p> <p><strong>Output</strong></p> <pre><code>$ py...
<python><django>
2023-01-16 12:38:17
1
539
Ewro
75,134,246
19,580,067
No module named 'mmcv._ext'
<p>Tried to train the model but got the mmcv error</p> <pre><code>No module named 'mmcv._ext' </code></pre> <p>mmcv library is already installed and imported</p> <pre><code>mmcv version = 1.4.0 Cuda version = 10.0 </code></pre> <p>Any suggestions to fix the issue??</p>
<python><pytorch><openmmlab>
2023-01-16 12:28:54
6
359
Pravin
75,134,135
5,392,813
Python not respecting __init__ on windows, ModuleNotFoundError
<p>The following code works on macOS, but not on Windows:</p> <pre><code>src ┣ __init__.py ┣ greeter.py ┗ helper.py </code></pre> <p>greeter.py</p> <pre class="lang-py prettyprint-override"><code>from src.helper import world def hello(): print(&quot;Hello {}&quot;.format(world())) if __name__ == &quot;__main...
<python><import><modulenotfounderror>
2023-01-16 12:20:05
0
665
flymg
75,134,118
245,362
Get Python ID as a number for Py03 PyAny object in Rust
<p>I'm using Py03 to build a python module in Rust. I have a class in Rust which accepts a <code>PyAny</code> to refer to an object in Python. As part of the hash function for the rust class, I want to use the Python ID for this object in the hash function in Rust so I can deduplicate the rust class if the same Python ...
<python><rust><pyo3>
2023-01-16 12:18:39
1
563
David Chanin
75,134,088
9,749,124
How to select number of topics for Latent Dirichlet Allocation Topic-Model
<p>I am new to topic modeling and I came across LDA model, but I am not sure if I am using it good. As far as I read the documentation, parameter called <code>n_components</code> is parameter that represent number of topics, am I right? This is my code:</p> <pre><code>import pandas as pd import numpy as np from sklearn...
<python><scikit-learn><topic-modeling>
2023-01-16 12:16:33
0
3,923
taga
75,133,876
17,696,880
Concatenate each element of a list with all the elements of its list and put these strings inside a new list
<pre class="lang-py prettyprint-override"><code>#Load the input lists load_names_list = ['Katherine', 'María Jose', 'Steve'] load_surnames_list = ['Taylor', 'Johnson', 'White', 'Clark'] #Shuffle the data lists: ['element_AA element_AA' , 'element_AA element_AB' , ... ] names_with_names_list = [] surnames_with_surna...
<python><arrays><python-3.x><string><list>
2023-01-16 11:57:19
1
875
Matt095
75,133,842
15,724,084
scrapy python project does not export data to excel with pandas
<p>my script is below, first it reads <code>plate_num_xlsx</code> value from excel file <code>data.xlsx</code> successfully then requests scrapy to scrape data from url. At each parse() invocation, I am taking values parsed to <code>item</code> then trying to export them to excel with pandas.</p> <pre><code> if ...
<python><excel><pandas><scrapy>
2023-01-16 11:52:30
2
741
xlmaster
75,133,682
5,810,060
'float' object is not iterable", 'occurred at index 1'
<p>i have for the following dataset</p> <pre><code>company_name_Ignite Mate Bence Raul Marina 01 TELECOM LTD NaN 01 Telecom, Ltd. 01 Telecom, Ltd. NaN 0404 Investments Ltd NaN 0404 INVESTMENTS LIMITED 0404 INVESTMENTS LIMITED...
<python><python-3.x><pandas><similarity>
2023-01-16 11:37:45
1
906
Raul Gonzales
75,133,613
5,758,423
Making decorators produce pickle-serializable functions
<p>Why is it that this works:</p> <pre><code>import pickle from functools import wraps def wrapper(func): @wraps(func) def _func(*args, **kwargs): print(args, kwargs) return func(*args, **kwargs) return _func def foo(a: int): return a + 1 foo = wrapper(foo) pickle.dumps(foo) # okay...
<python><pickle>
2023-01-16 11:30:57
0
2,432
thorwhalen
75,133,570
4,041,387
redis-py compiatable with redis-server using docker image redis:5.0.9-alpine
<p>we have a Redis-Server running as a stateful set on a K8s server with 3 replicas which is using the docker image <code>redis:5.0.9-alpine</code>. This server is running in cluster mode <code>yes</code>.</p> <p>Now we are trying to connect this cluster from the python code using the official Redis python package i.e....
<python><kubernetes><redis><redis-py>
2023-01-16 11:27:04
0
425
Imran