Skip a specified number of columns with numpy.genfromtxt()

前端 未结 2 1886
没有蜡笔的小新
没有蜡笔的小新 2021-02-06 10:16

I have a large table (numbers in text format) that I would like to load with numpy.genfromtxt(). I would like to ignore the first n columns, say 5. I do no

相关标签:
2条回答
  • 2021-02-06 10:48

    In newer versions of Numpy, np.genfromtxt can take an iterable argument, so you can wrap the file you're reading in a generator that generates lines, skipping the first N columns. If your numbers are space-separated, that's something like

    np.genfromtxt(" ".join(ln.split()[N:]) for ln in f)
    
    0 讨论(0)
  • 2021-02-06 10:55

    For older versions of numpy, peeking at the first line to discover the number of columns is not that hard:

    import numpy as np
    with open(fname, 'r') as f:
        num_cols = len(f.readline().split())
        f.seek(0)
        data = np.genfromtxt(f, usecols = range(5,num_cols))
    print(data)
    
    0 讨论(0)
提交回复
热议问题