pandas数组(pandas Series)-apply方法自定义函数

别裁伪体亲风雅,转益多师是汝师。这篇文章主要讲述pandas数组(pandas Series)-apply方法自定义函数相关的知识,希望能为你提供帮助。
有时候需要对  pandas Series  里的值进行一些操作,但是没有内置函数,这时候可以自己写一个函数,使用  pandas Series  的  apply  方法,可以对里面的每个值都调用这个函数,然后返回一个新的  Series 

import pandas as pds = pd.Series([1, 2, 3, 4, 5]) def add_one(x): return x + 1print s.apply(add_one)# 结果: 02 13 24 35 46 dtype: int64

 
一个栗子:
names = pd.Series([ ‘Andre Agassi‘, ‘Barry Bonds‘, ‘Christopher Columbus‘, ‘Daniel Defoe‘, ‘Emilio Estevez‘, ‘Fred Flintstone‘, ‘Greta Garbo‘, ‘Humbert Humbert‘, ‘Ivan Ilych‘, ‘James Joyce‘, ‘Keira Knightley‘, ‘Lois Lane‘, ‘Mike Myers‘, ‘Nick Nolte‘, ‘Ozzy Osbourne‘, ‘Pablo Picasso‘, ‘Quirinus Quirrell‘, ‘Rachael Ray‘, ‘Susan Sarandon‘, ‘Tina Turner‘, ‘Ugueth Urbina‘, ‘Vince Vaughn‘, ‘Woodrow Wilson‘, ‘Yoji Yamada‘, ‘Zinedine Zidane‘ ])

【pandas数组(pandas Series)-apply方法自定义函数】把以上Series里的名字从"Firstname Lastname" 转换成 "Lastname, FirstName"
可以使用apply方法:
def reverse_name(name): name_array = name.split(‘ ‘)new_name = ‘{}, {}‘.format(name_array[1],name_array[0]) return new_nameprint(names.apply(reverse_name))

0Agassi, Andre 1Bonds, Barry 2Columbus, Christopher 3Defoe, Daniel 4Estevez, Emilio 5Flintstone, Fred 6Garbo, Greta 7Humbert, Humbert 8Ilych, Ivan 9Joyce, James 10Knightley, Keira 11Lane, Lois 12Myers, Mike 13Nolte, Nick 14Osbourne, Ozzy 15Picasso, Pablo 16Quirrell, Quirinus 17Ray, Rachael 18Sarandon, Susan 19Turner, Tina 20Urbina, Ugueth 21Vaughn, Vince 22Wilson, Woodrow 23Yamada, Yoji 24Zidane, Zinedine dtype: object

 

    推荐阅读