的apply_pandas中apply、map和applymap

这些是我自己的理解如果有不当之处,还望大家不多多指教。当然还有一些其他的方法,以后有机会会补充。

方法简介:

  1. 分类

Series中的方法:map、apply

DataFrame中的方法:apply、applymap

2.定义

Series方法:

map:

官网解释

Map values of Series according to input correspondence.
Used for substituting each value in a Series with another value, that may be derived from a function, a dict or a Series.

返回值:

Returns: Series
Same index as caller.

可以接收函数、字典和Series类型的参数,并且返回一个Series类型的值。当时是字典或者Series的时候,返回值为key或者index对应的value值,当该key不存在的时候返回NaN。

实例:

fa4536f283312b467edacfba97d876b9.png
图1.1

3d0f2d8f88d4e3263a31f1a68e467a30.png
图1.2

apply:

官网解释:

nvoke function on values of Series.
Can be ufunc (a NumPy function that applies to the entire Series) or a Python function that only works on single values.

返回值:

Returns:Series or DataFrame
If func returns a Series object the result will be a DataFrame.

接收numpy的函数或者Python函数(只能接受单个参数),返回一个Series或者DataFrame类型的值。

注意当函数返回一个Series的时候,改方法返回一个Dataframe。

实例:

359342526779939257f4f976e5e47eb6.png
图2.1

5c18a8a5742d878ce40bce78b239e8ec.png
图2.2

Series中map和apply的异同:

同:

他们在返回值都是单个值的情况下的效果是一样的。请对比图2.2和图3.1

3a2cf194d4e0a2d9465c62a024c5a7c0.png
图3.1

异:

当函数返回值是Series时,返回值将发生变化。

fe39fda40852a82ccc0dbdb6bdbe57ab.png
图3.2

3a550388c401a4216de8ea8b496da5d0.png
图3.3

DataFrame方法:

apply:

官网解释:

Apply a function along an axis of the DataFrame.
Objects passed to the function are Series objects whose index is either the DataFrame’s index ( axis=0) or the DataFrame’s columns ( axis=1). By default ( result_type=None), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the result_type argument.

返回值:

Series or DataFrame
Result of applying func along the given axis of the DataFrame.

接收一个方法,方法的参数是Series

实例:

d48aba73b28e4ee25a016931ec13c3eb.png
图4.1

bd2e51b370beac72f1525b8d226cadb6.png
图4.2

applymap:

官网解释:

Apply a function to a Dataframe elementwise.
This method applies a function that accepts and returns a scalar to every element of a DataFrame.

返回值:

DataFrame
Transformed DataFrame.

接收一个函数并且将Dataframe中的所有值运用到这个函数上。

实例:

05e878cb6a5ef10cf6c52193f690fc61.png
图5.1

8d61e80ff35aec06764c5977755ad133.png
图5.2

观察图5.1和图5.2后发现这两个是一样的。在函数的矢量化变化的这种情况下图5.1将比图5.2,请避免在这种情况下使用applymap。

图4.2和图5.2中,发现apply和applymap返回的结果是一样的,但是请注意他们的计算方法过程是不一样。apply 作用于Dataframe的一行或者一列,applymap作用于Dataframe的每一个元素。

2a069148006071cea5ef7bc62b7fd8d9.png
图5.3

339667faf79c351a3d7aa391788e876a.png
图5.4

如果发生如下错误,请检查你的Dataframe是否为空:

ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a Series

写在最后,这些是我自己的一些理解,可能有些有错误,或者不理解的地方,欢迎指教。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值