Skip to main content
 首页 » 编程设计

python之如何将一行读入 Pandas——已被返回字符打破

2025年02月15日9bonelee

我正在尝试阅读人口普查 building permits text file有几行如下所示。 有时,描述字段太长会导致行中出现换行符——这会搞砸 pandas。

533 45220 Tallahassee, FL                        1613     810      
999 13980 Blacksburg-Christiansburg-Radford, 
  VA                                              543     455 
108 11100 Amarillo, TX                            740     718  

下面的代码会将文件读入 pandas——但是很多行都被移动了。你如何解析这样的文件文本文件?非常感谢。

testdf = pd.read_table('./csv/bldg_permits/metro/tb3u2016.txt', header='infer',  
                       encoding="ISO-8859-1",skiprows=9,  
                       delimiter = '\s+', skipinitialspace=True, 
                       error_bad_lines=False) 

请您参考如下方法:

作为 read_csv() 的一部分,Pandas 将无法像那样将行拼凑在一起。
我建议做第一遍来清理数据(分隔符也是一个问题),然后第二遍加载到 Pandas 中。

首先,从 URL 中获取数据(我使用的是 requests,但任何 URL 解析器都可以):

import pandas as pd 
import re 
import requests 
url = "https://www.census.gov/construction/bps/txt/tb3v2016.txt" 
r = requests.get(url) 

现在遍历行,将每一行写入lines。

lines = [] 
begin_data = 10 
backup_by = 1 
for i, l in enumerate(r.text.split("\n")[begin_data:]): 
    line = (pd.Series(l).str.replace("(,|,\\*) ", "\\1_") 
                        .str.replace("([A-z\\.]) ([A-z])", "\\1_\\2", n=-1)) 
    if line.str.match("\d")[0]: # normal line 
        lines.append(line[0]) 
    elif len(lines) > 0: # not a normal line, add to previous line 
        lines[i-backup_by] = lines[i-backup_by].strip() + line[0].strip() 
        backup_by += 1 
 
fname = "census_data.txt" 
f = open(fname, "w") 
_ = [print(line, file=f) for line in lines] 

上面 block 的注释:

  • 由于我们要使用 \s+ 分隔符将此表读入 Pandas,因此当空格不是列分隔符的一部分时,请将空格替换为 _。我们正在特别寻找其中两种极端情况:
    • 例如。 亚历山大,洛杉矶 --> 亚历山大,_LA
    • 例如。 明尼阿波利斯 - 圣。保罗-布卢明顿 --> 明尼阿波利斯-圣保罗-布卢明顿
  • 如果一行看起来很有趣(意味着它不是以数字 CSA 代码开头),则假设它实际上是它之前一行的一部分,并将其添加到前一行。
  • 我们需要跟踪代表我们要添加到的上一行的行 的索引。每次我们迭代一行原始数据并且不向 lines 添加新行时,我们的循环计数器 (i) 和lines 中的最后一个元素递增 1。因此我们使用计数器 (backup_by) 计算出要附加到的 lines 的正确索引。

现在将清理后的文本文件读入 Pandas:

colnames = ["CSA", "CBSA", "Name", "Total", "1 Unit", "2 Units",  
            "3 and 4 Units", "5 Units or more"] 
df = pd.read_table(fname, header=None, names=colnames, encoding="ISO-8859-1",  
                   engine='python', delim_whitespace=True, skipfooter=3) 
 
df.head() 
   CSA   CBSA                          Name   Total  1 Unit  2 Units  \ 
0  999  10180                   Abilene,_TX   55593   55193      400    
1  184  10420                     Akron,_OH  226669  226169        0    
2  999  10500                    Albany,_GA   28679   23686        0    
3  440  10540                    Albany,_OR   98763   97926        0    
4  104  10580  Albany-Schenectady-Troy,*_NY  512058  361454    10605    
 
   3 and 4 Units  5 Units or more   
0              0                0   
1            500                0   
2            360             4633   
3              0              837   
4          26585           113414   

此时,如果需要,您可以返回并删除插入到 Name 字段中的空格的 _ 占位符。