【问题标题】:Extract particular string which appears in multiple lines in cell Pandas提取出现在单元格 Pandas 中多行的特定字符串
【发布时间】:2019-05-01 15:25:09
【问题描述】:

我必须提取以“Year”开头并以“\n”结尾的字符串,但对于 Pandas 数据框中单元格中出现的每一行。 另外,我想在单元格末尾删除 \n。

这是数据框:

df

  Column1
  not_important1\nnot_important2\nE012-855 Year-1972\nE012-856 Year-1983\nnot_important3\nE012-857 Year-1977\nnot_important4\nnot_important5\nE012-858 Year-2012\n
  not_important6\nnot_important7\nE013-200 Year-1982\nE013-201 Year-1984\nnot_important8\nE013-202 Year-1987\n
  not_important9\nnot_important10\nE014-652 Year-1988\nE014-653 Year-1980\nnot_important11\nE014-654 Year-1989\n

这就是我想要的:

df

  Column1
  Year-1972\nYear-1983\nYear-1977\nYear-2012
  Year-1982\nYear-1984\nYear-1987
  Year-1988\nYear-1980\nYear-1989

如何做到这一点?

【问题讨论】:

    标签: python regex string pandas extract


    【解决方案1】:

    您可以使用 findall 和这个正则表达式 r'Year.*?\\n' 来捕获子字符串。然后使用''.join 从找到的元素列表中创建一个字符串,然后使用[:-2] 删除最后一个\n

    import re
    df['Column1'] = df['Column1'].apply(lambda x: ''.join(re.findall('Year.*?\\n', x))[:-2])
    

    或者,如果年份的 4 位数字后面总是有\n,你可以这样:

    df['Column1'] = df['Column1'].apply(lambda x: '\n'.join(re.findall('Year-\d\d\d\d', x)))
    

    【讨论】:

    • 它说:NameError: name 're' is not defined。我应该安装还是导入一些东西?
    • 是的,import re 是正则表达式库
    • 谢谢你的解释,看起来合乎逻辑。但是,当我打印(df)时,我只得到索引 0,1,2 - 没有 Column1 的内容。我想知道我做错了什么?
    • 显然它没有找到任何子字符串。 df和你发布的一样吗?或Year 不是大写字母?
    • 我使用了相同的 df。 “年”以大写字母出现。我将此用作 df: df = pd.DataFrame({'Column1': ['not_important1\nnot_important2\nE012-855 Year-1972\nE012-856 Year-1983\nnot_important3\nE012-857 Year-1977\nnot_important4\nnot_important5\ nE012-858 2012 年\n', 'not_important6\nnot_important7\nE013-200 1982 年\nE013-201 1984 年\nnot_important8\nE013-202 1987 年\n', 'not_important9\nnot_important10\nE014-652 年-1988\nE014-653 1980 年\nnot_important11\nE014-654 1989 年\n']})
    猜你喜欢
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多