首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何颠倒Pandas系列中名字和姓氏的顺序

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

Stack Overflow用户
提问于 2017-02-12 23:32:32
回答 4查看 2.6K关注 0票数 1

我有一个熊猫系列:

代码语言:javascript
复制
names = pd.Series([
'Andre Agassi',
'Barry Bonds',
'Christopher Columbus',
'Daniel Defoe',
'Emilio Estevez',
'Fred Flintstone',
'Greta Garbo',
'Humbert Humbert',
'Ivan Ilych'])

它看起来像这样:

代码语言:javascript
复制
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

我想这样做:

代码语言:javascript
复制
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

有人建议这样的代码,但它不起作用...

代码语言:javascript
复制
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?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-02-12 23:34:09

使用和不使用str.replace

代码语言:javascript
复制
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
票数 4
EN

Stack Overflow用户

发布于 2017-02-13 00:08:08

矢量化的Numpy解决方案:

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2017-02-12 23:32:32

将.map与字符串方法结合使用,如下所示:

代码语言:javascript
复制
names.map(lambda s: s.split()[1] + ', ' + s.split()[0])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42189469

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档