需要使用Python2.7将.txt文件排序到数据帧中

2024-05-23 18:15:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我对使用编程语言还很陌生,我在解决这个问题上遇到了困难。我是一名记者,正在尝试使用Python重新组织县调度办公室提供的911数据,这些数据以.txt文件的形式提供。
以下是当前格式的通话方式:

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中使用左右函数和其他一些步骤重新组织它,得到如下结果:

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

每个事件底部有9-10行调度时间的数据是冗余的,这是不必要的。你知道吗

我遇到的问题是如何告诉Pandas把名字放在冒号的左边,并将其识别为一个列标题,同时把信息放在列的右边,并将其分配给相应的列,然后重复到封闭的列之后,跳过多余的信息。你知道吗

在.txt文件中,一年的数据量约为600万行,一旦重新组织,数据量将减少到501000多行。在excel中手工操作每个文件大约需要4个小时,我想对10年内的调用次数进行分析。你知道吗

我需要学习用Python来实现这一点,使之成为一个实际的项目。 谢谢大家。第一次在这里发布问题。你知道吗


Tags: 文件数据txtnumbertypelocation调度person
1条回答
网友
1楼 · 发布于 2024-05-23 18:15:40

你对数据布局的描述模棱两可,所以我做了一些假设。我猜.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文件转换为一个数据帧并打印出来。你知道吗

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)

这里我们假设列之间至少有两个空格,并且数据中不会有任何双空格。如果列之间的空间大于此值,可以更改regex以查找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

但你可以做的远不止打印出来,因为它是一个数据帧。你知道吗

相关问题 更多 >