question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
59,617,184 | 2020-1-6 | https://stackoverflow.com/questions/59617184/why-are-some-python-exceptions-lower-case | In Python, exceptions are classes and cased as such. For example: OSError. However, there are some exceptions, such as those in the socket module, that are named in lower-case. For example: socket.timeout, socket.error. Why is this? | According to the docs, exception socket.error A deprecated alias of OSError. Changed in version 3.3: Following PEP 3151, this class was made an alias of OSError. PEP 3151 says while standard exception types live in the root namespace, they are visually distinguished by the fact that they use the CamelCase convention... | 9 | 7 |
59,572,706 | 2020-1-3 | https://stackoverflow.com/questions/59572706/django-collectstatic-not-working-on-production-with-s3-but-same-settings-work-l | I've been moving around some settings to make more defined local and production environments, and I must have messed something up. Below are the majority of relevant settings. If I move the production.py settings (which just contains AWS-related settings at the moment) to base.py, I can update S3 from my local machine ... | Ok, let me try, as discovered in comments from the question, you do S3 update using collectstatic, but this is a management command which is called using manage.py file where you set cobev.settings.local as settings which are not equal to cobev.settings.production which is used for wsgi.py file. I think you should man... | 7 | 2 |
59,596,261 | 2020-1-5 | https://stackoverflow.com/questions/59596261/return-or-yield-from-a-function-that-calls-a-generator | I have a generator generator and also a convenience method to it - generate_all. def generator(some_list): for i in some_list: yield do_something(i) def generate_all(): some_list = get_the_list() return generator(some_list) # <-- Is this supposed to be return or yield? Should generate_all return or yield? I want the u... | Generators are lazy-evaluating so return or yield will behave differently when you're debugging your code or if an exception is thrown. With return any exception that happens in your generator won't know anything about generate_all, that's because when generator is really executed you have already left the generate_all... | 33 | 15 |
59,600,000 | 2020-1-5 | https://stackoverflow.com/questions/59600000/none-propagation-in-python-chained-attribute-access | Is there a null propagation operator ("null-aware member access" operator) in Python so I could write something like var = object?.children?.grandchildren?.property as in C#, VB.NET and TypeScript, instead of var = None if not myobject\ or not myobject.children\ or not myobject.children.grandchildren\ else myobject.ch... | No. There is a PEP proposing the addition of such operators but it has not (yet) been accepted. In particular, one of the operators proposed in PEP 505 is The "None-aware attribute access" operator ?. ("maybe dot") evaluates the complete expression if the left hand side evaluates to a value that is not None | 14 | 31 |
59,587,183 | 2020-1-4 | https://stackoverflow.com/questions/59587183/python-dynamodb-expressionattributevalues-contains-invalid-key-syntax-error-ke | Trying to do an update_item which is supposed to create new attributes if it doesn't find existing ones (according to documentation) but I am getting a Sytax error. I have been wracking my brain all day trying to figure out why I am getting this and I can't seem to get past this. Thank you for any help Error I am getti... | just change the section like the following - ExpressionAttributeValues={ ':var0': 'Metzger', ':var1': 'CA', ':var2': 'none', ':var3': '949 302-9072', ':var4': '818-222-2311' } Hope the code will work then :) | 8 | 28 |
59,587,631 | 2020-1-4 | https://stackoverflow.com/questions/59587631/use-center-diverging-colormap-in-a-pandas-dataframe-heatmap-display | I would like to use a diverging colormap to color the background of a pandas dataframe. The aspect that makes this trickier than one would think is the centering. In the example below, a red to blue colormap is used, but the middle of the colormap isn't used for values around zero. How to create a centered background c... | import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from matplotlib import colors np.random.seed(24) df = pd.DataFrame() df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4)*10, columns=list('ABCD'))], axis=1) df.iloc[0, 2] = 0.0 cm = sns.diverging_palette(5, 250, as_cmap=Tru... | 7 | 5 |
59,594,516 | 2020-1-4 | https://stackoverflow.com/questions/59594516/how-to-sample-from-pandas-dataframe-while-keeping-row-order | Given any DataFrame 2-dimensional, you can call eg. df.sample(frac=0.3) to retrieve a sample. But this sample will have completely shuffled row order. Is there a simple way to get a subsample that preserves the row order? | What we can do instead is use df.sample(), and then sort the resultant index by the original row order. Appending the sort_index() call does the trick. Here's my code: df = pd.DataFrame(np.random.randn(100, 10)) result = df.sample(frac=0.3).sort_index() You can even get it in ascending order. Documentation here. | 10 | 9 |
59,589,494 | 2020-1-4 | https://stackoverflow.com/questions/59589494/how-do-i-change-the-index-values-of-a-pandas-series | How can I change the index values of a Pandas Series from the regular integer value that they default to, to values within a list that I have? e.g. x = pd.Series([421, 122, 275, 847, 175]) index_values = ['2014-01-01', '2014-01-02', '2014-01-03', '2014-01-04', '2014-01-05'] How do I get the dates in the index_values l... | You can assign index values by list: x.index = index_values print(x) 2014-01-01 421 2014-01-02 122 2014-01-03 275 2014-01-04 847 2014-01-05 175 dtype: int64 | 40 | 16 |
59,582,142 | 2020-1-3 | https://stackoverflow.com/questions/59582142/import-cannot-import-name-resolveinfo-from-graphql-error-when-using-newest | I am having some issues with my django app since updating my dependencies. Here aer my installed apps: INSTALLED_APPS = [ 'graphene_django', 'rest_framework', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contri... | Ok I was able to fix it by downgrading graphql-core==3.0.1 to graphql-core<3 (and all the depencencies). I must have missed the errors when performing pip install -r requirements.txt | 10 | 8 |
59,588,886 | 2020-1-4 | https://stackoverflow.com/questions/59588886/why-isnt-pip-installing-the-latest-version-of-a-package-even-when-a-newer-vers | I was trying to upgrade to the latest version of a package I had installed with pip, but for some reason it won't get the latest version. I've tried uninstalling the package in question, or even reinstalling pip entirely, but it still refuses to get the latest version from PyPI. When I try to pin the package version (e... | I was trying to upgrade Quart. Maybe other packages have something else going on. In this particular case, Quart had dropped support for Python 3.6 (the version I had installed) and only supported 3.7 or later. (This was a fairly recent change to the project, so I just didn't see the news.) However, when attempting to ... | 8 | 7 |
59,583,726 | 2020-1-3 | https://stackoverflow.com/questions/59583726/django-importerror-cannot-import-name-python-2-unicode-compatible | I'm building a website and I was trying to create a custom user-to-user messaging system so I installed django-messages and maybe a few other things, and suddenly when I tried to run my server I get the following error : Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most... | You are using Django 3, where all the Python 2 compatibility APIs that used to be bundled with Django were removed. django-messages still depends on these, and is trying and failing to import them. You either need to downgrade to Django 2.2, or wait for django-messages to be updated for Django 3 support. This applies f... | 14 | 17 |
59,585,624 | 2020-1-3 | https://stackoverflow.com/questions/59585624/vectorize-a-for-loop-in-numpy-to-calculate-duct-tape-overlaping | I'm creating an application with python to calculate duct-tape overlapping (modeling a dispenser applies a product on a rotating drum). I have a program that works correctly, but is really slow. I'm looking for a solution to optimize a for loop used to fill a numpy array. Could someone help me vectorize the code below?... | There is no need for any looping at all here. You have effectively two different line_mask functions. Neither needs to be looped explicitly, but you would probably get a significant speedup just from rewriting it with a pair of for loops in an if and else, rather than an if and else in a for loop, which gets evaluated ... | 7 | 8 |
59,582,663 | 2020-1-3 | https://stackoverflow.com/questions/59582663/cnn-pytorch-error-input-type-torch-cuda-bytetensor-and-weight-type-torch-cu | I'm receiving the error, Input type (torch.cuda.ByteTensor) and weight type (torch.cuda.FloatTensor) should be the same Following is my code, device = torch.device('cuda:0') trainData = torchvision.datasets.FashionMNIST('/content/', train=True, transform=None, target_transform=None, download=True) testData = torchvis... | Cast your input x_batch to float. Use x_batch = x_batch.float() before you pass it through your model. | 16 | 29 |
59,582,503 | 2020-1-3 | https://stackoverflow.com/questions/59582503/matplotlib-how-to-draw-vertical-line-between-two-y-points | I have 2 y points for each x points. I can draw the plot with this code: import matplotlib.pyplot as plt x = [0, 2, 4, 6] y = [(1, 5), (1, 3), (2, 4), (2, 7)] plt.plot(x, [i for (i,j) in y], 'rs', markersize = 4) plt.plot(x, [j for (i,j) in y], 'bo', markersize = 4) plt.xlim(xmin=-3, xmax=10) plt.ylim(ymin=-1, ymax=10)... | just add plt.plot((x,x),([i for (i,j) in y], [j for (i,j) in y]),c='black') | 7 | 12 |
59,563,025 | 2020-1-2 | https://stackoverflow.com/questions/59563025/how-to-reset-tensorboard-when-it-tries-to-reuse-a-killed-windows-pid | Apologies if two days' frustration leaks through... Problem: can't reliably run Tensorboard in jupyter notebook (actually, in Jupyter Lab) with %tensorboard --logdir {logdir} and if I kill the tensorboard process and start again in the notebook it says it is reusing the dead process and port, but the process is dead a... | Hey—sorry to hear that you’re running into issues. It’s entirely plausible that everything that you describe is both accurate and my fault. :-) How in the name of $deity do I get tensorboard to restart from scratch and forget what it thinks it knows about processes, ports etc.? If I could do that I could hack away at ... | 16 | 26 |
59,581,746 | 2020-1-3 | https://stackoverflow.com/questions/59581746/why-does-vs-code-autopep8-format-2-white-lines | print("Hello") def world(): print("Hello") world() Gets corrected to: print("Hello") def world(): print("Hello") world() I have tried to: Reinstall Virtual Studio Code Reinstall Python 3.8 Computer Reboot Using other formatters like Black and yapf but got the same result | Because autopep8 follows PEP8 which suggests 2 blank lines around top-level functions. Surround top-level function and class definitions with two blank lines. | 7 | 5 |
59,576,397 | 2020-1-3 | https://stackoverflow.com/questions/59576397/python-kernel-dies-on-jupyter-notebook-with-tensorflow-2 | I installed tensorflow 2 on my mac using conda according these instructions: conda create -n tf2 tensorflow Then I installed ipykernel to add this new environment to my jupyter notebook kernels as follows: conda activate tf2 conda install ipykernel python -m ipykernel install --user --name=tf2 That seemed to work wel... | After trying different things I run jupyter notebook on debug mode by using the command: jupyter notebook --debug Then after executing the commands on my notebook I got the error message: OMP: Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized. OMP: Hint This means that multiple copi... | 11 | 16 |
59,567,172 | 2020-1-2 | https://stackoverflow.com/questions/59567172/multiple-assignments-via-walrus-operator | I've attempted to make multiple assignments with the walrus operator, and seen questions on StackOverflow such as this which also fail to assign multiple variables using a walrus operator, and am just wondering what a successful multiple assignment would look like, or whether it is not possible. The purpose of doing so... | Iterable packing and unpacking is one difference between = and :=, with only the former supporting them. As found in PEP-572: # Equivalent needs extra parentheses loc = x, y # Use (loc := (x, y)) info = name, phone, *rest # Use (info := (name, phone, *rest)) # No equivalent px, py, pz = position name, phone, email, *ot... | 22 | 28 |
59,562,997 | 2020-1-2 | https://stackoverflow.com/questions/59562997/how-to-parse-and-read-id-field-from-and-to-a-pydantic-model | I am trying to parse MongoDB data to a pydantic schema but fail to read its _id field which seem to just disappear from the schema. The issue is definitely related to the underscore in front of the object attribute. I can't change _id field name since that would imply not parsing the field at all. Please find below the... | you need to use an alias for that field name from pydantic import BaseModel, Field class User_1(BaseModel): id: int = Field(..., alias='_id') See the docs here. | 24 | 36 |
59,559,941 | 2020-1-2 | https://stackoverflow.com/questions/59559941/how-to-round-decimal-places-in-a-dash-table | I have the following python code: import dash import dash_html_components as html import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/dougmellon/rockies_dash/master/rockies_2019.csv') def generate_table(dataframe, max_rows=10): return html.Table( # Header [html.Tr([html.Th(col) for col in dataframe.... | I would check this for the dataframe and maybe it might help - How to display pandas DataFrame of floats using a format string for columns? or simply try- pd.options.display.float_format = '${:.2f}'.format I just read in one of the DashTable forums that - you can format data in pandas dataframe and DataTable will disp... | 8 | 6 |
59,554,493 | 2020-1-1 | https://stackoverflow.com/questions/59554493/unable-to-fire-a-docker-build-for-django-and-mysql | I am building an application with Djnago and MySql. I want to use docker for the deployment of my application. I have prepared a requirement.txt, docker-compose.yml and a Dockerfile docker-compose.yml version: "3" services: law-application: restart: always build: context: . ports: - "8000:8000" volumes: - ./app:/app co... | Just run pip install requirements after apt-get install because mysqlclient requires libmysqlclient-dev: You're using apt package manager with alpine base linux image which is incompatible. I recommend to take python3.7-slim with debian os which supports apt. FROM python:3.7-slim MAINTAINER Intersources Inc. ENV PYTHON... | 7 | 19 |
79,418,235 | 2025-2-6 | https://stackoverflow.com/questions/79418235/msgraph-sdk-python-get-sharepoint-site-id-from-name | I want to work with SharePoint sites using Python. For now, I just want to ls on the site. I immediately ran into an issue where I need site id to do anything with it. How do I get site id from the site name? I did retrieve it using powershell: $uri = "https://graph.microsoft.com/v1.0/sites/"+$SharePointTenant+":/sites... | To get the Site ID from Site name and get Drives, modify the code like below: import asyncio from azure.identity.aio import ClientSecretCredential from msgraph import GraphServiceClient from msgraph.generated.sites.sites_request_builder import SitesRequestBuilder from kiota_abstractions.base_request_configuration impor... | 1 | 4 |
79,417,096 | 2025-2-6 | https://stackoverflow.com/questions/79417096/how-to-force-the-reinsall-of-my-local-package-with-uv | I'm starting to use uv for my CI as it's showing outstanding performances with respect to normal pip installation. for each CI run I (in fact nox does it on my behalf) create a virtual environment that will be used to run the tests. In this environment I run the following: uv pip install .[test] my folder is a simple ... | The uv team has been super fast to answer my question and since https://github.com/astral-sh/uv/issues/12038 it's part of the default mechanism: local sources are now always reinstalled | 3 | 0 |
79,424,466 | 2025-2-9 | https://stackoverflow.com/questions/79424466/python-socket-can-not-connect-on-two-separated-machines | I used the socket library in Python, and made two simple projects which are server.py and client.py, then I executed them as server.exe and client.exe When I run both (server.exe and client.exe) on my computer, it works fine, but when I run them on two separate computers, the client can not connect to the server that r... | I think this is virtually impossible without an online host or any third party programs, if I say correctly, this because a main difference between network and internet, we use network for devices which connected to a same router, these devices can easily communicating together because they are in a local network, but ... | 2 | 0 |
79,420,818 | 2025-2-7 | https://stackoverflow.com/questions/79420818/clearing-tf-data-dataset-from-gpu-memory | I'm running into an issue when implementing a training loop that uses a tf.data.Dataset as input to a Keras model. My dataset has an element spec of the following format: ({'data': TensorSpec(shape=(15000, 1), dtype=tf.float32), 'index': TensorSpec(shape=(2,), dtype=tf.int64)}, TensorSpec(shape=(1,), dtype=tf.int32)) ... | The problem is due to cache that does not get cleared when needed, this is an open issue. the only way I found is to make a large data set to replace the old one in cache dataset = tf.data.Dataset.range(num_epochs // 8) #drop the cache every 8 epochs dataset = dataset.flat_map(lambda newcache1: create_dataset().repeat(... | 9 | 2 |
79,421,366 | 2025-2-7 | https://stackoverflow.com/questions/79421366/plot-modification-to-align-both-x-axes-and-start-from-where-it-exists-in-list | import matplotlib.pyplot as plt size = 18 value = [20, 25, 30, 35] x_values1 = list(range(0, 100, 5)) x_values2 = [0.0, 20.0, 40.0, 60.0, 80.0, 90.0, 95.0] x_values3 = [80,76,72,68,64,60,56,52,48,44,40,36,32,28,24,20,16,12,8,4] y_value1 = [8.226502331074E-07, 2.23276092438077E-06, 4.05102969501409E-06, 6.37286188209644... | import matplotlib.pyplot as plt import itertools print('matplotlib version:', matplotlib.__version__) size = 18 value = [20, 25, 30, 35] x_values1 = list(range(0, 100, 5)) x_values2 = [0.0, 20.0, 40.0, 60.0, 80.0, 90.0, 95.0] x_values3 = [80, 76, 72, 68, 64, 60, 56, 52, 48, 44, 40, 36, 32, 28, 24, 20, 16, 12, 8, 4] y_v... | 1 | 1 |
79,422,336 | 2025-2-7 | https://stackoverflow.com/questions/79422336/azure-function-with-service-bus-trigger-managedidentitycredential-performance | I am working on an Azure Function that uses a ServiceBusTrigger and queries Azure Table Storage. In order to process multiple messages as quickly as possible we're using the MaxConcurrentCalls setting to enable parallel message processing (e.g. we set MaxConcurrentCalls to 200). We're using Managed Identity to access t... | To prevent each function instance from making a call to the /msi/token endpoint when obtaining a ManagedIdentityCredential, initialize DefaultAzureCredential once and cache it in _credential. This prevents redundant calls to /msi/token for each message. Additionally, ensure that the Storage Table Data Contributor and S... | 1 | 1 |
79,424,859 | 2025-2-9 | https://stackoverflow.com/questions/79424859/how-to-improve-efficiency-of-my-python-function-involving-sparse-matrices | I want to implement a particular function in python involving sparse matrices and want to make it as fast as possible. I describe in detail what the problem is and how I implemented it so far. Problem: I have N=1000 fixed (dimension is fixed, entries fixed) sparse matrices collectively called B each of size 1000x1000 (... | Here is another answer using another data structure for B which is different from the one in the question and Numba-friendly. Since B is "fixed", we can transform it to a more efficient array-based data-structure packing all COO matrices into only 4 big arrays. The number of non-zero values is stored so to know where e... | 4 | 3 |
79,418,290 | 2025-2-6 | https://stackoverflow.com/questions/79418290/pyspark-foreachpartition-not-getting-executed | I am trying to copy data from an iceberg table to a postgres table using a glue job. I have this code: def execute_job(spark, factory: DependencyFactory, environment, logger): print("Starting job") sql = f"SELECT * FROM {DATABASE_NAME}.transactions ORDER BY unique_identifier, in_date" df = spark.sql(sql) df.show(10) co... | foreachPartition function works on executor level, you can see details logs on the executor logs rather than driver logs. Worth checking the executor logs. Also, do you see the data getting updated in PostgreSQL table? | 3 | 0 |
79,423,247 | 2025-2-8 | https://stackoverflow.com/questions/79423247/how-to-color-excel-cells-with-specific-values-in-dataframe-python | I created a code to insert my dataframe, called df3, into an excel file. My code is working fine, but now I'd like to change background cells color in all cells based on value I tried this solution, I don't get any errors but I also don't get any cells colored My code: def cond_formatting(x): if x == 'OK': return 'back... | If you provided complete code, it would be easier for me to set colors for the cells for your excel file. But an example script given below might assist you: import pandas as pd from openpyxl import load_workbook from openpyxl.styles import PatternFill data = { "ID": [1, 2, 3, 4, 5], "Status": ["OK", "NO", "OK", "NO", ... | 2 | 3 |
79,428,256 | 2025-2-10 | https://stackoverflow.com/questions/79428256/dash-multi-value-dropdown-wrapping-text-skips-the-first-line | I'm making a Dash Multi-Value Dropdown and finding that long labels use a text wrapping process that skips the first line entirely. When I make a Dash Multi-Value Dropdown like this: dcc.Dropdown( options=[ { 'label': str(entity), 'value': entity, 'title': entity, } for entity in entity_list ], multi=True, optionHeight... | You can add explicit line breaks (\n) wrapped in html.Pre to preserve the line breaks and white space: from dash import Dash, html, dcc app = Dash() entity_list = ['vital sign measurements', 'vital sign\nmeasurements'] app.layout = [html.Div( [ dcc.Dropdown( options=[ { 'label': html.Pre(entity), 'value': entity, 'tit... | 2 | 1 |
79,428,279 | 2025-2-10 | https://stackoverflow.com/questions/79428279/incoming-http-requests-dont-get-read-from-python-socket-in-time | I'm making a simple HTTP server with Python using the socket module as a personal exercise to understand the HTTP protocol, and it appears that some incoming requests don't get read from the socket until new requests comes along. The (very) summarized version of the code is: import socket id = 0 def handle_request(clie... | The issue you're running into probably happens because your server handles requests one at a time and waits (blocks) on serverSocket.accept(). Since Firefox sends multiple requests at once (HTML, CSS, favicon, etc.), only the first couple get processed immediately. The favicon request gets stuck in the queue, and your ... | 1 | 2 |
79,428,300 | 2025-2-10 | https://stackoverflow.com/questions/79428300/interactive-brokers-ibkr-gateway-api-how-to-fix-no-security-definition-has-be | Requesting contract details for NQ futures... Error 200, reqId 9: No security definition has been found for the request, contract: Future(symbol='NQ', exchange='GLOBEX', currency='USD') No contract details found for NQ. Please verify your parameters in TWS/IB Gateway. #!/usr/bin/env python3 from ib_insync import IB, Fu... | GLOBEX is an old exchange code that is no longer valid. It should be CME. You can look up exchange codes on IBKR's website: https://www.interactivebrokers.com/en/trading/products-exchanges.php Or you can look it up on QuantRocket's website with fewer clicks: https://www.quantrocket.com/data/?modal=ibkrexchangesmodal | 1 | 1 |
79,415,181 | 2025-2-5 | https://stackoverflow.com/questions/79415181/quantum-circuit-not-drawing-on-colab | So, I tried to simulate this gate on Colab using matplotlib. The histogram is showing at the end, but not the circuit. I have tried out all fixes suggested by ChatGPT such as force inline and circuit_drawer, but it did not work. Please help me with the solution. qc_h = QuantumCircuit(1, 1, name = "qc") qc_h.h(0) qc_h.m... | We have to define the matplotlib axes (e.g. two matplotlib subplots) and input the axis as a kwargument for draw and plot_histogram. from qiskit import QuantumCircuit from qiskit_aer import Aer from qiskit.compiler import transpile from qiskit.visualization import plot_histogram from matplotlib import pyplot as plt fig... | 1 | 2 |
79,428,043 | 2025-2-10 | https://stackoverflow.com/questions/79428043/why-ast-assign-targets-is-a-list | ast.Assign.targets is a list a, b = c, d Yields following AST: Assign( targets=[ Tuple( elts=[ Name(id='a', ctx=Store()), Name(id='b', ctx=Store())], ctx=Store())], value=Tuple( elts=[ Name(id='c', ctx=Load()), Name(id='d', ctx=Load())], ctx=Load())) Under what conditions target would be a list with multiple elements... | When there are multiple destinations for the assignment of the value. That is: a = b = c = d AST: Module( body=[ Assign( targets=[ Name(id='a', ctx=Store()), Name(id='b', ctx=Store()), Name(id='c', ctx=Store())], value=Name(id='d', ctx=Load()))], type_ignores=[]) | 2 | 3 |
79,427,869 | 2025-2-10 | https://stackoverflow.com/questions/79427869/default-filter-expression-to-match-anything | What kind of polars expression (pl.Expr) might be used in a filter context that will match anything including nulls? Use case: Type hinting and helper Functions that should return an polars.Expr. | The expression representing the literal value True might be used. See pl.lit for more details. Example. import polars as pl df = pl.DataFrame({ "a": [1, 2, None] }) df.filter(pl.lit(True)) shape: (3, 1) ┌──────┐ │ a │ │ --- │ │ i64 │ ╞══════╡ │ 1 │ │ 2 │ │ null │ └──────┘ Note. In general, simply True also works, but... | 4 | 5 |
79,421,635 | 2025-2-7 | https://stackoverflow.com/questions/79421635/how-to-add-flask-sqlalchemy-multiple-tables-query-result-with-column-name-valu | I have got 2 tables, one is department and another one is supplier. For every department, there could be a supplier or it could be none. So I use the outerjoin and the result is correct. I need to know how add these results in to a list @department.route("/department/getDepartmentDetails/<int:id>", methods=['GET', 'POS... | Assuming that you want to return a single dict (or JSON object) for each row in the resultset, all that is required is generate a dict for each entity in each (Department, Supplier) row, and merge them. However we need to consider that the models may share some attribute names, which must be disambiguated. The disambig... | 1 | 1 |
79,426,835 | 2025-2-10 | https://stackoverflow.com/questions/79426835/pandas-in-python-dbt-model-duckdb | Im trying to use pandas in a dbt python model (dbt-duckdb), but I keep getting the problem Python model failed: No module named 'pandas'. Here you can find my dbt model configuration: import boto3 import pandas as pd def model(dbt, session): dbt.config( materialized="table", packages = ["pandas==2.2.3"], python_version... | Found it, make sure that the venv you are using is called dbt-env dbt will automatically take this venv where you have installed pandas or whatever package you needed! | 1 | 1 |
79,426,836 | 2025-2-10 | https://stackoverflow.com/questions/79426836/create-a-new-dataframe-form-an-existing-dataframe-taking-only-the-rows-matching | I have a dataframe called "base_dataframe" that looks as following: F_NAME L_NAME EMAIL 0 Suzy Maripol suzy@mail.com 1 Anna Smith anna@mail.com 2 Flo Mariland flo@mail.com 3 Sarah Linder sarah@mail.com 4 Nala Kross Nala@mail.com 5 Sarosh Fink sarosh@mail.com I would like to create a new dataframe that only contains t... | Since you goal seems to be filtering, couldn't you replace your extract logic by a simple boolean indexing?: # identify rows with F_NAME starting with "Sar" m1 = base_dataframe['F_NAME'].str.startswith('Sar') # identify rows with L_NAME starting with "Mari" m2 = base_dataframe['L_NAME'].str.startswith('Mari') # keep ro... | 3 | 2 |
79,426,847 | 2025-2-10 | https://stackoverflow.com/questions/79426847/how-to-express-the-dot-product-of-3-dimensions-arrays-with-numpy | How do I do the following dot product in 3 dimensions with numpy? I tried: x = np.array([[[-1, 2, -4]], [[-1, 2, -4]]]) W = np.array([[[2, -4, 3], [-3, -4, 3]], [[2, -4, 3], [-3, -4, 3]]]) y = np.dot(W, x.transpose()) but received this error message: y = np.dot(W, x) ValueError: shapes (2,2,3) and (2,1,3) not aligne... | The issue comes from the 3D transposition which does not transpose the axes you want by default. You need to specify the right axes during this call: W @ x.transpose(0, 2, 1) # Output: # array([[[-22], # [-17]], # # [[-22], # [-17]]]) | 4 | 6 |
79,426,845 | 2025-2-10 | https://stackoverflow.com/questions/79426845/in-pandas-a-groupby-followed-by-boxplot-gives-keyerror-none-of-indexa-1 | This very simple script gives error KeyError: "None of [Index(['A', 1], dtype='object')] are in the [index]": import pandas as pd import matplotlib.pyplot as plt L1 = ['A','A','A','A','B','B','B','B'] L2 = [1,1,2,2,1,1,2,2] V = [9.8,9.9,10,10.1,19.8,19.9,20,20.1] df = pd.DataFrame({'L1':L1,'L2':L2,'V':V}) print(df) df.... | You can use boxplot for the grouping as well df.boxplot(column='V', by=['L1', 'L2']) | 4 | 3 |
79,426,130 | 2025-2-10 | https://stackoverflow.com/questions/79426130/how-to-create-a-class-that-runs-business-logic-upon-a-query | I'd like to create a class/object that I can use for querying, that contains business logic. Constraints: Ideally that class/object is not the same one that is responsible for table creation. It's possible to use the class inside a query Alembic should not get confused. SQLAlchemy Version: 1.4 and 2.x. How do I do th... | You can use an execute event to intercept queries and modify them before execution. This sample event Checks the session's info dictionary to determine whether the query relates to an entity of interest Creates a modified query that checks whether valueA can be shown Replaces the original query with the modified query... | 2 | 0 |
79,426,203 | 2025-2-10 | https://stackoverflow.com/questions/79426203/problem-scraping-table-row-data-into-an-array | Background I am looking to measure statistics from a website wotstars for a XBOX and Playstation game, World of Tanks Console. Initially I tried just using Excel to scrape the site directly for me into Power Query, the immediate issue was that only 5 rows of recent match data (5 games) is available from the website as ... | Since you have to use selenium for the view more button click anyway, you don't need to use beautifulsoup. Using only class names for selecting elements is difficult for the page as it has multiple tables and buttons with the same class. Instead, use XPath to find the section BattleTracker by text. that way you can acc... | 2 | 2 |
79,425,937 | 2025-2-10 | https://stackoverflow.com/questions/79425937/how-do-i-modify-a-list-value-in-a-for-loop | In How to modify list entries during for loop?, the general recommendation is that it can be unsafe so don't do it unless you know it's safe. In comments under the first answer @martineau says: It [the loop variable] doesn't make a copies. It just assigns the loop variable name to successive elements or value of the t... | The line fv = fv[:v] will create a new variable named fv instead of mutating fv. You should mutate the existing list. One solution could be using while to strip unwanted values until none left. The .pop() method will mutate row instead of returning a new list: for row in foo: while row and row[-1] is None: row.pop() as... | 3 | 3 |
79,423,875 | 2025-2-8 | https://stackoverflow.com/questions/79423875/equivalent-of-pythons-selection-by-multiindex-level-especially-columns-in-juli | My understanding is that DataFrames do not support MultiIndexing, which generally does not pose much problems, but translating some pythonic habits to Julia poses difficulties. I wonder how one could load and subselect features by columns, as in the example below. import numpy as np import pandas as pd #generating samp... | Something like this ? using DataFrames, CSV # Used your sample data df = DataFrame(CSV.File("data.tsv")) # Filter the columns by country name france_cols = findall(x -> occursin("France", x), names(df)) # Subset the df dg = select(df, france_cols) # Optional : use "sampleX" as col names instead of the country name rena... | 2 | 2 |
79,422,455 | 2025-2-8 | https://stackoverflow.com/questions/79422455/gimp-wire-read-error-upon-adding-python-script-in-correct-folder | I am trying to learn GIMP 2.10.38 with python and I don't know either that well, so I tried adding a simple python script but it doesn't show up in GIMP at all. Here is the script I added: #!/usr/bin/env python from gimpfu import * def simple_plugin(image, drawable): gimp.message("Hello from a simple plugin!") register... | Your problem isn't the "wire-read" error (which has been showing in my Gimp console for years without being related to any trouble). In the same terminal output, you should also see this: Traceback (most recent call last): File "/path/to/your/file.py", line 17, in <module> simple_plugin, TypeError: register() takes at ... | 1 | 1 |
79,419,153 | 2025-2-6 | https://stackoverflow.com/questions/79419153/c-to-python-rsa-implement | Just trying to rewrite this c# code to python. Server send public key(modulus, exponent), need to encrypt it with pkcs1 padding. using (TcpClient client = new TcpClient()) { await client.ConnectAsync(ip, port); using (NetworkStream stream = client.GetStream()) { await App.SendCmdToServer(stream, "auth", this.Ver.ToStri... | The PyCryptodome is a good choice for cryptographic tasks in Python. The problem is with the data formatting, you are concatenating the strings directly in Python and the BinaryWriter in C# write the lengths of the strings as prefixes.This code show how you can do that: import struct data = b"" data += struct.pack(">I"... | 6 | 3 |
79,417,439 | 2025-2-6 | https://stackoverflow.com/questions/79417439/how-to-display-additional-count-near-progress-bar-in-enquiry-screen | I am working on Odoo 18 and need to modify the Enquiry Screen to display additional counts near the progress bar. The current progress bar already shows the Expected Revenue, but I want to add more details for better visibility. Requirements CHECK THIS IMAGES 👇 Current view Expected View For the "NEW" Stage: The dis... | To display an additional count near the progress bar in Odoo 18's Enquiry Screen, follow these steps: Template Inheritance: Extend the existing ColumnProgress template from the crm module using XML. This allows you to inject custom elements into the progress bar's structure. XPath Positioning: Use an XPath expression... | 2 | 2 |
79,422,061 | 2025-2-7 | https://stackoverflow.com/questions/79422061/problem-with-fastapi-pydantic-and-kebab-case-header-fields | In my FastAPI project, if I create a common header definition with Pydantic, I find that kebab-case header fields aren't behaving as expected. The "magic" conversion from kebab-case header fields in the request to their snake_case counterparts is not working, in addition to inconsistencies in the generated Swagger docs... | The only way I found is to define parameters without using Pydantic model. To use this common parameters in different endpoints you can define them using dependency function: from typing import Annotated from fastapi import Depends, FastAPI, Header from pydantic import BaseModel app = FastAPI() class CommonHeaders(Base... | 3 | 1 |
79,422,054 | 2025-2-7 | https://stackoverflow.com/questions/79422054/check-if-string-only-contains-characters-from-a-certain-iso-specification | Short question: What is the most efficient way to check whether a .TXT file contains only characters defined in a selected ISO specification? Question with full context: In the German energy market EDIFACT is used to automatically exchange information. Each file exchanged has a header segment which contains information... | Credits to Barmar for suggesting the use of .decode() I found a solution which looks smooth to me. If I encode the string using the latin_1 encoding the Chinese characters seem to not be encoded into bytes. I didn't check but I guess the .encode() method omits them since they don't belong to latin_1. If I then convert ... | 2 | 0 |
79,419,739 | 2025-2-7 | https://stackoverflow.com/questions/79419739/optimized-binary-matrix-inverse | I am attempting to invert (mod 2) a non-sparse binary matrix. I am trying to do it with very very large matricies, like 100_000 by 100_000. I have tried libraries, such as sympy, numpy, numba. Most of these do this with floats and don't apply mod 2 at each step. In general, numpy reports the determinant of a random bin... | First of all, the algorithmic complexity of a matrix inversion is identical to the complexity of a matrix multiplication. A naive matrix multiplication has a complexity of O(n**3). The best practical algorithm known so far is Strassen with a complexity of ~O(n**2.8) (other can be considered as galactic algorithms). Thi... | 3 | 3 |
79,421,406 | 2025-2-7 | https://stackoverflow.com/questions/79421406/are-there-any-builtin-frozen-modules-in-python | I was going through the python import process and found out about frozen modules. The only thing I understood after searching is that frozen modules are files that can be directly executed without python installed on the system. I wanted to know one thing. Like sys.modules and sys.builtin_module_names are any frozen mo... | If your goal is to know what names to avoid, you don't need to know about frozen modules for that. Just don't pick the name of a built-in function, stdlib module, or keyword, and you should be fine. So pretty much the 3 lists matszwecja linked. But learning about frozen modules is interesting too, so let's talk about ... | 1 | 3 |
79,420,610 | 2025-2-7 | https://stackoverflow.com/questions/79420610/undertanding-python-import-process-importing-custom-os-module | I was reading through the python docs for how import is resolved and found this ... the interpreter first searches for a built-in module with that name. These module names are listed in sys.builtin_module_names. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.... | sys.path is initialized the way the tutorial says, but Python needs the os module before that initialization can fully complete. os is needed during Python setup. It's imported by the site module, which is imported during Python setup unless you manually say not to do that (with the -S flag). These imports happen so ea... | 1 | 1 |
79,421,320 | 2025-2-7 | https://stackoverflow.com/questions/79421320/python-polars-expression-to-get-length-of-lists-in-a-struct | In Python Polars, I am trying to extract the length of the lists inside a struct to re-use it in an expression. For example, I have the code below: import polars as pl df = pl.DataFrame( { "x": [0, 4], "y": [ {"low": [-1, 0, 1], "up": [1, 2, 3]}, {"low": [-2, -1, 0], "up": [0, 1, 2]}, ], } ) df.with_columns( check=pl.c... | Unfortunately, I don't see a way to use an expression for the list length here. Also, direct comparisons of list columns are not yet natively supported. Still, some on-the-fly exploding and imploding of the list columns could be used to achieve the desired result without relying on knowing the list lengths upfront. ( d... | 2 | 2 |
79,421,288 | 2025-2-7 | https://stackoverflow.com/questions/79421288/interpolating-a-array-that-has-many-zeros-outputs-wrong-result | Im trying to interpolate a set of x coordinates to y coordinates. x are the points Im trying to find a y for. The points I know are: xp (x coordinates) and their respective fp (y coordinates). The problem is that when I run the code, y is the number 0.97610476 repeated 33 times. Which is of course not the right answer.... | If you look at the docs np.interp requires "One-dimensional linear interpolation for monotonically increasing sample points." Your data is actually monotically decreasing and the x values are negative. If we change the sign of x then the data reflects on the y axis and become monotically incresing. You can also filter ... | 2 | 3 |
79,421,290 | 2025-2-7 | https://stackoverflow.com/questions/79421290/reassigning-values-of-multiple-columns-to-values-of-multiple-other-columns | For the following df I wish to change the values in columns A,B and C to those in columns X,Y and Z, taking into account a boolean selection on column B. columns = {"A":[1,2,3], "B":[4,pd.NA,6], "C":[7,8,9], "X":[10,20,30], "Y":[40,50,60], "Z":[70,80,90]} df = pd.DataFrame(columns) df A B C X Y Z 0 1 4 7 10 40 70 1 2 <... | Your columns are not matching on the two sides of the assignment. Since you use a mask on both sides, don't perform index alignment and directly pass the values: m = ~df['B'].isna() df.loc[m, ['A', 'B', 'C']] = df.loc[m, ['X', 'Y', 'Z']].values For your approach to work, you could also rename the columns. In this case... | 1 | 2 |
79,416,139 | 2025-2-5 | https://stackoverflow.com/questions/79416139/adjust-matplotlib-polar-plot-to-show-sub-degree-motion-aka-stretch-a-polar-plot | I have RA and DEC pointing data I would like to show on a polar plot (converting to rho and theta). The theta motion is very small, ~0.01 degrees. This is not easily seen on a full polar plot so I am trying to 'zoom in' to the region and show the change from data point to data point. When I adjust the thetamin/thetamax... | First of all, you still have some potential concerning narrowing down the plotted radial range, e.g., to ax.set_ylim(1.91159, 1.91164). Please also note, that when I was searching for a solution (which I couldn't fin on the internet either), I found that using np.arctan2() is the appropriate approach for polar coordina... | 3 | 3 |
79,414,537 | 2025-2-5 | https://stackoverflow.com/questions/79414537/mongomock-bulkoperationbuilder-add-update-unexpected-keyword-argument-sort | I'm testing a function that performs a bulk upsert using UpdateOne with bulk_write. In production (using the real MongoDB client) everything works fine, but when running tests with mongomock I get this error: app.mongodb.exceptions.CatalogException: failure in mongo repository function `batch_upsert_catalog_by_sku`: Bu... | This seem to be related to pymongo version 4.11. In 4.10.1, the method _add_to_bulk in the class UpdateOne here calls add_update this way: def _add_to_bulk(self, bulkobj: _AgnosticBulk) -> None: """Add this operation to the _AsyncBulk/_Bulk instance `bulkobj`.""" bulkobj.add_update( self._filter, self._doc, False, boo... | 2 | 3 |
79,419,480 | 2025-2-6 | https://stackoverflow.com/questions/79419480/using-python-to-replace-triple-double-quotes-with-single-double-quote-in-csv | I used the pandas library to manipulate the original data down to a simple 2 column csv file and rename it to a text file. The file has triple double quotes that I need replaced with single double quotes. Every line of the file is formatted as: """QA12345""","""Some Other Text""" What I need is: "QA12345","Some Other ... | Judging by the OP's code, I guess the aim are Edit file in-place keep the first line unmodified For the rest of the lines, replace 3 double quotes with a single one My solution is almost the same, but with print(): with fileinput.input(input_file, inplace=True) as stream: print(next(stream), end="") for line in strea... | 1 | 1 |
79,417,722 | 2025-2-6 | https://stackoverflow.com/questions/79417722/python-script-unable-to-process-larger-zip-files-from-irs-990-aws-datalake | I am trying to access raw 990 (nonprofit tax returns) XML data through the AWS datalake. The XML files are organized into Zip files split by the month in which the IRS processed them ("2024_1A" for January, "2024_2A" for Feburary). See photo for the Zip files I am iterating through. In certain months, there are multipl... | Compression method 9 is not Deflate. (Deflate is method 8.) Method 9 is a proprietary PKWare enhancement of Deflate called Deflate64. Python's zipfile does not support it. You would need to use an unzip utility, such as Info-ZIP's unzip, 7-zip, or the like. When I try it, zipfile raises an error that says exactly that,... | 1 | 2 |
79,417,747 | 2025-2-6 | https://stackoverflow.com/questions/79417747/how-to-concatenate-gzip-streams-in-python | I am attempting to combine multiple gzip streams into a single stream, my understanding is this should be possible but my implementation is flawed. Based on what I have read, my expectation was that I should be able remove the 10byte header and 8 byte footer from all streams, concatenate the bytes together and reconstr... | This is much easier than you're making it out to be. Simply concatenate the gzip files without removing or in any way messing with the headers and trailers. Any concatenation of gzip streams is a valid gzip stream, and will decompress to the concatenation of the uncompressed contents of the individual gzip streams. | 1 | 4 |
79,418,676 | 2025-2-6 | https://stackoverflow.com/questions/79418676/plot-multiple-column-pairs-in-one-plot | I have columns of data in an excel sheet. The data is paired. I want to plot column 1 and 2 together, 3 and 4 together and so on. In my case I have four columns. I've tried creating a for loop to go through the data and plot it but I keep getting a separate plots. Anyone know what's wrong here? for i in range(0,data.s... | If I understand you correctly, you want to generate a single plot using several column combinations. You should create an axis object and then add the data to it. import numpy as np import pandas as pd from matplotlib import pyplot as plt data = pd.DataFrame({ 'col1': np.linspace(0, 0.2, 100), 'col2': np.linspace(0, 0.... | 1 | 1 |
79,417,642 | 2025-2-6 | https://stackoverflow.com/questions/79417642/softmax-with-polars-lazy-dataframe | I'm relatively new to using polars and it seems to be very verbose compared to pandas for what I would consider even relatively basic manipulations. Case in point, the shortest way I could figure out doing a softmax over a lazy dataframe is the following: import polars as pl data = pl.DataFrame({'a': [1,2,3,4,5,6,7,8,9... | You would use a multi-col selection e.g. pl.all() instead of list comprehensions. (Or pl.col(cols) for a named "subset" of columns) df.with_columns( pl.all().exp() / pl.sum_horizontal(pl.all().exp()) ) shape: (10, 3) ┌──────────┬──────────┬──────────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ f64 │ ╞══════════╪═... | 2 | 4 |
79,415,726 | 2025-2-5 | https://stackoverflow.com/questions/79415726/pandas-dataframe-slicing-performance-is-affected-by-how-subset-was-previously-as | In a recent post Pandas performance while iterating a state vector, I noticed a performance when slicing pandas dataframes that i do not understand. The code presented here does not do anything usefull, but highlight the issue: I create a dataframe with two areas of columns named extra_columns and columns The part of ... | TL;DR Your original df has a single block in memory. With stmt1, use of df["product"] = "x" makes the BlockManager (an internal memory manager) add a new block. Having multiple blocks adds overhead, as pandas needs to check and consolidate them each time a row gets modified. With stmt3, you do not have this issue, as d... | 4 | 2 |
79,416,850 | 2025-2-6 | https://stackoverflow.com/questions/79416850/how-to-reduce-verbosity-of-self-documenting-expressions-in-python-f-strings | This script: import numpy as np a = np.array([2, 3, 1, 9], dtype='i4') print(a) print(f'{a=}') produces: [2 3 1 9] a=array([2, 3, 1, 9], dtype=int32) Is there a way to get just a=[2 3 1 9] from {a=} f-string as in the standard formatting in the first line? | By default, = f-string syntax calls repr on the thing to be formatted, since that's usually more useful than str or format for the debugging use cases the = syntax was designed for. You can have it apply normal formatting logic instead by specifying a format - even an empty format will do, so this would work: print(f'{... | 3 | 4 |
79,412,165 | 2025-2-4 | https://stackoverflow.com/questions/79412165/trying-to-understand-differences-in-weighted-logistic-regression-outputs-between | I have a fictional weighted survey dataset that contains information about respondents' car colors and their response to the question "I enjoy driving fast." I would like to perform a regression to see whether the likelihood of slightly agreeing with this question varies based on whether or not the respondent drives a ... | As suggested in the comments by George Savva, DaveArmstrong, and BenBolker, I believe the issue here is that that my R code is interpreting the weights as sampling weights (which makes sense, since I'm applying survey analysis libraries), whereas Statsmodels is interpreting them as frequency weights. For further eviden... | 2 | 2 |
79,413,507 | 2025-2-5 | https://stackoverflow.com/questions/79413507/access-self-in-classmethod-when-instance-self-calls-classmethod | Is it possible to access the object instance in a Python @classmethod annotated function when the call occurs via the instance itself rather than the class? class Foo(object): def __init__(self, text): self.text = text @classmethod def bar(cls): return None print(Foo.bar()) foo = Foo('foo') # If possible, I'd like to r... | One possible approach without modifying Foo is to define bar as an instance method of a subclass, but use a custom descriptor to make attribute access to the method return the class method of the same name of the super class instead when the attribute is accessed from the class, when the instance passed to __get__ is N... | 1 | 1 |
79,416,288 | 2025-2-5 | https://stackoverflow.com/questions/79416288/django-compilemessages-error-cant-find-msgfmt-gnu-gettext-on-ubuntu-vps | I am trying to compile translation messages in my Django project by running the following command: python manage.py compilemessages However, I get this error: CommandError: Can't find msgfmt. Make sure you have GNU gettext tools 0.15 or newer installed. So then I tried installing gettext. sudo apt update && sudo apt ... | I've got the point. After deactivating the virtual environment, I tried installing gettext. Now it is okay. | 1 | 1 |
79,416,093 | 2025-2-5 | https://stackoverflow.com/questions/79416093/how-to-verify-if-a-instance-of-a-generic-class-is-from-the-good-type-variable-in | Let's assume that I have a generic class like that : import typing type_variable = typing.TypeVar("type_variable") class OneClass(typing.Generic[type_variable]): def __init__(self, value: type_variable): self.value = value Now I create two simple objects : a = OneClass("a str-typped object") b = OneClass(b'a byte-typp... | You are making a fundamental error. You are confusing types (int, float, OneClass) with type annotations (all the previous types, as well as OneClass[int], tuple[int, ...], etc.) As far as Python is concerned, tuple_object_1 and tuple_object_2 are just tuples, nothing more. It doesn't care in the least what the types o... | 1 | 3 |
79,412,275 | 2025-2-4 | https://stackoverflow.com/questions/79412275/pandas-performance-while-iterating-a-state-vector | I want to make a pandas dataframe that describes the state of a system at different times I have the initial state which describes the first row Each row correspond to a time I have reveserved the first two columns for "household" / statistics The following columns are state parameters At each iteration/row a number o... | Here's one approach that should be much faster: Data sample num_cols = 4 n_changes = 6 np.random.seed(0) # reproducibility # setup ... df_change col val 1 C 0.144044 4 A 1.454274 5 A 0.761038 7 A 0.121675 7 C 0.443863 10 B 0.333674 state {'A': 0.5488135039273248, 'B': 0.7151893663724195, 'C': 0.6027633760716439, 'D':... | 1 | 2 |
79,414,728 | 2025-2-5 | https://stackoverflow.com/questions/79414728/python-polars-how-to-add-columns-in-one-lazyframe-to-another-lazyframe | I have a Polars LazyFrame and would like to add to it columns from another LazyFrame. The two LazyFrames have the same number of rows and different columns. I have tried the following, which doesn't work as with_columns expects an iterable. def append_columns(df:pl.LazyFrame): df2 = pl.LazyFrame([1,2]) return df.with_c... | For this, pl.concat setting how="horizontal" might be used. import polars as pl df = pl.LazyFrame({ "a": [1, 2, 3], "b": [4, 5, 6], }) other = pl.LazyFrame({ "c": [9, 10, 11], "d": [12, 13, 14], "e": [15, 16, 17], }) result = pl.concat((df, other.select("c", "d")), how="horizontal") The resulting pl.LazyFrame then loo... | 2 | 3 |
79,415,141 | 2025-2-5 | https://stackoverflow.com/questions/79415141/pandas-convert-string-column-to-bool-but-convert-typos-to-false | I have an application that takes an input spreadsheet filled in by the user. I'm trying to bug fix, and I've just noticed that in one True/False column, they've written FLASE instead of FALSE. I'm trying to write in as many workarounds for user error as I can, as the users of this app aren't very technical, so I was wo... | If you want a generic approach, you could use fuzzy matching, for example with thefuzz: from thefuzz import process def to_bool(s, threshold=60): bools = [True, False] choices = list(map(str, bools)) match, score = process.extractOne(s, choices) d = dict(zip(choices, bools)) if score > threshold: return d[match] df['bo... | 1 | 1 |
79,414,891 | 2025-2-5 | https://stackoverflow.com/questions/79414891/how-to-make-my-dataclass-compatible-with-ctypes-and-not-lose-the-dunder-method | Consider a simple data class: from ctypes import c_int32, c_int16 from dataclasses import dataclass @dataclass class MyClass: field1: c_int32 field2: c_int16 According to the docs, if we want to make this dataclass compatible with ctypes, we have to define it like this: import ctypes from ctypes import Structure, c_in... | Both ctypes.Structure and dataclass have some similar functionality - but neither was built with the explicit intent of being collaborative with the other - therefore we have to make this bridging code. For one, the dataclass decorator will always attempt to be less disruptive as it can to whatever functionalities the ... | 1 | 2 |
79,415,052 | 2025-2-5 | https://stackoverflow.com/questions/79415052/how-to-keep-the-same-number-of-threads-on-python-all-the-time | This is a part of my code. For example, even if 3 out of 10 ends first, I want the next 3 to start right away and always keep 10 threads running. However, the current code is moving on to the next 10 only when all 10 are completely finished. How can I modify the code? I always want to keep a certain number of threads, ... | Use a queue-based approach with ThreadPoolExecutor, where tasks are continuously submitted as soon as one completes. import concurrent.futures import time import itertools def example_task(n): print(f"Task {n} started.") time.sleep(n) # Simulate work print(f"Task {n} completed.") return n def main(): max_threads = 5 to... | 2 | 2 |
79,414,070 | 2025-2-5 | https://stackoverflow.com/questions/79414070/seleniumbase-cdp-mode-execute-script-and-evaluate-with-javascript-gives-error-s | I am using SeleniumBase in CDP Mode. I am having a hard time figuring out if this a python issue or SeleniumBase issue. The below simple example shows my problem: from seleniumbase import SB with SB(uc=True, locale_code="en", headless=True) as sb: link = "https://news.ycombinator.com" print(f"\nOpening {link}") sb.wait... | In CDP Mode, don't include the final return when evaluating JS. Your script part should look like this: script = f""" function getSomeValue() {{ return '42'; }} getSomeValue(); """ data = sb.cdp.evaluate(script) (Instead of using "return getSomeValue();", which breaks evaluate(expression).) | 1 | 2 |
79,413,756 | 2025-2-5 | https://stackoverflow.com/questions/79413756/regex-a-string-with-a-space-between-words | import re texto = "ABC ABC. ABC.png ABC thumb.png" regex = r"ABC(?!.png)|ABC(?! thumb.png)" novo = re.sub(regex, "bueno", texto) print(novo) I'm trying to replace the ABC word with exceptions. I only want to replace it if it doesn't follow the word ".png" or " thumb.png". The string would be then "ABC thumb.png" I exp... | Starting with your original pattern: ABC(?!\.png)|ABC(?! thumb\.png) (Note: Dot is a regex metacharacter and should be escaped with backslash) This will match ABC which is not followed by .png or ABC not followed by thumb.png. Every possible occurrence of ABC will match this pattern. Therefore, all occurrences of ABC... | 8 | 8 |
79,414,138 | 2025-2-5 | https://stackoverflow.com/questions/79414138/using-a-dict-for-caching-async-function-result-does-not-use-cached-results | BASE_URL = "https://query2.finance.yahoo.com/" DATA_URL_PART = "v8/finance/chart/{ticker}" async def fetch_close_price(aiosession: aiohttp.ClientSession, ticker: str, start: datetime, end: datetime, ticker_price_dict): params = { 'period1': int(to_midnight(start, naive=False).timestamp()), 'period2': int(to_midnight(en... | For sure the simplest solution is to adopt the comment of @deceze and just ensure that your list of tickers has no duplicates, When that is not practical for whatever reason, then the following technique can be used: When fetch_close_price discovers that the ticker price is not in the cache, it will go ahead and make t... | 1 | 3 |
79,412,706 | 2025-2-4 | https://stackoverflow.com/questions/79412706/whats-going-on-with-the-chaining-in-pythons-string-membership-tests | I just realized I had a typo in my membership test and was worried this bug had been causing issues for a while. However, the code had behaved just as expected. Example: "test" in "testing" in "testing" in "testing" This left me wondering how this membership expression works and why it's allowed. I tried applying some... | in is a comparison operator. As described at the top of the section in the docs you linked to, all comparison operators can be chained: Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, excep... | 2 | 2 |
79,412,615 | 2025-2-4 | https://stackoverflow.com/questions/79412615/understanding-and-fixing-the-regex | I have a regex on my input parameter: r"^(ABC-\d{2,9})|(ABz?-\d{3})$" Ideally it should not allow parameters with ++ or -- at the end, but it does. Why is the regex not working in this case but works in all other scenarios? ABC-12 is a valid. ABC-123456789 is a valid. AB-123 is a valid. ABz-123 is a valid. | The problem is that your ^ and $ anchors don't apply to the entire pattern. You match ^ only in the first alternative, and $ only in the second alternative. So if the input matches (ABC-\d{2,9}) at the beginning, the match will succeed even if there's more after this. You can put a non-capturing group around everything... | 1 | 8 |
79,411,167 | 2025-2-4 | https://stackoverflow.com/questions/79411167/how-to-use-the-apply-function-to-return-a-list-to-new-column-in-pandas | I have a Pandas dataframe: import pandas as pd import numpy as np np.random.seed(150) df = pd.DataFrame(np.random.randint(0, 10, size=(10, 2)), columns=['A', 'B']) I want to add a new column "C" whose values are the combined-list of every three rows in column "B". So I use the following method to achieve my needs, b... | You can use numpy's sliding_window_view: from numpy.lib.stride_tricks import sliding_window_view as swv N = 3 df['C'] = pd.Series(swv(df['B'], N).tolist(), index=df.index[N-1:]) Output: A B C 0 4 9 NaN 1 0 2 NaN 2 4 5 [9, 2, 5] 3 7 9 [2, 5, 9] 4 8 3 [5, 9, 3] 5 8 1 [9, 3, 1] 6 1 4 [3, 1, 4] 7 4 1 [1, 4, 1] 8 1 9 [4, ... | 5 | 8 |
79,437,687 | 2025-2-13 | https://stackoverflow.com/questions/79437687/typeerror-asyncclient-init-got-an-unexpected-keyword-argument-proxies | Error: File "/app/.venv/lib/python3.11/site-packages/anthropic/_client.py", line 386, in __init__ super().__init__( File "/app/.venv/lib/python3.11/site-packages/anthropic/_base_client.py", line 1437, in __init__ self._client = http_client or AsyncHttpxClientWrapper(^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.venv/lib/python3... | Just upgrade anthropic to the latest version, the problem was fixed in version 0.45.2 and above. | 1 | 0 |
79,445,863 | 2025-2-17 | https://stackoverflow.com/questions/79445863/how-can-i-prevent-the-telemetry-client-instance-id-changed-from-aaaaaaaaaaaaaaa | When the consumer (which is a very simple confluent-kafka-python consumer), we see this log message after the assignment %6|1739802885.947|GETSUBSCRIPTIONS|<consumer id>#consumer-1| [thrd:main]: Telemetry client instance id changed from AAAAAAAAAAAAAAAAAAAAAA to <some random string> I tried running the consumer loca... | As per my previous comment, from confluent_kafka import Consumer conf = { 'bootstrap.servers': 'your broker', 'group.id': 'your group', 'enable.metrics.push': False } consumer = Consumer(conf) | 2 | 1 |
79,443,450 | 2025-2-16 | https://stackoverflow.com/questions/79443450/regex-for-ip-address-domain-and-url | Problem statement: I am trying to generate regex for ip-address, domain and url. These are my defitions: IP Address: 93.114.205.169 Domain: example.com sub.example.com Url: 93.114.205.169/path example.com/path sub.example.com/path So, an url always has a path to resource. But an IP-Address or domain should not have ... | Some Details Are Not Clear The "code" that you posted is not Python but rather appears to be some sort of configuration file. Without understanding how the input is being processed with this configuration, it is difficult to give you a precise answer. An example will illustrate this: It appears based on your English la... | 2 | 1 |
79,436,039 | 2025-2-13 | https://stackoverflow.com/questions/79436039/how-to-plot-polygons-from-categorical-grid-points-in-matplotlib-phase-diagram | I have a dataframe that contains 1681 evenly distributed 2D grid points. Each data point has its x and y coordinates, a label representing its category (or phase), and a color for that category. x y label color 0 -40.0 -30.0 Fe #660066 1 -40.0 -29.0 Fe #660066 2 -40.0 -28.0 FeS #ff7f50 3 -40.0 -27.0 FeS #ff7f50 4 -40.... | I am not sure if you can easily get a representation with contiguous polygons, however you could easily get the bounding polygon from a set of points using shapely.convex_hull: import shapely import matplotlib.pyplot as plt f, ax = plt.subplots(figsize=(8, 8)) for (name, color), coords in df.groupby(['label', 'color'])... | 9 | 12 |
79,428,750 | 2025-2-11 | https://stackoverflow.com/questions/79428750/python-multiprocessing-function-multiple-parameters | trying to run a function with 'X' cores simultaneously that has multiple parameters. with PROCESS I cant set the number of cores, and with POOL I cant set multiple parameters for a function. def funct(a, b): #run .bat file with params (a,b) if __name__ == '__main__': cores = int(cores) #set with input pool = Pool(proce... | Note - Multiprocessing.py doesn't work in IDLE, you have to use software like intellij or something. def funct(a, b): #run .bat file with params (a,b) if __name__ == "__main__": # run as many cores as in the range processes = [] for _ in range(4): p = multiprocessing.Process(target=funct, args=[2, "hello"]) p.start() p... | 1 | 0 |
79,432,064 | 2025-2-12 | https://stackoverflow.com/questions/79432064/image-preprocessing-to-extract-2d-number-list | I've been tring to make a puzzle solving program. The game is 'fruit box' and you can play it through the link below. https://en.gamesaien.com/game/fruit_box/ To do that, I have to extract numbers from game screen fruit box game screen shot I found 'pytesseract' which is able to identify characters from image, and almo... | My guess is that page segmentation mode 6 expects a true "block" of text and gets a bit nervous when seeing so much whitespace, so it decides to hallucinate a bit. Let's give it a hand by removing the whitespace and leave no more room for hallucinations: # [your code up to flood fill] # let the letters bleed out a bit... | 2 | 1 |
79,446,809 | 2025-2-17 | https://stackoverflow.com/questions/79446809/transpose-pitch-down-an-octave | Using music21, how can I transpose a pitch down an octave? If I use p.transpose(-12), flats get changed to sharps: import music21 p = music21.pitch.Pitch('D-4') print(p.transpose(-12)) output C#3 | Instead of -P12, use -P8, like this: import music21 p = music21.pitch.Pitch('D-4') print(p.transpose('-P8')) | 1 | 1 |
79,443,615 | 2025-2-16 | https://stackoverflow.com/questions/79443615/creating-a-adjecency-matrix-fast-for-use-in-path-finding-to-calculate-gird-dista | Goal I'm working on a project that requires me visualize how far a given budget can reach on a map with different price zones. Example with 3 price zones, water, countryside, and city, each having different costs per meter traveled: Red point is the origin, green point is just a sample point, it has no bearing on the ... | The complexity of this code seems fine. The main issue is that your code is a pure-Python code: it is not vectorized (i.e. it does not spent most of its time in fast native functions). As a result, it is very slow because Python codes are generally executed using the CPython interpreter. The key to fix this issue is to... | 1 | 2 |
79,444,392 | 2025-2-17 | https://stackoverflow.com/questions/79444392/how-does-pypy-implement-integers | CPython implements arbitrary-precision integers as PyLongObject, which extends PyObject. On 64-bit platforms they take at least 28 bytes, which is quite memory intensive. Also well-known is that it keeps a cache of small integer objects from -5 to 256. I am interested in seeing how PyPy implements these, in particular ... | The PyPy docs mention a tagged pointer optimization as something that you need to enable explicitly, and it's never enabled by default because it comes with a large performance cost. Instead, the story is: There are two different internal representations, one for 64-bit signed integers and one for larger integers. Th... | 2 | 2 |
79,444,122 | 2025-2-16 | https://stackoverflow.com/questions/79444122/how-can-i-save-the-32x32-icon-from-a-ico-file-that-has-the-highest-color-depth | I'm trying to extract and save the 32x32 icon from a .ico file that contains multiple icons with multiple sizes and color depths using Pillow. The 32x32 icon is available in the following color depths: 32-bit, 8-bit and 4-bit. I tried opening the icon file using Image.open(), then set its size to 32x32, and then save i... | WHile an ICO image loaded in PIL provide access to the individual images through the img.ico.frame call, there is one problem: upon loading, PIL will convert all loaded individual frames which are indexed into the RGBA format. Fortunately, it will preserve a bpp attribute listing the original bitcount for each frame in... | 3 | 3 |
79,437,928 | 2025-2-13 | https://stackoverflow.com/questions/79437928/override-property-from-wrapper-class | I have a class A with a property prop and a method method that uses this property: class A: @property def prop(self) -> int: return 1 def method(self) -> int: return self.prop * 2 # Uses self.prop Then I have a wrapper class that tries to override this property like this: class B: def __init__(self, a: A): self._a = a... | You can test if the attribute obtained from _a is a method and re-bind the underlying function (accessible via the __func__ attribute) to the B instance so that the method can have access to B's properties: from inspect import ismethod class B: def __getattr__(self, attr): value = getattr(self._a, attr) if ismethod(val... | 1 | 2 |
79,446,667 | 2025-2-17 | https://stackoverflow.com/questions/79446667/pandas-shifting-columns-to-a-specific-column-position | I have a simple dataframe: data = [[2025, 198237, 77, 18175], [202, 292827, 77, 292827]] I only want the 1st and 4th columns and I don't want header or index labels: df = pd.DataFrame(data).iloc[:,[0,3]] print(df.to_string(index=False, header=False)) Output is the following: 2025 18175 202 292827 How do I line up my... | Define a formatting function with a single arg and apply to relevant columns import pandas as pd mw=7 def left_align(x): return f"{x: <{mw}}" data = [[2025, 198237, 77, 18175], [202, 292827, 77, 292827]] df = pd.DataFrame(data).iloc[:,[0,3]] # get length of max value mw = len(str(df.max(numeric_only=True).max())) #prin... | 1 | 1 |
79,439,971 | 2025-2-14 | https://stackoverflow.com/questions/79439971/pandas-only-select-rows-containing-a-substring-in-a-column | I'm using something similar to this as input.txt header 040525 $$$$$ 9999 12345 random stuff 040525 $$$$$ 8888 12345 040525 $$$$$ 7777 12345 random stuff 040525 $$$$$ 6666 12345 footer Due to the way this input is being pre-processed, I cannot correctly use pd.read_csv. I must first create a list from the input; Then,... | data_list = [] with open('input.txt', 'r') as data: for line in data: #create split_row to check split_row = line.strip().split() #check if the second substring in split_row starts with "*****" if split_row[1].startswith("*****"): data_list.append(split_row) df = pd.DataFrame(data_list) | 1 | 1 |
79,446,382 | 2025-2-17 | https://stackoverflow.com/questions/79446382/negative-lookahead-regex-in-re-subn-context | I am trying to use regular expressions to replace numeric ranges in text, such as "4-5", with the phrase "4 to 5". The text also contains dates such as "2024-12-26" that should not be replaced (should be left as is). The regular expression (\d+)(\-)(\d+) (attempt one below) is clearly wrong, because it falsely matches ... | You need both a negative lookbehind and a negative lookahead, to prohibit an extra hyphen before or after the match. (?<![-\d])(\d+)-(\d+)(?![-\d]) The lookarounds also have to match digits, so it won't match part of the date, e.g. 024-1 from 2024-12-26. | 3 | 3 |
79,446,265 | 2025-2-17 | https://stackoverflow.com/questions/79446265/python-dataclassesslots-true-breaks-super | Consider the following code. I have a base and derived class, both dataclasses, and I want to call a method of the base class in the derived class via super(): import abc import dataclasses import typing SLOTS = False @dataclasses.dataclass(slots=SLOTS) class Base: @abc.abstractmethod def f(self, x: int) -> int: return... | WHen one uses the slots=True option on dataclasses, it will create a new class using the namespace of the decorated class - while not passing it makes it modify the class "in place". (This is needed because using slots really change how the class is built - its "layout" as it is called) The simplest thing to do is not ... | 1 | 2 |
79,445,857 | 2025-2-17 | https://stackoverflow.com/questions/79445857/pandas-dataframe-returning-only-1-column-after-creating-from-a-list | I'm using something similar to this as input.txt 040525 $$$$$ 9999 12345 040525 $$$$$ 8888 12345 040525 $$$$$ 7777 12345 040525 $$$$$ 6666 12345 Due to the way this input is being pre-processed, I cannot correctly use pd.read_csv. I must first create a list from the input; Then, create a DataFrame from the list. data... | In your loop, you should split the strings into a list of substrings for the fields: for line in input_txt: data_list.append(line.strip().split()) This will give you the correct number of columns. Alternatively, keep your loop as it is, but create a Series and str.split with expand=True. This might be less efficient, ... | 1 | 1 |
79,445,156 | 2025-2-17 | https://stackoverflow.com/questions/79445156/how-to-apply-a-function-to-all-possible-tuples-of-two-groups-obtained-by-groupby | I am grouping my data as below: all_groups = df.groupby('age').groups Printing all_groups shows: {1.0: [11, 14, 15, 22], 2.0: [12, 13, 27], 3.0: [16, 17, 19, 20, 23, 24], 6.0: [21], 7.0: [18, 25, 26], 11.0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]} Now I want to run stats.mannwhitneyu on all possible combinations of two cl... | You could compute a GroupBy object, then apply your test on all combinations: from itertools import combinations from scipy.stats import mannwhitneyu groups = df.groupby('age')['value'] out = pd.DataFrame.from_dict({(a[0], b[0]): mannwhitneyu(a[1], b[1]) for a, b in combinations(groups, 2)}, orient='index') Example: ... | 3 | 5 |
79,443,938 | 2025-2-16 | https://stackoverflow.com/questions/79443938/reading-excel-data-and-named-ranges-into-python-script | I am new to Python but have used Excel and named ranges for some time. I have a football workbook, several worksheets, with several named ranges for team name, colors, plays, rules, formations, etc. The workbook is used to create a wristband for football players. I have userforms and sheet change code that handles vari... | Python is fine to use with Excel and maybe even easier to use than VBA in some instances. It probable that the most issue would be converting a python script to an exe if that indeed is what you want at the end. There are two methods of working with Excel in Python, apart from Python in Excel which is running Python in... | 2 | 2 |
79,435,219 | 2025-2-13 | https://stackoverflow.com/questions/79435219/cannot-apply-operator-between-seriesfloat-and-float | I'm developing an indicator in Indie. I’m trying to calculate Bollinger Bands and Keltner Channels, but I’m running into an error when adding a Series[float] to a float value. Here’s the error message: Error: 20:20 cannot apply operator + to operands of types: <class 'indie.Series[float]'> and <class 'float'> Here’s ... | The problem is that you cannot add a Series container with a float number, you must extract a specific value from the Series and perform an arithmetic operation with it. You can extract the value from the Series using square brackets mid_line_bb[0] or using the get method mid_line_bb.get(offset=0, default=0). The sourc... | 2 | 1 |
79,442,836 | 2025-2-16 | https://stackoverflow.com/questions/79442836/python-asyncio-not-able-to-run-the-tasks | I am trying to test python asyncio and aiohttp. Idea is to fetch the data from API parallely and store the .html file in a local drive. Below is my code. import asyncio import aiohttp import time import os url_i = "<some_urls>-" file_path = "<local_drive>\\asynciotest" async def download_pep(pep_number: int) -> bytes: ... | The error occurs because you're passing raw coroutines to asyncio.wait() instead of scheduling them as tasks. All you have to do is wrap your web_scrape_task() call inside main() with asyncio.create_task(), like so: async def main() -> None: tasks = [] for i in range(8010, 8016): tasks.append(asyncio.create_task(web_sc... | 2 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.