Question

I have a CSV file containing an n * n distance matrix, and here's a part of view,

enter image description here

I want to use python to edit this CSV, making elements in the diagonal of the matrix replaced by 1, how should I do?

I am using python 2.7.4 under Windows 8.1 x64.

Was it helpful?

Solution

probably best to create a new csv from the old one. (untested)

import csv

newlines = []
with open('csvfilename.csv', 'rb') as csvfile:
  reader = csv.reader(csvfile)
  i=0
  for row in reader:
    newlines.append(row[:i] + [1] + row[i+1:])
    i+=1
with open('newcsvfilename.csv','wb') as csvfile:
  writer = csv.writer(csvfile)
  writer.writerows(newlines)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top