计算错误:类型错误:np.mean() 得到意外的关键字参数“axis”

问题描述 投票:0回答:1

当我尝试在极坐标数据框中使用 numpy.mean 时,我收到一条错误消息:

import numpy as np #v2.1.0
import polars as pl #v1.6.0
from polars import col

TRIALS = 1
SIMS = 10

np.random.seed(42)

df = pl.DataFrame({
  'a': np.random.binomial(TRIALS, .45, SIMS),
  'b': np.random.binomial(TRIALS, .5, SIMS),
  'c': np.random.binomial(TRIALS, .55, SIMS)
})

df.head()

df.with_columns(
  z_0 = np.mean(col("a"))
).head()

TypeError: mean() got an unexpected keyword argument 'axis'

添加显式轴参数不会改变错误。

df.with_columns(
  z_0 = np.mean(a=col("a"), axis=0)
).head()

TypeError: mean() got an unexpected keyword argument 'axis'

我知道我可以通过以下方式完成此计算:

df.with_columns(
  z_0 = ncol("a").mean()
).head()

但我试图了解非极函数如何在极函数中工作。

python python-polars
1个回答
0
投票

这可以完成,但相当复杂,因为你必须使用 UDF 并通过它调用 numpy 函数:

df.select(pl.col("a").map_batches(lambda x: np.mean(x.to_numpy())))
它的工作方式是通过调用
map_batches
(或
map_elements
)来应用 UDF,并且在您的函数中,您必须通过调用
to_numpy()
将 Polars 系列转换为 NumPy 系列。 这适用于 Polars 1.9.0

© www.soinside.com 2019 - 2024. All rights reserved.