Skip to main content
 首页 » 编程设计

python之如何颠倒 Pandas 系列中名字和姓氏的顺序

2025年05月04日23lonelyxmas

我有一个 Pandas 系列:

names = pd.Series([ 
'Andre Agassi', 
'Barry Bonds', 
'Christopher Columbus', 
'Daniel Defoe', 
'Emilio Estevez', 
'Fred Flintstone', 
'Greta Garbo', 
'Humbert Humbert', 
'Ivan Ilych']) 

看起来像这样:

0            Andre Agassi 
1             Barry Bonds 
2    Christopher Columbus 
3            Daniel Defoe 
4          Emilio Estevez 
5         Fred Flintstone 
6             Greta Garbo 
7         Humbert Humbert 
8              Ivan Ilych 

我想把它变成这样:

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 

有人建议这样的代码,但没有用...

names.apply(split)[1]+', ' + names.apply(split)[0] 

我检查了以下线程,但它们似乎也不是我想要的:

Pandas DataFrame, how do i split a column into two

pandas: How do I split text in a column into multiple rows?

请您参考如下方法:

是否使用 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