【问题标题】:pandas read IRS space-delimited txt datapandas 读取 IRS 空格分隔的 txt 数据
【发布时间】:2020-11-14 03:22:07
【问题描述】:

我最近正在处理 IRS 税务文件数据。它是以空格分隔的 txt 数据,如下所示(完整数据为here):

数据的存储方式存在一些模式。但对我来说,数据没有以标准方式格式化,并且不容易读入 Pandas。我想知道如何从上面的 txt 数据中获取如下数据框:

+------------+-------------+--------------------------+-----+-----+-----+------+
| fips_state | fips_county |           name           | c1  | c2  | c3  |  c4  |
+------------+-------------+--------------------------+-----+-----+-----+------+
|         02 |         013 | Aleutians East Borough T | 145 | 280 | 416 | 1002 |
|         02 |         016 | Aleutians West Total Mig | 304 | 535 | 991 | 2185 |
|        ... |         ... | ...                      | ... | ... | ... |  ... |
+------------+-------------+--------------------------+-----+-----+-----+------+

【问题讨论】:

    标签: pandas txt


    【解决方案1】:

    这会将您的数据放入 pandas 内或创建列表之前的两个单独数据框中的列中。解析后合并两个数据框。

    import urllib.request  # the lib that handles the url stuff
    
    target_url='https://raw.githubusercontent.com/shuai-zhou/DataRepo/master/data/C9091aki.txt'
    list_a = []
    list_b = []
    for line in urllib.request.urlopen(target_url):
        if line.decode('utf-8')[0:2] != '  ':
            print(line.decode('utf-8').strip())
            list_a.append(line.decode('utf-8').strip())
        if line.decode('utf-8')[0:5] == '     ':
            print(line.decode('utf-8').strip())
            list_b.append(line.decode('utf-8').strip())
     
    dfa = pd.DataFrame(list_a)
    dfb = pd.DataFrame(list_b)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多