【问题标题】:Split *.dat file with fixed width with each width known拆分具有固定宽度的 *.dat 文件,每个宽度已知
【发布时间】:2017-10-19 16:34:37
【问题描述】:

我有一个 *.dat 文件。我知道我要拆分文件的位置。他们是

[5,5,10,10,10,10,10,5,5,10]

但是,pandas read_fwf 采用以下格式的值:

[(0, 5), (5, 10), (10, 20), (20, 30), (30, 40), (40, 50), (50, 60), (60, 65), (65, 70), (70, 80)]

如何将上面的值转换为下面的值?

【问题讨论】:

    标签: python pandas split


    【解决方案1】:

    我会使用 numpy cumsum:

    In [11]: c = np.cumsum([5,5,10,10,10,10,10,5,5,10])
    
    In [12]: s = np.insert(c + 1, 0, 0)
    
    In [13]: list(zip(s, c))
    Out[13]:
    [(0, 5),
     (6, 10),
     (11, 20),
     (21, 30),
     (31, 40),
     (41, 50),
     (51, 60),
     (61, 65),
     (66, 70),
     (71, 80)]
    

    编辑

    s = np.insert(c, 0, 0)
    list(zip(s,c))
    
    [(0, 5),(5, 10),(10, 20), (20, 30), (30, 40), (40, 50), (50, 60), (60, 65), (65, 70), (70, 80)]
    

    【讨论】:

    • 对不起,我的问题错了,我不知道 read_fwf 读取的格式不同。我已经更正了这个问题。
    • @pnkjmndhl 然后只使用 c+1 而不是 c
    【解决方案2】:

    read_fwfcolspecs 参数使用的是半开区间,所以实际上它是期望的

    [(0, 5), (5, 10), (10, 20), …]
    

    如果你累积添加宽度,你会得到你的开始(和结束)索引:

    widths = [5,5,10,10,10,10,10,5,5,10]
    borders = np.cumsum([0] + widths)
    >>> array([ 0,  5, 10, 20, 30, 40, 50, 60, 65, 70, 80])
    

    然后在上下两端使用zip

    list(zip(borders[:-1], borders[1:]))
    >>> [(0, 5), (5, 10), (10, 20), (20, 30), (30, 40), (40, 50), (50, 60), (60, 65), (65, 70), (70, 80)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 2015-06-22
      • 2012-09-26
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多