保留全名,在 pandas 列中获取名字的首字母(如果有的话,还有中间名) [英] Preserve full surname, get initials of first name (and middle name if some) in pandas column

查看:104
本文介绍了保留全名,在 pandas 列中获取名字的首字母(如果有的话,还有中间名)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Pandas 数据框,其中有一列表示几个网球运动员的姓氏和名字,如下所示:

I have a pandas Dataframe with a column expressing the surname and name of several tennis players like the following one:

   | Player              | 
   |---------------------|
0  | 'Roddick Andy'      |
1  | 'Federer Roger'     |
2  | 'Tsonga Jo Wilfred  |

如果有的话,我想保留全名并获取姓名和中间名的首字母.因此,pandas 列应如下所示:

I want to keep the full surname and get the initial of the name and middle name if there is. So the pandas column should look like the following one:

   | Player            | 
   |-------------------|
0  | 'Roddick A.'      |
1  | 'Federer R.'      |
2  | 'Tsonga J.W.'     | N.B. J.W. with no space

有人有建议吗?谢谢!

推荐答案

以下是使用 str.extractallgroupby 的方法:

Here's an approach with str.extractall and groupby:

(df.Player
  .str.extractall('(?P<Surname>\w*)\s(?P<Name>\w*)')
  .groupby(level=0)
  .agg({'Surname':'first',
        'Name': lambda x: x.str[0].add('.').sum()
        })
  .agg(' '.join, axis=1)
)

输出:

0     Roddick A.
1     Federer R.
2    Tsonga J.W.
dtype: object

这篇关于保留全名,在 pandas 列中获取名字的首字母(如果有的话,还有中间名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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