Pandas 系列中的 apply() 方法有什么作用?


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

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

示例 1

# import pandas package
import pandas as pd

# create a pandas series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)

# Applying a function
result = s.apply(type)
print('Output of apply method',result)

解释

在下面的示例中,我们创建了一个 pandas.Series 对象“s”,其中包含 10 个整数值,并通过使用 apply() 方法执行 Series 对象“s”所有元素的 type 函数。

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

输出

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 Series apply() 方法将返回一个新的 Series 对象,其中包含给定 Series 对象“s”的每个值的 data type 表示。

示例 2

# import pandas package
import pandas as pd

# create a pandas series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)

# Apply power(2) function
result = s.apply(pow, args=(2,))
print('Output of apply method',result)

解释

让我们再举一个例子,并通过使用 apply() 方法将带有参数的函数应用于 Series 对象。在这里,我们应用了带有参数值 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() 方法的输出与实际的 Series 对象“s”一起显示在上面的代码块中。pow() 函数应用于 Series 元素,结果输出作为另一个 Series 对象返回。

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

更新于: 2022-03-09

173 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.