Pandas 系列应用方法

Pandas Series Apply Method

我一直在对系列和数据框使用 pandas apply 方法,但显然我仍然遗漏了一些东西,因为我对一个我试图执行的简单函数感到困惑。

这就是我在做的事情:

def minmax(row):
    return (row - row.min())/(row.max() - row.min())

row.apply(minmax)

但是,这个 return 是一个全零系列。例如,如果

row = pd.Series([0, 1, 2])

然后

minmax(row)

returns [0.0, 0.5, 1.0],根据需要。但是,row.apply(minmax) returns [0,0,0]。

我相信这是因为系列是整数和整数除法returns 0。但是,我不明白,

我怀疑我在应用程序的工作方式中缺少一些基本的东西......或者是密集的。无论哪种方式,提前感谢。

当您在 Series 上调用 row.apply(minmax) 时,只有值 被传递给函数。这称为 element-wise.

Invoke function on values of Series. Can be ufunc (a NumPy function that applies to the entire Series) or a Python function that only works on single values.

当您在 DataFrame 上调用 row.apply(minmax) 时,行(默认)或列被传递给函数(根据 axis 的值)。

Objects passed to functions are Series objects having index either the DataFrame’s index (axis=0) or the columns (axis=1). Return type depends on whether passed function aggregates, or the reduce argument if the DataFrame is empty. This is called row-wise or column-wise.

这就是您的示例在 DataFrame 而不是 Series 上按预期工作的原因。检查此 以获取有关将函数映射到 Series.

的信息