2013-10-27 37 views
1

我有一個整數數據的文件,其中前幾行/列用於名稱。get genfromtxt/loadtxt忽略被忽略的列/行中的數據類型

我希望能夠使用genfromtxtloadtxt,並仍然得到numpy讀取它作爲一個同源陣列。爲此,我使用了選項skiprowsusecols,但它沒有幫助。 在(工作)下面的例子,我期望print(test_array.shape)給(3,3)和print(test.array)

[[0 0 0] 
[0 1 0] 
[1 0 0]] 

有沒有什麼方法可以達到我想要的東西,而不與UNIX修整第一行/列工具在嘗試加載文件之前?請注意,我要加載的實際文件是B-I-G(〜6演出),因此任何解決方案都不應該計算量太大。

from __future__ import print_function 
from StringIO import StringIO #use io.StringIO with py3 
import numpy as np 

example_file = StringIO("FID 1 2 3\n11464_ATCACG 0 0 0\n11465_CGATGT 0 1 0\n11466_TTAGGC 1 0 0") 
test_array = np.loadtxt(example_file, skiprows=1, usecols=(1,), dtype=int) 

print(test_array.shape) #(3,) 
print(test_array) #[0 0 1] 

回答

1

可以在np.genfromtxt使用usecolsskip_header標誌。然後它可以正常工作:

test_array = np.genfromtxt(example_file, skip_header=1, usecols=(1,2,3)) 
>>> print(test_array) 
[[ 0. 0. 0.] 
[ 0. 1. 0.] 
[ 1. 0. 0.]]