這篇文章給大家介紹Python 中如何使用apply函數(shù),內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
創(chuàng)新互聯(lián)為客戶提供專業(yè)的網(wǎng)站建設(shè)、網(wǎng)站制作、程序、域名、空間一條龍服務(wù),提供基于WEB的系統(tǒng)開發(fā). 服務(wù)項目涵蓋了網(wǎng)頁設(shè)計、網(wǎng)站程序開發(fā)、WEB系統(tǒng)開發(fā)、微信二次開發(fā)、移動網(wǎng)站建設(shè)等網(wǎng)站方面業(yè)務(wù)。
apply函數(shù)是pandas里面所有函數(shù)中自由度最高的函數(shù)。該函數(shù)如下:
DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)
該函數(shù)最有用的是第一個參數(shù),這個參數(shù)是函數(shù),相當(dāng)于C/C++的函數(shù)指針。
這個函數(shù)需要自己實現(xiàn),函數(shù)的傳入?yún)?shù)根據(jù)axis來定,比如axis = 1,就會把一行數(shù)據(jù)作為Series的數(shù)據(jù) 結(jié)構(gòu)傳入給自己實現(xiàn)的函數(shù)中,我們在函數(shù)中實現(xiàn)對Series不同屬性之間的計算,返回一個結(jié)果,則apply函數(shù) 會自動遍歷每一行DataFrame的數(shù)據(jù),最后將所有結(jié)果組合成一個Series數(shù)據(jù)結(jié)構(gòu)并返回。
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)
輸出結(jié)果如下所示:
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
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)
輸出結(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.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
注意:當(dāng)數(shù)據(jù)量很大時,對于簡單的邏輯處理建議方法2(個人處理幾百M數(shù)據(jù)集時,方法1花時200s左右,方法2花時10s)?。?!
關(guān)于Python 中如何使用apply函數(shù)就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
文章標(biāo)題:Python中如何使用apply函數(shù)
文章來源:http://bm7419.com/article6/gijdig.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機(jī)網(wǎng)站建設(shè)、定制網(wǎng)站、域名注冊、企業(yè)網(wǎng)站制作、App開發(fā)、網(wǎng)站內(nèi)鏈
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)