这些是我自己的理解如果有不当之处,还望大家不多多指教。当然还有一些其他的方法,以后有机会会补充。
方法简介:
- 分类
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。
实例:
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。
实例:
Series中map和apply的异同:
同:
他们在返回值都是单个值的情况下的效果是一样的。请对比图2.2和图3.1
异:
当函数返回值是Series时,返回值将发生变化。
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 applyingfunc
along the given axis of the DataFrame.
接收一个方法,方法的参数是Series
实例:
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中的所有值运用到这个函数上。
实例:
观察图5.1和图5.2后发现这两个是一样的。在函数的矢量化变化的这种情况下图5.1将比图5.2,请避免在这种情况下使用applymap。
图4.2和图5.2中,发现apply和applymap返回的结果是一样的,但是请注意他们的计算方法过程是不一样。apply 作用于Dataframe的一行或者一列,applymap作用于Dataframe的每一个元素。
如果发生如下错误,请检查你的Dataframe是否为空:
ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a Series
写在最后,这些是我自己的一些理解,可能有些有错误,或者不理解的地方,欢迎指教。