Sometimes you need to do some work on the values in the Pandas series , but without the built-in functions, you can write a function yourself, using the Pandas series 's apply method, You can call this function on each value inside, and then return a new Series
Import= PD. Series ([1, 2, 3, 4, 5])def add_one (x): return x + 1print s.apply ( Add_one)# results:0 6dtype:int64
A chestnut:
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'])
Convert the names in the series from "Firstname Lastname" to "Lastname, Firstname"
You can use the Apply method:
def reverse_name (name): = Name.split (' )'{}, {}'. Format (name_array[1 ],name_array[0]) return new_nameprint(names.apply (reverse_name ))
0 Agassi, Andre1Bonds, Barry.2Columbus, Christopher3Defoe, Daniel.4Estevez, Emilio5Flintstone, Fred.6Garbo, Greta7Humbert, Humbert8Ilych, Ivan.9Joyce, James10Knightley, Keira11Lane, Lois12Myers, Mike.13Nolte, Nick.14Osbourne, Ozzy15Picasso, Pablo16Quirrell, Quirinus17Ray, Rachael.18Sarandon, Susan.19Turner, Tina20Urbina, Ugueth21stVaughn, Vince22Wilson, Woodrow23Yamada, Yoji24Zidane, Zinedinedtype:object
Pandas Array (Pandas Series)-(5) Apply method Custom function