一、總結
- apply —— 應用在 dataFrame 上,用於對 row 或者 column 進行計算
- applymap —— 應用在 dataFrame 上,元素級別的操作
- map —— python 系統自帶函數,應用在 series 上, 元素級別的操作
二、實操對比
構建測試數據框:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0, 10, (4, 3)),
columns=list('abc'),
index=range(4))
df
'''
a b c
0 5 4 8
1 7 5 2
2 1 2 2
3 1 6 2
'''
apply 作用在 dataframe 上的一行或者一列上
#Python學習交流群:531509025
# 默認按列操作 axis=0
# 求每列的最大值、最小值之差
df.apply(lambda x: x.max() - x.min()) # axis=0
# 求每行的最大值、最小值之差
df.apply(lambda x: x.max() - x.min(), axis=1)
applymap 作用在 dataframe 的每一個元素上
# 偶數放大10倍
df.applymap(lambda x: x*10 if x%2 == 0 else x)
map 函數作用在 series 上的每一個元素
# 單獨的序列
df['b'].map(lambda x: 1 if x%2 == 0 else 0)
總的來說,要對數據進行應用函數操作時,考慮數據結構是 DataFrame 還是 Series ,再考慮是要按行執行還是按列執行,進行函數的選擇。
結尾給大家推薦一個非常好的學習教程,希望對你學習Python有幫助!
Python基礎入門教程推薦:更多Python視頻教程-關注B站:Python學習者
[video(video-WX5IrDgs-1634800181977)(type-bilibili)(url-https://player.bilibili.com/player.html?aid=847801620)(image-https://img-blog.csdnimg.cn/img_convert/5ff15db56683729c38ee1547ef0bf3a9.png)(title-【Python教程】全網最容易聽懂的1000集python系統學習教程(答疑在最后四期,滿滿干貨))]
Python爬蟲案例教程推薦:更多Python視頻教程-關注B站:Python學習者
[video(video-1Ue5otke-1634800187124)(type-bilibili)(url-https://player.bilibili.com/player.html?aid=372208936)(image-https://img-blog.csdnimg.cn/img_convert/3abe5e4377a0a5f8b72a20ead4d640bb.png)(title-2021年Python最新最全100個爬蟲完整案例教程,數據分析,數據可視化,記得收藏哦)]