【问题标题】:Python - Retrieve and replace based on a regexPython - 基于正则表达式检索和替换
【发布时间】:2016-09-26 13:27:36
【问题描述】:

基本上,我已将大约 17000 行的 csv 导入到 pandas 数据框中。有一个日期列已导入为int64,因为数据质量很差。日期的示例包括11969121320011022013 等。所以我想我想做的就是从日期列中检索最后 4 个数字。

所以我使用的代码是:

test_str = str(df['Date'])
flags = re.MULTILINE
p = r'\d{4}$'
result = re.findall(p, test_str, flags)

当我print(result) 时,仅返回 17000 个值中的 60 个。我假设它只评估独特性,但经过长时间的谷歌搜索后,我无法弄清楚。关于如何解决这个问题的任何想法?

【问题讨论】:

    标签: python python-2.7 pandas jupyter-notebook


    【解决方案1】:

    您的方法似乎确实有效(至少对于您提供的示例):

    import pandas as pd
    rng = pd.Series([11969, 12132001, 1022013, 1022013])
    test_str = str(rng)
    flags = re.MULTILINE
    p = r'\d{4}$'
    result = re.findall(p, test_str, flags)
    print(result)
    # ['1969', '2001', '2013', '2013'] # not just unique values
    

    但是这种将pandas 系列转换为字符串的方法是一种奇怪的做法,并且没有利用pandas 的固有结构。

    您可以考虑这样做:

    df['year_int'] = df['Date'] % 10000
    

    如果df['Date']int64,则获取最后四位数字。或者这样:

    df['year_str'] = df['Date'].apply(lambda x: str(x)[-4:])
    

    如果您希望转换为字符串,然后取最后四个字符。

    print(df)
    #        Date  year_int year_str
    # 0     11969      1969     1969
    # 1  12132001      2001     2001
    # 2   1022013      2013     2013
    # 3   1022013      2013     2013
    

    【讨论】:

    • 非常感谢——您的替代方法奏效了。是的,我知道我的正则表达式方式工作的样本/小数据集..它只是我只会返回 17000 行中的 60 行。正如你所说,我一定对熊猫做了一些奇怪的事情。应该多研究一下。
    猜你喜欢
    • 2015-02-16
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2022-06-10
    • 2020-11-11
    • 2011-04-15
    • 1970-01-01
    • 2013-06-14
    相关资源
    最近更新 更多