【问题标题】:Does data frame row and column contains string? If so, return that string in new column数据框行和列是否包含字符串?如果是这样,则在新列中返回该字符串
【发布时间】:2022-01-20 14:57:48
【问题描述】:

我有一个数据框,我想创建一个新列,如果特定列中存在字符串,则将该字符串输出为新列的值加上之后的 3 个空格。

例子-

在本例中,我想搜索字符串“Note”,如果该字符串存在于 note 列中,则输入“Note”,然后在接下来的三个空格中输入。

之前:

id partNumber note
1 a1b33 apples
2 hhgh5667 banana, Note 55, and pineapples
3 hhgh5667 Note 1A, and blueberries
4 09890ii blackberries

之后:

id part_number note Note_number
1 a1b33 apples NA
2 hhgh5667 banana, Note 55, and pineapples Note 55
3 hhgh5667 Note 1A, and blueberries Note 1A
4 09890ii blackberries NA

【问题讨论】:

    标签: python dataframe transformation contains data-processing


    【解决方案1】:

    您可以使用带有 str.extract 的正则表达式来捕获从 Note 到逗号之前的所有内容。

    df['Note_number'] = df.note.str.extract('(Note.*)(?=\,)')
    

    输出

       id partNumber                             note Note_number
    0   1      a1b33                           apples         NaN
    1   2   hhgh5667  banana, Note 55, and pineapples     Note 55
    2   3   hhgh5667         Note 1A, and blueberries     Note 1A
    3   4    09890ii                     blackberries         NaN
    

    【讨论】:

    • 成功了,谢谢! '.*' 和 '(?=\,)' 是什么意思?另外,如果字符串'Note'在note列中出现的次数超过一次,有没有办法提取多个notes?
    • 肯定可以,只需要修改正则表达式,regex101.com/r/zUOzJe/1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2015-05-02
    • 2014-10-30
    • 2023-01-26
    • 2020-04-14
    • 2016-04-15
    相关资源
    最近更新 更多