首页 > 编程问答 >Polars 数据框中的条件分配

Polars 数据框中的条件分配

时间:2024-07-25 07:13:00浏览次数:5  
标签:python python-polars

我想知道是否有一种方法可以在不使用 numpy 相关的情况下处理 Polars 数据框中的条件分配。

import polars as pl
import numpy as np

df = pl.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'C'],
                   'conference': ['East', 'East', 'East', 'West', 'West', 'East'],
                   'points': [11, 8, 10, 6, 6, 5],
                   'rebounds': [7, 7, 6, 9, 12, 8]})
shape: (6, 4)
┌──────┬────────────┬────────┬──────────┐
│ team ┆ conference ┆ points ┆ rebounds │
│ ---  ┆ ---        ┆ ---    ┆ ---      │
│ str  ┆ str        ┆ i64    ┆ i64      │
╞══════╪════════════╪════════╪══════════╡
│ A    ┆ East       ┆ 11     ┆ 7        │
│ A    ┆ East       ┆ 8      ┆ 7        │
│ A    ┆ East       ┆ 10     ┆ 6        │
│ B    ┆ West       ┆ 6      ┆ 9        │
│ B    ┆ West       ┆ 6      ┆ 12       │
│ C    ┆ East       ┆ 5      ┆ 8        │
└──────┴────────────┴────────┴──────────┘

使用 numpy,我们可以这样做:

conditions = [
    df['points'].le(6) & df['rebounds'].le(9),
    df['points'].gt(10) & df['rebounds'].gt(6)
]
choicelist = ['Bad','Good']

df.with_columns(rating = np.select(conditions, choicelist, 'Aveg'))
shape: (6, 5)
┌──────┬────────────┬────────┬──────────┬────────┐
│ team ┆ conference ┆ points ┆ rebounds ┆ rating │
│ ---  ┆ ---        ┆ ---    ┆ ---      ┆ ---    │
│ str  ┆ str        ┆ i64    ┆ i64      ┆ str    │
╞══════╪════════════╪════════╪══════════╪════════╡
│ A    ┆ East       ┆ 11     ┆ 7        ┆ Good   │
│ A    ┆ East       ┆ 8      ┆ 7        ┆ Aveg   │
│ A    ┆ East       ┆ 10     ┆ 6        ┆ Aveg   │
│ B    ┆ West       ┆ 6      ┆ 9        ┆ Bad    │
│ B    ┆ West       ┆ 6      ┆ 12       ┆ Aveg   │
│ C    ┆ East       ┆ 5      ┆ 8        ┆ Bad    │
└──────┴────────────┴────────┴──────────┴────────┘

可以使用 when.then.otherwise 语句来使用 Polars 执行条件分配。以下是实现请求的代码示例:

import polars as pl

df = pl.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'C'],
                   'conference': ['East', 'East', 'East', 'West', 'West', 'East'],
                   'points': [11, 8, 10, 6, 6, 5],
                   'rebounds': [7, 7, 6, 9, 12, 8]})

df = df.with_column(
    pl.when((pl.col("points") <= 6) & (pl.col("rebounds") <= 9))
    .then("Bad")
    .when((pl.col("points") > 10) & (pl.col("rebounds") > 6))
    .then("Good")
    .otherwise("Aveg")
    .alias("rating")
)

print(df)

此代码通过执行以下操作来工作:

  1. with_column 这用于基于现有列添加一个新列。
  2. pl.when.then.otherwise 此结构用于基于条件逻辑创建新列“评级”。
  3. pl.when((pl.col("points") <= 6) & (pl.col("rebounds") <= 9)) 这定义了第一个条件,其中如果“分数”小于或等于 6 且“篮板”小于或等于 9,则条件为真。
  4. .then("Bad") 如果第一个条件为真,则在“评级”列中分配值“差”。
  5. .when((pl.col("points") > 10) & (pl.col("rebounds") > 6)) 这定义了第二个条件,其中如果“分数”大于 10 且“篮板”大于 6,则条件为真。
  6. .then("Good") 如果第二个条件为真,则在“评级”列中分配值“好”。
  7. .otherwise("Aveg") 如果前两个条件都不为真,则为“评级”列分配默认值“平均”。
  8. .alias("rating") 这会将结果表达式命名为“评级”。

此方法利用了 Polars 的表达语言,为操作数据框提供了一种简洁且高效的方式。

标签:python,python-polars
From: 74122921

相关文章

  • Python multiprocessing.connection.Connection 的行为不符合规范
    根据python规范,recv()pythonConnection的方法,(从multiprocessing.Pipe()返回,当管道为空且管道的另一端关闭时抛出EOFError(这里参考:https://docs.python.org/3.9/library/multiprocessing.html#multiprocessing.connection.Connection.re......
  • 使用 python Flask 发送邮件中的图像
    我想发送一封包含html代码和图像的电子邮件但在gmail中它说图像已附加,我不想要这样,我只想要电子邮件正文中的图像。html_content=f"<imgsrc="cid:banner"alt=""style="width:80%;">"msg=MIMEMultipart('related')html_part=MIMEText(html_c......
  • 在 python requests modul 中,如何检查页面是否使用“POST”方法或“GET”方法
    如何使用python“requests”模块检查页面是否使用“GET”方法或“POST”方法。我期望输出为True或False,或者GET或Post预期代码:importrequestsurl=f"www.get_example.com"response=requests.get(url)ifresponse.check_get==True:print("get")你......
  • VS Code Python - 如果括号(括号、大括号等)未关闭,内联建议不起作用
    我遇到的问题是,当我在未闭合的括号或方括号“内部”开始变量名称时,VSCode将不会显示任何建议。但是,如果在键入变量名称之前闭合括号,则建议效果很好。如果我可以避免它,我宁愿不将自动完成括号关闭设置为True也不使用TabOut扩展。第一个屏幕截图显示建议在闭括号/方......
  • 在 Azure 上部署代码时使用 Python 的多处理模块是否有意义?
    我们的团队在Azure机器学习(AML)上部署了一个Python脚本来处理存储在Azure存储帐户上的文件。我们的管道由一个ForEach活动组成,该活动调用每个或列出的文件的Python脚本。从Azure数据工厂(ADF)运行它会触发多个单独的管道同时运行......
  • 我已成功安装 pypdf2 但无法将其导入到我的 python 文件中
    我已经成功安装了pypdf2模块,但在导入它时,我发现该模块丢失了。我尝试使用fromPyPDF2importPdfReader导入,但它不起作用此问题的各种解决方案是什么?在尝试导入PyPDF2时遇到问题。以下是可能导致此问题的一些常见原因和解决方案:安......
  • Python3打开图片时请求ConnectionResetError(10054)
    我试图从'http://xxx.jpg'之类的网站下载图片。代码:headers={'user-agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/66.0.3359.139Safari/537.36'}url='http://xxx.jpg'resp......
  • Jupyter Notebook 环境中的 Python 版本不匹配
    我遇到Jupyter笔记本启动横幅中报告的Python版本与我在笔记本中查询python--version时显示的版本之间的差异。启动横幅指示Python3.11.9,但是当我运行!python--version时,它返回Python3.11.7。我所做的步骤:basecondahas3.11.7versio......
  • Python XML 解析:字符串中的“<”被阻塞
    我有一个使用ET.XMLParser来解析CppCheckXML报告文件的Python模块。当尝试解析字符串中包含“<”的XML元素中的属性之一时,它会令人窒息,它会将其解释为格式错误的XML,例如:<errormsg="Includefile<iostream>notfound.">(注意字符和“iostream”之间的空格必须放......
  • 任意几行代码要成为Python中的函数需要什么?
    我正在上一门计算机科学课,我的任务是创建一个程序来实现一个带有参数的函数。我的老师告诉我,下面的代码不是一个函数,这让我很困惑,对于将某些代码行归类为“函数”所需的条件,我感到很困惑。defgame(numbers,max_turns,pfl,tgl):turns=0flag=Falseprint("You......