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]: 
0     <class 'str'>
1     <class 'str'>
2     <class 'int'>
3    <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的内置函数要快

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值