I am trying to write the index values in a csv file but I am getting error.
code used for writing into csv
test = df.sort_values(['sqdist'], ascending=[False])
for i in range(len(test)):
print(test.index[i])
The above code gives me output like this. These are the index values and I am trying to write this in a CSV using the below code.
7163
4332
3319
1213
1212
6984
4331
4362
6393
515
Trying to write the above output into a csv file exactly like how i see above.
with open ("scores.txt",'w') as f1:
writer = csv.writer(f1, lineterminator='\n', )
for i in range(len(test)):
writer.writerow(test.index[i])
print("Saved the scores in the text file score.txt")
Error:
---------------------------------------------------------------------------
Error Traceback (most recent call last)
<ipython-input-26-748f3db1997a> in <module>()
94 writer = csv.writer(f1, lineterminator='\n', )
95 for i in range(len(test)):
---> 96 writer.writerow(test.index[i])
97 print("Saved the scores in the text file ranking.txt")
98
Error: iterable expected, not numpy.int64
CodePudding user response:
with open ("/scores.txt",'w') as f1:
writer = csv.writer(f1, delimiter='\t', lineterminator='\n', )
for i in test:
writer.writerow([i])
print("Saved the scores in the text file scores.txt")
Above is the modified code
CodePudding user response:
The argument to writerow()
must be a sequence, since each element of the sequence will be a separate field in the CSV.
If you're just writing a single field, wrap it in a list or tuple.
writer.writerow([i])
Although if you just have one field, there's not much point in using the csv
module in the first place.