获得电子邮件名称的有效方式

时间:2017-02-07 10:14:26

标签: string pandas

我的任务是从fullname中提取电子邮件名称,如下所示(以及我的代码来处理它)

virtual

我的代码返回了:

list_=['peter mary','peter mary david ','pop david','peter pop ronaldo bulma']
sr=pd.Series(list_,range(4))
sr_split=sr.str.split()
first_name=sr_split.str[-1]
other_name=sr_split.str[0:-1]
other_name=other_name.str.join(' ')
other_=other_name.str.split(expand=True)
other_.fillna(' ',inplace=True)
add_name=other_[0].str[0]+other_[1].str[0]+other_[2].str[0]
email_name=pd.concat([first_name,add_name],axis=1)
email_name[2]=email_name[0]+email_name[1]

它符合我的期望。但是,我的代码有两个问题:   1)使用大量拆分和连接   2)不能使用长名称,说:10个字的名称

这是一种让它变得更好的方法吗?

2 个答案:

答案 0 :(得分:1)

如何使用apply和string方法?

In [469]: (sr.str.strip().str.split(' ')
             .apply(lambda x: x[-1] + ''.join([y[0] for y in x[:-1]]))
          )
Out[469]:
0       maryp
1     davidpm
2      davidp
3    bulmappr
dtype: object

答案 1 :(得分:0)

这应该这样做。

list_=['peter mary','peter mary david ','pop david','peter pop ronaldo bulma']


def mk_email_name(x):
    #get names
    names = x.split(' ')
    if len(names) == 1:
        return x
    else:
        #get first name
        fn = names[0]
        #get last_names
        lns = ''.join(map(lambda y:y[:1], names[1:]))
    email = '%s%s' % (fn, lns)
    return email


#apply without pandas
print map(mk_email_name, list_)
# ['peterm', 'petermd', 'popd', 'peterprb']
#apply on pandas df
df = pd.DataFrame(list_, columns=['full_name'])
df['email'] = df.full_name.apply(mk_email_name)