eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I have a tsv file that contains integers with thousand separators. I'm trying to read it using polars==1.6.0, the encoding is utf-16 from io import BytesIO import polars as pl data = BytesIO( """ Id\tA\tB 1\t537\t2,288 2\t325\t1,047 3\t98\t194 """.encode("utf-16") ) df = pl.read_csv(data, encoding="utf-16", separator="\t") print(df)  I cannot figure out how to get polars to treat column "B" as integer rather than string, and I also cannot find a clean way of casting it to an integer. shape: (3, 3) ┌────────┬─────┬───────┐ │ Id ┆ A ┆ B │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str │ ╞════════╪═════╪═══════╡ │ 1 ┆ 537 ┆ 2,288 │ │ 2 ┆ 325 ┆ 1,047 │ │ 3 ┆ 98 ┆ 194 │ └────────┴─────┴───────┘  cast fails, as does passing the schema explicitly. I also tried using str.strip_chars and to remove the comma, my work-around is to use str.replace_all instead. df = df.with_columns( pl.col("B").str.strip_chars(",").alias("B_strip_chars"), pl.col("B").str.replace_all("[^0-9]", "").alias("B_replace"), ) print(df)  shape: (3, 5) ┌────────┬─────┬───────┬───────────────┬───────────┐ │ Id ┆ A ┆ B ┆ B_strip_chars ┆ B_replace │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str ┆ str ┆ str │ ╞════════╪═════╪═══════╪═══════════════╪═══════════╡ │ 1 ┆ 537 ┆ 2,288 ┆ 2,288 ┆ 2288 │ │ 2 ┆ 325 ┆ 1,047 ┆ 1,047 ┆ 1047 │ │ 3 ┆ 98 ┆ 194 ┆ 194 ┆ 194 │ └────────┴─────┴───────┴───────────────┴───────────┘  Also for this to work in general I'd need to ensure that read_csv doesn't try and infer types for any columns so I can convert them all manually (any numeric column with a value > 999 will contain a comma)

Answer: To allow for possible multiple , separators use .str.replace_all: df = df.with_columns(pl.col('B').str.replace_all(",", "").cast(pl.Int64))  which gives for the sample data:  shape: (3, 3) ┌─────┬─────┬──────┐ │ Id ┆ A ┆ B │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪══════╡ │ 1 ┆ 537 ┆ 2288 │ │ 2 ┆ 325 ┆ 1047 │ │ 3 ┆ 98 ┆ 194 │ └─────┴─────┴──────┘
Question: I have a Polars dataframe with a lot of duplicate data I would like to consolidate. Input: shape: (3, 2) ┌─────┬──────┐ │ id ┆ data │ │ --- ┆ --- │ │ i64 ┆ str │ ╞═════╪══════╡ │ 1 ┆ a │ │ 1 ┆ b │ │ 1 ┆ c │ └─────┴──────┘  My current (non-working) solution: df = pl.DataFrame({'id': [1, 1, 1], 'data': ['a', 'b', 'c']}) df = df.join(df.select('id', 'data'), on='id')  Output: shape: (9, 3) ┌─────┬──────┬────────────┐ │ id ┆ data ┆ data_right │ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str │ ╞═════╪══════╪════════════╡ │ 1 ┆ a ┆ a │ │ 1 ┆ b ┆ a │ │ 1 ┆ c ┆ a │ │ 1 ┆ a ┆ b │ │ 1 ┆ b ┆ b │ │ 1 ┆ c ┆ b │ │ 1 ┆ a ┆ c │ │ 1 ┆ b ┆ c │ │ 1 ┆ c ┆ c │ └─────┴──────┴────────────┘  Desired output: shape: (1, 4) ┌─────┬────────┬────────┬────────┐ │ id ┆ data_1 ┆ data_2 ┆ data_3 │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str ┆ str │ ╞═════╪════════╪════════╪════════╡ │ 1 ┆ a ┆ b ┆ c │ └─────┴────────┴────────┴────────┘  It seems like a self join would be the way to get a table with all the columns I want, but I'm unsure how to write a self join that would include multiple columns instead of just a bunch of rows with only two, and looping through self joins does not seem like the correct thing to do as it quickly balloons in size. This isn't specifically a Polars problem, but I am working in Python-Polars

Answer: The following gives you a df in the format you want: import polars as pl df = ( pl.DataFrame({"id": [1, 1, 1], "data": ["a", "b", "c"]}) .group_by("id") .agg(pl.col("data")) .with_columns(structure=pl.col("data").list.to_struct()) .unnest("structure") .drop("data") ) print(df) """ ┌─────┬─────────┬─────────┬─────────┐ │ id ┆ field_0 ┆ field_1 ┆ field_2 │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str ┆ str │ ╞═════╪═════════╪═════════╪═════════╡ │ 1 ┆ a ┆ b ┆ c │ └─────┴─────────┴─────────┴─────────┘ """
Question: I have a data frame with 4 columns. The columns are: Home_team, Away_team, Home_team_goal, Away_team_goal I want to create a winner column by using goals. I wrote the code below, but when I run it, I get only home teams in the winner column. A = ['A', '1', 'D', '2'] B = ['B', '2', 'E', '2'] C = ['C', '3', 'F', '2'] df = pd.DataFrame(np.array([A,B,C]), columns = ['Home_team', 'Home_team_goal', 'Away_team', 'Away_team_goal']) df['Home_team_goal'] = pd.to_numeric(df['Home_team_goal']) df['Away_team_goal'] = pd.to_numeric(df['Away_team_goal']) df['Average'] = df['Home_team_goal'] - df['Away_team_goal'] df['Winner'] = '' for i, e in enumerate(df['Average']): if e > 0: df['Winner'] = df['Home_team'] elif e < 0: df['Winner'] = df['Away_team'] else: df['Winner'] = 'Tie' 

Answer: Here another approach: def Winner(x): if x > 0: return 1 elif x < 0: return 2 else: return 0 df['Winner'] = df['Average'].apply(Winner)
Question: I have a dataframe that has a field called fields which is a list of dicts (all rows have the same format). Here is how the dataframe is structured: formId fields 123 [{'number': 1, 'label': 'Last Name', 'value': 'Doe'}, {'number': 2, 'label': 'First Name', 'value': 'John'}]  I am trying to unpack the fields column so it looks like: formId Last Name First Name 123 Doe John  The code I have currently is: for i,r in df.iterrows(): for field in r['fields']: df.at[i, field['label']] = field['value']  However this does not seem like the most efficient way. Is there a better way to accomplish this?

Answer: Personally, I'd construct new dataframe: df = pd.DataFrame( [ {"formId": form_id, **{f["label"]: f["value"] for f in fields}} for form_id, fields in zip(df["formId"], df["fields"]) ] ) print(df)  Prints:  formId Last Name First Name 0 123 Doe John
Question: How can I include a decorated function inside a Python doctest? def decorator(func): def wrapper() -> None: func() return wrapper def foo() -> None: """ Stub. Examples: >>> @decorator >>> def stub(): ... """ if __name__ == "__main__": import doctest doctest.testmod()  Running the above with Python 3.12 throws a SyntaxError: UNEXPECTED EXCEPTION: SyntaxError('invalid syntax', ('<doctest path.to.a[0]>', 1, 0, '@decorator\n', 1, 0)) 

Answer: Multi-line commands should use ... for continuation lines. So the proper way is to use ... instead of >>> on the second line: def foo() -> None: """ Stub. Examples: >>> @decorator ... def stub(): ... """
Question: I am a bit confused about the proper way to deal with complex numbers in polar form and the way to separate its real and imaginary part. Notice that I am expecting as real part the radius, as imaginary part the angle. The inbuilt re and im functions get always the real and imaginary part of the Cartesian representation of the complex number. Here an example from sympy import I, pi, re, im, exp, sqrt # complex num in Cartesian form z = -4 + I*4 print(re(z), im(z)) # 4 -4 # complex num in polar form z = 4* sqrt(2) * exp(I * pi * 3/4) print(re(z), im(z)) # 4 -4 but expacting 4*sqrt(2), pi*3/4  What is the most SymPytonic way to deal with such problem?

Answer: Maybe you are looking for Abs and arg functions? z = -4 + I*4 print(Abs(z), arg(z)) # 4*sqrt(2) 3*pi/4 z = 4* sqrt(2) * exp(I * pi * 3/4) print(Abs(z), arg(z)) # 4*sqrt(2) 3*pi/4
Question: I am trying to switch values between the Range and Unit columns in the dataframe below based on the condition that if Unit contains -, then replace Unit with Range and Range with Unit. To do that, I am creating a unit_backup column so that I don't lose the original Unit value. 1. dataframe sample_df = pd.DataFrame({'Range':['34-67',12,'gm','45-90'], 'Unit':['ml','35-50','10-100','mg']}) sample_df   Range Unit 0 34-67 ml 1 12 35-50 2 gm 10-100 3 45-90 mg  2. Function Below is the code I have tried but I am getting an error in this: def range_unit_correction_fn(df): # creating backup of Unit column df['unit_backup'] = df['Unit'] # condition check if df['unit_backup'].str.contains("-"): # if condition is True then replace `Unit` value with `Range` and `Range` with `unit_backup` df['Unit'] = df['Range'] df['Range'] = df['unit_backup'] else: # if condition False then keep the same value df['Range'] = df['Range'] # drop the backup column df = df.drop(['unit_backup'],axis=1) return df   Applying the above function on the dataframe  sample_df = sample_df.apply(range_unit_correction_fn, axis=1) sample_df  Error:  1061 def apply_standard(self): 1062 if self.engine == "python": -> 1063 results, res_index = self.apply_series_generator() ... ----> 4 if df['unit_backup'].str.contains("-"): 5 df['Unit'] = df['Range'] 6 df['Range'] = df['unit_backup'] AttributeError: 'str' object has no attribute 'str'  It seems like some silly mistake, but I am not sure where I am going wrong. Appreciate any sort of help here.

Answer: When you access df['unit_backup'], you get a scalar string value, not a pandas Series, so calling .str on it raises an error. To fix it you can check the condition directly on the string value in a row-wise approach: def range_unit_correction_fn(df): # creating backup of Unit column df['unit_backup'] = df['Unit'] # condition check if '-' in df['unit_backup']: # if condition is True then replace `Unit` value with `Range` and `Range` with `unit_backup` df['Unit'] = df['Range'] df['Range'] = df['unit_backup'] # drop the backup column df = df.drop(['unit_backup']) return df
Question: I'm having some problems rendering axis date correctly in Shiny for Python with plotly surface plots. In particular, axis of type date are render as floats. Find here an example in shiny playground. Note that same exact code works if I render the figure with fig.show() outside of Shiny for Python (i.e. the x axis renders as a date not as a float). I already tried to explicitly cast the layout of the figure as fig.update_layout( scene=dict( xaxis=dict( type="date", tickformat='%Y' ) )  But I get even worst result (figure not rendering at all).

Answer: Replace the @render_widget with express.render.ui and replace the return fig with return ui.HTML(fig.to_html()) (see express.ui.HTML and plotly.io.to_html).  Link to playground import plotly.graph_objects as go import pandas as pd import numpy as np from shiny.express import render, ui def plotSurface(plot_dfs: list, names: list, title: str, **kwargs): """helper function to plot multiple surface with ESM color themes. Args: plot_dfs (list): list of dataframes containing the matrix. index of each df is datetime format and columns are maturities names (list): list of names for the surfaces in plot_dfs title (str): title of the plot Raises: TypeError: _description_ TypeError: _description_ ValueError: _description_ Returns: Figure: plotly figure """ for i, plot_df in enumerate(plot_dfs): if not isinstance(plot_df.index, pd.core.indexes.datetimes.DatetimeIndex): raise TypeError(f"plot_df number {i} in plot_dfs should have an index of type datetime but got {type(plot_df.index)}") if not (isinstance(plot_dfs, list) and isinstance(names, list)): raise TypeError(f"both plot_dfs and names should be list. Instead got {type(plot_dfs), {type(names)}}") if len(plot_dfs) != len(names): raise ValueError(f"plot_dfs and names should have the same length but got {len(plot_dfs)} != {len(names)}") fig = go.Figure() # stack surfaces. The last one will overwrite the first one when values are equal for i, (plot_df, name) in enumerate(zip(plot_dfs, names)): X, Y = np.meshgrid(plot_df.index, plot_df.columns) Z = plot_df.values.T fig.add_trace(go.Surface(z=Z, x=X, y=Y, name=name, showscale=False, showlegend=True, opacity=0.9)) # Update layout for better visualization and custom template fig.update_layout( title=title, title_x=0.5, scene=dict( xaxis_title='Date', yaxis_title='Maturity', zaxis_title='Value', ), margin=dict(l=30, r=30, b=30, t=50), # template=esm_theme, legend=dict(title="Legend"), ) return fig @render.ui def plot_1(): plot_dfs = [ pd.DataFrame( index = pd.to_datetime([f"{y}/01/01" for y in range(2020, 2100)]), columns = ["3m", "6m", "9m"] + [f"{y}Y" for y in range(1,31)], data = 1 ) ] fig = plotSurface(plot_dfs, names=["t"], title=" ") return ui.HTML(fig.to_html())
Question: I am trying to calculate the IRR for a month using numpy_financial, but I am not succeeding. At which position in the array am I making a mistake? For example: initial_balance = 579676.18 final_balance = 2921989.17  From what I understand from the documentation, the final balance should be treated as a withdrawal (positive value) on the last day because it calculates as zero. The cash flows are an array of 31, corresponding to the number of days in that month: [0, 22700.00, 0 ,0 ,0 ,5320.00 ,0 ,0 ,-39900.00 ,0 ,0 ,0 ,0 ,0 ,0 ,-2278500.00 ,0, 31472.00, -42000.00, 0 , 0 , 0, -70300.00, 0, 0, 0, 0, 0, 0,36650.00, 0]  So, from what I understand from the documentation, the final array should be an array of 32? With the first being the initial balance and the other 31 being the daily cash flows + final balance? [initial_balance, 0, 22700.00, 0, 0, 0, 5320.00, 0, 0, -39900.00, 0, 0, 0, 0, 0, 0, -2278500.00, 0, 31472.00, -42000.00, 0, 0, 0, -70300.00, 0, 0, 0, 0, 0, 0, 36650.00, final_balance]  The correct IRR for this is 0.0001465, but the output is 0.001685. What am I doing wrong? from numpy_financial import irr final_array = [initial_balance, 0, 22700.00, 0, 0, 0, 5320.00, 0, 0, -39900.00, 0, 0, 0, 0, 0, 0, -2278500.00, 0, 31472.00, -42000.00, 0, 0, 0, -70300.00, 0, 0, 0, 0, 0, 0, 36650.00, final_balance] irr(final_array) 

Answer: According to the document:  Thus, for example, at least the first element of values, which represents the initial investment, will typically be negative.  Your initial_balance should be negative, rest everything is correct in your example. from numpy_financial import irr final_array = [-initial_balance, 0, 22700.00, 0, 0, 0, 5320.00, 0, 0, -39900.00, 0, 0, 0, 0, 0, 0, -2278500.00, 0, 31472.00, -42000.00, 0, 0, 0, -70300.00, 0, 0, 0, 0, 0, 0, 36650.00, final_balance] # see negative sign before initial_balance irr(final_array)  #Output 0.00014651601147774862
Question: I've been asked to add some BASH script to a server .bashrc file so I can then initialise conda. When I log into the server, I get the following message: Last login: Wed Aug 28 16:57:04 2024 from {IP ADDRESS} -bash: /home/{username}/.bashrc: line 129: syntax error near unexpected token `then' -bash: /home/{username}/.bashrc: line 129: ` if [ -f "/opt/anaconda3/etc/profile.d/conda.sh" ]; then'  Here's the code: # >>> conda initialize >>> # !! Contents within this block are managed by 'conda init' !! __conda_setup="$('/opt/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)" if [ $? -eq 0 ]; then eval "$__conda_setup" else if [ -f "/opt/anaconda3/etc/profile.d/conda.sh" ]; then . "/opt/anaconda3/etc/profile.d/conda.sh" else export PATH="/opt/anaconda3/bin:$PATH" fi fi unset __conda_setup # <<< conda initialize <<<  I ran the bash script through shellcheck and it produced this: Line 126: if [ $? -eq 0 ]; then ^-- SC1046 (error): Couldn't find 'fi' for this 'if'. ^-- SC1073 (error): Couldn't parse this if expression. Fix to allow more checks. Line 129: if [ -f "/opt/anaconda3/etc/profile.d/conda.sh" ]; then ^-- SC1047 (error): Expected 'fi' matching previously mentioned 'if'. >> ^-- SC1072 (error): Unexpected keyword/token. Fix any mentioned problems and try again  Can anybody see the error? Edit: The /opt/anaconda3/bin/conda file is definitely there, and the /opt/anaconda3/etc/profile.d/conda.sh file is also there.

Answer: Your file is filled with non-ASCII characters. For example, here's a hexdump of line 7: $ sed -n 7p foo.sh | xxd 00000000: e280 afe2 80af e280 af20 6966 205b 202d ......... if [ - 00000010: 6620 222f 6f70 742f 616e 6163 6f6e 6461 f "/opt/anaconda 00000020: 332f 6574 632f 7072 6f66 696c 652e 642f 3/etc/profile.d/ 00000030: 636f 6e64 612e 7368 2220 5d3b 2074 6865 conda.sh" ]; the 00000040: 6e0a n.  The byte sequence e280f is a NARROW NO-BREAK SPACE, and bash doesn't know what to do with that. Replace all the whitespace with actual spaces; the code is otherwise correct. # >>> conda initialize >>> # !! Contents within this block are managed by 'conda init' !! __conda_setup="$('/opt/anaconda3/bin/conda' 'shell.bash' 'hook' 2>/dev/null)" if [ $? -eq 0 ]; then "$__conda_setup" else if [ -f "/opt/anaconda3/etc/profile.d/conda.sh" ]; then . "/opt/anaconda3/etc/profile.d/conda.sh" else export PATH="/opt/anaconda3/bin:$PATH" fi fi unset __conda_setup # <<< conda initialize <<<
Question: I have a simple Polars dataframe with some nulls and some NaNs and I want to drop only the latter. I'm trying to use drop_nans() by applying it to all columns and for whatever reason it replaces NaNs with a literal 1.0. I am confusion. Maybe I'm using the method wrong, but the docs don't have much info and definitely don't describe this behaviour: ex = pl.DataFrame( { 'a': [float('nan'), 1, float('nan')], 'b': [None, 'a', 'b'] } ) ex.with_columns(pl.all().drop_nans()) Out: a b 1.0 null 1.0 "a" 1.0 "b"  I'm using the latest Polars 1.5. What is the correct way of dropping NaNs across all the columns given that in Polars 1.5 dataframes don't seem to have drop_nans() method, only the Series do? EDIT: I'm expecting the result should be: a b 1.0 'a' 

Answer: What happens in your example is that drop_nans works on a per-column basis. It will first convert the series [float('nan'), 1, float('nan')] to [1], and then broadcast that value to the entire column when combined with ["a", "b"]. It does this because Polars doesn't have a concept of a scalar value yet, and it will treat any column with a single value as such when deciding when to broadcast. In the future this will change, but it is a lot of work. So right now you can see incorrect broadcasts like that when using functions that filter columns, like drop_nan, if it happens to filter down to a length-1 column. Instead of doing pl.all().drop_nans() you should filter to just those rows where column a is not nan: >>> df.filter(pl.col.a.is_not_nan()) shape: (1, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ f64 ┆ str │ ╞═════╪═════╡ │ 1.0 ┆ a │ └─────┴─────┘  Or more generically, if you have multiple columns with floating-point values: >>> import polars.selectors as cs >>> df.filter(pl.all_horizontal(cs.float().is_not_nan())) shape: (1, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ f64 ┆ str │ ╞═════╪═════╡ │ 1.0 ┆ a │ └─────┴─────┘
Question: I wanted to create a ForeignKey field in Django using .annotate, but I couldn't find any option for it, maybe it doesn't exist. I just want to LEFT JOIN a specific model with a specific condition. But now I have to do it like this: queyrset = Invoice.objects.annotate(provided_amount=Subquery(InvoicePayment.objects.filter(invoice_id=OuterRef("id"), date=timezone.now().date()).values("provided_amount"))) queryset.first().provided_amount  But I want it like this: queryset = Invoice.objects.annotate(invoice_payment=...) queryset.first().invoice_payment.provided_amount  I could do it using property, but I don't want to do it like that, I would like to do everything in one query. Maybe there is a library for this? Django - 4.2.4 Python - 3.10 I tried creating a SQL VIEW and binding it to the model with managed = False, but it's not very convenient to do that every time.

Answer: Please don't use related_name='+': it means querying in reverse is now a lot harder. We can name the relation payments instead: class InvoicePayment(models.Model): invoice = models.ForeignKey( Invoice, on_delete=models.CASCADE, related_name='payments' ) date = models.DateField() provided_amount = models.DecimalField( max_digits=64, decimal_places=24, null=True ) class Meta: unique_together = ['invoice', 'date'] class Invoice(models.Model): pass Then, we can work with a FilteredRelation [Django-doc]: from django.db.models import FilteredRelation, Q qs = Invoice.objects.annotate( todays_payment=FilteredRelation( 'payments', condition=Q(payments__date=timezone.now().date()) ), ).select_related('todays_payment') and for example: qs.first().todays_payment.provided_amount
Question: The regex should match  /exampleline - match exampleline exampleline - match exampleline exampleline/ - match exampleline /exampleline/ - match exampleline  I tried ?\/(.+)\/? but it didn't work /exampleline/ and exampleline/ matched exampleline/, instead of exampleline

Answer: You can use negative lookarounds to assert that a match does not start with and does not end with a /: (?!/).+(?<!/)  Demo: https://regex101.com/r/EKOvzG/2
Question: I'm trying out uv to manage my Python project's dependencies and virtualenv but I can't see how to install all my dependencies for local development, including the dev dependencies. In my pyproject.toml I have this kind of thing: [project] name = "my-project" dependencies = [ "django", ] [tool.uv] dev-dependencies = [ "factory-boy", ] [tool.uv.pip] python-version = "3.10"  I can do the following to create a virtualenv and then generate a requirements.txt lockfile, which does not contain dev-dependencies (which is OK, because that is for production): $ uv venv --python 3.10 $ uv pip compile pyproject.toml -o requirements.txt  But I can't see how to install all the dependencies in my virtualenv. uv pip sync will use the requirements.txt. There's also uv sync but I don't understand how that differs, and trying that generates an error: error: Multiple top-level packages discovered in a flat-layout: ['conf', 'hines', 'docker', 'assets', 'node_modules']. 

Answer: To expand on the other good answers by Phil Dependency Groups With uv >= 0.4.27 we can use the new Python packaging feature dependency groups to make pyproject uv-agnostic: [project] name = "my-project" dynamic = ["version"] requires-python = ">=3.10" dependencies = ["django"] [dependency-groups] dev = ["factory-boy"]  Python Pinned Also can make use of .python-version to pin the project Python version, which be created manually or by uv python: uv python pin 3.10  Check version written to file $ cat .python-version 3.10  Dev venv With the above configuration in place, a developer virtualenv can be created with: uv sync  Finally activate venv: source .venv/bin/activate
Question: Is there a command for uv that exports/extracts just the dependencies declared as dev dependencies from the pyproject.toml file, for example to pass test dependencies to tox? uv add Django uv add pytest --dev  Results in this pyproject.toml: [project] dependencies = [ "django>=4.2.15", ] [tool.uv] dev-dependencies = [ "pytest>=8.3.2", ]  How can I generate a file that only contains the dev dependencies, basically a requirements-dev.txt? uv pip compile pyproject.toml does not include the dev deps, only the main deps. And I did not see an argument to make it include it: Resolved 4 packages in 83ms # This file was autogenerated by uv via the following command: # uv pip compile pyproject.toml asgiref==3.8.1 # via django django==4.2.15 # via hatch-demo (pyproject.toml) sqlparse==0.5.1 # via django typing-extensions==4.12.2 # via asgiref  For comparison, poetry has poetry export --only dev -o requirements-dev.txt, which will generate something like this: iniconfig==2.0.0 ; python_version >= "3.12" and python_version < "4.0" packaging==24.1 ; python_version >= "3.12" and python_version < "4.0" pluggy==1.5.0 ; python_version >= "3.12" and python_version < "4.0" pytest==8.3.2 ; python_version >= "3.12" and python_version < "4.0" 

Answer: Update uv to the version 0.4.11 or greater (uv self update), and use the following command: uv export --only-dev --no-hashes | awk '{print $1}' FS=' ;' > requirements-dev.txt