0

For example, I have csv file contains ten columns. Is it possible to read it into two variables -- first one will contain 1-2..9 columns and second will contain last column by means of loadtxt or genfromtxt?

Kenenbek Arzymatov
  • 8,439
  • 19
  • 58
  • 109
  • 2
    You could read it into one big array `a` (very easy with `loadtxt`) and then look at two different slices, `a1 = a[:, :-1]` and `a2 = a[:, [-1]]` – jez Apr 11 '17 at 20:56
  • Have you looked into the import csv module? This answer should get the job done: http://stackoverflow.com/questions/24662571/python-import-csv-to-list – Z. Bagley Apr 11 '17 at 20:56
  • @Z.Bagley yes, but this is a `numpy` question, which already has functions to load csvs directly into `numpy` data structures. Using `csv` in this case is an unnecessary middleman. – juanpa.arrivillaga Apr 11 '17 at 20:59

3 Answers3

3
a = numpy.loadtxt('blah.csv', delimiter=',')    # loads it all into one big array
a1 = a[:, :-1]    # a view of all but the last column
a2 = a[:, [-1]]   # a copy of just the last column

(Or, if you want your last-column variable to be one-dimensional, you can get a view of it using a[:,-1] instead of saying a[:, [-1]].)

jez
  • 14,867
  • 5
  • 37
  • 64
0
numpy.loadtext('filename.csv', usecols(0,1,2,...,n-2))
numpy.loadtext('filename.csv', usecols = n-1)

Note: The index of your columns should be decremented by 1, as numpy would start at 0 when loading.

From the Documentation https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html:

usecols : int or sequence, optional Which columns to read, with 0 being the first. For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th columns. The default, None, >results in all columns being read."

boethius
  • 418
  • 6
  • 15
0

In case you don't really need numpy. You could use pandas (http://pandas.pydata.org/), or csv (https://docs.python.org/2/library/csv.html) libraries.

  • Although this doesn't answer the question, I can second the recommendation that the OP look into pandas—it sounds like they're about to do something for which pandas is very well-suited. – jez Apr 11 '17 at 21:04