How to reverse the order of first and last name in a Pandas Series

前端 未结 4 864
太阳男子
太阳男子 2021-01-24 16:42

I have a pandas series:

names = pd.Series([
\'Andre Agassi\',
\'Barry Bonds\',
\'Christopher Columbus\',
\'Daniel Defoe\',
\'Emilio Estevez\',
\'Fred Flintstone\         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-24 17:12

    With and without using str.replace?

    In [451]: names.str.split().apply(lambda x: ', '.join(x[::-1]))
    Out[451]:
    0            Agassi, Andre
    1             Bonds, Barry
    2    Columbus, Christopher
    3            Defoe, Daniel
    4          Estevez, Emilio
    5         Flintstone, Fred
    6             Garbo, Greta
    7         Humbert, Humbert
    8              Ilych, Ivan
    dtype: object
    
    In [452]: names.apply(lambda x: ', '.join(x.split()[::-1]))
    Out[452]:
    0            Agassi, Andre
    1             Bonds, Barry
    2    Columbus, Christopher
    3            Defoe, Daniel
    4          Estevez, Emilio
    5         Flintstone, Fred
    6             Garbo, Greta
    7         Humbert, Humbert
    8              Ilych, Ivan
    dtype: object
    

提交回复
热议问题