欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

pandas使用函數(shù)批量處理數(shù)據(jù)(map、apply、applymap)

 更新時間:2020年11月27日 11:45:55   作者:william_cheng666  
這篇文章主要介紹了pandas使用函數(shù)批量處理數(shù)據(jù)(map、apply、applymap),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

前言

在我們對DataFrame對象進(jìn)行處理時候,下意識的會想到對DataFrame進(jìn)行遍歷,然后將處理后的值再填入DataFrame中,這樣做比較繁瑣,且處理大量數(shù)據(jù)時耗時較長。Pandas內(nèi)置了一個可以對DataFrame批量進(jìn)行函數(shù)處理的工具:map、apply和applymap。

提示:為方便快捷地解決問題,本文僅介紹函數(shù)的主要用法,并非全面介紹

一、pandas.Series.map()是什么?

把Series中的值進(jìn)行逐一映射,帶入進(jìn)函數(shù)、字典或Series中得出的另一個值。

Series.map(arg, na_action=None)

參數(shù):

  • arg:函數(shù)、字典類數(shù)據(jù)、Series;映射對應(yīng)關(guān)系
  • na_action{None, ‘ignore'}:默認(rèn)為None;處理NaN變量,如果為None則不處理NaN對象,如果為‘ignore'則將NaN對象當(dāng)做普通對象帶入規(guī)則。

返回Series

二、pandas.Series.map()用法和優(yōu)點

本節(jié)主要講述map()函數(shù)的主要用法和相比于方法的優(yōu)點

1、map()用法

創(chuàng)建案例DataFrame

import pandas as pd
import numpy as np
import time

data = pd.DataFrame({'name':['Verne Raymond','Chapman Becher','Patrick George','Saxon MacArthur',
               'Joshua Marjory','Luther Pigou','Fanny Agnes','Karen Bush','Elaine Whitman'],
             'gender':[0,1,0,0,1,1,1,0,1],'first_name':np.nan,'last_name':np.nan})

print(data)

              name  gender  first_name  last_name
0    Verne Raymond       0         NaN        NaN
1   Chapman Becher       1         NaN        NaN
2   Patrick George       0         NaN        NaN
3  Saxon MacArthur       0         NaN        NaN
4   Joshua Marjory       1         NaN        NaN
5     Luther Pigou       1         NaN        NaN
6      Fanny Agnes       1         NaN        NaN
7       Karen Bush       0         NaN        NaN
8   Elaine Whitman       1         NaN        NaN

現(xiàn)在需要將name列的姓和名拆分開來分別放入first_name 和last_name里面,使用map()函數(shù)實現(xiàn),并計算所用時間

def first_name_map(x):
  return x.split(' ')[0]
def last_name_map(x):
  return x.split(' ')[1]

data['first_name'] = data['name'].map(first_name_map)
data['last_name'] = data['name'].map(last_name_map)

print('use time:'+str(end-start))
print(data)

use time:0.0009970664978027344
              name  gender first_name  last_name
0    Verne Raymond       0      Verne    Raymond
1   Chapman Becher       1    Chapman     Becher
2   Patrick George       0    Patrick     George
3  Saxon MacArthur       0      Saxon  MacArthur
4   Joshua Marjory       1     Joshua    Marjory
5     Luther Pigou       1     Luther      Pigou
6      Fanny Agnes       1      Fanny      Agnes
7       Karen Bush       0      Karen       Bush
8   Elaine Whitman       1     Elaine    Whitman

如果要將性別代號的0、1替換為中文Male和Female,可以使用字典映射功能,如下

data['gender'] = data['gender'].map({0:'Female',1:'Male'})

print(data)

              name  gender first_name  last_name
0    Verne Raymond  Female      Verne    Raymond
1   Chapman Becher    Male    Chapman     Becher
2   Patrick George  Female    Patrick     George
3  Saxon MacArthur  Female      Saxon  MacArthur
4   Joshua Marjory    Male     Joshua    Marjory
5     Luther Pigou    Male     Luther      Pigou
6      Fanny Agnes    Male      Fanny      Agnes
7       Karen Bush  Female      Karen       Bush
8   Elaine Whitman    Male     Elaine    Whitman

2、map()相比其他方式的優(yōu)點

較普通的方法主要是方便和速度快,下面例子進(jìn)行對比,上面已經(jīng)計算過使用map()方法處理的速度為:0.0009970664978027344

傳統(tǒng)遍歷

start = time.time()
for index,rows in data.iterrows():
  data['first_name'][index] = rows['name'].split(' ')[0]
  data['last_name'][index] = rows['name'].split(' ')[1]
end = time.time()
print('use time:'+str(end-start))

use time:0.5146446228027344

可以看到使用map()方法比使用直接遍歷的方式快了500多倍

list暫存的方法

start = time.time()
first_name = []
last_name = []
for index,rows in data.iterrows():
  first_name.append(rows['name'].split(' ')[0])
  last_name.append(rows['name'].split(' ')[1])
data['first_name'] = first_name
data['last_name'] = last_name
end = time.time()
print('use time:'+str(end-start))

use time:0.001994609832763672

可以看出來使用list暫存的方法比遍歷方法快了250多倍,但是比map方法還是慢了一半

二、apply()函數(shù)

apply()的使用方法與map()的使用方法類似,只是apply()除了傳入Series參數(shù)外還可以多傳入額外的參數(shù)。

Series.apply(func,convert_dtype = True,args = (), **kwds)

參數(shù):
func:函數(shù)名稱

convert_dtype:bool類值, 默認(rèn)為True;嘗試自己尋找最適合的數(shù)據(jù)類型。如果為False則dtype=object。

args:元組;在Series之后傳遞位置參數(shù)信息

**kwds:給函數(shù)傳遞其他參數(shù)(以字典的形式)

返回Series或DataFrame

下面是案例(參考官方文檔案例)

s = pd.Series([20, 21, 12],index=['London', 'New York', 'Helsinki'])
print(s)

London      20
New York    21
Helsinki    12
dtype: int64

處理數(shù)據(jù)

def subtract_custom_value(x, custom_value):
  return x - custom_value
s.apply(subtract_custom_value, args=(5,))

London      15
New York    16
Helsinki     7
dtype: int64

使用**kwds參數(shù)

def subtract_custom_value(x, **kwds):
  for key in kwds:
    x -= kwds[key]
  return x
s.apply(subtract_custom_value, num = 5)

London      15
New York    16
Helsinki     7
dtype: int64

三、applymap()函數(shù)用法

applymap()函數(shù)處理的對象是DataFrame,并非Series,它沒有前面兩個函數(shù)用得多,但在某些情況也很有用。

DataFrame.applymap(func)

參數(shù):
func:函數(shù);要調(diào)用的Python函數(shù),輸入輸出都為單個值

返回DataFrame

下面是簡單的案例:

import pandas as pd
import numpy as np
data = pd.DataFrame(
  {
    "A":np.random.randn(3),
    "B":np.random.randn(3),
    "C":np.random.randn(3),
  }
)
print(data )

          A         B         C
0  2.128483 -1.701311 -1.362955
1 -1.149937  1.108856 -0.259637
2 -0.076621 -0.379672 -2.636464

計算所有值的平方:

data.applymap(lambda x: x**2)

          A         B         C
0  4.530439  2.894459  1.857645
1  1.322356  1.229561  0.067411
2  0.005871  0.144151  6.950940

總結(jié)

本文展示了Pandas將數(shù)據(jù)映射到函數(shù)里批量快速處理的方法,主要使用的了Pandas自帶的map、apply和applymap工具,實驗結(jié)果是比普通循環(huán)快500倍,后續(xù)還將介紹更多數(shù)據(jù)處理實用的技巧。

到此這篇關(guān)于pandas使用函數(shù)批量處理數(shù)據(jù)(map、apply、applymap)的文章就介紹到這了,更多相關(guān)pandas函數(shù)批量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python中跳臺階、變態(tài)跳臺階與矩形覆蓋問題的解決方法

    Python中跳臺階、變態(tài)跳臺階與矩形覆蓋問題的解決方法

    這篇文章主要給大家介紹了關(guān)于Python中跳臺階、變態(tài)跳臺階與矩形覆蓋問題的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-05-05
  • python使用rsa加密算法模塊模擬新浪微博登錄

    python使用rsa加密算法模塊模擬新浪微博登錄

    這篇文章主要介紹了python使用rsa加密算法模塊模擬新浪微博登錄的示例,大家參考使用吧
    2014-01-01
  • Python Print實現(xiàn)在輸出中插入變量的例子

    Python Print實現(xiàn)在輸出中插入變量的例子

    今天小編就為大家分享一篇Python Print實現(xiàn)在輸出中插入變量的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • python處理xls文件openpyxl基礎(chǔ)操作

    python處理xls文件openpyxl基礎(chǔ)操作

    這篇文章主要為大家介紹了python處理xls文件openpyxl基礎(chǔ)操作,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • Python對wav文件的重采樣實例

    Python對wav文件的重采樣實例

    今天小編就為大家分享一篇Python對wav文件的重采樣實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • Python中的//符號是什么意思呢

    Python中的//符號是什么意思呢

    這篇文章主要介紹了Python中的//符號是什么意思,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • 基于pandas數(shù)據(jù)樣本行列選取的方法

    基于pandas數(shù)據(jù)樣本行列選取的方法

    下面小編就為大家分享一篇基于pandas數(shù)據(jù)樣本行列選取的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-04-04
  • python利用蒙版摳圖(使用PIL.Image和cv2)輸出透明背景圖

    python利用蒙版摳圖(使用PIL.Image和cv2)輸出透明背景圖

    這篇文章主要介紹了python利用蒙版摳圖(使用PIL.Image和cv2)輸出透明背景圖,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • pandas通過字典生成dataframe的方法步驟

    pandas通過字典生成dataframe的方法步驟

    這篇文章主要介紹了pandas通過字典生成dataframe的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • Python實現(xiàn)Harbor私有鏡像倉庫垃圾自動化清理詳情

    Python實現(xiàn)Harbor私有鏡像倉庫垃圾自動化清理詳情

    這篇文章主要介紹了Python實現(xiàn)Harbor私有鏡像倉庫垃圾自動化清理詳情,文章圍繞主題分享相關(guān)詳細(xì)代碼,需要的小伙伴可以參考一下
    2022-05-05

最新評論