将函数应用于 Polars-DataFrame 的所有列

Gia*_*auz 9 python apply dataframe pandas python-polars

我知道如何将函数应用于Pandas-DataFrame中存在的所有列。但是,我还没有弄清楚如何在使用Polars-DataFrame时实现这一点。

我查看了《Polars 用户指南》中专门讨论此主题的部分,但我还没有找到答案。在这里,我附上了我不成功的尝试的代码片段。

import numpy as np
import polars as pl
import seaborn as sns

# Loading toy dataset as Pandas DataFrame using Seaborn
df_pd = sns.load_dataset('iris')

# Converting Pandas DataFrame to Polars DataFrame
df_pl = pl.DataFrame(df_pd)

# Dropping the non-numeric column...
df_pd = df_pd.drop(columns='species')                     # ... using Pandas
df_pl = df_pl.drop('species')                             # ... using Polars

# Applying function to the whole DataFrame...
df_pd_new = df_pd.apply(np.log2)                          # ... using Pandas
# df_pl_new = df_pl.apply(np.log2)                        # ... using Polars?

# Applying lambda function to the whole DataFrame...
df_pd_new = df_pd.apply(lambda c: np.log2(c))             # ... using Pandas
# df_pl_new = df_pl.apply(lambda c: np.log2(c))           # ... using Polars?
Run Code Online (Sandbox Code Playgroud)

预先感谢您的帮助和时间。

rit*_*e46 19

您可以使用表达式语法来选择所有列pl.col("*")/pl.all(),然后对这些列使用mapnumpy函数。np.log2(..)

df.select(
    pl.all().map_batches(np.log2)
)
Run Code Online (Sandbox Code Playgroud)

Polars 表达式还支持 numpy 通用函数https://numpy.org/doc/stable/reference/ufuncs.html

这意味着您可以将极坐标表达式传递给 numpy ufunc

df.select([
    np.log2(pl.all())
])
Run Code Online (Sandbox Code Playgroud)

apply请注意, (now map_elements) 和map(now )之间的区别map_batches在于,map_elements会在每个数值上调用,而 则map_batches在整个 上调用Series。我们选择map_batches这里,因为那样会更快。