[英]numpy read TSV file as ndarray
我想把TSV讀成numpy數組。 是否有通用的方法從文件中讀取數據並將其轉換為numpy浮點數組。 (缺少值也很少)
該文件看起來像
Variable_1 ..... Variable_100
0.001 ..... 0.25
... ...
1.65 ..... 1.32
我試過了
def converter(x):
return float(x)
data = np.genfromtxt(fname="file.tsv", delimiter="\t", skip_header=0, names=True, converters={"Variable_" + str(n):converter for n in range(1554)})
但是在讀取文件形狀之后是1D數組而不是ndarray of rows = 200 cols = 100
data.shape
(200,)
在不知道file.tsv
文件的樣子的情況下,您可以使用pandas read_csv
方法將.tsv
文件作為數據幀讀入內存,然后訪問數據幀的.values
,它將返回感興趣的數組:
import pandas as pd
import numpy as np
# make a dummy .tsv file, save it to disk
dummy = pd.DataFrame(np.random.randint(0,10,(200,100)))
save_path = "foo.tsv"
dummy.to_csv(save_path, index=False, sep="\t")
df = pd.read_csv(save_path, sep="\t") # read dummy .tsv file into memory
a = df.values # access the numpy array containing values
現在你將擁有一個形狀數組(200,100):
print a.shape
print a
(200, 100)
[[4 1 8 ... 2 7 0]
[0 1 9 ... 7 1 3]
[7 6 6 ... 9 0 2]
...
[1 5 1 ... 1 8 7]
[7 4 6 ... 9 6 0]
[2 0 1 ... 3 2 9]]
您已經提到在原始.tsv
文件中缺少值。 為了適應這種情況,您可以利用pandas的fillna
方法來填充特定列或整個數據幀中的值:
df.col_1.fillna(1, inplace=True) # fill missing values with 1 in a single col
df.fillna(1, inplace=True) # fill all missing values with 1 in entire frame
OP請求只使用 numpy的genfromtxt()
。 在這種情況下,需要以下內容:
data = np.genfromtxt(fname="foo.tsv", delimiter="\t", skip_header=1, filling_values=1) # change filling_values as req'd to fill in missing values
print data.shape # (200,100)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.