pandas.Series.apply#
- Series.apply(func, convert_dtype=_NoDefault.no_default, args=(), *, by_row='compat', **kwargs)[源代码]#
在 Series 的值上调用函数。
可以是 ufunc(适用于整个 Series 的 NumPy 函数)或仅处理单个值的 Python 函数。
- Parameters:
- funcfunction
要应用的 Python 函数或 NumPy ufunc。
- convert_dtypebool, default True
尝试为逐元素函数结果查找更好的 dtype。如果为 False,则保留为 dtype=object。请注意,对于某些扩展数组 dtype(如 Categorical),dtype 始终保持不变。
自 2.1.0 版本弃用:
convert_dtype已被弃用。如果想要convert_dtype=False,请改为执行ser.astype(object).apply()。- argstuple
传递给 func 的位置参数,位于 series 值之后。
- by_rowFalse 或 “compat”,默认为 “compat”
如果为 “compat” 且 func 是可调用的,则 func 将会接收 Series 的每个元素,类似于 Series.map。如果 func 是可调用对象的列表或字典,将首先尝试将每个 func 转换为 pandas 方法。如果失败,将尝试再次使用
by_row="compat"调用 apply,如果仍然失败,将再次使用by_row=False调用 apply(向后兼容)。如果为 False,则 func 将一次性接收整个 Series。当
func为字符串时,by_row无任何效果。在 2.1.0 版本加入.
- **kwargs
传递给 func 的其他关键字参数。
- Returns:
- Series 或 DataFrame
如果 func 返回 Series 对象,则结果将是一个 DataFrame。
参见
Series.map用于逐元素操作。
Series.agg仅执行聚合类型操作。
Series.transform仅执行转换类型操作。
Notes
修改传入对象的函数可能会导致意外行为或错误,因此不受支持。有关详细信息,请参阅 使用用户定义函数 (UDF) 方法进行变异 。
Examples
创建一个 Series,包含每个城市的典型夏季温度。
>>> s = pd.Series([20, 21, 12], ... index=['London', 'New York', 'Helsinki']) >>> s London 20 New York 21 Helsinki 12 dtype: int64
通过定义一个函数并将其作为参数传递给
apply()来计算值的平方。>>> def square(x): ... return x ** 2 >>> s.apply(square) London 400 New York 441 Helsinki 144 dtype: int64
通过将匿名函数作为参数传递给
apply()来计算值的平方。>>> s.apply(lambda x: x ** 2) London 400 New York 441 Helsinki 144 dtype: int64
定义一个需要额外位置参数的自定义函数,并使用
args关键字参数传递这些额外参数。>>> def subtract_custom_value(x, custom_value): ... return x - custom_value
>>> s.apply(subtract_custom_value, args=(5,)) London 15 New York 16 Helsinki 7 dtype: int64
定义一个接受关键字参数的自定义函数,并将这些参数传递给
apply。>>> def add_custom_values(x, **kwargs): ... for month in kwargs: ... x += kwargs[month] ... return x
>>> s.apply(add_custom_values, june=30, july=20, august=25) London 95 New York 96 Helsinki 87 dtype: int64
使用 NumPy 库中的一个函数。
>>> s.apply(np.log) London 2.995732 New York 3.044522 Helsinki 2.484907 dtype: float64