日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python基础中apply()函数的正确用法

發布時間:2025/3/20 python 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python基础中apply()函数的正确用法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

函數格式為:apply(func,*args,**kwargs)

用途:當一個函數的參數存在于一個元組或者一個字典中時,用來間接的調用這個函數,并肩元組或者字典中的參數按照順序傳遞給參數

解析:args是一個包含按照函數所需參數傳遞的位置參數的一個元組,是不是很拗口,意思就是,假如A函數的函數位置為 A(a=1,b=2),那么這個元組中就必須嚴格按照這個參數的位置順序進行傳遞(a=3,b=4),而不能是(b=4,a=3)這樣的順序
kwargs是一個包含關鍵字參數的字典,而其中args如果不傳遞,kwargs需要傳遞,則必須在args的位置留空

apply的返回值就是函數func函數的返回值

def function(a,b): print(a,b) apply(function,('good','better')) apply(function,(2,3+6)) apply(function,('cai','quan')) apply(function,('cai',),{'b':'caiquan'}) apply(function,(),{'a':'caiquan','b':'Tom'}) #--使用 apply 函數調用基類的構造函數 class Rectangle: def __init__(self, color="white", width=10, height=10): print "create a", color, self, "sized", width, "x", height class RoundedRectangle(Rectangle): def __init__(self, **kw): apply(Rectangle.__init__, (self,), kw) rect = Rectangle(color="green", height=100, width=100) rect = RoundedRectangle(color="blue", height=20)

輸出結果:

('good', 'better') (2, 9) ('cai', 'quan') ('cai', 'caiquan') ('caiquan', 'Tom') create a green <__main__.Rectangle instance at 0x0678FA08> sized 100 x 100 create a blue <__main__.RoundedRectangle instance at 0x06620468> sized 10 x 20

apply函數默認的是axis為 axis=0

''' 學習中遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' data= [[1,2,3],[5,4,1],[3,2,2] ] df = pd.DataFrame(data,columns=['A','B','C'])<br>f = lambda x: (x - np.min(x)) / (np.max(x) - np.min(x)) print(df)A B C 0 1 2 3 1 5 4 1 2 3 2 2

1、axis=1

df1 = df.copy() df1 = df1.apply(f,axis=1) #計算的時候取的是行數 df1A B C 0 0.0 0.50 1.0 1 1.0 0.75 0.0 2 1.0 0.00 0.0

2、axis=2

''' 學習中遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' df2 = df.copy() df2 = df2.apply(f,axis=0) df2A B C 0 0.0 0.0 1.0 1 1.0 1.0 0.0 2 0.5 0.0 0.5

3、默認axis

df3 = df.copy() df3 = df3.apply(f) df3 # 在DataFrame中apply函數默認的是axis=0,取的是列數A B C 0 0.0 0.0 1.0 1 1.0 1.0 0.0 2 0.5 0.0 0.5 (df['A'] - df['A'].min())/(df['A'].max()-df['A'].min()) 0 0.0 1 1.0 2 0.5 Name: A, dtype: float64

總結

以上是生活随笔為你收集整理的python基础中apply()函数的正确用法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。