新聞中心
在python中如果想要對數(shù)據(jù)使用函數(shù),可以借助apply()、applymap()、map()來應(yīng)用函數(shù),括號里面可以是直接函數(shù)式,或者自定義函數(shù)(def)或者匿名函數(shù)(lambad)。

創(chuàng)新互聯(lián)主營晉安網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,重慶App定制開發(fā),晉安h5成都微信小程序搭建,晉安網(wǎng)站營銷推廣歡迎晉安等地區(qū)企業(yè)咨詢
import pandas as pd
import numpy as np
from pandas import DataFrame
from pandas import Series
df1= DataFrame({
"sales1":[-1,2,3],
"sales2":[3,-5,7],
})
df11、當(dāng)我們要對數(shù)據(jù)框(DataFrame)的數(shù)據(jù)進(jìn)行按行或按列操作時用apply()。
df1.apply(lambda x :x.max()-x.min(),axis=1) #axis=1,表示按行對數(shù)據(jù)進(jìn)行操作 #從下面的結(jié)果可以看出,我們使用了apply函數(shù)之后,系統(tǒng)自動按行找值和最小值計算,每一行輸出一個值
0 4
1 7
2 4
dtype: int64
df1.apply(lambda x :x.max()-x.min(),axis=0) #默認(rèn)參數(shù)axis=0,表示按列對數(shù)據(jù)進(jìn)行操作 #從下面的結(jié)果可以看出,我們使用了apply函數(shù)之后,系統(tǒng)自動按列找值和最小值計算,每一列輸出一個值
sales1 4
sales2 12
dtype: int64
2、當(dāng)我們要對數(shù)據(jù)框(DataFrame)的每一個數(shù)據(jù)進(jìn)行操作時用applymap(),返回結(jié)果是DataFrame格式。
df1.applymap(lambda x : 1 if x>0 else 0) #從下面的結(jié)果可以看出,我們使用了applymap函數(shù)之后, #系統(tǒng)自動對每一個數(shù)據(jù)進(jìn)行判斷,判斷之后輸出結(jié)果
3、當(dāng)我們要對Series的每一個數(shù)據(jù)進(jìn)行操作時用map()。
df1.sales1.map(lambda x : 1 if x>0 else 0) #df1.sales1就是一個Series
0 0
1 1
2 1
Name: sales1, dtype: int64
4、總結(jié):要對數(shù)據(jù)進(jìn)行應(yīng)用函數(shù)時,先看數(shù)據(jù)結(jié)構(gòu)是DataFrame還是Series,Seriesj結(jié)構(gòu)直接用map(),DataFrame結(jié)構(gòu)的話再看是要按行還是按列進(jìn)行操作來選擇對應(yīng)的函數(shù)即可。
python學(xué)習(xí)網(wǎng),免費的在線學(xué)習(xí)python平臺,歡迎關(guān)注!
名稱欄目:創(chuàng)新互聯(lián)Python教程:pythonapply和map區(qū)別是什么
標(biāo)題路徑:http://www.fisionsoft.com.cn/article/djgpoge.html


咨詢
建站咨詢
