【问题标题】:Why re.findall only return first ten rows为什么 re.findall 只返回前十行
【发布时间】:2020-08-26 15:28:37
【问题描述】:

我尝试使用 59k 行中的正则表达式来匹配字符串。当然,我希望得到与结果相同的 59k 行。但是结果只返回前 10 行。

我觉得这是一个愚蠢的问题,但仍然想知道这里有什么问题。

y = str(data[['geometry']])
z = re.findall("(?<=\()\d.*(?=\))", y)

【问题讨论】:

  • 因为 pandas 数据框列的字符串表示会截断数据。
  • 您可以使用专为此设计的内置series.str.findall method

标签: python python-3.x regex pandas jupyter-notebook


【解决方案1】:

您可能需要str.findalltolist()

例如:

data['geometry'].str.findall("(?<=\()\d.*(?=\))").tolist()

演示:

df = pd.DataFrame({'geometry': ['aa (123) bb (1.5)', 'aa (123) bb (1.5)', 'aa (123) bb (1.5)', 'aa (123) bb (1.5)']})
print(df['geometry'].str.findall("(?<=\()(\d.*?)(?=\))").tolist())

输出:

[['123', '1.5'], ['123', '1.5'], ['123', '1.5'], ['123', '1.5']]

【讨论】:

    【解决方案2】:

    使用str.extract:

    data['geometry'].str.extract(r'\((\d.*)\)', expand=False).tolist()
    

    regex demo

    解释

                             EXPLANATION
    --------------------------------------------------------------------------------
      \(                       '('
    --------------------------------------------------------------------------------
      (                        group and capture to \1:
    --------------------------------------------------------------------------------
        \d                       digits (0-9)
    --------------------------------------------------------------------------------
        .*                       any character except \n (0 or more times
                                 (matching the most amount possible))
    --------------------------------------------------------------------------------
      )                        end of \1
    --------------------------------------------------------------------------------
      \)                       ')'
    

    【讨论】:

      【解决方案3】:

      我使用循环得到了自己的解决方案:

      location = []
      for l in data['geometry']:
          latlon = re.findall("(?<=\()\d.*(?=\))", l)
          location.append(z)
      
      
      df_latlon = DataFrame(location)
      df_latlon
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-05
        • 1970-01-01
        相关资源
        最近更新 更多