[英]Unable to write index into CSV file
我正在尝试在 csv 文件中写入索引值,但出现错误。
用于写入 csv 的代码
test = df.sort_values(['sqdist'], ascending=[False])
for i in range(len(test)):
print(test.index[i])
上面的代码给了我这样的 output 。 这些是索引值,我正在尝试使用以下代码将其写入 CSV 中。
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
writerow()
的参数必须是一个序列,因为序列的每个元素都是 CSV 中的一个单独字段。
如果您只是编写一个字段,请将其包装在列表或元组中。
writer.writerow([i])
尽管如果您只有一个字段,那么首先使用csv
模块没有多大意义。
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")
以上是修改后的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.