2022-03-08 11:59小小程序員ol Python
這篇文章主要介紹了 Python函數(shù)中apply,、map,、applymap的區(qū)別 ,文章圍繞 Python函數(shù)中apply,、map,、applymap的相關(guān)資料展開詳細(xì)內(nèi)容,需要的朋友可以參考一下
一,、總結(jié)
-
apply —— 應(yīng)用在 dataFrame 上,用于對 row 或者 column 進(jìn)行計(jì)算
-
applymap —— 應(yīng)用在 dataFrame 上,元素級別的操作
-
map —— python 系統(tǒng)自帶函數(shù),,應(yīng)用在 series 上,, 元素級別的操作
二、實(shí)操對比
構(gòu)建測試數(shù)據(jù)框:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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 上的一行或者一列上
?
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#Python學(xué)習(xí)交流群:531509025
# 默認(rèn)按列操作 axis=0
# 求每列的最大值,、最小值之差
df. apply ( lambda x: x. max () - x. min ()) # axis=0
# 求每行的最大值、最小值之差
df. apply ( lambda x: x. max () - x. min (), axis = 1 )
|
applymap 作用在 dataframe 的每一個(gè)元素上
?
1
2
3
|
# 偶數(shù)放大10倍
df.applymap( lambda x: x * 10 if x % 2 = = 0 else x)
|
map 函數(shù)作用在 series 上的每一個(gè)元素
?
1
2
3
|
# 單獨(dú)的序列
df['b'].map(lambda x: 1 if x%2 == 0 else 0)
|
總的來說,,要對數(shù)據(jù)進(jìn)行應(yīng)用函數(shù)操作時(shí),,考慮數(shù)據(jù)結(jié)構(gòu)是 DataFrame 還是 Series ,再考慮是要按行執(zhí)行還是按列執(zhí)行,,進(jìn)行函數(shù)的選擇,。
到此這篇關(guān)于 Python 函數(shù)中apply 、map ,、applymap 的區(qū)別 的文章就介紹到這了,更多相關(guān) Python中的apply,、map、applymap內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家,!
原文鏈接:https://www.cnblogs.com/python960410445/p/15463099.html
|