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
78,149,918
2024-3-12
https://stackoverflow.com/questions/78149918/split-record-into-two-records-with-a-calculation-based-on-condition
As title says, Let's say I have following dataframe import pandas as pd df = pd.DataFrame({'UID':['A','B','C','D'],'FlagVal':[0,100,50,90],'TrueVal':[1000,1000,1000,1000]}) ndf = df.loc[~df['FlagVal'].between(0,100,inclusive='neither')] mdf = df.loc[df['FlagVal'].between(0,100,inclusive='neither')] I want to split rec...
You can create split_df in two steps (this will be very fast): # create the 100% part: mdf_100 = pd.DataFrame({"TrueVal": mdf["FlagVal"].div(100) * mdf["TrueVal"]}).assign( FlagVal=100, UID=mdf["UID"] + "_T1", Flag="Y" ) # create the 0% part: mdf_0 = pd.DataFrame( {"TrueVal": (1 - mdf["FlagVal"].div(100)) * mdf["TrueVa...
2
1
78,149,859
2024-3-12
https://stackoverflow.com/questions/78149859/is-there-a-way-to-integrate-vector-embeddings-in-a-langhcain-agent
I'm trying to use the Langchain ReAct Agents and I want to give them my pinecone index for context. I couldn't find any interface that let me provide the LLM that uses the ReAct chain my vector embeddings as well. Here I set up the LLM and retrieve my vector embedding. llm = ChatOpenAI(temperature=0.1, model_name="gpt-...
You can specify the retriever as a tool for the agent. Example: from langchain.tools.retriever import create_retriever_tool retriever = vector_store.as_retriever(search_type='similarity', search_kwargs={'k': k}) retriever_tool = create_retriever_tool( retriever, "retriever_name", "A detailed description of the retrieve...
2
2
78,149,546
2024-3-12
https://stackoverflow.com/questions/78149546/multiindex-dataframe-to-a-standard-index-df
How do I convert a MultiIndex DataFrame to a Standard index DF? import pandas as pd df1 = pd.DataFrame({'old_code': ['00000001', '00000002', '00000003', '00000004'], 'Desc': ['99999991', '99999992 or 99999922', 'Use 99999993 or 99999933', '99999994']}, ) df1.set_index('old_code', inplace=True) df2=df1["Desc"].str.extra...
You can drop the second level index and then reset the index: print(df2.droplevel(1).reset_index()) Prints: old_code new_code 0 00000001 99999991 1 00000002 99999992 2 00000002 99999922 3 00000003 99999993 4 00000003 99999933 5 00000004 99999994
2
1
78,149,052
2024-3-12
https://stackoverflow.com/questions/78149052/in-a-dataframe-how-can-i-find-if-each-row-number-appears-in-a-column-of-lists
Given a data frame, I need to create a new column 'flag' which will have value True in row i if i is not in any of the lists in column 'id' and False otherwise. For the example below, flag for rows 1, 3, 5, and 6 should be True. I attempt it with lambda, but cannot get it work. import pandas as pd pos = pd.DataFrame(co...
With (~)isin/explode: pos["flag"] = ~pos.index.isin(pos["id"].explode()) # .astype(int) ? Output : id pred flag 1 [4, 4] NaN True 2 [2] NaN False 3 [2, 4] NaN True 4 [2] NaN False 5 [2, 4] NaN True 6 [4] NaN True [6 rows x 3 columns]
3
3
78,148,461
2024-3-12
https://stackoverflow.com/questions/78148461/how-do-i-create-a-preface-page-before-the-title-page-in-quarto
I am using quarto, python, and jupyter lab/notebook to be able to create reproducible reports. Our reports include a preface page before the title page with additional information about what is included in the report. So, how do I place content before the title page? The final document will be a .pdf. After much googli...
Yes, you need to use before-body.tex latex template partials. Include your preface contents before the title. before-body.tex $if(has-frontmatter)$ \frontmatter $endif$ % ----------- PREFACE ---------- \begin{center} \Large{Preface} \end{center} Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut vulputate bibe...
3
2
78,134,640
2024-3-10
https://stackoverflow.com/questions/78134640/polars-expanding-window-at-fixed-points
I have a Polars dataframe with 3 columns - group, date, value. The goal is to calculate cumsum(value) for each expanding window ends at the first time point at each year for each group. For example, for the following sample dataframe: import polars as pl df = pl.DataFrame( { "date": [ "2020-03-01", "2020-05-01", "2020-...
A "naive" approach could be to calculate the full cum_sum and then keep the first yearly row of each group. df.with_columns( cum_sum = pl.col("value").cum_sum().over("group") ).filter( pl.col("date").dt.year().is_first_distinct().over("group") ) shape: (6, 4) ┌────────────┬───────┬───────┬─────────┐ │ date ┆ group ┆ v...
3
4
78,146,458
2024-3-12
https://stackoverflow.com/questions/78146458/strategy-to-make-django-models-with-lots-of-memberfunctions-more-manageable
I have a huge model because of its many member functions. I would like to organize the functions into separate classes according to their purpose, so everything is a bit more organized. Using OneToOneField is not a good option for me, because my app heavily relies on query caching (with cacheops). And I noticed that ge...
I have a huge model because of its many member functions. I would like to organize the functions into separate classes according to their purpose, so everything is a bit more organized. Probably the best way would be to work with a proxy, like: class FunctionCategory(type): def __get__(self, obj, objtype=None): retur...
2
2
78,147,903
2024-3-12
https://stackoverflow.com/questions/78147903/how-to-create-a-conditional-incremented-column-in-polars
I'd like to create a conditional incremented column in polars. It should start from 1 and increment only if a certain condition (pl.col('code') == 'L') is met. import polars as pl df = pl.DataFrame({'file': ['a.txt','a.txt','a.txt','a.txt','b.txt','b.txt','c.txt','c.txt','c.txt','c.txt','c.txt'], 'code': ['X','Y','Z',...
Not sure which output exactly you're expecting, but here's an example of incrementing the counter only at rows which meet the criteria, using cum_sum(): df.with_columns( pl.when(pl.col('code') == 'L').then(pl.lit(1)).otherwise(pl.lit(0)).alias('rrr') ).with_columns( pl.col('rrr').cum_sum().over('file') + 1 ) ┌───────┬─...
2
1
78,147,344
2024-3-12
https://stackoverflow.com/questions/78147344/how-to-get-the-number-of-the-row-that-contains-a-specific-value-in-the-given-col
I need to get the number of the row that contains a specific value in the given column. It is guaranteed that such value exists in the column and in a unique row. My attempt: import pandas as pd pos = pd.DataFrame(columns=['id', 'pred']) pos.loc[1,'id'] = [4, 4, 4] pos.loc[2,'id'] = [2, 3, 3] pos.loc[3,'id'] = [1, 1, 2...
You need to loop. If you want the position: next(i for i, x in enumerate(pos['id']) if [1,1,2] == x) Output: 2 Or, to have the index: next(i for i, x in zip(pos.index, pos['id']) if [1,1,2] == x) Output: 3
4
3
78,145,973
2024-3-12
https://stackoverflow.com/questions/78145973/bug-in-large-sparse-csr-binary-matrices-multiplication-result
This boggles my mind, is this a known bug or am I missing something? If a bug is there a way to circumvent it? Suppose I have a relatively small binary (0/1) n x q scipy.sparse.csr_matrix, as in: import numpy as np from scipy import sparse def get_dummies(vec, vec_max): vec_size = vec.size Z = sparse.csr_matrix((np.on...
You are using uint8 in get_dummies print(Z.dtype, (Z.T @ Z)[:5, :5].dtype) # uint8, uint8 So the result is overflowing. The pattern is because the result is the true result modulo 256. If you change the dtype to uint16, the problem disappears. The fact that sum increases the precision of the dtype is a bit surprising,...
2
2
78,140,395
2024-3-11
https://stackoverflow.com/questions/78140395/python-function-compatible-with-sync-and-async-client
I'm developing a library that should support sync and async users while minimizing code duplication inside the library. The ideal case would be implementing the library async (since the library does remote API calls) and adding support for sync with a wrapper or so. Consider the following function as part of the librar...
Do not try to be too flexible or solve problems that yet not occurred. That would make your life harder and potentially your code more complex to develop and maintain and in result not really that flexible as you'd have thought. It's nothing wrong to not babysit fellow developers and let them take some bit of responsib...
3
4
78,144,684
2024-3-12
https://stackoverflow.com/questions/78144684/how-to-find-closed-objects-among-an-array-of-lines
I have a list of tuples. Each tuple contains coordinate points (x, y, x1, y1,...) forming a line. All these lines form a drawing. There are 5 closed objects in this picture. How can I get the number of these objects with their coordinates? Coordinates_list = [(939, 1002, 984, 993, 998, 1001, 1043, 995, 1080, 1004, 110...
Here is a condensed version of Grismar's answer, where he has a good explanation as well. I just removed the manual search for segments and treated each point as a node directly. import networkx as nx lines = [ (939, 1002, 984, 993, 998, 1001, 1043, 995, 1080, 1004, 1106, 994, 1147, 1003, 1182, 995, 1223, 1005), (939, ...
3
2
78,143,341
2024-3-11
https://stackoverflow.com/questions/78143341/explode-a-polars-dataframe-column-without-duplicating-other-column-values
As a minimum example, let's say we have next polars.DataFrame: df = pl.DataFrame({"sub_id": [1,2,3], "engagement": ["one:one,two:two", "one:two,two:one", "one:one"], "total_duration": [123, 456, 789]}) sub_id engagement total_duration 1 one:one,two:two 123 2 one:two,two:one 456 3 one:one 789 then, we expl...
An option to handle this in polars would be to split total_duration equally between engagement rows within sub_id. For this, we simply divide total_duration by the number of rows of the given sub_id. ( df .with_columns( pl.col("engagement").str.split(",") ) .explode("engagement") .with_columns( pl.col("total_duration")...
6
3
78,144,401
2024-3-12
https://stackoverflow.com/questions/78144401/how-could-i-handle-superclass-and-subclass-cases
Problem statement: I have 100s of py files which defines pydantic schema. Suddenly I need to treat empty string as None. I am expecting minimal changes across all the files. Approach I implemented: I created an inherited class such as class ConstrainedStr(str): @classmethod def __get_validators__(cls): yield cls.valida...
While an instance of a subclass is automatically an instance of the base class, the reverse isn't true. This is analogous to that every cat is a mammal, but not every mammal is a cat. Similarly, since ConstrainedStr is a subclass of str, an instance of the child class ConstrainedStr is automatically an instance of the ...
3
3
78,143,771
2024-3-11
https://stackoverflow.com/questions/78143771/polars-replacing-the-first-n-rows-with-certain-values
In Pandas we can replace the first n rows with certain values: import pandas as pd import numpy as np df = pd.DataFrame({"test": np.arange(0, 10)}) df.iloc[0:5] = np.nan df out: test 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 5.0 6 6.0 7 7.0 8 8.0 9 9.0 What would be the equivalent operations in Python Polars?
You can use DataFrame.with_row_index(): import polars as pl df = pl.DataFrame({"test": np.arange(1, 11)}) print( df.with_row_index() .with_columns( pl.when(pl.col("index") < 5) .then(None) .otherwise(pl.col("test")) .alias("test") ) .drop("index") ) Prints: shape: (10, 1) ┌──────┐ │ test │ │ --- │ │ f64 │ ╞══════╡ │ N...
3
3
78,143,178
2024-3-11
https://stackoverflow.com/questions/78143178/how-to-check-multiple-items-for-nullity-in-an-and-fashion-in-python
I was wondering if there's a Pythonic/hacky way to check for all (or none) items and dependencies in a set to be null. Suppose I have a variable foo that is a dict, but can be nullable: foo: Optional[dict] = None And I want to check that both foo is not None or one of its keys: if foo is not None and foo.get('bar') is...
Simply separate the foo from all the foo.gets and use an and: if foo is not None and all(foo.get(key) is not None for key in ('bar', 'baz')): You can also use key in foo to check if the key exists in the dictionary, this is actually safer because if the key exists and has a value of None in the dictionary, then using ...
2
3
78,141,652
2024-3-11
https://stackoverflow.com/questions/78141652/pandas-remove-rows-with-only-one-type-of-value-repeated-or-not
I am trying to remove rows whose all values are the same, or a combination of the same values. I have, for example a dataframe like: data = {'A': ['1, 1, 1', '1', '2', '3', '1'], 'B': ['1', '1,1,1,1', '2', '4', '1'], 'C': ['1, 1', '2', '3', '5', '1']} I want to remove rows whose values in all columns are '1' or any co...
You could convert to string and check if each cell contains a character other than 1 (or space/comma), if at least one True, keep the row: out = df[df.apply(lambda s: s.astype(str).str.contains('[^1 ,]')).any(axis=1)] Or, with your original idea of splitting the strings on ', ': import re out = df[~df.applymap(lambda ...
2
2
78,140,607
2024-3-11
https://stackoverflow.com/questions/78140607/how-to-relate-list-items-from-two-pandas-dataframe-columns
I have a DataFrame that contains two columns composed by lists. One column has the categories of certain item, the other column has the points associated to this category. import pandas as pd cat = [ ['speed', 'health', 'strength', 'health'], ['strength', 'speed', 'speed'], ['strength', 'speed', 'health', 'speed'] ] pt...
Try: def pos(vals): return (vals > 0).sum() def neg(vals): return (vals < 0).sum() tmp = df.explode(["cat", "pts"]) tmp = tmp.pivot_table( index=tmp.index, columns="cat", values="pts", aggfunc=["sum", pos, neg], ) tmp.columns = [f"{b}_{a}" for a, b in tmp.columns] out = pd.concat([df, tmp], axis=1) print(out) Prints: ...
2
3
78,140,231
2024-3-11
https://stackoverflow.com/questions/78140231/vscode-pylance-false-positive-reaction-on-importerror
I am trying to write cross-platform app in python. I want to use uvloop (only if possible), using this code: import asyncio try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass However, pylance shows message that "Import "uvloop" could not be resolved" in Windows (because...
Set an inline ignore statement: import asyncio try: import uvloop # type: ignore asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass It'd be better to be more specific with the rule you want to ignore. The above will ignore all type checking errors. https://github.com/microsoft/pylance-rel...
2
2
78,122,541
2024-3-7
https://stackoverflow.com/questions/78122541/unexpected-keyword-argument-use-dora-when-attempting-to-generate-summary-from
I have fine-tuned a Mistral7B LLM using LoRA in 16 bit configuration using samsum training set from Hugginggace. The idea is to feed the fine-tuned LLM a conversation an it should generate a summary. here is my trining script: # set the train & validation data set from datasets import load_dataset train_dataset = load_...
I had the same issue, simply upgrading the peft library to the latest version solved the problem for me.
2
3
78,130,914
2024-3-9
https://stackoverflow.com/questions/78130914/fill-null-in-polars-dataframe-by-sampling-the-rest-of-the-column
How would you fill_null in a DataFrame by sampling the rest of the column for a unique value each time a null is occurred? Example: Suppose I have this DataFrame: >>> daf=pl.DataFrame({"a":[1,2, None, None, 5, 6, None, None, None, 10], "b":[None, "two", "three", None, "five", "six", "seven", None, "nine", "ten"]}) >>> ...
Solution This seems to work. It's based on your original idea, it just does the same operations to each column purely with expressions. daf.select( pl.col("*").fill_null( pl.col("*").drop_nulls().sample(pl.len(), with_replacement=True) ) ) ┌─────┬───────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ str │ ╞═════╪═══════╡ │ 1 ┆ two...
2
2
78,118,265
2024-3-7
https://stackoverflow.com/questions/78118265/efficiently-calculate-angle-between-three-points-over-triplets-of-rows-in-a-nump
Suppose we have a numpy array A of size M x N which we interpret as M vectors of dimension N. For three vectors a,b,c we'd like to compute the cosine of the angle they form: cos(angle(a,b,c)) = np.dot((a-b)/norm(a-b), (c-b)/norm(c-b)) We want to compute this quantity over triplets of A, of which there should be (M cho...
of which there should be (M choose 2)*(M-2) unique triplets (by symmetry of a and c; please correct me if I'm wrong on this) I think that's right. I counted M * ((M-1) choose 2), and that's equivalent. I am hoping someone can furnish a recipe that computes exactly the unique quantities, preferably without extra comp...
2
4
78,132,690
2024-3-9
https://stackoverflow.com/questions/78132690/strange-base64-python-decoding
From a stream of TCP segments, I pulled binary data with the help of wireshark, which I later found out is a bmp file. Then I load one big line of binary data, clear it from spaces, newline character and intermediate "=". I mean their separation at the end of each TCP segment. Then I execute the following code: import ...
Using this script, I get an uncorrupted image shown: import io from pathlib import Path import yaml from PIL import Image packets = yaml.safe_load(Path("5bksih1B.txt").read_text()) raw = b"".join([p["data"] for p in packets]) im = Image.open(io.BytesIO(raw)) im.show() There are two 320x240 images in the full data you ...
2
5
78,122,836
2024-3-7
https://stackoverflow.com/questions/78122836/difference-between-numpy-power-and-for-certain-values
I have a numpy array where the entries in f**2 differ from f[i]**2, but only for some specific value. import numpy as np np.set_printoptions(precision = 16) f = np.array([ -40709.6555510835, -40708.6555510835, -33467.081758611654, -27653.379955714125]) f2 = f**2 # f2 = np.power(f,2) print("outside loop", np.abs(f[1]**2...
The results are different because f**2 calls numpy.square, while f[0]**2 and numpy.power(f, 2) call numpy.power. numpy.ndarray.__pow__ is written in C. It looks like this: static PyObject * array_power(PyObject *a1, PyObject *o2, PyObject *modulo) { PyObject *value = NULL; if (modulo != Py_None) { /* modular exponenti...
10
6
78,128,890
2024-3-8
https://stackoverflow.com/questions/78128890/pandas-dataframe-title-caption-in-plain-text-to-string-output
As an example: import pandas as pd df = pd.DataFrame({ "Hello World": [1, 2, 3, 4], "And Some More": [10.0, 20.0, 30.0, 40.0], }) df_caption = "Table 1: My Table" df.style.set_caption(df_caption) # only works for HTML; https://stackoverflow.com/q/57958432 with pd.option_context('display.max_rows', None, 'display.max_co...
DataFrame.style has a specific use that does not relate to printing DataFrames in the console. From the code documentation: Contains methods for building a styled HTML representation of the DataFrame. DataFrame.to_string() has many attributes, but none of them relate to displaying a caption or a name. It does take...
3
1
78,130,743
2024-3-8
https://stackoverflow.com/questions/78130743/parsing-a-csv-file-to-add-details-to-xml-file
Ned help to parse a csv file which has following details to xml file csv file is in the following format: name,ip,timeout domain\user1,10.119.77.218,9000 domain\user2,2.80.189.26,9001 domain\user3,4.155.10.110,9002 domain\user4,9.214.119.86,9003 domain\user5,4.178.187.27,9004 domain\user6,3.76.178.117,9005 The above d...
If the structure of CSV/XML file is simple you can use csv module and construct the string directly (for more complicated scenarios I recommend lxml/bs4 modules): import csv with open("your_data.csv", "r") as f: reader = csv.reader(f) header = next(reader) data = list(reader) out = ["<login>"] for line in data: s = " "...
3
1
78,130,544
2024-3-8
https://stackoverflow.com/questions/78130544/groupby-as-list-into-new-column
How can I aggreate all product names of the grouped dataframe into a new column as list or set: import pandas as pd # 2.0.3 df = pd.DataFrame( { "customer_id": [1, 2, 3, 2, 1], "order_id": [1, 2, 3, 4, 1], "products": ["foo", "bar", "baz", "foo", "bar"], "amount": [1, 1, 1, 1, 1] } ) print(df) grouped = df.groupby(["cu...
You could use transform with a function that returns something that is the same length with the group: df["all_products"] = grouped["products"].transform(lambda x: [list(x)]*len(x)) Output: customer_id order_id products amount product_order_count all_products 0 1 1 foo 1 2 [foo, bar] 1 2 2 bar 1 1 [bar] 2 3 3 baz 1 1...
2
2
78,130,203
2024-3-8
https://stackoverflow.com/questions/78130203/pandas-make-list-size-in-a-column-same-as-in-another-column
I have two columns: serial_number and inv_number containing lists. If there is one inv_number for multiple serial_number, I need to make the size of inv_number's list the same as serial_number's. serial_number inv_number 28 [С029768, С029775] [101040031171, 101040031172] 29 [090020960190402011, 090020960190402009] [21...
Try: mask = (df["serial_number"].str.len() > 1) & (df["inv_number"].str.len() == 1) df.loc[mask, "inv_number"] = df["serial_number"].str.len() * df.loc[mask, "inv_number"] print(df) Prints: serial_number inv_number 28 [С029768, С029775] [101040031171, 101040031172] 29 [090020960190402011, 090020960190402009] [2101340...
4
4
78,129,071
2024-3-8
https://stackoverflow.com/questions/78129071/break-wrap-long-text-of-column-names-in-pandas-dataframe-plain-text-to-string-ou
Consider this example: import pandas as pd df = pd.DataFrame({ "LIDSA": [0, 1, 2, 3], "CAE": [3, 5, 7, 9], "FILA": [1, 2, 3, 4], # 2 is default, so table idx 1 is default "VUAMA": [0.5, 1.0, 1.5, 2.0], }) df_colnames = { # https://stackoverflow.com/q/48243818 "LIDSA": "Lorem ipsum dolor sit amet", "CAE": "Consectetur a...
You could use textwrap.wrap and tabulate: # pip install tabulate from textwrap import wrap from tabulate import tabulate df_colnames_wrap = {k: '\n'.join(wrap(v, 20)) for k,v in df_colnames.items()} print(tabulate(df.rename(columns=df_colnames_wrap), headers='keys', tablefmt='plain')) Output: Lorem ipsum dolor Consec...
3
5
78,127,976
2024-3-8
https://stackoverflow.com/questions/78127976/how-to-add-new-columns-from-a-list-to-an-existing-dataframe-in-polars
I'd like to add new empty columns (elements of mylist) to an existing dataframe. This code does it: import polars as pl df = pl.DataFrame({'a': [1,2,3]}) mylist = [f'col{i}' for i in range(1,4)] data = [[''] for i in range(1,len(mylist)+1)] df.join(pl.DataFrame(data=data,schema=mylist), how='cross') But is there a mo...
You seem to be looking for pl.lit() which allows you to create an "expression" from a literal value. You can then use .alias() to choose the name. df.with_columns(pl.lit('').alias(col) for col in mylist) shape: (3, 4) ┌─────┬──────┬──────┬──────┐ │ a ┆ col1 ┆ col2 ┆ col3 │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str ┆...
4
5
78,128,662
2024-3-8
https://stackoverflow.com/questions/78128662/converting-pytorch-bfloat16-tensors-to-numpy-throws-typeerror
When you try to convert a Torch bfloat16 tensor to a numpy array, it throws a TypeError: import torch x = torch.Tensor([0]).to(torch.bfloat16) x.numpy() # TypeError: Got unsupported ScalarType BFloat16 import numpy as np np.array(x) # same error Is there a work-around to make this conversion?
Currently, numpy does not support bfloat16**. One work-around is to upcast the tensor from half-precision to single-precision before making the conversion: x.float().numpy() The Pytorch maintainers are also considering adding a force=True option to the Tensor.numpy method to this automatically. ** although that may ch...
3
4
78,128,367
2024-3-8
https://stackoverflow.com/questions/78128367/cross-merge-by-group-in-pandas
I am trying to cross merge two dataframes but limiting the merge so only combinations within the same group are provided. The pandas documentation says When performing a cross merge, no column specifications to merge on are allowed. At the moment to achieve this I'm using a for loop and concatenating the resulting dfs ...
A cross-merge by group would be equivalent to a merge on the group: out = df1.merge(df2, on='group') # if "group" is the only common column # out = df1.merge(df2) Output: group field_a field_b 0 1 apple apple 1 1 apple strawberry 2 1 pear apple 3 1 pear strawberry 4 2 banana coconut 5 2 banana papaya 6 2 papaya cocon...
2
2
78,127,307
2024-3-8
https://stackoverflow.com/questions/78127307/how-to-read-parquet-files-from-aws-s3-with-polars
Following the documentation for reading from cloud storage, I have created the below script that fails. import boto3 import polars as pl import os session = boto3.Session(profile_name=os.environ["AWS_PROFILE"]) credentials = session.get_credentials() current_credentials = credentials.get_frozen_credentials() # Specify ...
You might also need to pass the corresponding session token as follows. import polars as pl import boto3 profile_name = "your-profile" s3_path = "s3://my-s3-bucket/my_file.parquet" session = boto3.session.Session(profile_name=profile_name) credentials = session.get_credentials().get_frozen_credentials() df = pl.read_pa...
4
5
78,125,310
2024-3-8
https://stackoverflow.com/questions/78125310/how-to-calculate-mode-when-using-python-polars-in-aggregation
I am involving in a data-mining project and have some problems whiling doing feature engineering. One of my goal is to aggregate data according to the primary key, and to produce new columns. So I write this: df = df.group_by("case_id").agg(date_exprs(df,df_base)) def date_expr(df, df_base): # Join df and df_base on 'c...
In your example it fails because there's no syntactic sugar for Expr.mode() as it is for aggregate functions (for example, pl.max() is a syntactic sugar for Expr.max(). The mode() is actually not aggregation function but computation one, which means it just calculates the most occuring value(s) within the column. So, g...
4
3
78,126,235
2024-3-8
https://stackoverflow.com/questions/78126235/is-it-possible-to-exclude-first-n-values-in-each-window-when-using-rolling-to
This is my DataFrame: import pandas as pd df = pd.DataFrame({'a': [150, 106, 119, 131, 121, 140, 160, 119, 170]}) And this is the expected output. I want to create column b: a b 0 150 140 1 106 160 2 119 160 3 131 161 4 121 NaN 5 140 NaN 6 160 NaN 7 119 NaN 8 170 NaN I want to get the maximum value in a rolling wind...
The naive approach would be to use groupby.transform and drop the first item: N = 6 df['out'] = df.loc[::-1, 'a'].rolling(N).apply(lambda x: x.iloc[:-1].max()) However, since your operation is independent of this value, better compute the rolling.max on N-1 and shift after the fact. Which can simplify the code to: N =...
2
3
78,124,783
2024-3-7
https://stackoverflow.com/questions/78124783/coding-whack-a-mole-and-my-keypress-wont-register-for-the-current-mole
I'm trying to get a whack-a-mole game running for a homework assignment. The program executes fine and it generates a random mole that hops between squares. The mole is supposed to be hit using the numberpad at the reference, so 7 on the top-left and so on. However, whenever it plays, it tells me I miss every time. Wit...
There's a good deal going on here (I generally suggest minimizing your question code to isolate the issue), but the fundamental problem is using while and sleep in a turtle program. Generally, neither belong. The usual tool to implement loops and events is Screen().ontimer(). Here's a partial rewrite that cleans up a f...
4
1
78,125,526
2024-3-8
https://stackoverflow.com/questions/78125526/computeerror-with-polars-dataframe-while-trying-to-chain-expressions-in-a-single
I am trying to do a series of operations on a single column in a lazy polars DataFrame and I am trying to avoid using with_columns_seq repeatedly in doing so, but there's a ComputeError stating a duplicate column name. Is there a better alternative to this? df = ( df .with_columns_seq([ pl.col('sentiment').cast(pl.UInt...
Explanation Your error message tells you already almost everything to grasp the problem: It's possible that multiple expressions are returning the same default column name. If this is the case, try renaming the columns with .alias("new_name") to avoid duplicate column names. However, it does not in this case actually...
3
5
78,122,301
2024-3-7
https://stackoverflow.com/questions/78122301/how-to-handle-multi-line-results-of-user-defined-functions-in-polars
I'd like to parse lines of text to multiple columns and lines in polars, with user defined function. import polars as pl df = pl.DataFrame({'file': ['aaa.txt','bbb.txt'], 'text': ['my little pony, your big pony','apple+banana, cake+coke']}) def myfunc(p_str: str) -> list: res = [] for line in p_str.split(','): x = lin...
The error is likely due to the complex return type returned by the UDF. Polars quickly infers the dtype of the inner dictionaries. However, the dictionaries being evaluated later might have a different number of fields and the error is raised. A simpler reproducible example would be the following. import random import ...
2
2
78,124,238
2024-3-7
https://stackoverflow.com/questions/78124238/pydantic-non-default-argument-follows-default-argument
I don't understand why the code: from typing import Optional from pydantic import Field from pydantic.dataclasses import dataclass @dataclass class Klass: field1: str = Field(min_length=1) field2: str = Field(min_length=1) field3: Optional[str] throws the error: TypeError: non-default argument 'field3' follows default...
TL;DR field3 is a required argument with type Optional[str], not an optional argument, because you didn't assign anything to field3 in the class definition. field1 and field2 are technically optional, because the Field object you assign to each provides a default of PydanticUndefined. That value, though, causes a val...
5
3
78,124,477
2024-3-7
https://stackoverflow.com/questions/78124477/can-an-awk-file-be-executed-with-subprocess
I have 3 files all within the same directory: ex.awk data.csv file.py I want to execute my awk file using subprocess so I can call it within a PyTest testcase in the future. These are my sample files: ex.awk #!/usr/bin/awk -f BEGIN { FS = ","; } { print NF; } END {print "DONE"} data.csv 10,34,32 4,76,8304 4759,5869,...
To execute the awk script from Python on Windows where you have encountered a FileNotFoundError, it's often due to the way Windows handles file paths or the execution of Unix/Linux-specific utilities that might not be directly available in the Windows command prompt environment. So you need to provide the absolute path...
2
1
78,123,745
2024-3-7
https://stackoverflow.com/questions/78123745/python-itertools-product-challenge-to-expand-a-dict-with-tuples
Given a dictionary like this with some items being tuples... params = { 'a': 'static', 'b': (1, 2), 'c': ('X', 'Y') } I need the "product" of the items into a list of dict like this, with the tuples expanded so each item in b will be matched with each item in c... [{ 'a': 'static', 'b': 1, 'c': 'X' }, { 'a': 'static',...
product takes multiple iterables, but the key thing to remember is that an iterable can contain a single item. In cases where a value in your original dict isn't a tuple (or maybe a list), you want to convert it to a tuple containing a single value and pass that to product: params_iterables = {} for k, v in params.item...
2
3
78,120,071
2024-3-7
https://stackoverflow.com/questions/78120071/how-to-calculate-day-difference-between-rows-with-specific-conditions-in-pandas
I am a beginner of Pandas. I have a dataframe like below and want to calculate the "CV" day difference since "Visit" per "ID", as the "CV_days_after_visit" in the expected result. May I know how I can achieve this with Pandas in Python import pandas as pd data1 = {'ID': ['A2A', 'A2A', 'A2A', 'BB3', 'BB3', 'BB3', '5EE'...
You can subtract forward filling by GroupBy.ffill dates if Visit by Series.sub and convert timedeltas to days by Series.dt.days, last if necessary remove 0 days by Series.mask: #convert column to datetimes df['date'] = pd.to_datetime(df['date']) m = df['Acton'].eq('Visit') df['CV_days_after_visit'] = (df['date'].sub(df...
2
5
78,119,374
2024-3-7
https://stackoverflow.com/questions/78119374/how-do-i-dynamically-import-a-function-by-its-pythonic-path
I have a function in a submodule that normally can be imported like this: from core.somepack import my_func Instead I would like to import it lazily by a given pythonic string core.somepack.my_func. What is the best way to do it? my_func = some_function_i_am_asking_for('core.somepack.my_func') my_func()
Try using python built-in importlib module. It helps importing a module or a function at runtime when i.e the module name is not known until runtime. Here is a sample code for having a lazy import using importlib: import importlib def lazy_import(fn_path): module_path, fn_name = fn_path.rsplit('.', 1) module = importli...
2
2
78,118,100
2024-3-7
https://stackoverflow.com/questions/78118100/pandas-filter-dataframe-by-difference-between-adjacent-rows
I have the following data in a dataframe. Timestamp MeasureA MeasureB MeasureC MeasureD 0.00 26.46 63.60 3.90 0.67 0.94 26.52 78.87 1.58 0.42 1.94 30.01 82.04 1.13 0.46 3.00 30.19 82.00 1.17 0.36 4.00 30.07 81.43 1.13 0.42 5.94 30.02 82.46 1.05 0.34 8.00 30.22 82.48 0.98 0.35 9.00 30.00 82.21 1.13 ...
Try: from itertools import cycle # the interval: A, B = 1.0, 1.5 comparing, out, last_t = cycle([B, A]), [], float("-inf") j = next(comparing) for i, t in zip(df.index, df.Timestamp): if t >= last_t + j: out.append(i) last_t = t j = next(comparing) print(df.loc[out]) Prints: Timestamp MeasureA MeasureB MeasureC Measu...
3
3
78,117,898
2024-3-6
https://stackoverflow.com/questions/78117898/web-scraping-wikipedia-table-using-beautiful-soup-getting-none-returned
New to web scraping and coding in general. This is probably an easy problem for someone more experienced... maybe not... here it is: Trying to web scrape a table from wikipedia. I've located the table in the html and added that info in my code. However when I run it I get 'none' returned instead of confirmation the tab...
Remove the jquery-tablesorter from the "class" string - this class is added by javascript and beautifulsoup doesn't see it (note: always observe the real HTML document the servers sends you, that's what is beautifulsoup seeing - press ctrl-U in your browser): from urllib.request import urlopen from bs4 import Beautiful...
2
2
78,113,717
2024-3-6
https://stackoverflow.com/questions/78113717/why-python-is-running-as-32-bit-on-64-bit-windows-10-with-64-bit-python-installe
I have a Python script that runs on Windows 10 Pro x64. When I open Task Manager, it shows that Python is running as 32-bit application. This is weird because: Python 3.12.2 is installed as 64-bit variant (double-checked) Installer got from here This is the only Python instance installed on this PC Script was launc...
Your Python launcher is 32-bit, but it runs 64-bit Python interpreter.
3
2
78,116,908
2024-3-6
https://stackoverflow.com/questions/78116908/pandas-slice-3-level-multiindex-based-on-a-list-with-2-levels
Here is a minimal example: import pandas as pd import numpy as np np.random.seed(0) idx = pd.MultiIndex.from_product([[1,2,3], ['a', 'b', 'c'], [6, 7]]) df = pd.DataFrame(np.random.randn(18), index=idx) selection = [(1, 'a'), (2, 'b')] I would like to select all the rows in df that have as index that starts with any o...
You could use boolean indexing with isin: out = df[df.index.isin(selection)] Output: 0 1 a 6 1.560268 7 0.674709 2 b 6 0.848069 7 0.130719 If you want to select other levels, drop the unused leading levels: # here we want to select on levels 1 and 2 selection = [('a', 6), ('b', 7)] df[df.index.droplevel(0).isin(sele...
3
2
78,116,325
2024-3-6
https://stackoverflow.com/questions/78116325/pyspark-where-clause-can-work-on-a-column-that-doesnt-exist
I noticed by accident a weird behavior of pyspark. Basically, it can execute where function on a column that doesn't exist in a dataframe: print(spark.version) df = spark.read.format("csv").option("header", True).load("abfss://some_abfs_path/df.csv") print(type(df), df.columns.__len__(), df.count()) c = df.columns[0] #...
When in doubt, use df.explain() to figure out what's going on under the hood. This will confirm your intution: Spark context available as 'sc' (master = local[*], app id = local-1709748307134). SparkSession available as 'spark'. >>> df = spark.read.option("header", True).option("inferSchema", True).csv("taxi.csv") >>> ...
2
3
78,112,700
2024-3-6
https://stackoverflow.com/questions/78112700/why-am-i-getting-mean-of-empty-slice-warnings-without-nans
I've got a dataframe keptdata. I have a for loop to search through the rows of keptdata, and at one point need to average the previous values. This is the relevant line in my code, that produces the warning: avg = np.average(keptdata.iloc[i-500:i].price[keptdata.price != 0]) Here i is the variable that's being looped ...
I figured this one out. The problem was the keptdata dataframe had a series of at least five hundred 0's for price. This means that after inserting the condition keptdata.price != 0, there was no longer anything to take an average over, and numpy sensibly returns a "Mean of empty slice" warning.
2
2
78,112,019
2024-3-6
https://stackoverflow.com/questions/78112019/pass-parameters-to-mainargv-from-within-another-python-script
I have a python script that passes arguments "-i on" to argv in main define this is part of the code; def main(argv): status = "none" try: opts, args = getopt.getopt(argv,"hi:") except getopt.GetoptError: print sys.argv[0], ' -i on|off' sys.exit(2) for opt, arg in opts: if opt == '-h': print sys.argv[0]," -i on|off" pr...
Have you tried to pass them as a list? import sys from flask import Flask, request sys.path.insert(0, '/home/domoticame/epever-inverter-read') import ivctl ... ivctl.main('-i on'.split())
2
3
78,076,401
2024-2-28
https://stackoverflow.com/questions/78076401/uninstall-uv-python-package-installer
I recently installed uv on linux using the command line provided in the documentation: curl -LsSf https://astral.sh/uv/install.sh | sh It created an executable in /home/currentuser/.cargo/bin/uv. Now, just out of curiosity, I would like to know how to remove it properly. Is it as simple as deleting a file ? Or is ther...
The official documentation now has complete uninstall instructions: # Remove all data that uv has stored uv cache clean rm -r "$(uv python dir)" rm -r "$(uv tool dir)" # Remove binaries rm ~/.local/bin/uv ~/.local/bin/uvx If your original installation was a version earlier than 0.5.2 (November 2024), then replace the ...
5
7
78,090,426
2024-3-1
https://stackoverflow.com/questions/78090426/cannot-import-name-binom-test-from-scipy-stats-error-when-using-borutashap
I am trying to use borutashap for feature selection of a machine learning project. I can't run: from BorutaShap import BorutaShap always came across this error: ImportError: cannot import name 'binom_test' from 'scipy.stats' I upgraded both borutashap and scipy to make sure they are the latest version. I am using a c...
The function scipy.stats.binom_test() was removed from SciPy 1.12.0. Source. There is an alternative, scipy.stats.binomtest(), which is called slightly differently. Here are the docs for old and new. I believe you could fix this either by downgrading SciPy to 1.11.4 or by applying a fix to BorutaShap to call the new bi...
3
5
78,102,296
2024-3-4
https://stackoverflow.com/questions/78102296/how-to-group-dataframe-rows-into-list-in-polars-group-by
import polars as pl df = pl.DataFrame({ "Letter": ["A", "A", "B", "B", "B", "C", "C", "D", "D", "E"], "Value': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }) I want to group Letter and collect their corresponding Value in a List. Related Pandas question: How to group dataframe rows into list in pandas groupby I know pandas code w...
You could do this. import polars as pl df = pl.DataFrame( { 'Letter': ['A', 'A', 'B', 'B', 'B', 'C', 'C', 'D','D','E'], 'Value': [1, 2, 3, 4, 5, 6, 7, 8, 9,10] } ) g = df.group_by('Letter', maintain_order=True).agg(pl.col('Value')) print(g) This will print ┌────────┬───────────┐ │ Letter ┆ Value │ │ --- ┆ --- │ │ str ...
9
9
78,080,159
2024-2-29
https://stackoverflow.com/questions/78080159/how-to-type-annotate-a-polars-dataframe-created-from-an-arrow-table
In python, I'm trying to create a polars DataFrame from a pyarrow table, like so: import pyarrow as pa import polars as pl table = pa.table( { "a": [1, 2, 3], "b": [4, 5, 6], } ) df = pl.from_arrow(table) The return-type of pl.from_arrow() is (DataFrame | Series), even though my df really always is a DataFrame. This r...
You can use the cast function. from typing import cast import pyarrow as pa import polars as pl table = pa.table( { "a": [1, 2, 3], "b": [4, 5, 6], } ) df = cast(pl.DataFrame, pl.from_arrow(table)) reveal_type(df) Since pl.from_arrow can also return a Series, this force the typechecker to consider the type you put th...
3
2
78,079,857
2024-2-29
https://stackoverflow.com/questions/78079857/apache-arrow-with-apache-spark-unsupportedoperationexception-sun-misc-unsafe
I am trying to integrate Apache Arrow with Apache Spark in a PySpark application, but I am encountering an issue related to sun.misc.Unsafe or java.nio.DirectByteBuffer during the execution. import os import pandas as pd from pyspark.sql import SparkSession extra_java_options = os.getenv("SPARK_EXECUTOR_EXTRA_JAVA_OPTI...
Same issue with: Apache Spark version 3.5.1 Java JDK 21 Downgrading java to test minimum supported version. Update: Java JDK 17 resolves this issue, please see supported version of Spark: https://spark.apache.org/docs/latest/ (see Spark runs on Java)
4
2
78,084,538
2024-2-29
https://stackoverflow.com/questions/78084538/openai-assistants-api-how-do-i-upload-a-file-and-use-it-as-a-knowledge-base
My goal is to create a chatbot that I can provide a file to that holds a bunch of text, and then use the OpenAI Assistants API to actually use the file when querying my chatbot. I will use the gpt-3.5-turbo model to answer the questions. The code I have is the following: file_response = client.files.create( file=open("...
Note: The code below works with the OpenAI Assistants API v1. In April 2024, the OpenAI Assistants API v2 was released. See the migration guide. I created a customer support chatbot and made a YouTube tutorial about it. The process is as follows: Step 1: Upload a File with an "assistants" purpose my_file = client.file...
2
6
78,092,914
2024-3-2
https://stackoverflow.com/questions/78092914/django-cant-change-username-in-custom-user-model
I have the following User model in Django's models.py: class User(AbstractBaseUser): username = models.CharField(max_length=30, unique=True, primary_key=True) full_name = models.CharField(max_length=65, null=True, blank=True) email = models.EmailField( max_length=255, unique=True, validators=[EmailValidator()] ) When ...
This is one of the reasons not to use a username as primary key. Indeed, Django uses the primary key as token to check if two items are the same. If the primary key changes, and you save it, it will first try to update the user with that primary key, and if that fails, make an insert. This can thus produce several unwa...
2
2
78,095,982
2024-3-3
https://stackoverflow.com/questions/78095982/having-one-vector-column-for-multiple-text-columns-on-qdrant
I have a products table that has a lot of columns, which from these, the following ones are important for our search: Title 1 to Title 6 (title in 6 different languages) Brand name (in 6 different languages) Category name (in 6 different languages) Product attributes like size, color, etc. (in 6 different languages) ...
You seem like you have thought this through already, and your method is valid, practical, simple and scalable. Here is a quick overview of what I think about your particular question. Pros of your method By segregating data into collections based on language, you ensure that searches are conducted within the correct ...
4
2
78,100,006
2024-3-4
https://stackoverflow.com/questions/78100006/how-to-change-cpu-affinity-on-linux-with-python-in-realtime
I know I can use os.sched_setaffinity to set affinity, but it seems that I can't use it to change affinity in realtime. Below is my code: First, I have a cpp program // test.cpp #include <iostream> #include <thread> #include <vector> void workload() { unsigned long long int sum = 0; for (long long int i = 0; i < 500000...
The root of the problem is that on Linux, sched_setaffinity() affects a thread, not a process. The main thread has the same id as the process, but subsequent threads have different ids, and they inherit the CPU affinity from the parent thread. Apparently Python is quick enough to set the CPU affinity of the main thread...
2
2
78,097,487
2024-3-3
https://stackoverflow.com/questions/78097487/pylance-in-visual-studio-code-does-not-recognise-poetry-virtual-env-dependencies
I am using Poetry to manage a Python project. I create a virtual environment for Poetry using a normal poetry install and pyproject.toml workflow. Visual Studio Code and its PyLance does not pick up project dependencies in Jupyter Notebook. Python stdlib modules are recognised The modules of my application are recogni...
Some other people were having the same issue. Pylance does not show auto import information from site-packages directory #3281 Pylance not indexing all files and symbols for sqlalchemy even with package depth of 4 Visual Studio Code's PyLance implementation seems to have some internal limits that may prevent indexing...
6
1
78,088,888
2024-3-1
https://stackoverflow.com/questions/78088888/how-to-calculate-the-midpoints-of-each-triangle-edges-of-an-icosahedron
Am trying to compute the midpoints of each triangle edges of an icosahedron to get an icosphere which is the composion of an icosahedron subdivided in 6 or more levels. i tried to calculate the newly created vertices of each edges but some points wore missing. I tried to normalize each mid point but still the points wo...
Pardon the JavaScripty answer (because that's easier for showing things off in the answer itself =), and the "cabinet projection", which is a dead simple way to turn 3D into 2D but it'll look "strangly squished" (unless you're playing an isometric platformer =) Icosahedrons are basically fully defined by their edge len...
2
5
78,095,645
2024-3-3
https://stackoverflow.com/questions/78095645/how-do-i-get-selenium-on-python-to-connect-to-an-existing-instance-of-firefox
I am trying to use Selenium to connect to existing instance of Firefox - the documentation says to use something like this options=webdriver.FirefoxOptions() options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe' webdriver_service = Service(r'c:\tmp\geckodriver.exe') driver = webdriver.Firefox(servic...
You should put the service_args parameter in the Service class and not on Firefox. I believe this should work options=webdriver.FirefoxOptions() options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe' webdriver_service = Service(r'c:\tmp\geckodriver.exe', service_args=['--marionette-port', '2828', '--...
2
2
78,108,792
2024-3-5
https://stackoverflow.com/questions/78108792/why-is-builtin-sorted-slower-for-a-list-containing-descending-numbers-if-each
I sorted four similar lists. List d consistently takes much longer than the others, which all take about the same time: a: 33.5 ms b: 33.4 ms c: 36.4 ms d: 110.9 ms Why is that? Test script (Attempt This Online!): from timeit import repeat n = 2_000_000 a = [i // 1 for i in range(n)] # [0, 1, 2, 3, ..., 1_999_999] b =...
As alluded to in the comments by btilly and Amadan, this is due to how the Timsort sorting algorithm works. Detailed description of the algorithm is here. Timsort speeds up operation on partially sorted arrays by identifying runs of sorted elements. A run is either "ascending", which means non-decreasing: a0 <= a1 <= ...
32
43
78,110,125
2024-3-5
https://stackoverflow.com/questions/78110125/how-to-dynamically-create-fastapi-routes-handlers-for-a-list-of-pydantic-models
I have a problem using FastAPI, trying to dynamically define routes. It seems that the final route/handler defined overrides all the previous ones (see image below) Situation: I have a lot of Pydantic models as a list (imported from models.py: simplified in example), and would like to create a GET endpoint for each mod...
Most likely the issue lies in the fact that you are using the same model reference for every endpoint created, and hence, it is always assigned the last value given in the for loop. You should rather use a helper function that returns an inner function, as demonstrated in Option 2 of this answer. Example from fastapi i...
3
4
78,109,250
2024-3-5
https://stackoverflow.com/questions/78109250/running-a-python-file-that-imports-from-airflow-package-requires-airflow-instan
I am running into a weird import issue with Airflow. I want to create a module from which others can import. I also want to run unit tests on this module. However, I noticed that as soon as you import anything from the airflow package, it will try and run Airflow. Example: # myfile.py from airflow import DAG print("Hel...
This is happening because of how impoorts work in python. You're importing from the airflow package which has an __init__ file. If you inspect it, there's a piece of code in it that does all of the airflow init stuff. lines 67-68 in __init__py: if not os.environ.get("_AIRFLOW__AS_LIBRARY", None): settings.initialize()...
2
3
78,106,081
2024-3-5
https://stackoverflow.com/questions/78106081/how-to-generate-graph-from-pandas-dataframe-with-full-hierachical-data
Having a Pandas dataframe with sample hierarchical data i.e. data = pd.DataFrame({ "manager_id": ["A", "A", "B", "A", "C", "A", "B"], "employee_id": ["B", "C", "C", "D", "E", "E", "E"] } ) Given that the data consists of all the descendent relationships for each manager. For example in each manager id (e.g. "A"), the ...
Read the DataFrame as a directed graph with from_pandas_edgelist, then sort the nodes with topological_sort and only keep the edge with the parent that has the greatest topological index per child: G = nx.from_pandas_edgelist(data, source='manager_id', target='employee_id', create_using=nx.DiGraph) # topological order ...
3
2
78,108,812
2024-3-5
https://stackoverflow.com/questions/78108812/display-information-using-django-tags
I am writing a site on Django, the purpose of this site is to create a test to assess students' knowledge I need help with outputting options for answers to a question I keep the questions in a list and the answer options in a nested list for example: questions = [ "question1","question2","question3"] answers = [[ "ans...
Perform the joining in the view: def my_view(request): questions = ['question1', 'question2', 'question3'] answers = [ ['answer11', 'answer12', 'answer13'], ['answer21', 'answer22', 'answer23', 'answer24'], ['answer31', 'answer32', 'answer33'], ] return render(request, 'some_template.html', {'qas': zip(questions, answe...
3
3
78,106,827
2024-3-5
https://stackoverflow.com/questions/78106827/pandas-find-last-value-before-a-given-timestamp
For the dataframe below, I am trying to add a column to each row that captures the ask_size at different time intervals, for the sake of example, say 1 millisecond. So for instance, for row 1, the size 1ms before should be 165 since that is the prevailing ask size 1ms before - even though the previous timestamp (2024-0...
IIUC you can indeed use a merge_asof. You however need to adapt the parameters to perform the search in the correct order: delta = pd.Timedelta('1ms') df['out'] = pd.merge_asof(df['event_timestamp'].sub(delta), df, direction='backward')['ask_size_1'] NB. I'm assuming here that the timestamps are already sorted. If not...
4
1
78,107,054
2024-3-5
https://stackoverflow.com/questions/78107054/convert-time-zone-function-to-retrieve-the-values-based-on-the-timezone-specif
I'm attempting to determine the time based on the timezone specified in each row using Polars. Consider the following code snippet: import polars as pl from datetime import datetime from polars import col as c df = pl.DataFrame({ "time": [datetime(2023, 4, 3, 2), datetime(2023, 4, 4, 3), datetime(2023, 4, 5, 4)], "tzon...
The only way to do this which fully works with lazy execution is to use the polars-xdt plugin: df = pl.DataFrame( { "time": [ datetime(2023, 4, 3, 2), datetime(2023, 4, 4, 3), datetime(2023, 4, 5, 4), ], "tzone": ["Asia/Tokyo", "America/Chicago", "Europe/Paris"], } ).with_columns(pl.col("time").dt.replace_time_zone("UT...
5
4
78,106,285
2024-3-5
https://stackoverflow.com/questions/78106285/polars-dataframe-rolling-sum-look-ahead
I want to calculate rolling_sum, but not over x rows above the current row, but over the x rows below the current row. My solution is to sort the dataframe with descending=True before applying the rolling_sum and sort back to descending=False. My solution: import polars as pl # Dummy dataset df = pl.DataFrame({ "Date":...
You can avoid sorting the rows and instead reverse the specific column twice using pl.Expr.reverse. ( df .with_columns( pl.col("Close") .reverse().rolling_sum(3).reverse() .over("Company").alias("Cumsum_lead") ) ) For readability, this could also be wrapped into a helper function. def rolling_sum_lead(expr: pl.Expr, w...
4
2
78,105,407
2024-3-5
https://stackoverflow.com/questions/78105407/how-do-i-pass-in-a-parameter-name-into-a-function-as-an-argument-in-python
How do I pass in a parameter name into a function as an argument? def edit_features_retry(editType,data): AGOLlayer.edit_features(editType=data) edit_features_retry("adds", datalayer) error: TypeError: edit_features() got an unexpected keyword argument 'editType' If I do it this way as a string: def edit_features_ret...
You can use dictionary unpacking. Here's a simple example: def f(a = 1, b = 2): print(f"{a = }, {b = }") f(b=5) # output: "a = 1, b = 5" kwargs = {"b": 5} f(**kwargs) # output: "a = 1, b = 5" Which can be applied to your scenario: def edit_features_retry(editType, data): AGOLlayer.edit_features(**{editType: data}) edi...
2
3
78,106,064
2024-3-5
https://stackoverflow.com/questions/78106064/how-can-i-import-a-py-file-in-ibm-quantum-lab
I created a separate Python file for numerical calculations when implementing a quantum circuit. Now, I'm trying to use IBM Quantum Lab to apply this code to a circuit using Qiskit. %matplotlib inline import math import decomposition_2qubit as d2 import numpy as np from qiskit import QuantumCircuit, execute, Aer from q...
You are probably facing an issue with the file path. As suggested here, you can either specify your own import path explicitly or just prepend path modifiers like .. and/or /.
3
2
78,105,399
2024-3-5
https://stackoverflow.com/questions/78105399/what-is-the-best-way-to-filter-groups-by-two-lambda-conditions-and-create-a-new
This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'a': ['x', 'x', 'x', 'x', 'y', 'y', 'y', 'y', 'z', 'z', 'z', 'p', 'p', 'p', 'p'], 'b': [1, -1, 1, 1, -1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1] } ) And this the expected output. I want to create column c: a b c 0 x 1 first 1 x -1 first 2 x 1 first 3 x 1 first ...
A generic method that works with any number of positions for the first 1: d = {0: 'first', 1: 'second'} s = (df.groupby('a')['b'] .transform(lambda g: g.reset_index()[g.values==1] .first_valid_index()) .replace(d) ) out = df.assign(c=s).dropna(subset=['c']) Notes: if you remove the replace step you will get an intege...
6
2
78,105,655
2024-3-5
https://stackoverflow.com/questions/78105655/django-rest-framework-django-channels-errno-111-connect-call-failed-127
I am programming a project with Django (4.2.6), Django Rest Framework (3.14.0), Channels (4.0.0) and Channels-Redis(4.2.0), which acts as a backend for a mobile application. So far, I haven't had any problems with the Rest API connections and the endpoints I developed. I try to test the connection through websockets, b...
Channels need a REDIS backend to be able to operate. You need to install and start REDIS to solve the error
2
2
78,105,003
2024-3-5
https://stackoverflow.com/questions/78105003/401-unauthorized-error-when-making-post-request-to-google-apps-script-web-app-wi
I am trying to send a POST request to a Google Apps Script web app using a Python script. While accessing the web app's URL in a web browser works fine with GET requests, sending a POST request with Python results in a 401 Unauthorized error. The authentication process is as follows: from google_auth_oauthlib.flow impo...
About the status code 401, it means The HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource.. Ref In order to request Web Apps with the access token, in the current ...
3
1
78,104,696
2024-3-5
https://stackoverflow.com/questions/78104696/new-column-sampled-from-list-based-on-column-value
values = [1,2,3,2,3,1] colors = ['r','g','b'] expected_output = ['r', 'g', 'b', 'g', 'b', 'r'] # how to create this in pandas? df = pd.DataFrame({'values': values}) df['colors'] = expected_output I want to make a new column in my dataframe where the colors are selected based on values in an existing column. I remember...
Code use numpy indexing import numpy as np df['colors'] = np.array(colors)[df['values'] - 1] df values color 0 1 r 1 2 g 2 3 b 3 2 g 4 3 b 5 1 r If you want to solve this problem using only Pandas, use map function. (with @Onyambu comment) m = dict(enumerate(colors, 1)) df['colors'] = df['values'].map(m)
7
5
78,103,638
2024-3-4
https://stackoverflow.com/questions/78103638/sklearn-linearregression-dont-require-iterations-and-learning-rate-as-paramet
As far as I know the cost is minimized using the Gradient Descent algorithm by updating the weights(repeat until convergence), In case of linear regression we have m : slope c : intercept (constant value) import numpy as np from sklearn.linear_model import LinearRegression x= np.asarray([(i+np.random.randint(1,7)) for...
Just to add a demonstration to Muhammed's answer (you should accept it, btw), here is an example import numpy as np np.random.seed(12) # Just to have a reproducible example from sklearn.linear_model import LinearRegression X=np.random.normal(0,1,(20,10)) # Or any array of X you want. Just a mre Y=np.random.normal(0,1,(...
2
3
78,102,561
2024-3-4
https://stackoverflow.com/questions/78102561/is-there-a-way-to-have-tuples-woking-fine-as-index-in-pandas
I would like to use a MultiIndex in Pandas where at every level I have a nested tuple. I know I could in principle unpack the thing but this would be less legible and annoying. In general, the elements of the tuple (a class name and some parameters) have meaning only together, I would like to make it harder to end up w...
If I understand correctly, your issue is with this assignments: index=pd.MultiIndex.from_arrays([[("foo",("spam",)),("foo",("spam",))],[("bar",("egg",)),("bar",("egg",))],[("baz",("bacon",)),("pam",("bacon",))]]) this_index = (("foo",("spam",)),("bar",("egg",)),("baz",("bacon",))) df = pd.DataFrame(index=index, columns...
2
1
78,101,392
2024-3-4
https://stackoverflow.com/questions/78101392/switch-row-column-on-a-chartsheet-using-openpyxl
I have a large Excel sheet with data. Due to several reasons, I have data that is structured in a transposed way: Histogram bin 0 bin 1 bin 2 bin 3 bin 4 bin 5 test 1 0 1 5 2 1 0 test 2 0 0 1 7 2 0 When I plot this data, I get 5 series with each 2 values in my plot. What I would like is 2 Series with each 5...
If you refer to the Switch Row/Column button, you can simply turn-on the from_rows parameter. chart.add_data(data) chart.add_data(data, from_rows=True) Output (text.xlsx):
2
2
78,101,029
2024-3-4
https://stackoverflow.com/questions/78101029/multidimensional-indexing-in-numpy-with-tuples-as-indices-for-certain-axes
I have a 3D numpy array which is really an array of matrices. I want to set the diagonals to zero by using the following approach. When I print the tuple and din it is exactly the same, but it returns different views of the array. m = np.random.normal(0, 0.2, (10, 4, 4)) din = np.diag_indices(m.shape[1], ndim = 2) m[:,...
As described in comments, you need to unpack the indices. Since python 3.11, you can use: m[:, *din] Output: array([[ 8.61622699e-02, -1.46919069e-01, -9.37771599e-02, 1.94698315e-03], [ 1.60933774e-01, -2.77077615e-02, -1.74135776e-01, -1.72223723e-01], [-1.54804225e-01, 1.08146714e-01, 2.51844877e-01, -2.91622737e-0...
2
3
78,100,258
2024-3-4
https://stackoverflow.com/questions/78100258/as-index-false-groupby-doesnt-work-with-count
When I run groupby on a dataframe with as_index set to False, count seems to not work at all. For example, import pandas as pd word_list = ['a', 'b', 'c', 'a', 'c', 'c', 'b', 'a', 'c'] df = pd.DataFrame(word_list, columns=['word']) as_counts = df.groupby('word', as_index=False).count() print(as_counts) word 0 a 1 b 2...
groupby.count is designed to work on the columns other than the grouping columns while groupby.size is designed to output a single new column (named size), irrespective of the number of existing columns. This makes sense since count depends on the NA status, while size is always constant within a group (the number of r...
2
3
78,089,594
2024-3-1
https://stackoverflow.com/questions/78089594/python-reading-long-lines-with-asyncio-streamreader-readline
The asyncio version of readline() (1) allows reading a single line from a stream asynchronously. However, if it encounters a line that is longer than a limit, it will raise an exception (2). It is unclear how to resume reading after such an exception is raised. I would like a function similar to readline(), that simply...
The standard library implementation of asyncio.StreamReader.readline is almost what you want. That function raises a ValueError in the event of a buffer overrun, but it first removes a chunk of data from the buffer and discards it. If you catch the ValueError and keep calling readline, the stream would keep going. But ...
4
2
78,095,190
2024-3-3
https://stackoverflow.com/questions/78095190/how-to-run-a-background-task-when-using-websockets-in-fastapi-starlette
My ultimate goal is to write code that only triggers other servers when calling an endpoint and waits for data from a specific channel in Redis to come in. I don't want to know external server's business logic is done due to latency. The call_external_server background task function below will notify the external serve...
A BackgroundTask is executed after returning a response to a client's request (not on ongoing websocket connections)—see this answer, as well as this answer and this related comment for more details on Background Tasks. As explained by @tiangolo (the creator of FastAPI): Background Tasks internally depend on a Request...
2
4
78,089,964
2024-3-1
https://stackoverflow.com/questions/78089964/syntax-highlights-intellisense-and-autocomplete-not-working-in-jupyter-notebook
for some background, I usually use vscode for creating input for my calculation, especially using the jupyter notebook extension to my WSL Ubuntu. so I've been setting up my vscode using standard Python and Jupyter noteboook extensions. Everything looked good and ran smoothly as the day before until two days ago (29-02...
According to this reply in github, the fix will come in the stable recovery release 1.87.1. You can either wait or try an older version of VSCode, such as vscode v1.86.2
2
2
78,095,216
2024-3-3
https://stackoverflow.com/questions/78095216/pyright-lsp-install-in-neovim-nodeutil-module-not-found
Fresh installed neovim on a new LinuxMint machine with lsp-config, mason plugins and pyright LSP Server (through Mason) and found out that it was not working with lsp.log registering this !!! .../vim/lsp/rpc.lua:734 "rpc" "/home/manjunath/.local/share/nvim-kick/mason/bin/pyright-langserver" "stderr" "internal/modules/...
Found out what the issue was. node.js on apt was outdated. Installing latest version from here fixed it.
6
10
78,092,187
2024-3-2
https://stackoverflow.com/questions/78092187/highlight-the-changes-or-areas-of-discrepancy-between-the-two-images
These are my images, I want to Convert the PDF documents (file_1.pdf and file_2.pdf) into images. Compare the images to detect any differences between them. Highlight the changes or areas of discrepancy between the two images. This is my code from pdf2image import convert_from_path import cv2 import numpy as np fro...
I'd like to present some simple operations to get exactly the colors you want, without thresholding. im1 and im2 (grayscale): # assuming white sheet of paper, ink is the inverse # positive = added # negative = deleted signed_difference = (255 - im2).astype(np.int16) - (255 - im1).astype(np.int16) (white = added, bl...
2
2
78,097,177
2024-3-3
https://stackoverflow.com/questions/78097177/how-to-get-specific-unique-combinations-of-a-dataframe-using-only-dataframe-oper
I have this data that contains entries of 2 players playing a game one after another then after they both gain a win or lose they get a shared score (logic of this is unimportant numbers are random anyway this is just an example to describe what I want). So there are scores obtained for every possible outcome after pla...
I hope I've understood your question right. From the comments I'm supposing you have total 4 players in the dataframe: from itertools import product p1, p2, p3, p4 = np.unique(df[["Player_1", "Player_2"]].values) df = df.set_index(["Player_1", "Player_2", "Outcome_1", "Outcome_2"]) all_data = [] for p1o1, p2o2, p3o1, p...
3
3
78,094,782
2024-3-3
https://stackoverflow.com/questions/78094782/make-code-faster-to-solve-which-letter-represents-which-digit-in-a-given-equatio
I am going to do a math competition which allows writing programs to solve problems. The code attempts to solve this problem: WHITE+WATER=PICNIC where each distinct letter represents a different digit. Find the number represented by PICNIC. No imports are allowed (tqdm was just a progress bar). What I tried is below. A...
Observations: P=1 due to a carry to its sixth digit W must be 5-9 due to a carry being generated (1) No letter can be the same value as another letter. def find_solution(): P = 1 for W in range(5,10): for H in range(10): if H in (P,W): continue for I in range(10): if I in (H,P,W): continue for T in range(10): if T in...
2
3
78,094,521
2024-3-2
https://stackoverflow.com/questions/78094521/how-to-shift-matrix-upper-right-triangular-values-to-lower-right
Given the following upper triangular matrix, I need to shift the values to the bottom as shown: input_array = np.array([ [np.nan, 1, 2, 3], [np.nan, np.nan, 4, 5], [np.nan, np.nan, np.nan, 6], [np.nan, np.nan, np.nan, np.nan], ]) result = np.array([ [np.nan, np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan, 3], [np.nan...
Try: ind = (~np.isnan(input_array)).argsort(axis=0) print(np.take_along_axis(input_array, ind, axis=0)) Prints: [[nan nan nan nan] [nan nan nan 3.] [nan nan 2. 5.] [nan 1. 4. 6.]]
2
1
78,094,327
2024-3-2
https://stackoverflow.com/questions/78094327/streamlining-generic-property-creation
I'm new to Python and I find that when making classes I keep having to write @property def example(self): return self._example @example.setter def example(self, example): if #some conditions here: self._example = example I am working on a project and there are over a dozen of these across it, so I tried to make a func...
The problem isn't with your property, but with the fact that you aren't using the property in City.__init__. _name is really a private implementation detail of the property itself (though the value is stored on the instance of City), so City methods should not use it directly, either. While I'm answering the question,...
3
3
78,093,070
2024-3-2
https://stackoverflow.com/questions/78093070/pandas-how-to-transform-multi-select-column-to-index-column
I have a dataframe looking like that : 2023-12-31 2024-01-31 myvalue1 myvalue2 myvalue1 myvalue2 a 2 6 2 6 b 3 7 3 7 c 4 8 4 8 which can be created by : df = pd.DataFrame(index=['a', 'b', 'c'], data= {'myvalue1':[2,3, 4], 'myvalue2':[6,7,8]})\ .reindex(['myvalue1', 'myvalue2'] * 2, axis=1) \ .set_axis(pd.MultiIndex.f...
sum the rows and reshape with unstack: out = df.sum().unstack() Output: myvalue1 myvalue2 2023-12-31 9 21 2024-01-31 9 21
3
3
78,092,661
2024-3-2
https://stackoverflow.com/questions/78092661/which-one-should-i-used-in-order-to-check-the-uniqueness-of-enum-values-in-pytho
I have an enum in Python, which I want to make sure that its values are unique. I see that there are 2 ways I can use to achieve it: Wrapping the class with @verify(UNIQUE) Wrapping the class with @unique What is the difference with using each one of them? Which one should I use to gain the best performance?
You can use which ever you prefer. In terms of implementation the both are the same and I mean the same, its literally copy pasted code in enum.py in in the cpython repo. This code is for the @verify(Unique) and this one for the @unique. I would suggest to use @verify if you have other checks as well but if you only wa...
5
3
78,076,552
2024-2-28
https://stackoverflow.com/questions/78076552/how-can-i-generate-detect-signals-2-4ghz-and-generate-spectrograms-from-them-l
I'm new to the world of RF and signal processing. I have a USRP B210 and I'm trying to detect and generate spectrograms that will be later used to train an AI model that identifies if the signal is a wifi, bluetooth, drone... which means we're focusing on 2.4GHz I guess. this is the code provided by ettus research on i...
Here's an example of my code that I used to get a signal similar to the one you're trying to get import uhd import numpy as np import matplotlib.pyplot as plt import scipy usrp = uhd.usrp.MultiUSRP() num_samps = 1000 * 1000 # number of samples received num_samps_h = 2000 # number of samples received num_samps_w = 2000 ...
3
1
78,092,439
2024-3-2
https://stackoverflow.com/questions/78092439/calculating-the-average-of-a-specific-row-with-loc-loc-is-not-finding-the-row-v
I'm new to Python and stackoverflow. So please forgive any shortcomings in my posting. I want to calculate the row average of a specific row(e.g. Bahrain) and I'm having problem achieving it. I used df.loc but It's returning a key error with the name of the country as it doesn't recognize the name. My dataframe look li...
You need to specify the Bahrain at the df["Country"]. And also, you cannot mix text with numbers and take average. Here is how you can do it: rowAverage = df[df['Country'] == 'Bahrain'].iloc[:, 1:].mean()
3
4
78,091,150
2024-3-2
https://stackoverflow.com/questions/78091150/conditional-python-polars-cum-sum-over-a-group-is-there-a-better-way
I want to create a column that is a cumulative sum over a group column but the cumulative sum only happens when the 'days' column meets a certain condition. I have come up with what I regard as a "duct tape" solution, there must be a more elegant way. import polars as pl # Create a DataFrame with literal values df = pl...
As mentioned by @jqurious, a single pl.DataFrame.with_columns call can be used to compute the conditional cumulative sum. Moreover, the conditional amount can be computed without a pl.when().then().otherwise() construct, by multiplying the amount with the condition. ( df .with_columns( (pl.col("amount") * (pl.col("days...
2
2
78,091,020
2024-3-2
https://stackoverflow.com/questions/78091020/how-do-i-check-that-parameters-of-a-variadic-callable-are-all-of-a-certain-subcl
This might be a tough one. Suppose I have a type JSON = Union[Mapping[str, "JSON"], Sequence["JSON"], str, int, float, bool, None] And I have a function def memoize[**P, T: JSON](fn: Callable[P,T]) -> Callable[P,T]: # ...make the function memoizable return wrapped_fn How do I constrain the parameters of fn to all be ...
There isn't a way of currently doing this, if fn has an arbitrary signature. I believe that the next best thing is generating errors at the call site (see Pyright playground): import collections.abc as cx import typing as t type JSON = cx.Mapping[str, JSON] | cx.Sequence[JSON] | str | int | float | bool | None class _J...
2
2
78,089,462
2024-3-1
https://stackoverflow.com/questions/78089462/how-to-extract-dominant-frequency-from-numpy-array
I am working with simulations of populations of neurons, and would like to extract the dominant frequency from their local field potential. This takes the form of just a single vector of values, which I have plotted here. Clearly, there is some oscillatory activity happening, and I am interested in what frequency the l...
Why you don't find a peak at 1 Just to reproduce the probable problem with my own [mre] import numpy as np import matplotlib.pyplot as plt # time with a 0.00006 second per sample t=np.arange(0,12,0.00006) # y is roughly sin(2π.f.t)⁴. But with some noise. # Because of power 4, it is a 2f periodic signal. So I choose f #...
2
3
78,088,193
2024-3-1
https://stackoverflow.com/questions/78088193/integrate-a-function-that-takes-as-input-a-scalar-value-and-outputs-a-matrix
I have a function that takes as an input a scalar value, and outputs a matrix (following is an MRE with size 2x2, my actual function has problem specific matrix dimensions, like say 100x100). I'd like to integrate said function over a range. import numpy as np from scipy.integrate import quad def func(x): return np.arr...
Try scipy.integrate.quad_vec. import numpy as np from scipy.integrate import quad_vec def func(x): return np.array([[np.cos(x), np.sin(x)], [np.sin(x), np.cos(x)]]) quad_vec(func, 0, np.pi) # (array([[2.22044605e-16, 2.00000000e+00], # [2.00000000e+00, 2.22044605e-16]]), # 1.3312465980656846e-13) The first output is y...
2
2
78,086,474
2024-3-1
https://stackoverflow.com/questions/78086474/recursive-matrix-construction-with-numpy-array-issues-broadcasting
The following is a seemingly simple recursion for finding a hybercube matrix. The recursion is defined as: (Formula) I tried to put it into code but I keep running into broadcasting issues with numpy. I tried instead of taking the size of the previous matrix, just taking powers of 2 to reduce recursive calls (for the p...
Use np.block instead of np.array to assemble the block matrix. import numpy as np from numpy import linalg as LA Q1 = np.array([[0, 1], [1, 0]]) def Qn(n): if n <= 1: return Q1 else: Qnm1 = Qn(n-1) I = np.eye(2**(n-1)) return np.block([[Qnm1, I], [I, Qnm1]]) Q3 = Qn(3) eig_value, eig_vectors = LA.eig(Q3) print(eig_valu...
2
2
78,088,133
2024-3-1
https://stackoverflow.com/questions/78088133/all-columns-to-uppercase-in-a-dataframe
Suppose there are hundreds of columns in a DataFrame. Some of the column names are in lower and some are in upper case. Now, I want to convert all the columns to upper case. import polars as pl df = pl.DataFrame({ "foo": [1, 2, 3, 4, 5, 8], "baz": [5, 4, 3, 2, 1, 9], }) What I tried: df.columns = [x.upper() for x in d...
.rename() also accepts a Callable. df.rename(str.upper) shape: (6, 2) ┌─────┬─────┐ │ FOO ┆ BAZ │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 1 ┆ 5 │ │ 2 ┆ 4 │ │ 3 ┆ 3 │ │ 4 ┆ 2 │ │ 5 ┆ 1 │ │ 8 ┆ 9 │ └─────┴─────┘
3
3