gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:44:16 26 4
gpt4 key购买 nike

我有一个 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

关于python - 如何颠倒 Pandas 系列中名字和姓氏的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42189469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com