【问题标题】:Extracting number from string only when string is present in a dataframe仅当数据框中存在字符串时才从字符串中提取数字
【发布时间】:2021-12-26 21:35:03
【问题描述】:

我正在尝试提取一串数字,这些数字可能会在数据框中进行字符列表。如果没有字符,则无需对单元格进行任何操作。如果有字符,那么我希望这些字符成为外卖。我希望最终结果是同一列但没有字符。见例子。

之前:

ID Price Item Code
1 3.60 a/b 80986
2 4.30 45772
3 0.60 fF/6 9778
4 9.78 48989
5 3.44 \ 545
6 3.44 r. 509

结果:

ID Price Item Code
1 3.60 80986
2 4.30 45772
3 0.60 9778
4 9.78 48989
5 3.44 545
6 3.44 509

【问题讨论】:

    标签: python pandas dataframe data-cleaning


    【解决方案1】:

    Series.str.extract 与正则表达式模式r'(?:^|\s)(\d+) 一起使用:

    • (?:^|\s) 匹配字符串的开头 ('^') 或 ('|') 任何空白字符 ('\s') 而不捕获它 ((?:...))
    • (\d+) 捕获一个或多个数字(贪婪)
    df['Item Code'] = df['Item Code'].str.extract(r'(?:^|\s)(\d+)', expand=False)
    

    请注意,“项目代码”的值在提取后仍然是刺痛的。如果要将它们转换为整数,请使用 Series.astype

    df['Item Code'] = df['Item Code']str.extract(r'(?:\s|^)(\d+)', expand=False).astype(int)
    

    输出

    >>> df
    
       ID  Price Item Code
    0   1   3.60     80986
    1   2   4.30     45772
    2   3   0.60      9778
    3   4   9.78     48989
    4   5   3.44       545
    5   6   3.44       509
    

    【讨论】:

    • 这里需要注意的是,“Item Code”仍然是字符串数据类型。原始发帖人需要将数据类型更改为 INT 或任何下游分析所需的任何一种。
    • @AndrewHamel 好点,谢谢!我会将其添加到答案中。
    • @BobbyPlourde 请改用r'\b(\d+)\b''\b' 表示单词边界。
    • 试试df['Item Code'].str.extract(r'(^|\s+)(\d+)')[1].astype(int)
    • @hpchavaz 感谢您的建议!我会用一个非常相似的答案来更新答案。
    【解决方案2】:

    我认为使用正则表达式是解决方案:

    import re
    
    dt["Item code"] = list(map(lambda x:int(re.findall("\d+", x)[0]), dt["Item code"]))
    

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 2015-05-31
      • 2020-06-03
      • 1970-01-01
      • 2013-02-11
      • 2012-06-15
      • 2021-11-14
      • 2012-06-06
      • 1970-01-01
      相关资源
      最近更新 更多