2017-04-17 19 views
1

我已經建造使用R和輸出它看起來像這樣的文件特徵向量矩陣:如何從一個矩陣式的數據集刪除第一行和第一列

"","values","vectors.1","vectors.2","vectors.3","vectors.4","vectors.5","vectors.6" 
"1",5,0.49,0.40,-0.577,0,0.28,-0.4 
"2",4,0,-0.40,0.283,0.5,0.577,-0.4 
"3",3,-0.5,0.4,0.28,-0.5,0.28,-0. 
"4",3,0.5,-0.4,0.28,-0.5,-0.28,-0.4 
"5",1,-0.5,-0.4,-0.57,0,-0.28,-0.4 
"6",0,0,0.4,0.28,0.5,-0.57,-0.4 

我想刪除的第一行和第一列提取矩陣本身並將其存儲在另一個文件中(我相信您不能在打開的同一文件中進行讀寫操作)。因此,我嘗試了以下方法,但我不知道如何繼續。感謝任何幫助。

with open('./test.csv', 'r') as csvfile, open('./output.csv', 'w') as outputfile: 
    reader = csv.reader(csvfile, delimiter='\t') 
    for line in reader: 
     print line[0][3:] 

回答

1

您可以在不使用csv模塊的情況下讀取和寫入CSV文件。您可以通過所有的線重複,除了第一行,然後寫每一行的所有行,除了第一行,輸出文件,像這樣:

with open('./test.csv', 'r') as input_file, open('./output.csv', 'w') as output_file: 
    for index, line in enumerate(input_file): 
     if index != 0: 
      output_file.write(",".join(line.split(",")[1:])) 

讓我知道如果這個作品爲你。

1

您可以使用類似:

new_file = open("new.csv", "a") # opens/creates new.csv to append the results 
with open('old.csv') as f: # opens csv file for reading 
    f.next() # skips the first line 
    for line in f: # loop all lines in old.csv 
     new_file.write(",".join(line.split(",")[1:])) # append to new.csv 

new_file.close() # closes new.csv