Python 类型错误:数组 dtype ('float64') 和格式说明符之间不匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45580330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:08:14  来源:igfitidea点击:

TypeError: Mismatch between array dtype ('float64') and format specifier

pythonarraysnumpy

提问by Test Test

I have a numpy array with dimension 1000*30*150. I am trying to save it as txt file. So far I have tried this

我有一个尺寸为 1000*30*150 的 numpy 数组。我正在尝试将其保存为 txt 文件。到目前为止,我已经尝试过这个

np.savetxt("test.txt", mydata, fmt='%.5f', delimiter=",")
#and 
with open('test.txt', 'w') as f:
    for row in mydata:
        np.savetxt(f, row, delimiter=',', fmt='%.5f')

both method give me error

两种方法都给我错误

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py", line 1254, in savetxt
    fh.write(asbytes(format % tuple(row) + newline))
TypeError: only length-1 arrays can be converted to Python scalars

During handling of the above exception, another exception occurred:

Traceback (most recent call last):


        np.savetxt("test.txt", train, fmt='%.5f', delimiter=",")
      File "/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py", line 1258, in savetxt
        % (str(X.dtype), format))
    TypeError: Mismatch between array dtype ('float64') and format specifier ('%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f')

采纳答案by Yigal

You did not mention what is the purpose of writing the 3-d array to a text file, would you be reading it back in the future, and what format are you looking for, but that is one possibility:

您没有提到将 3-d 数组写入文本文件的目的是什么,您将来会读回它,以及您要寻找什么格式,但这是一种可能性:

import json
print(json.dumps(mydata, default=lambda x: list(x), indent=4))

If you clarify the purpose, people will be able to suggest better suited solutions.

如果您明确目的,人们将能够提出更合适的解决方案。

回答by DJK

The problem is your array is 3 dimensional and can't be saved in a 2 dimensional format. Either reshape it, so that it is 2d:

问题是你的数组是 3 维的,不能以 2 维格式保存。要么重塑它,使其成为二维:

mydata = mydata.reshape(mydata.shape[0],mydata.shape[1]*mydata.shape[2])
np.savetxt('text.txt',mydata,fmt='%.5f',delimiter=',')

or if you do not need to read it as a text file and want to just reload it later in python use:

或者,如果您不需要将其作为文本文件读取并希望稍后在 python 中重新加载它,请使用:

np.save('text.npy',mydata)

回答by hpaulj

Tell us about mydata. In particular its dtypeand shape.

告诉我们关于mydata. 特别是它的dtypeshape

To save with %.5fformat it needs to be a 2d array of numbers.

要以%.5f格式保存,它需要是一个二维数字数组。

savetxtdoes, roughly:

savetxt做,大致:

 for row in arr:
   print(format % tuple(row))

where formatis constructed from your fmtparameter, and the number columns in the array. It looks like your array has a large number of columns, so formatis that '%.5f,%.5f,%.5f,%.5f,%.5f,%...string.

whereformat是根据您的fmt参数和数组中的列数构造的。看起来您的数组有很多列,format'%.5f,%.5f,%.5f,%.5f,%.5f,%...字符串也是如此。

tupleis needed to turn that 1d array rowinto a tuple that works with format%().

tuple需要将该一维数组row转换为与format%().

If the array is higher dimensions, or an array of objects, it would have problems.

如果数组是更高维度的,或者是一个对象数组,就会有问题。



edit - so you say the array is 1000*30*150. So it tries to iterate on the 1000 rows, 30 looks like the size of that format. But it can't apply that to a (30,150)array.

编辑 - 所以你说数组是 1000*30*150。所以它尝试迭代 1000 行, 30 看起来像那个的大小format。但它不能将其应用于(30,150)数组。

With the openand rowiteration, do you get the same error? In Py3 you might need to open with 'wb'. Iterating yourself on the first dimension means eachsavetxtcall works with a 30x150 array. It will iterate on the 30, and try to format rows of 150. The would create a largerformat`, but I think that would run.

openrow迭代,你得到同样的错误吗?在 Py3 中,您可能需要使用'wb'. Iterating yourself on the first dimension means eachsavetxtcall works with a 30x150 array. It will iterate on the 30, and try to format rows of 150. The would create a larger格式打开,但我认为这会运行。

In any case, savetxtis designed for 2d numeric arrays. 3d requires some sort of fudge. Keep in mind also that csvreaders aren't designed for 3d arrays either. They expect rows with consistent columns separated by a simple delimiter.

在任何情况下,savetxt都是为二维数值数组设计的。3d 需要某种软糖。还要记住,csv阅读器也不是为 3d 数组设计的。他们希望行具有由简单分隔符分隔的一致列。



In [260]: arr = np.arange(24).reshape(4,3,2)

It can work with 3d - if allowed to format each subrow with %s:

它可以与 3d 一起使用 - 如果允许使用以下格式格式化每个子行%s

In [261]: np.savetxt('test',arr, fmt='%s')
In [262]: cat test
[0 1] [2 3] [4 5]
[6 7] [8 9] [10 11]
[12 13] [14 15] [16 17]
[18 19] [20 21] [22 23]

3d numeric format - error

3d 数字格式 - 错误

In [263]: np.savetxt('test',arr, fmt='%d')
....
TypeError: Mismatch between array dtype ('int32') and format specifier ('%d %d %d')

Reshape 3d to 2d - save works:

将 3d 重塑为 2d - 保存作品:

In [264]: np.savetxt('test',arr.reshape(-1,2), fmt='%d')
In [265]: cat test
0 1
2 3
4 5
6 7
8 9
...
22 23

With an extra iteration; could add a blank line between blocks

额外的迭代;可以在块之间添加一个空行

In [267]: with open('test','wb') as f:
     ...:     for row in arr:
     ...:         np.savetxt(f, row, '%d',delimiter=', ')
     ...:         
In [268]: cat test
0, 1
2, 3
4, 5
6, 7
...
22, 23

回答by Larry

An alternative to np.savetxt()could be using the csv module:

np.savetxt()的替代方法是使用 csv 模块:

with open("filename.","w+") as my_csv:            # writing the file as my_csv
    csvWriter = csv.writer(my_csv,delimiter=',')  # using the csv module to write the file
    csvWriter.writerows(array_2d)                 # write every row in the matrix

I have encountered a similar TypeError problem with numpy, but the CSV method seems to work fine.

我在 numpy 中遇到了类似的 TypeError 问题,但 CSV 方法似乎工作正常。

回答by humbleHacker

If you're looking to write the data out in formatted rows and columns along the axis at mydata[i,:,:]with the intention of producing something in a more readable table format, see this answer: How to write a multidimensional array to a text file?by @JoeKington. My code adds a loop through the rows and columns of each slice because I couldn't find any other resolution to a TypeError I was getting when implementing the original code:

如果您希望沿轴以格式化的行和列的形式写入数据,以便mydata[i,:,:]以更易读的表格格式生成某些内容,请参阅此答案: 如何将多维数组写入文本文件?来自@JoeKington。我的代码在每个切片的行和列中添加了一个循环,因为在实现原始代码时我找不到任何其他解决 TypeError 的方法:

    with open('test.txt', 'w') as outfile:
        # Add header giving shape of array
        # Any line starting with "#" will be ignored by numpy.loadtxt
        outfile.write('# Array shape: {0}\n'.format(x_train.shape))

        # Iterating through a ndimensional array produces slices along
        # the last axis. This is equivalent to data[i,:,:] in this case
        sliceCount = 0
        for data_slice in x_train:
            # Keep track of the slice numbers
            outfile.write('# New slice %d\n'%sliceCount)

            # Work through each row and column of the 2d numpy array inside the 
            # slice, writing each column number to file in format of your choosing
            for row in data_slice:
                for col in row:
                    itemStr = "%8.6f,"%col
                    outfile.write(itemStr)
                outfile.write("\n")

            sliceCount += 1