如何在 Pandas Series 上应用匿名函数?
Pandas Series 构造函数具有一个 apply() 方法,它接受任何应用于给定 Series 对象值的自定义函数。
同样,我们可以在 Pandas Series 对象上应用匿名函数。我们可以在 Pandas 的两个数据结构 DataFrame 和 Series 上使用此 apply() 方法。它执行逐元素转换并返回一个新的 Series 对象作为结果。
示例 1
# import pandas package import pandas as pd import numpy as np # create a pandas series s = pd.Series(np.random.randint(10,20,5)) print(s) # Applying an anonymous function result = s.apply(lambda x: x**2) print('Output of apply method',result)
解释
在以下示例中,我们使用 lambda 函数作为匿名函数传递给 apply() 方法。
最初,我们使用 NumPy 随机模块创建了一个包含 5 个整数值的 Pandas.Series 对象“s”,然后我们使用 apply() 方法和 lambda 函数应用平方函数。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
0 12 1 17 2 11 3 15 4 15 dtype: int32 Output of apply method 0 144 1 289 2 121 3 225 4 225 dtype: int64
代码 s.apply(lambda x:x**2) 将计算 Series 元素每个值的平方。这里 lambda 是一个匿名函数。apply() 方法将返回一个新的 Series 对象,如上述输出块中所示。
示例 2
# import pandas package import pandas as pd import numpy as np # create a pandas series s = pd.Series(np.random.randint(10,20,5)) print(s) # Applying an anonymous function result = s.apply(lambda x : True if x%2==0 else False) print('Output of apply method',result)
解释
让我们再取一个 Pandas Series 对象并应用一个匿名函数,这里我们应用了一个 lambda 函数来识别 Series 对象“s”的偶数和奇数值。
输出
0 15 1 18 2 15 3 14 4 18 dtype: int32 Output of apply method 0 False 1 True 2 False 3 True 4 True dtype: bool
给定示例的 apply() 方法的输出与实际的 Series 对象“s”一起显示在上面的代码块中。
结果 Series 对象包含布尔值(True 和 False),True 代表偶数,False 代表奇数。
广告