AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79059121
Accepted
gillesa
gillesa
Asked: 2024-10-06 20:56:51 +0800 CST2024-10-06 20:56:51 +0800 CST 2024-10-06 20:56:51 +0800 CST

从熊猫视角使用 Polars 裁剪标签

  • 772

我正在将一些代码从 迁移Pandas到Polars。我尝试使用cut但polars存在差异(没有bin,所以我必须计算它)。

label但我还是不明白极坐标的结果。

我必须使用比我想要的更多的标签才能获得相同的结果pandas。

import numpy as np
import pandas as pd
import polars as pl

# Exemple de DataFrame Polars
data = {
    "value": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
}
df_pl = pl.DataFrame(data)

# Convertir en DataFrame Pandas pour obtenir les breakpoints
df_pd = df_pl.to_pandas()

# Use returbins to get the breakpoints (from pandas)
df_pd["cut_label_pd"], breakpoints = pd.cut(df_pd["value"], 4, labels=["low", "medium", "hight", "very high"], retbins=True)
print(pl.from_pandas(df_pd))
shape: (10, 2)
┌───────┬──────────────┐
│ value ┆ cut_label_pd │
│ ---   ┆ ---          │
│ i64   ┆ cat          │
╞═══════╪══════════════╡
│ 1     ┆ low          │
│ 2     ┆ low          │
│ 3     ┆ low          │
│ 4     ┆ medium       │
│ 5     ┆ medium       │
│ 6     ┆ hight        │
│ 7     ┆ hight        │
│ 8     ┆ very high    │
│ 9     ┆ very high    │
│ 10    ┆ very high    │
└───────┴──────────────┘

print(breakpoints)
# [ 0.991  3.25   5.5    7.75  10.   ]

labels有没有更好的方法?(注意中的值polars cut)

# Cut in polars
labels = ["don't use it", "low", "medium", "hight", "very high", "don't use it too"] 
df_pl = df_pl.with_columns(
    pl.col("value").cut(breaks=breakpoints, labels=labels).alias("cut_label_pl")
)

print(df_pl)
shape: (10, 2)
┌───────┬──────────────┐
│ value ┆ cut_label_pl │
│ ---   ┆ ---          │
│ i64   ┆ cat          │
╞═══════╪══════════════╡
│ 1     ┆ low          │
│ 2     ┆ low          │
│ 3     ┆ low          │
│ 4     ┆ medium       │
│ 5     ┆ medium       │
│ 6     ┆ hight        │
│ 7     ┆ hight        │
│ 8     ┆ very high    │
│ 9     ┆ very high    │
│ 10    ┆ very high    │
└───────┴──────────────┘
python-polars
  • 1 1 个回答
  • 53 Views

1 个回答

  • Voted
  1. Best Answer
    Henry Harbeck
    2024-10-07T19:43:48+08:002024-10-07T19:43:48+08:00

    简而言之,Polars 不需要 pandasretbins参数产生的那么多断点。Polars 的文档字符串labels指出“标签数量必须等于切点数量加一”。由于我们有 4 个标签,因此我们需要 3 个断点。Polars 不需要 pandas 产生的第一个或最后一个断点。

    无需添加虚假标签,只需减少中断数量即可。您可以将现有代码从 更改为pl.col("value").cut(breaks=breakpoints, ...),pl.col("value").cut(breaks=breakpoints[1:-1], ...)然后删除两个“不要使用它”标签,这样会更好一些。

    但显然你不想依赖熊猫来计算一些均匀分布的箱子,所以让我们自己做吧!

    从基线开始:

    data = {"value": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
    df = pl.DataFrame(data)
    
    # we know these in this case, but we want to generate them dynamically
    breaks = [3.25, 5.5, 7.75]
    labels = ["low", "medium", "high", "very high"] 
    df.with_columns(
        pl.col("value").cut(breaks=breaks, labels=labels).alias("cut_label_pl")
    )
    

    现在让我们计算这些中断。pandas.cut表示bins定义 x 范围内等宽箱的数量。

    def calculate_breakpoints(ser: list | pl.Series, bins: int) -> list:
        if isinstance(ser, list):
            ser = pl.Series(ser)
        min_value, max_value = ser.min(), ser.max() # 1, 10
        bin_size = (max_value - min_value) / bins # (10 - 1) / 4 -> 2.25
        return [min_value + (bin_size * i) for i in range(1, bins)]
    
    # can take a list or a Polars Series
    calculate_breakpoints(data["value"], 4) # [3.25, 5.5, 7.75]
    calculate_breakpoints(df["value"], 4) # [3.25, 5.5, 7.75]
    

    总之(如果你改变标签数量,它仍然有效)

    data = {"value": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
    df = pl.DataFrame(data)
    
    labels = ["low", "medium", "high", "very high"]
    breaks = calculate_breakpoints(df["value"], len(labels))
    df.with_columns(
        pl.col("value").cut(breaks=breaks, labels=labels).alias("cut_label_pl")
    )
    

    祝愿你们从熊猫到北极的迁徙顺利!

    • 3

相关问题

  • Polars - 获取包含每行最大值的列名称

  • Polars 模式与列表类型不同

  • 当过滤器不匹配时,通过返回值来进行极性分组

  • 极地扫描镶木地板;有没有办法获取扫描的文件数量?

  • 部分基于其他列名称创建新列

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve