-1

我是使用编程语言的新手,我在解决这个特定问题时遇到了麻烦。我是一名记者,试图使用 Python 重组来自县调度办公室的 .txt 文件中提供的 911 数据。
这是一个呼叫以当前格式出现的方式:

Incident Number: PD160010001
Incident Type: SUSPICIOUS PERSON(S)          
EMS Blk: 186605  Fire Blk: 65005   Police Blk: 22145 
Location: Location name,22                  
          at XXXX Name RD ,22                
       Entered: 01/01/16  00:00
    Dispatched: 01/01/16  00:00
       Enroute: 01/01/16  00:00
      On Scene: 01/01/16  00:00
     Transport:   /  /      :  
Trans Complete:   /  /      :  
        Closed: 01/01/16  00:04

01/01/16  00:00  OUTSRV
01/01/16  00:00  DISPOS  22H4  
01/01/16  00:00  PREMPT  22H4  
01/01/16  00:00  DISPOS  2212  
01/01/16  00:00  EXCH    22H4  
01/01/16  00:01  ADDER   22H4  
01/01/16  00:04  CLEAR   2212  
01/01/16  00:04  CLEAR   22H4  
01/01/16  00:04  CLOSE   22H4

我能够在 Excel 中使用 Right 和 Left 函数和其他一些步骤来重新组织它,以获得如下结果:

Incident Number Incident Type         EMS Blk:    Closed
PD160010001     SUSPICIOUS PERSON(S)  186605  ... 01/01/16  00:04        

每个事件底部有调度时间的 9-10 行数据是多余的,没有必要。

我遇到的麻烦是找到一种方法告诉 Pandas 将名称放在冒号左侧并将其识别为一个列标题,同时将信息放在列的右侧并将其分配给相应的列,然后重复直到关闭列之后并跳过冗余信息。

.txt 文件中一年的数据价值约为 600 万行,并且在重新组织后减少到略高于 501,000 行。手动在 excel 中完成每个文件大约需要 4 个小时,我想对 10 年的调用时间进行分析。

我需要学习在 Python 中执行此操作,以使其成为一个实用的项目。谢谢大家。第一次在这里发问题。

4

1 回答 1

0

您对数据布局的描述模棱两可,所以我在做一些假设。我猜 .txt 文件看起来有点像这样:

          header2  header3  header4  header5  header6  header7  header8  header9
index 1   data12   data13   data14   data15   data16   data17   data18   data19
index 2   data22   data23   data24   data25   data26   data27   data28   data29

其中每个索引对应于某个调用,每列对应于调用的某些属性,标题表示列中的数据代表什么。

以下程序将上述 .txt 文件转换为 pandas 数据框并打印出来。

import pandas as pd
import re

with open(filename) as file:
    rows = file.readlines()
columns = rows[0] # get the top row
columns = re.sub(' {2,}', ',', columns) # substitute whitespaces of more than
                                     # two spaces with commas
columns = columns.strip().split(',') # turn the row into a list
content = rows[1:] # All but the first row
content = [re.sub(' {2,}',',',row).strip() for row in content] # again, whitespace to commas
content = [row.split(',') for row in content] # turn rows into lists
index = [row[0] for row in content] # take the first element of each row as the index
content = [row[1:] for row in content] # remove index from content
df = pd.DataFrame(data=content, index=index, columns=columns) # Combine into a dataframe
print(df)

在这里,我们假设列之间至少有两个空格,并且您的数据中不会有任何双空格。如果列之间的空间比列之间的空间多,则可以更改正则表达式以查找 3 个或更多连续空格。

输出是

        header2 header3 header4 header5 header6 header7 header8 header9
index 1  data12  data13  data14  data15  data16  data17  data18  data19
index 2  data22  data23  data24  data25  data26  data27  data28  data29

但既然它是一个数据框,你可以做的不仅仅是打印出来。

于 2017-11-17T00:11:18.063 回答