pandas數組(pandas Series)-(5)apply方法自訂函數

來源:互聯網
上載者:User

標籤:方法   bar   print   col   int   fir   nic   lan   pre   

有時候需要對 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)# 結果:0    21    32    43    54    6dtype: 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‘])

把以上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))
0             Agassi, Andre1              Bonds, Barry2     Columbus, Christopher3             Defoe, Daniel4           Estevez, Emilio5          Flintstone, Fred6              Garbo, Greta7          Humbert, Humbert8               Ilych, Ivan9              Joyce, James10         Knightley, Keira11               Lane, Lois12              Myers, Mike13              Nolte, Nick14           Osbourne, Ozzy15           Picasso, Pablo16       Quirrell, Quirinus17             Ray, Rachael18          Sarandon, Susan19             Turner, Tina20           Urbina, Ugueth21            Vaughn, Vince22          Wilson, Woodrow23             Yamada, Yoji24         Zidane, Zinedinedtype: object

 

pandas數組(pandas Series)-(5)apply方法自訂函數

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.