2016-11-27 143 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