In [22]: def get_first_word(s):
...: return s.split(maxsplit=1)[0]
Чтобы применить функцию только к одному столбцу:
In [24]: df['FirstName'] = df['FullName'].apply(get_first_word)
In [25]: df
Out[25]:
id Sex FullName FirstName
0 1 male Jonh Snow Jonh
1 2 male Robert Boui Robert
2 3 female Sara Konnor Sara
3 4 male Alan Miller Alan
4 5 female Sara Konnor Sara
Также можно воспользоваться готовыми векторизированными Pandas методами:
In [27]: df['FullName'].str.split(n=1).str[0]
Out[27]:
0 Jonh
1 Robert
2 Sara
3 Alan
4 Sara
Name: FullName, dtype: object
In [29]: df['FullName'].str.extract(r'(\w+)', expand=False)
Out[29]:
0 Jonh
1 Robert
2 Sara
3 Alan
4 Sara
Name: FullName, dtype: object
иногда при работе со строковыми данными list comprehension
оказывается быстрее встроенных векторизированных функций.
Пример использования list comprehension
:
In [36]: df['FirstName'] = [n.split(maxsplit=1)[0] for n in df['FullName']]
In [37]: df
Out[37]:
id Sex FullName FirstName
0 1 male Jonh Snow Jonh
1 2 male Robert Boui Robert
2 3 female Sara Konnor Sara
3 4 male Alan Miller Alan
4 5 female Sara Konnor Sara
Замеры времени для DF с 50.000 строк:
In [39]: df = pd.concat([df] * 10**4, ignore_index=True)
In [40]: df.shape
Out[40]: (50000, 3)
In [41]: %timeit df['FullName'].apply(get_first_word)
26.3 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [42]: %timeit df['FullName'].str.split(n=1).str[0]
44.4 ms ± 1.32 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [43]: %timeit df['FullName'].str.extract(r'(\w+)', expand=False)
51.9 ms ± 2.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [44]: %timeit [n.split(maxsplit=1)[0] for n in df['FullName']]
20.6 ms ± 131 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Замеры времени для DF с 500.000 строк:
In [45]: df = pd.concat([df] * 10, ignore_index=True)
In [46]: df.shape
Out[46]: (500000, 3)
In [47]: %timeit df['FullName'].apply(get_first_word)
266 ms ± 921 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [48]: %timeit df['FullName'].str.split(n=1).str[0]
381 ms ± 739 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [49]: %timeit df['FullName'].str.extract(r'(\w+)', expand=False)
512 ms ± 1.53 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [50]: %timeit [n.split(maxsplit=1)[0] for n in df['FullName']]
229 ms ± 11.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)