无法将索引写入 CSV 文件

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])

上面的代码给出了这样的输出。这些是索引值,我正在尝试使用以下代码将其写入 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")

以上是修改后的代码