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

前端 未结 4 863
太阳男子
太阳男子 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 16:57

    Vectorized Numpy solution:

    In [276]: arr = names.str.split(expand=True).values[:, ::-1]
    
    In [277]: names.values[:] = np.sum(np.insert(arr, 1, ', ', axis=1), axis=1)
    
    In [278]: names
    Out[278]:
    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
    

提交回复
热议问题