With pandas functions use split
:
df = pd.DataFrame({'a':['random@yahoo.com','random@aol.uk','random@aol.co.uk']})
print (df)
a
0 random@yahoo.com
1 random@aol.uk
2 random@aol.co.uk
print ('@' + df.a.str.split('@').str[1].str.split('.', 1).str[0] )
0 @yahoo
1 @aol
2 @aol
Name: a, dtype: object
But faster is use apply
, if in column are not NaN
values:
df = pd.concat([df]*10000).reset_index(drop=True)
print ('@' + df.a.str.split('@').str[1].str.split('.', 1).str[0] )
print (df.a.apply(lambda x: '@' + x.split('@')[1].split('.')[0]))
In [363]: %timeit ('@' + df.a.str.split('@').str[1].str.split('.', 1).str[0] )
10 loops, best of 3: 79.1 ms per loop
In [364]: %timeit (df.a.apply(lambda x: '@' + x.split('@')[1].split('.')[0]))
10 loops, best of 3: 27.7 ms per loop
Another solution with extract
is faster as split
, it can be used if NaN
values in column:
#not sure with all valid characters in email address
print ( '@' + df.a.str.extract(r"\@([A-Za-z0-9_]+)\.", expand=False))
In [365]: %timeit ( '@' + df.a.str.extract(r"\@([A-Za-z0-9 _]+)\.", expand=False))
10 loops, best of 3: 39.7 ms per loop