對(duì)pandas中Series的map函數(shù)詳解
Series的map方法可以接受一個(gè)函數(shù)或含有映射關(guān)系的字典型對(duì)象。
使用map是一種實(shí)現(xiàn)元素級(jí)轉(zhuǎn)換以及其他數(shù)據(jù)清理工作的便捷方式。
(DataFrame中對(duì)應(yīng)的是applymap()函數(shù),當(dāng)然DataFrame還有apply()函數(shù))
1、字典映射
import pandas as pd from pandas import Series, DataFrame data = DataFrame({'food':['bacon','pulled pork','bacon','Pastrami', 'corned beef','Bacon','pastrami','honey ham','nova lox'], 'ounces':[4,3,12,6,7.5,8,3,5,6]}) meat_to_animal = { 'bacon':'pig', 'pulled pork':'pig', 'pastrami':'cow', 'corned beef':'cow', 'honey ham':'pig', 'nova lox':'salmon' } data['animal'] = data['food'].map(str.lower).map(meat_to_animal) data data['food'].map(lambda x: meat_to_animal[x.lower()])
2、應(yīng)用函數(shù)
In [579]: import pandas as pd In [580]: from pandas import Series, DataFrame In [581]: index = pd.date_range('2017-08-15', periods=10) In [582]: ser = Series(list(range(10)), index=index) In [583]: ser Out[583]: 2017-08-15 0 2017-08-16 1 2017-08-17 2 2017-08-18 3 2017-08-19 4 2017-08-20 5 2017-08-21 6 2017-08-22 7 2017-08-23 8 2017-08-24 9 Freq: D, dtype: int64 In [585]: ser.index.map(lambda x: x.day) Out[585]: Int64Index([15, 16, 17, 18, 19, 20, 21, 22, 23, 24], dtype='int64') In [586]: ser.index.map(lambda x: x.weekday) Out[586]: Int64Index([1, 2, 3, 4, 5, 6, 0, 1, 2, 3], dtype='int64') In [587]: ser.map(lambda x: x+10) Out[587]: 2017-08-15 10 2017-08-16 11 2017-08-17 12 2017-08-18 13 2017-08-19 14 2017-08-20 15 2017-08-21 16 2017-08-22 17 2017-08-23 18 2017-08-24 19 Freq: D, dtype: int64 In [588]: def f(x): ...: if x < 5: ...: return True ...: else: ...: return False ...: In [589]: ser.map(f) Out[589]: 2017-08-15 True 2017-08-16 True 2017-08-17 True 2017-08-18 True 2017-08-19 True 2017-08-20 False 2017-08-21 False 2017-08-22 False 2017-08-23 False 2017-08-24 False Freq: D, dtype: bool
以上這篇對(duì)pandas中Series的map函數(shù)詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python?Tkinter庫從入門到進(jìn)階使用教程
Tkinter是Python標(biāo)準(zhǔn)庫中內(nèi)置的圖形用戶界面(GUI)工具包,提供了創(chuàng)建窗口、按鈕、文本框等GUI元素的功能,本文將介紹Tkinter的基礎(chǔ)知識(shí),幫助大家快速入門2023-12-12python中字符串?dāng)?shù)組逆序排列方法總結(jié)
在本篇文章里小編給大家整理了關(guān)于python中字符串?dāng)?shù)組如何逆序排列的相關(guān)知識(shí)點(diǎn),需要的朋友們學(xué)習(xí)下。2019-06-06Python自動(dòng)修改電腦靜態(tài)IP地址的實(shí)現(xiàn)示例
通過Python自動(dòng)修改電腦的靜態(tài)IP地址可以極大地提高我們的工作效率,減少手動(dòng)修改IP地址帶來的錯(cuò)誤,本文就來介紹一下Python自動(dòng)修改電腦靜態(tài)IP地址的實(shí)現(xiàn)示例,感興趣的可以了解一下2023-11-11numpy使用技巧之?dāng)?shù)組過濾實(shí)例代碼
這篇文章主要介紹了numpy使用技巧之?dāng)?shù)組過濾實(shí)例代碼,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02python通過函數(shù)屬性實(shí)現(xiàn)全局變量的方法
這篇文章主要介紹了python通過函數(shù)屬性實(shí)現(xiàn)全局變量的方法,實(shí)例分析了Python中函數(shù)屬性的相關(guān)使用技巧,需要的朋友可以參考下2015-05-05對(duì)Python中的@classmethod用法詳解
下面小編就為大家分享一篇對(duì)Python中的@classmethod用法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04Python編程中的文件讀寫及相關(guān)的文件對(duì)象方法講解
這篇文章主要介紹了Python編程中的文件讀寫及相關(guān)的文件對(duì)象方法講解,其中文件對(duì)象方法部分講到了對(duì)文件內(nèi)容的輸入輸出操作,需要的朋友可以參考下2016-01-01