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

學無先后,達者為師

網站首頁 編程語言 正文

python中apply函數詳情_python

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

函數原型:

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

  • 1.該函數最有用的是第一個參數,這個參數是函數,相當于C/C++的函數指針。
  • 2.這個函數需要自己實現,函數的傳入參數根據axis來定,比如axis = 1,就會把一行數據作為Series的數據
  • 結構傳入給自己實現的函數中,我們在函數中實現對Series不同屬性之間的計算,返回一個結果,則apply函數
  • 會自動遍歷每一行DataFrame的數據,最后將所有結果組合成一個Series數據結構
  • 并返回。
  • 3.apply函數常與groupby函數一起使用,如下圖所示:

  • 4.舉栗子

對指定列進行操作:

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

對行操作:

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

整體對列操作:

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

整體對行操作:

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

欄目分類
最近更新