平時在處理df series格式的時候並沒有注意 map和apply的差異
總感覺沒啥卻別。不過還是有區別的。下面總結一下:
import pandas as pd df1= pd.DataFrame({ "sales1":[-1,2,3], "sales2":[3,-5,7], })
1.apply
1、當我們要對數據框(DataFrame)的數據進行按行或按列操作時用apply()
note:操作的原子是行和列 ,可以用行列統計描述符 min max mean ......
當axis=0的時候是對“列”進行操作
df2=df1.apply(lambda x: x.max()-x.min(),axis=0)
print(type(df2),"\n",df2)
axis=1的時候是對“行”進行操作
df3=df1.apply(lambda x: x.max()-x.min(),axis=1)
print(type(df3),"\n",df3)
2.也可以直接選定一列series,或者df直接操作
2.applymap
1.applymap函數之后,自動對DataFrame每一個元素進行處理,判斷之后輸出結果
df4=df1.applymap(lambda x: x>0)
print(type(df4),"\n",df4)
2.applymap是對 DataFrame 進行每個元素的單獨操作
ie:不能添加列統計函數,因為是只針對單個元素的操作
df5=df1.applymap(lambda x: x.min()) print(type(df5),"\n",df5)
3.'Series' object has no attribute 'applymap'
df4=df1["sales1"].applymap(lambda x: x>0) print(type(df4),"\n",df4)
3.map
1.'DataFrame' object has no attribute 'map'
df4=df1.map(lambda x: x**2) print(type(df4),"\n",df4)
2.map其實是對 列,series 等 進行每個元素的單獨操作
ie:不能添加列統計函數,因為是只針對單個元素的操作
df3=df1["sales1"].map(lambda x: x.max()-x.min()) print(type(df3),"\n",df3)
3.正常
df4=df1["sales1"].map(lambda x: x**2) print(type(df4),"\n",df4)