有多少人工,就有多少智能

Pandas Apply函数

 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])
   ...: df
Out[1]: 
0       1
1       a
2       1
3    True
dtype: object

In [2]: df.apply(type)# 这里使用type()函数
Out[2]: 
     <class 'str'>
     <class 'str'>
     <class 'int'>
    <class 'bool'>
dtype: object
In [3]: %timeit df.apply(type) #每次循环的时间是101us
10000 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的内置函数要快

posted @ 2021-01-10 10:47  lvdongjie-avatarx  阅读(140)  评论(0编辑  收藏  举报