日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python中apply函數(shù)詳情_python

作者:sorrythanku? ? 更新時(shí)間: 2022-03-29 編程語言

函數(shù)原型:

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

  • 1.該函數(shù)最有用的是第一個(gè)參數(shù),這個(gè)參數(shù)是函數(shù),相當(dāng)于C/C++的函數(shù)指針。
  • 2.這個(gè)函數(shù)需要自己實(shí)現(xiàn),函數(shù)的傳入?yún)?shù)根據(jù)axis來定,比如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)
  • 并返回。
  • 3.apply函數(shù)常與groupby函數(shù)一起使用,如下圖所示:

  • 4.舉栗子

對(duì)指定列進(jìn)行操作:

data=np.arange(0,16).reshape(4,4)
data=pd.DataFrame(data,columns=['0','1','2','3'])
def f(x):
? ? return x-1
print(data)
print(data.ix[:,['1','2']].apply(f))
? ? 0 ? 1 ? 2 ? 3
0 ? 0 ? 1 ? 2 ? 3
1 ? 4 ? 5 ? 6 ? 7
2 ? 8 ? 9 ?10 ?11
3 ?12 ?13 ?14 ?15
? ? 1 ? 2
0 ? 0 ? 1
1 ? 4 ? 5
2 ? 8 ? 9
3 ?12 ?13

對(duì)行操作:

data=np.arange(0,16).reshape(4,4)
data=pd.DataFrame(data,columns=['0','1','2','3'])
def f(x):
? ? return x-1
print(data)
print(data.ix[[0,1],:].apply(f))
? ? 0 ? 1 ? 2 ? 3
0 ? 0 ? 1 ? 2 ? 3
1 ? 4 ? 5 ? 6 ? 7
2 ? 8 ? 9 ?10 ?11
3 ?12 ?13 ?14 ?15
? ?0 ?1 ?2 ?3
0 -1 ?0 ?1 ?2
1 ?3 ?4 ?5 ?6

整體對(duì)列操作:

data=np.arange(0,16).reshape(4,4)
data=pd.DataFrame(data,columns=['0','1','2','3'])
def f(x):
? ? return x.max()
print(data)
print(data.apply(f))
? ? 0 ? 1 ? 2 ? 3
0 ? 0 ? 1 ? 2 ? 3
1 ? 4 ? 5 ? 6 ? 7
2 ? 8 ? 9 ?10 ?11
3 ?12 ?13 ?14 ?15

0 ? ?12
1 ? ?13
2 ? ?14
3 ? ?15
dtype: int64

整體對(duì)行操作:

data=np.arange(0,16).reshape(4,4)
data=pd.DataFrame(data,columns=['0','1','2','3'])
def f(x):
? ? return x.max()
print(data)
print(data.apply(f,axis=1))
? ? 0 ? 1 ? 2 ? 3
0 ? 0 ? 1 ? 2 ? 3
1 ? 4 ? 5 ? 6 ? 7
2 ? 8 ? 9 ?10 ?11
3 ?12 ?13 ?14 ?15
0 ? ? 3
1 ? ? 7
2 ? ?11
3 ? ?15
dtype: int64

原文鏈接:https://blog.csdn.net/starmoth/article/details/86323026

欄目分類
最近更新