新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

Python中如何使用apply函数-创新互联

为恩施土家等地区用户提供了全套网页设计制作服务,及恩施土家网站建设行业解决方案。主营业务为网站制作、成都网站制作、恩施土家网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!

这篇文章给大家介绍Python 中如何使用apply函数,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

1、介绍

apply函数是pandas里面所有函数中自由度最高的函数。该函数如下:

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)

该函数最有用的是第一个参数,这个参数是函数,相当于C/C++的函数指针。

这个函数需要自己实现,函数的传入参数根据axis来定,比如axis = 1,就会把一行数据作为Series的数据 结构传入给自己实现的函数中,我们在函数中实现对Series不同属性之间的计算,返回一个结果,则apply函数 会自动遍历每一行DataFrame的数据,最后将所有结果组合成一个Series数据结构并返回。

2、样例

Python 中如何使用apply函数

import numpy as npimport pandas as pd
f = lambda x: x.max()-x.min()
df = pd.DataFrame(np.random.randn(4,3),columns=list('bde'),index=['utah', 'ohio', 'texas', 'oregon'])print(df)
t1 = df.apply(f)print(t1)
t2 = df.apply(f, axis=1)print(t2)

Python 中如何使用apply函数

输出结果如下所示:

Python 中如何使用apply函数

               b         d         e
utah    1.106486  0.101113 -0.494279ohio    0.955676 -1.889499  0.522151texas   1.891144 -0.670588  0.106530oregon -0.062372  0.991231  0.294464b    1.953516d    2.880730e    1.016430dtype: float64
utah      1.600766ohio      2.845175texas     2.561732oregon    1.053603dtype: float64

Python 中如何使用apply函数

3、性能比较

Python 中如何使用apply函数

df = pd.DataFrame({'a': np.random.randn(6),                   'b': ['foo', 'bar'] * 3,                   'c': np.random.randn(6)})def my_test(a, b):    return a + bprint(df)
df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1) # 方法1print(df)
df['Value2'] = df['a'] + df['c']  # 方法2print(df)

Python 中如何使用apply函数

输出结果如下:

Python 中如何使用apply函数

          a    b         c
0 -1.194841  foo  1.648214
1 -0.377554  bar  0.496678
2  1.524940  foo -1.245333
3 -0.248150  bar  1.526515
4  0.283395  foo  1.282233
5  0.117674  bar -0.094462
          a    b         c     Value
0 -1.194841  foo  1.648214  0.453374
1 -0.377554  bar  0.496678  0.119124
2  1.524940  foo -1.245333  0.279607
3 -0.248150  bar  1.526515  1.278365
4  0.283395  foo  1.282233  1.565628
5  0.117674  bar -0.094462  0.023212
          a    b         c     Value    Value2
0 -1.194841  foo  1.648214  0.453374  0.453374
1 -0.377554  bar  0.496678  0.119124  0.119124
2  1.524940  foo -1.245333  0.279607  0.279607
3 -0.248150  bar  1.526515  1.278365  1.278365
4  0.283395  foo  1.282233  1.565628  1.565628
5  0.117674  bar -0.094462  0.023212  0.023212

Python 中如何使用apply函数

注意:当数据量很大时,对于简单的逻辑处理建议方法2(个人处理几百M数据集时,方法1花时200s左右,方法2花时10s)!!!

关于Python 中如何使用apply函数就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


分享题目:Python中如何使用apply函数-创新互联
本文地址:http://www.wjwzjz.com/article/copsod.html
在线咨询
服务热线
服务热线:028-86922220
TOP