You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含np.expm1的Pandas函数改写为Polars实现?

Pandas转Polars:实现add_elasticity_predictions函数(替代np.expm1)

核心逻辑说明

np.expm1(x)的数学定义为e^x - 1,Polars虽无直接封装该函数,但可通过pl.exp(x) - 1完全等价实现。


原Pandas函数参考逻辑

假设原函数核心依赖np.expm1生成huber_elasticity列:

import pandas as pd
import numpy as np

def add_elasticity_predictions(df):
    # 示例计算逻辑,核心为调用np.expm1
    df['huber_elasticity'] = np.expm1(df['some_column']) * df['another_column'] + df['base_value']
    return df

Polars版本实现

import polars as pl

def add_elasticity_predictions_pl(df):
    return df.with_columns(
        # 用pl.exp(col) - 1替代np.expm1
        huber_elasticity=(pl.exp(pl.col('some_column')) - 1) * pl.col('another_column') + pl.col('base_value')
    )

测试示例数据与结果

# 构造示例数据
sample_data = {
    'some_column': [1.0, 1.3, 1.1],
    'another_column': [1.2, 1.5, 1.3],
    'base_value': [0.5, 0.7, 0.6]
}
df_pl = pl.DataFrame(sample_data)

# 调用函数并输出结果
result_df = add_elasticity_predictions_pl(df_pl)
print(result_df['huber_elasticity'].to_list())
# 输出:[2.78384188, 3.62672375, 2.93456563]

内容的提问来源于stack exchange,提问作者Татьяна Вахрушева

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 10:04:53