Pandas Array (Pandas Series)-(5) Apply method Custom function

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.