【问题标题】:Pandas extract in another column the reference name, middle name and surnamePandas 在另一列中提取参考名称、中间名和姓氏
【发布时间】: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


    【解决方案1】:

    您可以使用str.extract 和带有命名捕获组的正则表达式:

    df = pd.DataFrame({'column': ['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......']})
    
    df['column'].str.extract('nameis: (?P<first_last_name>[^,]+?)(?:,|\s*and) (?P<column_2>.*)')
    

    输出:

       first_last_name                        column_2
    0          joe doe              the student is....
    1      patric test             this question is...
    2       franck joe                      he is.....
    3  lucash de brown  the academic achievement......
    

    如果你只想要名字:

    print(df['column'].str.extract('nameis: (?P<first_last_name>[^,]+?)(?:,|\s*and)'))
    

    输出:

       first_last_name
    0          joe doe
    1      patric test
    2       franck joe 
    3  lucash de brown 
    

    【讨论】:

    • 那很好,谢谢....不幸的是,我必须有一个参考:) 类似这样的句子:jon bwownborn in london ... etc etc ...真是一团糟
    • 文本的某些部分不以和或逗号结尾....但是它是完美的,但我认为没有参考是不可能的!再次感谢!
    • 我已经用另一个问题更新了这个问题!你能帮我吗:)
    • @scofx 最好的做法是打开一个新问题以便清楚起见(您可以参考这个问题)。您应该可以使用extractall,但您应该再次提供您期望的确切输出;)
    • 啊抱歉,我认为在同一问题上打开一个新问题是错误的!我尝试使用 extractall 但什么都没有……如果有的话,我尝试开启一个新的讨论!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 2020-12-22
    相关资源
    最近更新 更多