gpt4 book ai didi

Python:如何将 int32 写入 csv 文件?

转载 作者:行者123 更新时间:2023-12-01 05:26:59 25 4
gpt4 key购买 nike

我正在尝试使用 csv.writer 对象将 numpy 数组写入 csv 文件。但写完后我得到了我的 numpy 数组的字符串表示!

with open('res.csv', 'w') as csvfile:
csv_writer = csv.writer(csvfile, delimiter=',', lineterminator='\n')
csv_writer.writerow(['Id', 'Solution'])
csv_writer.writerows(y_pred)

res.csv 的一些输出行是:

Id,Solution
1,0
2,1
3,1
4,0
...

但是它们存储为字符串!

实际上我正在尝试通过Kaggel site学习python但在我提交 res.csv 文件后,排行榜显示我的条目采用 string 格式,并且必须采用 int32 格式。

如何修复它?

最佳答案

试试这个:

numpy.savetxt('res.csv', y_pred, fmt='%d', delimiter=',', newline='\n', header='Id, Solution', footer='', comments='# ')

此输出:

$ cat res.csv
# Id, Solution
1,0
2,1
3,1
4,0

您可以使用fmt关键字设置的格式字符串来更改格式。请参阅numpy.savetxt() 。您也可以更改评论符号。

关于Python:如何将 int32 写入 csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21143062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com