Pandas:DataFrame的apply()函數和applymap()函數

1.apply()函數

apply()函數主要作用是對DataFramed的每一column和每一index執行一個處理函數。先來看看apply()函數的參數。

參數 說明
func 函數參數。該函數會應該在dataframe的每一行或每一列上。
axis axis=0時,func函數會應用在每個column上。而當axis=1時,func函數會應用在每一index上。
broadcast

布爾型的可選參數。當爲None或False時,會返回一個與原dataframe的column或index長度相同的 Series。 當爲True時,會返回一個index和column跟原dataframe相同的dataframe(想當然結果進行了廣播)。

在0.23版本以後,這個參數會被替換成 result_type='broadcast'

raw 布爾型。默認爲False。當爲False時,會將dataframe中的每一個columadn或每一個index上以Series的形式傳到函數中。當爲True時,則會把數據以np.array的形式傳到函數中,如果這個時候func用的就是numpy的函數,則執行效率會非常高。
reduce 布爾型或None,默認爲None。當DataFrame爲空,reduce爲True時,函數會返回Series,當爲False時,會返回一個DataFrame。
result_type

可選值包括以下幾種:expand、reduce、broardcast、None。確定返回形式。(0.23.0以後版本纔有並且只有當axis=1時這個參數才能發揮作用)

agrs 傳遞到func中的位置參數
**kwds 傳到到func中的關鍵字參數
import pandas as pd
import numpy as np
df=pd.DataFrame(np.arange(10,34).reshape(4,6),index=list('ABCE'),
                columns=['one','two','three','four','five','six'])
def app_1(data):
    return data.mean()
#先來看看broadcast參數的作用
r1=df.apply(app_1,axis=0,broadcast=False)
print(r1)#返回Series類型
r2=df.apply(app_1,broadcast=True)
print(r2)#返回DataFrame類型
r3=df.apply(app_1,axis=1,broadcast=True)
print(r3)

r1的結果爲:

r2的結果爲:

r3的結果爲:

import pandas as pd
import numpy as np
df=pd.DataFrame(np.arange(10,34).reshape(4,6),index=list('ABCE'),
                columns=['one','two','three','four','five','six'])
def app_1(data,n):
    return max(map(lambda x:x//n,data))
#先來看看broadcast參數的作用
r1=df.apply(app_1,axis=1,n=5)
def app_2(data,n,k):
    return max(map(lambda x:x if x%n==0 and x%k==0 else 0,data))
r2=df.apply(app_2,axis=1,**{'n':4,'k':5})
r3=df.apply(app_2,axis=1,args=(4,5))#注意axis作爲關鍵字參數之後,在往func傳入位置參數時args不能省略
print(r1)
print(r2)
print(r3)

其結果截圖如下:

import pandas as pd
df=pd.DataFrame({'str_1':['o n e','t w o','t h r'],'str_2':['t h r e','h e l l o','w o r l d']})
def app_4(row):
    return [x.split() for x in row]
r5=df.apply(app_4,axis=1,result_type='expand')
r6=df.apply(app_4,axis=1,result_type='reduce')
def app_5(row):
    return row[0].split()
r7=df[['str_1']].apply(app_5,axis=1,result_type='expand')

r5的結果:

r6的結果:

r7的結果:

2.applymap()函數

applymap()函數的主要作用是對DataFrame中的每一個元素執行一個func函數。applymap()函數中只有一個func參數。

import pandas as pd
import numpy as np
df=pd.DataFrame(np.arange(10,34).reshape(4,6),index=list('ABCE'),
                columns=['one','two','three','four','five','six'])
def app_3(num):
    if num>25:
        return num
    else:
        return False
r4=df.applymap(app_3)
print(r4)

其結果如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章