Pandas Series 中的 apply() 方法起什么作用?

pandasserver side programmingprogramming更新于 2025/10/11 15:52:17

Pandas Series 中的 apply() 方法用于在 Series 对象上调用我们自定义的函数。通过使用此 apply() 方法,我们可以将自定义函数应用于 Series 对象。

apply() 方法与 Pandas Series 中的其他一些方法(例如 agg() 和 map())非常相似。这里的区别在于,我们可以对给定的系列对象的值应用函数。

示例 1

# 导入 pandas 包
import pandas as pd

# 创建一个 pandas 系列
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)

# 应用函数
result = s.apply(type)
print('apply 方法的输出',result)

解释

在下面的示例中,我们创建了一个 pandas.Series 对象"s"具有 10 个整数值,通过使用 apply() 方法,我们执行系列对象"s"所有元素的类型函数。

apply() 方法的操作类似于 agg() 方法,但区别在于 agg() 方法仅用于聚合操作,而 apply() 方法可用于对系列数据应用任何方法。

输出

0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
9 10
dtype: int64

Output of apply method
0  <class 'int'>
1  <class 'int'>
2  <class 'int'>
3  <class 'int'>
4  <class 'int'>
5  <class 'int'>
6  <class 'int'>
7  <class 'int'>
8  <class 'int'>
9  <class 'int'>
dtype: object

Pandas 系列的 apply() 方法将返回一个新的系列对象,其中包含给定系列对象"s"每个值的数据类型表示。

示例 2

# 导入 pandas 包
import pandas as pd

# 创建一个 pandas 系列
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)

# 应用 power(2) 函数
result = s.apply(pow, args=(2,))
print('apply 方法的输出',result)

解释

我们再举一个例子,使用 apply() 方法将一个带参数的函数应用于系列对象。这里我们应用了参数值为 2 的 pow 函数。

输出

0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
9 10
dtype: int64
Output of apply method
0   1
1   4
2   9
3  16
4  25
5  36
6  49
7  64
8  81
9 100
dtype: int64

apply() 方法的输出与实际的系列对象"s"一起显示在上面的代码块中。pow() 函数应用于系列元素,并将结果输出作为另一个系列对象返回。

要在 apply() 方法中传递函数的参数,我们需要使用 args 关键字参数。


相关文章