【问题标题】:Convert text with no separators in Dataframe in Python?在Python的Dataframe中转换没有分隔符的文本?
【发布时间】:2021-11-11 11:24:50
【问题描述】:

所以我有很多类似这样的日志 txt 文件:

2021-04-01T12:54:38.156Z START RequestId: 123 Version: $LATEST

2021-04-01T12:54:42.356Z END RequestId: 123

2021-04-01T12:54:42.356Z REPORT RequestId: 123  Duration: 4194.14 ms    Billed Duration: 4195 ms    Memory Size: 2048 MB    Max Memory Used: 608 MB 

我需要使用这些数据创建一个 pandas 数据框,该数据框具有以下特征,其中每一行都会显示一个日志:

DateTime, Keyword(start/end), RequestId, Duration, BilledDuration, MemorySize, MaxMemoryUsed

问题是每个文件都有不同的长度,并且有不同类型的日志,所以不是每一行看起来都一样,但有模式。我从未使用过 RegEx,但我认为这是我必须使用的。那么有没有办法把这个字符串转换成数据集呢?

(我的目标是执行内存使用异常检测)

【问题讨论】:

  • 预期的数据框是什么?您需要哪些栏目/信息?
  • DateTime、RequestId、Duration、BilledDuration、MemorySize、MaxMemoryUsed
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: python regex dataframe separator


【解决方案1】:

这里有一个类似的问题: Log file to Pandas Dataframe

您可以将read_csv 与分隔符一起使用:\s*\[

【讨论】:

    【解决方案2】:

    所以显然我仍然不擅长在这个网站上提出正确的问题,但很高兴自己能更好地找到解决方案,所以如果其他人有同样的问题,这就是我所做的:

    import re
    import gzip
    
    counter = 0
    
    for file in file_list:
        # open and read
        file_content = gzip.open(file, 'rb').read().decode("utf-8")
        
        # split file in lines
        splitted_file_content = file_content.splitlines()
        for line in splitted_file_content:
            # look for the report lines
            if re.search('REPORT', line):
                tokens = line.split()
        
                timestamp = tokens[0]
                id = tokens[3]
                billed_duration = tokens[9]
                max_memory_size_used = tokens[18]
                init_duration = tokens[22]
                
                # if you want to pack it in a dataframe
                df.loc[counter] = [timestamp, id, billed_duration,
                                   max_memory_size_used, init_duration]
                counter += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多