numpy.savetxt 不断给出 2d 列表错误

numpy.savetxt keeps giving an error with 2d list

所以我一直在编写用户可以在 python 中编辑的二维列表。最后,我需要将列表保存到一个 txt 文件中,然后我得到了错误。这是有问题的代码:

tdlist = [["trash","laundry","dishes"],[1,2,3]]
items = numpy.array(tdlist)

savelist = open("list.txt", "w")
for row in items:
  numpy.savetxt("list.txt", row)
savelist.close()

这是文字墙错误

Traceback (most recent call last):
  File "/home/runner/ToDoList/venv/lib/python3.8/site-packages/numpy/lib/npyio.py", line 1450, in savetxt
    v = format % tuple(row) + newline
TypeError: must be real number, not numpy.str_

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "main.py", line 113, in <module>
    numpy.savetxt("list.txt", row)
  File "<__array_function__ internals>", line 180, in savetxt
  File "/home/runner/ToDoList/venv/lib/python3.8/site-packages/numpy/lib/npyio.py", line 1452, in savetxt
    raise TypeError("Mismatch between array dtype ('%s') and "
TypeError: Mismatch between array dtype ('<U21') and format specifier ('%.18e')

任何帮助都很好,谢谢!

有2个问题。格式问题只是其中之一。您混合了两种将内容写入文本文件的方法。

要么打开文件,写入,然后再次关闭。可以这样做:

tdlist = [["trash", "laundry", "dishes"], [1, 2, 3]]
items = numpy.array(tdlist)

savelist = open("list.txt", "w")
for row in items:
    savelist.write(", ".join(row) + "\n") #needs to be a string
savelist.close()

或者您只使用 numpy.savetxt 并一步将整个项目数组写入文本文件。可以这样做:

tdlist = [["trash", "laundry", "dishes"], [1, 2, 3]]
items = numpy.array(tdlist)
numpy.savetxt("list.txt", items, fmt="%s") #like in the comments already mentioned, you need to specify a format here
In [84]: tdlist = [["trash","laundry","dishes"],[1,2,3]]
    ...: items = numpy.array(tdlist)

请注意,生成的数组是字符串 dtype,甚至是整数:

In [85]: items
Out[85]: 
array([['trash', 'laundry', 'dishes'],
       ['1', '2', '3']], dtype='<U21')

如另一个答案所示,这可以用'%s'(一般字符串格式)来写:

In [86]: np.savetxt('test.txt', items, fmt='%s')
In [87]: cat test.txt
trash laundry dishes
1 2 3

通常这样的数据是用一致类型的列写入的 - 字符串、标签列、数字数据列等:

In [88]: np.savetxt('test.txt', items.T, fmt='%10s %s', delimiter=',')
In [89]: cat test.txt
     trash 1
   laundry 2
    dishes 3

另一种方法是创建一个包含字符串和整数字段的结构化数组:

In [92]: arr = np.array([(i,j) for i,j in zip(*tdlist)], dtype='U10,i')
In [93]: arr
Out[93]: 
array([('trash', 1), ('laundry', 2), ('dishes', 3)],
      dtype=[('f0', '<U10'), ('f1', '<i4')])

可以写成同样的格式:

In [95]: np.savetxt('test.txt', arr, fmt='%10s %d', delimiter=',')
In [96]: cat test.txt
     trash 1
   laundry 2
    dishes 3

savetxt 迭代数组的行,并为每个写入

fmt%tuple(row)

其中 fmt 要么是给定的,要么是更简单的复制品,中间有分隔符。