對pandas中Series的map函數(shù)詳解
更新時間:2018年07月25日 09:25:39 作者:曉東邪
今天小編就為大家分享一篇對pandas中Series的map函數(shù)詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
Series的map方法可以接受一個函數(shù)或含有映射關系的字典型對象。
使用map是一種實現(xiàn)元素級轉(zhuǎn)換以及其他數(shù)據(jù)清理工作的便捷方式。
(DataFrame中對應的是applymap()函數(shù),當然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、應用函數(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
以上這篇對pandas中Series的map函數(shù)詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python中字符串數(shù)組逆序排列方法總結(jié)
在本篇文章里小編給大家整理了關于python中字符串數(shù)組如何逆序排列的相關知識點,需要的朋友們學習下。2019-06-06Python自動修改電腦靜態(tài)IP地址的實現(xiàn)示例
通過Python自動修改電腦的靜態(tài)IP地址可以極大地提高我們的工作效率,減少手動修改IP地址帶來的錯誤,本文就來介紹一下Python自動修改電腦靜態(tài)IP地址的實現(xiàn)示例,感興趣的可以了解一下2023-11-11python通過函數(shù)屬性實現(xiàn)全局變量的方法
這篇文章主要介紹了python通過函數(shù)屬性實現(xiàn)全局變量的方法,實例分析了Python中函數(shù)屬性的相關使用技巧,需要的朋友可以參考下2015-05-05