Pandas Apply函数

来源:互联网 发布:tomcat修改1099端口 编辑:程序博客网 时间:2024/06/05 15:15

Series.apply

Series.apply(func, convert_dtype=True, args=(), **kwds)
对序列的每一个元素作用传入的函数

参数

参数 描述 func : function 所要应用的函数 convert_dtype : boolean, default True 试着找到最适合的结果类型 args : tuple 传入函数的参数

返回

  1. y : Series or DataFrame if func returns a Series

DataFrame.apply

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)
在给定轴方向应用函数

参数

func : function|要应用在行和列的函数
axis : {0 or ‘index’, 1 or ‘columns’}, default 0|选择是行还是列
broadcast : boolean, default False|For aggregation functions, return object of same size with values propagated
raw : boolean, default False|If False, convert each row or column into a Series. If raw=True the passed function will receive ndarray objects instead.
reduce : boolean or None, default None|Try to apply reduction procedures.
args : tuple|函数的参数

应用

查看序列中元素的类型

In [1]: import pandas as pd   ...: df=pd.Series(["1","a",1,True])   ...: dfOut[1]: 0       11       a2       13    Truedtype: objectIn [2]: df.apply(type)# 这里使用type()函数Out[2]: 0     <class 'str'>1     <class 'str'>2     <class 'int'>3    <class 'bool'>dtype: objectIn [3]: %timeit df.apply(type) #每次循环的时间是101us10000 loops, best of 3: 101 µs per loop

apply函数类似与如下的循环

In [4]: [type(x) for x in df]Out[4]: [str, str, int, bool]In [5]: %timeit [type(x) for x in df]100000 loops, best of 3: 13.3 µs per loop

很奇怪,循环要比pandas的内置函数要快

原创粉丝点击