对pandas中Series的map函数详解
Series的map方法可以接受一个函数或含有映射关系的字典型对象。
使用map是一种实现元素级转换以及其他数据清理工作的便捷方式。
(DataFrame中对应的是applymap()函数,当然DataFrame还有apply()函数)
1、字典映射
importpandasaspd frompandasimportSeries,DataFrame data=DataFrame({'food':['bacon','pulledpork','bacon','Pastrami', 'cornedbeef','Bacon','pastrami','honeyham','novalox'], 'ounces':[4,3,12,6,7.5,8,3,5,6]}) meat_to_animal={ 'bacon':'pig', 'pulledpork':'pig', 'pastrami':'cow', 'cornedbeef':'cow', 'honeyham':'pig', 'novalox':'salmon'} data['animal']=data['food'].map(str.lower).map(meat_to_animal) data data['food'].map(lambdax:meat_to_animal[x.lower()])
2、应用函数
In[579]:importpandasaspd In[580]:frompandasimportSeries,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-150 2017-08-161 2017-08-172 2017-08-183 2017-08-194 2017-08-205 2017-08-216 2017-08-227 2017-08-238 2017-08-249 Freq:D,dtype:int64 In[585]:ser.index.map(lambdax:x.day) Out[585]:Int64Index([15,16,17,18,19,20,21,22,23,24],dtype='int64') In[586]:ser.index.map(lambdax:x.weekday) Out[586]:Int64Index([1,2,3,4,5,6,0,1,2,3],dtype='int64') In[587]:ser.map(lambdax:x+10) Out[587]: 2017-08-1510 2017-08-1611 2017-08-1712 2017-08-1813 2017-08-1914 2017-08-2015 2017-08-2116 2017-08-2217 2017-08-2318 2017-08-2419 Freq:D,dtype:int64 In[588]:deff(x): ...:ifx<5: ...:returnTrue ...:else: ...:returnFalse ...: In[589]:ser.map(f) Out[589]: 2017-08-15True 2017-08-16True 2017-08-17True 2017-08-18True 2017-08-19True 2017-08-20False 2017-08-21False 2017-08-22False 2017-08-23False 2017-08-24False Freq:D,dtype:bool
以上这篇对pandas中Series的map函数详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。