如何从数据帧的列中提取特定内容并生成新列?

2024-04-23 16:45:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个新的列包含标题(例如:先生,小姐,上尉等)的名字在'姓名'栏下面

train_df['Name'].head()

0                              Braund, Mr. Owen Harris
1    Cumings, Mrs. John Bradley (Florence Briggs Th...
2                               Heikkinen, Miss. Laina
3         Futrelle, Mrs. Jacques Heath (Lily May Peel)
4                             Allen, Mr. William Henry
Name: Name, dtype: object

你能用'pandas.Series.str.extract'来解释上面的任务吗?谢谢你


Tags: name标题dftrain名字johnhead姓名
1条回答
网友
1楼 · 发布于 2024-04-23 16:45:48

您可以使用str.extract

df['Titles'] = df['Name'].str.extract(r', (\w+\.)')

退货:

                                           Name Titles
0                       Braund, Mr. Owen Harris    Mr.
1  Cumings, Mrs. John Bradley (Florence Briggs)   Mrs.
2                        Heikkinen, Miss. Laina  Miss.
3  Futrelle, Mrs. Jacques Heath (Lily May Peel)   Mrs.
4                      Allen, Mr. William Henry    Mr.

您可以看到regex在运行here

相关问题 更多 >