2016-11-27 138 views
1

我有這樣一段代碼工作:如何正確使用numpy.loadtxt來正確分離數據?

import sys 
import numpy as np 
file_path = sys.argv[1] 
training_examples = np.loadtxt(file_path) 
print(training_examples) 

和輸出含空格和換行分隔的1/0序列的文本:

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

我想實現的是一個容易將該數據分離爲矩陣和矢量,而矢量將由如此的最後值構成:

[1. 1. 1.] 

和相應的該矢量的矩陣將是:

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

在此先感謝!

+0

那個文件的內容是什麼? – Abdou

+0

作爲輸出剛剛分隔與每個序列之間的一個空格和每個序列之間的換行符像這樣。 –

+0

'matrix = np.loadtxt(file_path,usecols =(0,1,2)); vector = np.loadtxt(file_path,usecols =(3,))'?這假設你有4列,當然。 – Abdou

回答

0

可以使用usecols參數從loadtxt功能,如果您知道您的文件中的列數:

# Assuming you have 4 columns 
matrix = np.loadtxt(file_path, usecols=(0,1,2)) 
vector = np.loadtxt(file_path, usecols=(3,)) 

但是,如果你不知道的列數,你可以嘗試導入整個文件,然後將數據切片成矩陣和矢量:

# Get the whole file 
data = np.loadtxt(file_path) 

# Get the number of columns in the data 
col_num = data.shape[1] 

# Get the matrix 
matrix = data[:,:(col_num-1)] 

# Get the vector 
vector = data[:,col_num-1] 

我希望這有助於。

+0

很好的回答!非常感謝! –

+0

不客氣。我很高興能夠提供幫助。 – Abdou