【发布时间】:2021-12-17 21:39:41
【问题描述】:
将 jupyter 与 pandas 一起使用,我需要在另一列中提取出现在任何冒号之后的引用,例如:
nameis: joe doe, the student is....
nameis: patric test, this question is...
nameis: franck joe and he is.....
nameis: lucash de brown and the academic achievement......
当我必须在 nameis 之后提取时,这个问题对我来说变得很复杂:名字和姓氏,不幸的是随后被任何文本表达出来!在这种情况下,唯一的参考是 nameis: 这是重复出现的,我想把名字和姓氏放在另一个专用列上!
first_last_name,column_2....
joe doe,....
patric test,....
franck joe,......
lucash de brown,.....
并非所有的名字和姓氏都以逗号结尾,但极端情况下,我很乐意只带上这些! 与此同时,我想把这个名字更接近 nameis:
df['column'] = df['column'].str.replace(r'nameis: ', '')
然后是类似的东西,但不幸的是我还在!尤其是在处理中间名时
pat=r'([nameis:]+[a-zA-Z])'
df['first_last_name']=df['column'].str.extract(pat,expand=False)
df
感谢任何帮助我的人!
更新:
字符串捕获的完美操作:
df['column'].str.extract('nameis: (?P<first_last_name>[^,]+?)(?:,|\s*and) (?P<column_2>.*)')
我需要进一步澄清这个问题: 如果在同一行中我有更多 nameis: 我怎样才能提取 seconds..thirds..etc?
示例:
nameis: joe doe, the student is has excellent marks in the subject of professor nameis: adrian muller, ....
nameis: patric test, in the subject of the teacher nameis: adam joe, ...
与:
df['column'].str.extract('nameis: (?P<first_last_name>[^,]+?)(?:,|\s*and) (?P<column_2>.*)')
我只能提取第一个nameis:!我怎样才能将它们都提取出来并将它们放在用逗号分隔的同一列中?
【问题讨论】:
标签: python pandas jupyter-notebook