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

阅读 148 收藏 0 点赞 0 评论 0

pandas Series 中的apply()方法用于在 series 对象上调用我们的函数。通过使用这种apply()方法,我们可以在我们的系列对象上应用我们自己的函数。

该方法与其他一些 pandas 系列方法(如和apply())非常相似。这里的区别是我们可以对给定系列对象的值应用一个函数。agg()map()

示例 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具有 10 个整数值的对象“s”,并使用该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 seriesapply()方法将返回一个新的系列对象,其中包含给定系列对象“s”的每个值的数据类型表示。

示例 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()方法将带参数的函数应用到系列对象。在这里,我们应用了参数值为 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 关键字参数。

评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号