标签: python-polars

是否有与 Spark Pandas UDF 等效的 Apache Arrow

Spark 提供了几种不同的方法来实现使用和返回 Pandas DataFrame 的 UDF。我目前正在使用联合版本,该版本采用两个(联合分组)Pandas DataFrame 作为输入并返回第三个。

为了在 Spark DataFrame 和 Pandas DataFrame 之间进行高效转换,Spark 使用 Apache Arrow 内存布局,但是仍然需要在 Arrow 和 Pandas 之间进行转换。我真的很想直接访问 Arrow 数据,因为这就是我最终处理 UDF 中的数据的方式(使用Polars)。

来时从 Spark -> Arrow -> Pandas -> Arrow (Polars) 走,返回时相反,似乎很浪费。

user-defined-functions pandas apache-spark apache-arrow python-polars

5
推荐指数
1
解决办法
634
查看次数

在 Python 中使用 Polars 读取/写入 Parquet 文件时可以指定架构吗?

在Python中使用Polars读取CSV文件时,我们可以使用参数dtypes来指定要使用的模式(对于某些列)。我想知道我们在读取或写入 Parquet 文件时可以做同样的事情吗?我试图指定dtypes参数,但它不起作用。

我有一些从 PySpark 生成的 Parquet 文件,并且想要将这些 Parquet 文件加载到 Rust 中。Rust 需要无符号整数,而 Spark/PySpark 没有无符号整数并将有符号整数输出到 Parquet 文件中。为了让事情变得更简单,我想在将 Parquet 文件加载到 Rust 之前转换它们的列类型。我知道有几种不同的方法可以实现这一点(无论是在 pandas 还是在 Polars 中),但我想知道是否有简单有效的方法可以使用 Polars 来实现此目的。

我在 Python 中使用极坐标转换列类型的代码如下。

import polars as pl

...
df["id0"] = df.id0.cast(pl.datatypes.UInt64)
Run Code Online (Sandbox Code Playgroud)

python schema dataframe rust python-polars

5
推荐指数
1
解决办法
4768
查看次数

检索极坐标的行号(索引)的推荐方法是什么?

我知道 Polars 不支持设计索引,所以df.filter(expr).index不是一个选项,我能想到的另一种方法是在应用任何过滤器之前添加一个新列,不确定这是否是在 Polars 中这样做的最佳方法

df.with_column(pl.Series('index', range(len(df))).filter(expr).index
Run Code Online (Sandbox Code Playgroud)

python dataframe data-science python-polars

5
推荐指数
1
解决办法
7719
查看次数

从 Pandas 到 Polars 的数据帧转换——最终尺寸的差异

我正在尝试将 Pandas Dataframe 转换为 Polar Dataframe。

我只是简单地使用了该功能result_polars = pl.from_pandas(result)。转换进展顺利,但是当我检查两个数据帧的形状时,我发现 Polars 数据帧的大小是原始 Pandas 数据帧的一半。

我相信长度 4172903059 几乎是极坐标数据帧允许的最大尺寸。

有人有建议吗?

这是两个数据框形状的屏幕截图。

这是一个最小工作示例

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

df = pd.DataFrame(np.zeros((4292903069,1), dtype=np.uint8))
df_polars = pl.from_pandas(df)
Run Code Online (Sandbox Code Playgroud)

使用这些维度,两个数据框具有相同的大小。如果我输入以下内容:

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

df = pd.DataFrame(np.zeros((4392903069,1), dtype=np.uint8))
df_polars = pl.from_pandas(df)
Run Code Online (Sandbox Code Playgroud)

Polars 数据框的尺寸要小得多 (97935773)。

data-conversion dataframe pandas rust-polars python-polars

5
推荐指数
1
解决办法
2401
查看次数

使用 Polars 计算布尔(或数字)列中连续的 True(或 1)值?

我希望计算列中的连续值,最好使用 Polars 表达式。

import polars
df = pl.DataFrame(
   {"values": [True,True,True,False,False,True,False,False,True,True]}
)
Run Code Online (Sandbox Code Playgroud)

通过上面的示例数据框,我想计算连续 True 值的数量。

下面是使用 R 的 Data.Table 包的示例输出。

library(data.table)
dt <- data.table(value = c(T,T,T,F,F,T,F,F,T,T))
dt[, value2 := fifelse((1:.N) == .N & value == 1, .N, NA_integer_), by = rleid(value)]
dt
Run Code Online (Sandbox Code Playgroud)
价值 值2
真的 不适用
真的 不适用
真的 3
错误的 不适用
错误的 不适用
真的 1
错误的 不适用
错误的 不适用
真的 不适用
真的 2

有什么想法可以使用 Polars 有效地完成此操作吗?

[用新方法编辑]

我用下面的代码让它工作,但希望有一种更有效的方法。有人知道 value_counts 中的默认结构/字典字段名称吗?

(
    df.lazy()
    .with_row_count()
    .with_column(
        pl.when(pl.col("value") == False).then(
            pl.col("row_nr")
            
        ).fill_null(
            strategy …
Run Code Online (Sandbox Code Playgroud)

python-polars

5
推荐指数
1
解决办法
539
查看次数

Polars:用每组内唯一有效的值填充空值

每组在随机行中只有一个有效值或 not_null 值。如何为每个组填充该值?

\n
import polars as pl\n\ndata = {\n    \'group\': [\'1\', \'1\', \'1\', \'2\', \'2\', \'2\', \'3\', \'3\', \'3\'],\n    \'col1\': [1, None, None, None, 3, None, None, None, 5],\n    \'col2\': [\'a\', None, None, None, \'b\', None, None, None, \'c\'],\n    \'col3\': [False, None, None, None, True, None, None, None, False]\n}\ndf = pl.DataFrame(data)\n
Run Code Online (Sandbox Code Playgroud)\n
shape: (9, 4)\n\xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xac\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xac\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xac\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x90\n\xe2\x94\x82 group \xe2\x94\x86 col1 \xe2\x94\x86 col2 \xe2\x94\x86 col3  \xe2\x94\x82\n\xe2\x94\x82 ---   \xe2\x94\x86 ---  \xe2\x94\x86 ---  \xe2\x94\x86 ---   \xe2\x94\x82\n\xe2\x94\x82 str   \xe2\x94\x86 i64  \xe2\x94\x86 str  \xe2\x94\x86 bool  \xe2\x94\x82\n\xe2\x95\x9e\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xaa\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xaa\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xaa\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xa1\n\xe2\x94\x82 …
Run Code Online (Sandbox Code Playgroud)

python-polars

5
推荐指数
1
解决办法
1308
查看次数

如何实现滚动均值忽略空值

我正在尝试计算 RSI 指标。为此,我需要滚动平均损益。

我想计算滚动平均值忽略空值。因此平均值将通过现有值的总和和计数来计算。

例子:

window_size = 5

df = DataFrame(price_change: { 1, 2, 3, -2, 4 })

df_gain = .select(
            pl.when(pl.col('price_change') > 0.0)
            .then(pl.col('price_change'))
            .otherwise(None)
            .alias('gain')
          )

# UNKOWN HOW TO GET WANTED RESULT:
rol_mean_gain = df_gain.select(
                  pl.col('gain').rolling_mean(window_size=window_size, ignore_null=True)
                )
Run Code Online (Sandbox Code Playgroud)

以便计算 rol_mean_gain:[1, 2, 3, skip, 4] / 4 (not 5)

我知道 Pandas 有.mean(skipna=True).apply(pandas.np.nanmean) 但据我所知 Polars 不提供这样的 API。

python pandas python-polars

5
推荐指数
1
解决办法
338
查看次数

在Python中检测日期时间字符串的格式

我正在寻找一种方法来检测strftimePython 中日期时间字符串的 -style 格式。我发现的所有日期时间库都具有解析字符串以创建日期时间对象的功能,但我想检测可与格式datetime.strptime参数一起使用的格式或模式。

为什么?我正在处理长列表(或系列)的日期时间字符串,并使用dateutil.parser它们来解析它们太不准确且缓慢。

  • :它每次都会检查所有潜在的格式,尽管每个列表的所有条目都具有相同的格式(在我的例子中)。
  • 不准确:不明确的条目将以多种方式中的一种进行解析,而不从其他明确的条目中获取知识。

所以我想检测格式。一旦有了这个,我就可以使用该to_datetime函数polars以更快的方式创建日期时间序列。

我在更现代的日期时间库(如钟摆)中找不到这样的功能。我还实现了我自己的版本,它迭代固定的格式列表并检查是否可以使用datetime.strptime如下方式读取它:

patterns = [
        "%Y.%m.%d %H:%M:%S",
        "%Y-%m-%d %H:%M",
        "%Y-%m-%d",
        ...
    ]

    for pattern in patterns:
        try:
            for val in col:
                assert datetime.datetime.strptime(val, pattern)
            return pattern
        except:
            continue
Run Code Online (Sandbox Code Playgroud)

这对我来说并不是一个优雅的解决方案,我想知道是否有更好的方法来做到这一点,甚至有一个可用的库可以完成此类事情。

python format datetime parsing python-polars

5
推荐指数
1
解决办法
676
查看次数

长 .when().then().when().then().otherwise() 链的替代方案

是否有一些聪明的替代方法可以编写长的when().then().otherwise()链而不对值进行硬编码,请参见下面的示例:

\n

假设我们有以下数据框

\n
df = pl.DataFrame(\n    {\n        "Market":["AT", "AT", "DE", "DE", "CA", "DE", "UK", "US"],\n        "Number of Days":[1, 2, 3, 4, 3, 4, 2, 1],\n        \n    }\n)\n
Run Code Online (Sandbox Code Playgroud)\n

用户将一些条件定义为不同国家的字典

\n
params = {\n    "AT":{"Value": 1},\n    "DE":{"Value": 2},\n    "CA":{"Value": 3},\n    "UK":{"Value": 1},\n    "US":{"Value": 2}\n}\n
Run Code Online (Sandbox Code Playgroud)\n

然后我对国家/地区进行硬编码并使用 Polars .with_columns() 中的国家/地区,如下所示:

\n
(\n    df\n    .with_columns(\n        [\n            pl.when(pl.col("Market") == "AT").then(pl.col("Number of Days") + params["AT"]["Value"])\n            .when(pl.col("Market") == "DE").then(pl.col("Number of Days") + params["DE"]["Value"])\n            .when(pl.col("Market") == "CA").then(pl.col("Number of Days") + params["CA"]["Value"])\n            .when(pl.col("Market") == "UK").then(pl.col("Number of Days") …
Run Code Online (Sandbox Code Playgroud)

python-polars

5
推荐指数
1
解决办法
194
查看次数

Polars:“ValueError:无法将值‘未知’转换为文字”

我在 Polars 中有一行代码,在我最近将 Polars 包更新为“0.19.0”之前,该代码行有效。这个例子之前运行过:

import polars as pl

df = pl.DataFrame(
    {
        "a": [5, 6, 7, 8, 9],
        "b": [5, 6, 7, 8, 9],
        "c": [5, 6, 7, 8, None],})

cols_1 = ["a", "b"]
cols_2 = ["c"]

df = df.filter(pl.all(pl.col(cols_1 + cols_2).is_not_null()))

Run Code Online (Sandbox Code Playgroud)

但现在引发错误:

ValueError: could not convert value 'Unknown' as a Literal
Run Code Online (Sandbox Code Playgroud)

python python-polars

5
推荐指数
1
解决办法
1152
查看次数