Python apply函数
1、介紹
apply函數(shù)是pandas里面所有函數(shù)中自由度最高的函數(shù)。該函數(shù)如下:
DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)該函數(shù)最有用的是第一個(gè)參數(shù),這個(gè)參數(shù)是函數(shù),相當(dāng)于C/C++的函數(shù)指針。
這個(gè)函數(shù)需要自己實(shí)現(xiàn),函數(shù)的傳入?yún)?shù)根據(jù)axis來(lái)定,比如axis = 1,就會(huì)把一行數(shù)據(jù)作為Series的數(shù)據(jù) 結(jié)構(gòu)傳入給自己實(shí)現(xiàn)的函數(shù)中,我們?cè)诤瘮?shù)中實(shí)現(xiàn)對(duì)Series不同屬性之間的計(jì)算,返回一個(gè)結(jié)果,則apply函數(shù) 會(huì)自動(dòng)遍歷每一行DataFrame的數(shù)據(jù),最后將所有結(jié)果組合成一個(gè)Series數(shù)據(jù)結(jié)構(gòu)并返回。
2、樣例
import numpy as np import pandas as pdf = 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)輸出結(jié)果如下所示:
b d e utah 1.106486 0.101113 -0.494279 ohio 0.955676 -1.889499 0.522151 texas 1.891144 -0.670588 0.106530 oregon -0.062372 0.991231 0.294464b 1.953516 d 2.880730 e 1.016430 dtype: float64utah 1.600766 ohio 2.845175 texas 2.561732 oregon 1.053603 dtype: float643、性能比較
''' 遇到問題沒人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書! ''' 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) # 方法1 print(df)df['Value2'] = df['a'] + df['c'] # 方法2 print(df)輸出結(jié)果如下:
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.094462a 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.023212a 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注意:當(dāng)數(shù)據(jù)量很大時(shí),對(duì)于簡(jiǎn)單的邏輯處理建議方法2(個(gè)人處理幾百M(fèi)數(shù)據(jù)集時(shí),方法1花時(shí)200s左右,方法2花時(shí)10s)!!!
總結(jié)
以上是生活随笔為你收集整理的Python apply函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python基础教程:赋值、深拷贝与浅拷
- 下一篇: python从字符串解析方法名