Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Single Line CSV using numpy.genfromtxt

Tags:

python

csv

numpy

I am using the following script to read a file from standard input using numpy.

#!/usr/bin/env python
import numpy as np
import sys

data = np.genfromtxt(sys.stdin, delimiter=",")
print data.shape
print data

This works correctly for files that have more than 1 line. But fails to work for this file:

1,2,2,2,2,2,1,1,1

I am running it like this

$ cat input-file.txt | ./test.py

The output is as follows:

(9,)
[ 1.  2.  2.  2.  2.  2.  1.  1.  1.]

It should have shape (,9). Does anyone know how to fix it?

like image 766
Mihir Shinde Avatar asked Jul 24 '14 21:07

Mihir Shinde


1 Answers

Force it into a 2-dimensional array:

data = np.genfromtxt(sys.stdin, delimiter=",")
if len(data.shape) == 1:
    data = np.array([data])
like image 186
Fabricator Avatar answered Sep 28 '22 04:09

Fabricator