eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I have a dataframe with income for a certain period of time. The period is given by a start date and an end date (For example 2023-04-01 and 2023-06-30). The period can vary between 3, 6 and 12 months. My goal is to bring everything to the same period, but I did not find an easy way to do it. This is how I am doing it now:  get the periods in months: df["date_diff"] = (df.date_to.dt.to_period("M") - df.date.dt.to_period("M")).apply(lambda x: x.n) + 1 iterate over rows  create a new row for each month in the date_diff column divide income by number of months in period shift date append new rows to array of new rows   get df from array of new rows   new_rows = [] for _,row in df.iterrows(): for i in range(row["date_diff"]): new_row = row.copy() new_row["new_date"] = row["date"] + relativedelta(months=i) + pd.offsets.MonthEnd() new_row["new_net_revenues"] = row["net_revenues"] / row["date_diff"] new_rows.append(new_row) new_df = pd.DataFrame(new_rows)  This obviously takes a hell lot of time for larger dataframes. I wonder if there is a much faster solution with builtin funtions? Essentially it is kind of an explode to the months in the period. I also tried to just concat the rows according to the number of months in the period and do the math afterwards, but still not very elegant. Edit: The code above transforms this:  net_revenues date date_to date_diff 0 0.02 2023-04-01 2023-06-30 3 1 0.01 2023-04-01 2023-06-30 3 2 0.02 2023-01-01 2023-03-31 3  into this:  new_net_revenues new_date 0 0.006667 2023-04-30 0 0.006667 2023-05-31 0 0.006667 2023-06-30 1 0.003333 2023-04-30 1 0.003333 2023-05-31 1 0.003333 2023-06-30 2 0.006667 2023-01-31 2 0.006667 2023-02-28 2 0.006667 2023-03-31 3 0.003333 2023-01-31 3 0.003333 2023-02-28 3 0.003333 2023-03-31 

Answer: You can create new rows with Index.repeat, add months by counter by GroupBy.cumcount and create datetimes by Series.dt.to_timestamp: df = pd.DataFrame({'date':['2023-04-01', '2023-01-01'], 'date_to':['2023-06-30', '2023-06-30'], }).apply(pd.to_datetime).assign(net_revenues=[100,20]) print (df) date date_to net_revenues 0 2023-04-01 2023-06-30 100 1 2023-01-01 2023-06-30 20 periods = df.date.dt.to_period("M") diff = (df.date_to.dt.to_period("M") - periods).apply(lambda x: x.n) + 1 new_df = df.loc[df.index.repeat(diff)] new_df['new_date'] = (periods + new_df.groupby(level=0).cumcount()).dt.to_timestamp("M") new_df["new_net_revenues"] = new_df["net_revenues"] / diff print (new_df) date date_to net_revenues new_date new_net_revenues 0 2023-04-01 2023-06-30 100 2023-04-30 33.333333 0 2023-04-01 2023-06-30 100 2023-05-31 33.333333 0 2023-04-01 2023-06-30 100 2023-06-30 33.333333 1 2023-01-01 2023-06-30 20 2023-01-31 3.333333 1 2023-01-01 2023-06-30 20 2023-02-28 3.333333 1 2023-01-01 2023-06-30 20 2023-03-31 3.333333 1 2023-01-01 2023-06-30 20 2023-04-30 3.333333 1 2023-01-01 2023-06-30 20 2023-05-31 3.333333 1 2023-01-01 2023-06-30 20 2023-06-30 3.333333
Question: I want to run the DAN repo. I am using Google Cloud Collab. I cloned the project on my Google Drive in the following directory /content/drive/MyDrive/DAN/DAN Trying to run An example script file is available at OCR/document_OCR/dan/predict_examples to recognize images directly from paths using trained weights. using collab notebook located inside /content/drive/MyDrive/DAN/DAN from google.colab import drive drive.mount('/content/drive') import sys sys.path.append('/content/drive/MyDrive/DAN/DAN') !python3 /content/drive/MyDrive/DAN/DAN/OCR/document_OCR/dan/predict_example.py  But this is not working for me And I am facing the following issue Traceback (most recent call last): File "/content/drive/MyDrive/DAN/DAN/OCR/document_OCR/dan/predict_example.py", line 9, in <module> from basic.models import FCN_Encoder ModuleNotFoundError: No module named 'basic' Where the predict_example.py scripts starts with import os.path import torch from torch.optim import Adam from PIL import Image import numpy as np from basic.models import FCN_Encoder from OCR.document_OCR.dan.models_dan import GlobalHTADecoder from OCR.document_OCR.dan.trainer_dan import Manager from basic.utils import pad_images from basic.metric_manager import keep_all_but_tokens 

Answer: !python3 spawns a new interpreter which doesn't know about sys.path.append(...) above it, it only affects the current interpreter. instead either use runpy.run_path to execute a file within the current interpreter, or modify os.environ["PYTHONPATH"] by appending :/your_path to it before calling !python3 so it will carry over to other spawned interpreters.
Question: Imagine I have a dataset like: data = { "a": [1, 4, 2, 4, 7, 4], "b": [4, 2, 3, 3, 0, 2], "c": ["a", "b", "c", "d", "e", "f"], }  and I want to keep only the rows for which a + b is uniquely described by a single combination of a and b. I managed to hack this: df = ( pl.DataFrame(data) .with_columns(sum_ab=pl.col("a") + pl.col("b")) .group_by("sum_ab") .agg(pl.col("a"), pl.col("b"), pl.col("c")) .filter( (pl.col("a").list.unique().list.len() == 1) & (pl.col("b").list.unique().list.len() == 1) ) .explode(["a", "b", "c"]) .select("a", "b", "c") ) """ shape: (2, 3) ┌─────┬─────┬─────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str │ ╞═════╪═════╪═════╡ │ 4 ┆ 2 ┆ b │ │ 4 ┆ 2 ┆ f │ └─────┴─────┴─────┘ """  Can someone suggest a better way to achieve the same? I struggled a bit to figure this logic out, so I imagine there is a more direct/elegant way of getting the same result.

Answer:  .struct() to combine a and b into one column so we can check uniqueness. n_unique() to check uniqueness. over() to limit the calculation to be within a + b.  df.filter( pl.struct("a","b").n_unique().over(pl.col.a + pl.col.b) == 1 ) ┌─────┬─────┬─────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str │ ╞═════╪═════╪═════╡ │ 4 ┆ 2 ┆ b │ │ 4 ┆ 2 ┆ f │ └─────┴─────┴─────┘  If you would need to extend it to larger number of columns then you could use sum_horizontal() to make it more generic: columns = ["a","b"] df.filter( pl.struct(columns).n_unique().over(pl.sum_horizontal(columns)) == 1 )
Question: So I have m number of different vectors (say x), each one is (1,n), stacked horizontally, totally in a (m,n) matrix we call it B, and a matrix (A) with dimension (n,n). I want to compute xAx^T for all vectors x, output should be (m,1) How can I write an einsum query for this given B and A? Here is a sample without einsum:  import torch m = 30 n = 4 B = torch.randn(m, n) A = torch.randn(n, n) result = torch.zeros(m,1) for i in range(m): x = B[i].unsqueeze(0) result[i] = torch.matmul(x, torch.matmul(A, x.T)) 

Answer: Using einsum and tensordot : import torch import numpy as np A = torch.tensor([[1.0, 0.0, 0.0, 0.0], [0.0, 2.0, 0.0, 0.0], [0.0, 0.0, 3.0, 0.0], [0.0, 0.0, 0.0, 4.0]]) B = torch.tensor([[1.0, 4.0, 7.0, 10.0], [2.0, 5.0, 8.0, 11.0], [3.0, 6.0, 9.0, 12.0]]) # Using einsum res_using_einsum = torch.einsum('bi,ij,bj -> b',B,A,B).unsqueeze(dim = -1) print(res_using_einsum) ''' tensor([[580.], [730.], [900.]]) ''' # Using tensordot BA = torch.tensordot(B, A, dims = ([1],[0])) ''' BA : tensor([[ 1., 8., 21., 40.], [ 2., 10., 24., 44.], [ 3., 12., 27., 48.]]) ''' res_using_tensordot = torch.tensordot(BA, B, dims =([1],[1]))#.unsqueeze(-1) ''' res_using_tensordot : tensor([[580., 650., 720.], [650., 730., 810.], [720., 810., 900.]]) ''' diagonal_result = torch.diagonal(res_using_tensordot, 0).unsqueeze(1) ''' tensor([[580.], [730.], [900.]]) '''
Question: I have the following code: from typing import TypeVar, Any, Generic class Foo: ... class Bar(Generic[FooT]): def __init__(self, foo: FooT): self._foo = foo FooT = TypeVar('FooT', bound=Foo) T = TypeVar('T') def func(a: FooT | T) -> Bar[FooT] | T: if isinstance(a, Foo): return Bar(a) return a def my_other_func(a: Foo) -> None: func(a)   func takes either a Foo subclass and returns Bar which wraps that Foo object, or returns the input unaltered  I thought I could type it as def func(a: FooT | T) -> Bar[FooT] | T:  But if I run mypy on this I get main.py:18: error: Argument 1 to "Bar" has incompatible type "Foo"; expected "FooT" [arg-type] main.py:22: error: Argument 1 to "func" has incompatible type "Foo"; expected "Never" [arg-type] Found 2 errors in 1 file (checked 1 source file)  and I don't understand either. How should I have typed it?

Answer: Use typing.overload: from typing import TypeVar, Generic class Foo: ... FooT = TypeVar('FooT', bound=Foo) class Bar(Generic[FooT]): def __init__(self, foo: FooT): self._foo = foo T = TypeVar('T') @overload def func(a: FooT) -> Bar[FooT]: ... @overload def func(a: T) -> T: ... def func(a): if isinstance(a, Foo): return Bar(a) return a def my_other_func(a: Foo) -> None: func(a)  Essentially, Callable[[FooT|T], Bar[FooT]|T] is not the same as Callable[[FooT], Bar[FooT]] | Callable[[T], T]. typing.overload lets you define the latter instead of the former.
Question: I am trying to draw a simple exponential in python. When using the code below, everything works fine and the exponential is shown import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np def graph(func, x_range): x = np.arange(*x_range) y = func(x) plt.plot(x, y) graph(lambda x: pow(3,x), (0,20)) plt.savefig("mygraph.png")  However if I change the range from 20 to 30, it draws a curve which is not exponential at all.  Why is that happening?

Answer: I can't make time to nail this now, but the graph looks a whole lot like what I'd expect if integer arithmetic is overflowing. numpy's ints are fixed-width, unlike Python's ints (which are unbounded). In particular, >>> 3**20 3486784401 >>> _.bit_length() 32  so at the point things start to go crazy the result is overflowing a 32-bit int. Try replacing the 3 with 3.0 in your pow(3,x)?
Question: Using python 3.10: I have a function with a first argument and then *args and **kwargs. I want to bind the first argument and leave the *args and **kwargs free. If I do this and the bound function gets called using a list of arguments, python interprets it as multiple values for the bound argument. An example: from functools import partial def foo1(a : int, *args, **kwargs): print(a) print(args) print(kwargs) pfoo1 = partial(foo1, a=10) pfoo1() # works pfoo1(something="testme") # works # pfoo1("testme") # !! interpreted as multiple values for argument a? # pfoo1(*("testme")) # !! interpreted as multiple values for argument a? # pfoo1(*["testme"]) # !! interpreted as multiple values for argument a?  I know I can easily solve this by replacing the foo1 function with: def foo1(*args, **kwargs): print(args) print(kwargs)  And then running the same code, but I do not have the luxury of control over the incoming functions so I am stuck with a given signature. A solution could be to create one's own partial class through lambdas and bound members, but that seems excessive. Is there a way of doing this in the partial framework or at least a simple way?

Answer: a is the first parameter to function foo1. If you want a partial, do not use keyword:  pfoo1 = partial(foo1, 10)
Question: How can I replace the first index 0 with "Color" and 1 with "Size"? import pandas as pd clothes = {"shirt": ["red", "M"], "sweater": ["yellow", "L"], "jacket": ["black", "L"]} # pd.DataFrame.from_dict(clothes) df = pd.DataFrame.from_dict(clothes) df  I tried like this but nothing changes. The output shows index name as an error df = pd.DataFrame.from_dict(clothes, index = ['color', 'size']) 

Answer: don't use from_dict, but the DataFrame constructor directly: df = pd.DataFrame(clothes, index=['color', 'size'])  If the DataFrame is already existing, set_axis: df = pd.DataFrame(clothes) df = df.set_axis(['color', 'size'])  output:  shirt sweater jacket color red yellow black size M L L
Question: I have a polars dataframe that contain some ID, actions, and values : Example Dataframe: data = { "ID" : [1, 1, 2,2,3,3], "Action" : ["A", "A", "B", "B", "A", "A"], "Where" : ["Office", "Home", "Home", "Office", "Home", "Home"], "Value" : [1, 2, 3, 4, 5, 6] } df = pl.DataFrame(data)  I want to select for each ID and action the biggest value, so i know where he rather do the action. I'm taking the following approach : ( df .select( pl.col("ID"), pl.col("Action"), pl.col("Where"), TOP = pl.col("Value").max().over(["ID", "Action"])) )  After that , i sorted the values and keep the unique values (The first one) to maintain the desired info, however the input its incorrect : ( df .select( pl.col("ID"), pl.col("Action"), pl.col("Where"), TOP = pl.col("Value").max().over(["ID", "Action"])) .sort( pl.col("*"), descending =True ) .unique( subset = ["ID", "Action"], maintain_order = True, keep = "first" ) )  Current Output : shape: (3, 4) ┌─────┬────────┬────────┬─────┐ │ ID ┆ Action ┆ Where ┆ TOP │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str ┆ i64 │ ╞═════╪════════╪════════╪═════╡ │ 3 ┆ A ┆ Home ┆ 6 │ │ 2 ┆ B ┆ Office ┆ 4 │ │ 1 ┆ A ┆ Office ┆ 2 │ └─────┴────────┴────────┴─────┘  Expected Output: shape: (3, 4) ┌─────┬────────┬────────┬─────┐ │ ID ┆ Action ┆ Where ┆ TOP │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str ┆ i64 │ ╞═════╪════════╪════════╪═════╡ │ 3 ┆ A ┆ Home ┆ 6 │ │ 2 ┆ B ┆ Office ┆ 4 │ │ 1 ┆ A ┆ Home ┆ 2 │ └─────┴────────┴────────┴─────┘  Also, i think this approach its not the optimal way

Answer: The over and unique could be combined into a group_by  .arg_max() can give you the index of the max .get() will extract the corresponding values at that index  (df.group_by("ID", "Action") .agg( pl.all().get(pl.col("Value").arg_max()) ) )  shape: (3, 4) ┌─────┬────────┬────────┬───────┐ │ ID ┆ Action ┆ Where ┆ Value │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str ┆ i64 │ ╞═════╪════════╪════════╪═══════╡ │ 1 ┆ A ┆ Home ┆ 2 │ │ 2 ┆ B ┆ Office ┆ 4 │ │ 3 ┆ A ┆ Home ┆ 6 │ └─────┴────────┴────────┴───────┘
Question: I am using Python 3.10.7 64-bit in VSCode. I have a Python package "pxml" built using setuptools. It is in a folder with an empty __init.py__ and a pyproject.toml containing: [build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [project] name = "pxml" version = "0.0.1" dependencies = []  When installed normally with python -m pip install path/to/folder, an import pxml works just fine. However, when installed with python -m pip install -e path/to/folder, I get the error "Import 'pxml' cannot be resolved." python -m pip list shows the package installed and when I run a simple test file to access one of pxml's methods it runs just fine. Making sure that I am using the same python version in the terminal, python -c "import pxml" reports no errors. One thing that does show up as an autocomplete option when I type import pxml is __editable___pxml_0_0_1_finder, not sure if that is a clue. The directory structure is:  - src + XML * pxml.py * __init__.py * pyproject.toml + test.py  I am using test.py to import pxml. Any ideas?

Answer: For the package structure shown in your question, this is import statement is incorrect: import pxml  pxml is not a top-level import, it is a submodule of a package named XML. If python -c "import pxml" works that is only by accident and you happen to have pxml visible on sys.path for some reason - perhaps the subdirectory XML is your current working directory, and it is resolved that way because the first element of sys.path is the empty string. Instead, the import should be one of: import XML.pxml  or from XML import pxml
Question: Recently, I started using Altair and liked it a lot. However, I stumbled across something I could not figure out using the docs: I have a scatter plot that encodes some continuous data as color. Is there a way of selecting a range of these values via the colorbar? Similar to how it is possible to select discrete features in a clickable legend. I tried the following code: cars = data.cars() colorbar_brush = alt.selection_interval(fields=["Acceleration"], bind="legend") chart = alt.Chart(cars).mark_circle().encode( x="Horsepower", y="Miles_per_Gallon", color=alt.condition(colorbar_brush, "Acceleration:Q", alt.value("lightgray")), ).add_params( colorbar_brush, )  I also tried colorbar_brush = alt.selection_interval(encodings=["color"], bind="legend")  Both did not work. Alternatively, it is possible to use separate charts as clickable legends. But how could I create a chart of a color gradient?

Answer: As @joelostblom mentioned in his comment you can use a second plot to generate a color scale with a selection interval. I have implemented this using a mark_tick with good results. Most of the options for the scale chart's y encoding are only for aesthetics and can be removed / tweaked as desired. cars = data.cars() color_encoding = alt.Color("Acceleration:Q", legend=None) selection = alt.selection_interval(encodings=["y"]) chart = ( alt.Chart(cars) .mark_circle() .encode( x="Horsepower", y="Miles_per_Gallon", color=alt.condition(selection, color_encoding, alt.ColorValue("lightgray")), ) ) legend_chart = ( alt.Chart( alt.sequence( min(cars.Acceleration), max(cars.Acceleration), 0.01, as_="Acceleration" ) ) .mark_tick(orient="horizontal") .encode( y=alt.Y( "Acceleration:Q", axis=alt.Axis( orient="right", ticks=False, grid=False, titleAngle=0, titleAnchor="end", titleAlign="center", titleBaseline="bottom", titleY=-10, tickCount=3 ), ).scale(zero=False, padding=0), color=color_encoding, ) ).add_params(selection) chart | legend_chart
Question: I'm trying to get all keys from a python dict which has the same value. as part of this, I have made the below attempt and it works. but checking if there is a neater way to do this. I have gone through the thread Finding all the keys with the same value in a Python dictionary b = {'a1': ['b1', 'b2', 'b3'], 'a2': ['b1', 'b2', 'b3'], 'a3': ['b4', 'b5', 'b6'], 'a4': ['b4', 'b5', 'b6'] } c = [] for i in b.values(): if i not in c: c.append(i) f = list() for i in c: print(i) e = [k for k, v in b.items() if v == i] print(e) f.append((i, e)) print(f)  This gives the output as: [(['a1', 'a2'], ['b1', 'b2', 'b3']), (['a3', 'a4'], ['b4', 'b5', 'b6'])]

Answer: Why not go for defaultdict it is proven to be quite efficient and faster and you dont have to worry about getting errors such as the famous KeyError.. Ref: Stackoverflow_old_question I am not sure but python lawyers might have me for this and also tuple my guess is that your b1, b2, b3 needs to be immutable, I would go for this implementation which provides readability from collections import defaultdict b = { 'a1': ['b1', 'b2', 'b3'], 'a2': ['b1', 'b2', 'b3'], 'a3': ['b4', 'b5', 'b6'], 'a4': ['b4', 'b5', 'b6'] } # group keys with collections group_keys = defaultdict(list) for k, v in b.items(): group_keys[tuple(v)].append(k) # make use of packing ans = [(v, [*k]) for k, v in group_keys.items()] print(ans)  clean result: [(['a1', 'a2'], ['b1', 'b2', 'b3']), (['a3', 'a4'], ['b4', 'b5', 'b6'])]  Bench mark testing: Average Execution Time for the code above: 1.921582967042923e-06 seconds Average Execution Time for large dataset: 0.01955163748934865 seconds Average Execution Time for larger dataset: 2.0231823625043033 seconds  Taking advise from @nocomment: If you are using python --version : 3.12, this should also work nicely for k, v in b.items(): group_keys[*v].append(k) # make use of packing ans = [(v, [*k]) for k, v in group_keys.items()] print(ans)
Question: There are some sentences and words in Chinese and Japanese that I just want to drop. Or if there is a better solution than just dropping them, I would like to explore them as well. import pandas as pd import re # Define the function to check for English text def is_english(text): # Regex pattern for English letters, numbers, and common English symbols pattern = r"^[A-Za-z0-9\s.,!?\'\"()@#$%^&*;:\[\]{}±_+=/\\|`~]*$" return bool(re.match(pattern, text)) # Apply the function to check each relevant column and create a boolean mask df["is_english"] = df_clean.apply( lambda row: is_english(str(row.get("column_name1", ""))) if isinstance(row.get("column_name1", ""), str) else False and is_english(str(row.get("column_name2", ""))) if isinstance(row.get("column_name2", ""), str) else False, axis=1, ) # Delete rows where at least one relevant column contains non-English characters df_cleaned = df_clean[listings_clean["is_english"]].drop( columns="is_english" ) 

Answer: If you just want to keep ASCII characters, be explicit, select those and drop the rest with str.replace: df = pd.DataFrame({'col': ['Aaäá😀αあ今']}) df['ascii'] = df['col'].str.replace(r'[^\x00-\x7F]', '', regex=True)  You can also remove specific character ranges: # removing CJK, CJK symbols, hiragana, katakana # you can add all desired blocks here df['non_chinese_japanese'] = df['col'].str.replace( r'[\u4E00-\u9FFF\u3000-\u303F\u3040-\u309F\u30A0-\u30FF]', '', regex=True )  Output:  col ascii non_chinese_japanese 0 Aaäá😀αあ今 Aa Aaäá😀α
Question: I have a Polars (v1.5.0) dataframe with 4 columns as shown in example below. When I multiply decimal columns with an integer column, the scale of the resultant decimal column doubles. from decimal import Decimal import polars as pl df = pl.DataFrame({ "a": [1, 2], "b": [Decimal('3.45'), Decimal('4.73')], "c": [Decimal('2.113'), Decimal('4.213')], "d": [Decimal('1.10'), Decimal('3.01')] })  shape: (2, 4) ┌─────┬──────────────┬──────────────┬──────────────┐ │ a ┆ b ┆ c ┆ d │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ decimal[*,2] ┆ decimal[*,3] ┆ decimal[*,2] │ ╞═════╪══════════════╪══════════════╪══════════════╡ │ 1 ┆ 3.45 ┆ 2.113 ┆ 1.10 │ │ 2 ┆ 4.73 ┆ 4.213 ┆ 3.01 │ └─────┴──────────────┴──────────────┴──────────────┘  df.with_columns(pl.col("c", "d").mul(pl.col("a")))  shape: (2, 4) ┌─────┬──────────────┬──────────────┬──────────────┐ │ a ┆ b ┆ c ┆ d │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ decimal[*,2] ┆ decimal[*,6] ┆ decimal[*,4] │ ╞═════╪══════════════╪══════════════╪══════════════╡ │ 1 ┆ 3.45 ┆ 2.113000 ┆ 1.1000 │ │ 2 ┆ 4.73 ┆ 8.426000 ┆ 6.0200 │ └─────┴──────────────┴──────────────┴──────────────┘  I don't know why the scale doubles, when I am just multiplying a decimal with an integer. What do I do so that the scale does not change?

Answer: The scale indeed seems to double. You could cast back to the original dtype: cols = ['c', 'd', 'e'] df.with_columns(pl.col(c).mul(pl.col('a')).cast(df[c].dtype) for c in cols)  Note that there currently doesn't seem to be a way to access the dtype in an Expr, but this is a discussed feature. Example: ┌─────┬─────┬──────────────┬──────────────┬──────────────┐ │ a ┆ b ┆ c ┆ d ┆ e │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ decimal[*,2] ┆ decimal[*,3] ┆ decimal[*,4] │ ╞═════╪═════╪══════════════╪══════════════╪══════════════╡ │ 1 ┆ 3 ┆ 2.11 ┆ 1.100 ┆ 1.1001 │ │ 2 ┆ 4 ┆ 8.42 ┆ 6.022 ┆ 6.0004 │ └─────┴─────┴──────────────┴──────────────┴──────────────┘  Used input: from decimal import Decimal df = pl.DataFrame({ "a": [1, 2], "b": [3, 4], "c": [Decimal('2.11'), Decimal('4.21')], "d": [Decimal('1.10'), Decimal('3.011')], "e": [Decimal('1.1001'), Decimal('3.0002')], })