![](/img/trans.png)
[英]Reading CSV file with numpy.genfromtxt() - delimiter as a part of a row name
[英]Reading Single Line CSV using numpy.genfromtxt
我使用以下腳本使用numpy從標准輸入中讀取文件。
#!/usr/bin/env python
import numpy as np
import sys
data = np.genfromtxt(sys.stdin, delimiter=",")
print data.shape
print data
這適用於具有多行的文件。 但無法為此文件工作:
1,2,2,2,2,2,1,1,1
我這樣運行它
$ cat input-file.txt | ./test.py
輸出如下:
(9,)
[ 1. 2. 2. 2. 2. 2. 1. 1. 1.]
它應該有形狀(,9)。 有誰知道如何修理它?
強制它成為一個二維數組:
data = np.genfromtxt(sys.stdin, delimiter=",")
if len(data.shape) == 1:
data = np.array([data])
您可以使用適用於所有情況的csv:
import csv
reader=csv.reader(sys.stdin)
for row in reader:
print row
從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.