简体   繁体   English

使用numpy.genfromtxt读取单行CSV

[英]Reading Single Line CSV using numpy.genfromtxt

I am using the following script to read a file from standard input using numpy. 我使用以下脚本使用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). 它应该有形状(,9)。 Does anyone know how to fix it? 有谁知道如何修理它?

Force it into a 2-dimensional array: 强制它成为一个二维数组:

data = np.genfromtxt(sys.stdin, delimiter=",")
if len(data.shape) == 1:
    data = np.array([data])

You could use csv which works in all cases: 您可以使用适用于所有情况的csv:

import csv

reader=csv.reader(sys.stdin)
for row in reader:
    print row

Testing from Bash: 从Bash测试:

$ printf '1,2,3,4' | ./test.py
['1', '2', '3', '4']
$ printf '1,2,3,4\n5,6,7,8' | ./test.py
['1', '2', '3', '4']
['5', '6', '7', '8']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM