天天看點

pandas 中Series的map函數

Series的map方法可以接受一個函數或含有映射關系的字典型對象。

使用map是一種實作元素級轉換以及其他資料清理工作的便捷方式。

(DataFrame中對應的是applymap()函數,當然DataFrame還有apply()函數)

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':[,,,,,,,,]})
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.應用函數

In []: import pandas as pd

In []: from pandas import Series, DataFrame

In []: index = pd.date_range('2017-08-15', periods=)

In []: ser = Series(list(range()), index=index)

In []: ser
Out[]: 
--    
--    
--    
--    
--    
--    
--    
--    
--    
--    
Freq: D, dtype: int64


In []: ser.index.map(lambda x: x.day)
Out[]: Int64Index([, , , , , , , , , ], dtype='int64')

In []: ser.index.map(lambda x: x.weekday)
Out[]: Int64Index([, , , , , , , , , ], dtype='int64')

In []: ser.map(lambda x: x+)
Out[]: 
--    
--    
--    
--    
--    
--    
--    
--    
--    
--    
Freq: D, dtype: int64

In []: def f(x):
     ...:     if x < :
     ...:         return True
     ...:     else:
     ...:         return False
     ...:     

In []: ser.map(f)
Out[]: 
--     True
--     True
--     True
--     True
--     True
--    False
--    False
--    False
--    False
--    False
Freq: D, dtype: bool