mannaroth
mannaroth

Reputation: 1543

NumPy loadtxt load every other column

I have an ASCII file containing a large number of columns and I'd like to load only every other column (skip first, load second, skip third, load fourth, etc.).

Is there a way to do that with numpy.loadtxt, except for using usecols=(2,4,6,...)?

Upvotes: 0

Views: 692

Answers (1)

user2357112
user2357112

Reputation: 280207

You don't need to write out a giant tuple of even or odd numbers; you can have Python do that for you:

data = numpy.loadtxt(..., usecols=xrange(1, numcols, 2))

I've passed an xrange here, since the usecols parameter can be any sequence type, but even if you needed a tuple, you could just call tuple:

data = numpy.loadtxt(..., usecols=tuple(xrange(1, numcols, 2)))

Upvotes: 3

Related Questions