作者:Peter 出品:尤而小屋 Pandas三大利器-map、apply、applymap實際工作中,我們在利用 pandas 進行數(shù)據(jù)處理的時候,經(jīng)常會對數(shù)據(jù)框中的單行、多行(列也適用)甚至是整個數(shù)據(jù)進行某種相同方式的處理,比如將數(shù)據(jù)中的 sex 字段將 男替換成1,女替換成0。 在這個時候,很容易想到的是 for 循環(huán)。用 for 循環(huán)是一種很簡單、直接的方式,但是運行效率很低。本文中介紹了 pandas 中的三大利器: map、apply、applymap 來解決上述同樣的需求。 
— 01 — 模擬數(shù)據(jù) 通過一個模擬的數(shù)據(jù)來說明3個函數(shù)的使用,在這個例子中學(xué)會了如何生成各種模擬數(shù)據(jù)。數(shù)據(jù)如下: import pandas as pd
import numpy as np
boolean = [True, False]
gender = ['男','女']
color = ['white','black','red']
# 好好學(xué)習(xí)如何生成模擬數(shù)據(jù):非常棒的例子
# 學(xué)會使用random模塊中的randint方法
df = pd.DataFrame({'height':np.random.randint(160,190,100),
'weight':np.random.randint(60,90,100),
'smoker':[boolean[x] for x in np.random.randint(0,2,100)],
'gender':[gender[x] for x in np.random.randint(0,2,100)],
'age':np.random.randint(20,60,100),
'color':[color[x] for x in np.random.randint(0,len(color),100)]
})
df.head()

— 02 — map demomap() 會根據(jù)提供的函數(shù)對指定序列做映射。 第一個參數(shù) function 以參數(shù)序列中的每一個元素調(diào)用 function 函數(shù),返回包含每次 function 函數(shù)返回值的新列表。 map(function, iterable)

實際數(shù)據(jù)將gender中男變成1,女變成0 # 方式1:通過字典映射實現(xiàn)
dic = {'男':1, '女':0} # 通過字典映射
df1 = df.copy() # 副本,不破壞原來的數(shù)據(jù)df
df1['gender'] = df1['gender'].map(dic)
df1
# 方式2:通過函數(shù)實現(xiàn)
def map_gender(x):
gender = 1 if x == '男' else 0
return gender
df2 = df.copy()
# 將df['gender']這個S型數(shù)據(jù)中的每個數(shù)值傳進去
df2['gender'] = df2['gender'].map(map_gender)
df2

— 03 — apply apply 方法的作用原理和 map 方法類似,區(qū)別在于 apply 能夠傳入功能更為復(fù)雜的函數(shù),可以說 apply 是 map 的高級版
pandas 的 apply() 函數(shù)可以作用于 Series 或者整個 DataFrame ,功能也是自動遍歷整個 Series 或者 DataFrame , 對每一個元素運行指定的函數(shù)。 在 DataFrame 對象的大多數(shù)方法中,都會有 axis 這個參數(shù),它控制了你指定的操作是沿著0軸還是1軸進行。 axis=0 代表操作對 列columns 進行, axis=1 代表操作對 行row 進行 demo上面的數(shù)據(jù)中將age字段的值都減去3,即加上-3
def apply_age(x,bias):
return x + bias
df4 = df.copy()
# df4['age']當做第一個值傳給apply_age函數(shù),args是第二個參數(shù)
df4['age'] = df4['age'].apply(apply_age,args=(-3,))

計算BMI指數(shù)
# 實現(xiàn)計算BMI指數(shù):體重/身高的平方(kg/m^2)
def BMI(x):
weight = x['weight']
height = x['height'] / 100
BMI = weight / (height **2)
return BMI
df5 = df.copy()
df5['BMI'] = df5.apply(BMI,axis=1) # df5現(xiàn)在就相當于BMI函數(shù)中的參數(shù)x;axis=1表示在列上操作
df5

DataFrame 型數(shù)據(jù)的 apply 操作總結(jié):
當 axis=0 時,對 每列columns 執(zhí)行指定函數(shù);當 axis=1 時,對 每行row 執(zhí)行指定函數(shù)。 無論 axis=0 還是 axis=1 ,其傳入指定函數(shù)的默認形式均為 Series ,可以通過設(shè)置 raw=True 傳入 numpy數(shù)組 。 對每個Series執(zhí)行結(jié)果后,會將結(jié)果整合在一起返回(若想有返回值,定義函數(shù)時需要 return 相應(yīng)的值)
apply實現(xiàn)需求通過apply方法實現(xiàn)上面的性別轉(zhuǎn)換需求。apply方法中傳進來的第一個參數(shù)一定是函數(shù) 
— 04 — applymap DF數(shù)據(jù)加1applymap函數(shù)用于對DF型數(shù)據(jù)中的每個元素執(zhí)行相同的函數(shù)操作,比如下面的加1: 
保留2位有效數(shù)字
|