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。但是,我不明白,
- 为什么它与 minmax(row) 一起工作(它的行为不应该一样吗?),以及
- 如何在应用函数中将它正确地转换为 return 适当的浮点值(我尝试使用 .astype 转换它,这给了我所有的 NaNs...我也不明白)
- 如果将此应用于数据框,因为 df.apply(minmax) 它也可以按需要工作。 (编辑添加)
我怀疑我在应用程序的工作方式中缺少一些基本的东西......或者是密集的。无论哪种方式,提前感谢。
当您在 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
.
的信息
我一直在对系列和数据框使用 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。但是,我不明白,
- 为什么它与 minmax(row) 一起工作(它的行为不应该一样吗?),以及
- 如何在应用函数中将它正确地转换为 return 适当的浮点值(我尝试使用 .astype 转换它,这给了我所有的 NaNs...我也不明白)
- 如果将此应用于数据框,因为 df.apply(minmax) 它也可以按需要工作。 (编辑添加)
我怀疑我在应用程序的工作方式中缺少一些基本的东西......或者是密集的。无论哪种方式,提前感谢。
当您在 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
.