如何颠倒 Pandas 系列中名字和姓氏的顺序 [英] How to reverse the order of first and last name in a Pandas Series

查看:83
本文介绍了如何颠倒 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

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

Someone suggested code like this, but it didn't work...

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

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

I checked the following threads, but they didn't seem to be what I wanted either:

Pandas DataFrame,我如何拆分列一分为二

pandas:我该怎么做将列中的文本拆分为多行?

推荐答案

使用和不使用 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

这篇关于如何颠倒 Pandas 系列中名字和姓氏的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆