使用numpy.savetxt时出现值错误 [英] value error when using numpy.savetxt

查看:539
本文介绍了使用numpy.savetxt时出现值错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将每个numpy数组(A,B和C)另存为文本文件中的一列,并以空格分隔:

I want to save each numpy array (A,B, and C) as column in a text file, delimited by space:

import numpy as np

A = np.array([5,7,8912,44])

B = np.array([5.7,7.45,8912.43,44.99])

C = np.array([15.7,17.45,18912.143,144.99])

np.savetxt('test.txt', (A, B, C), fmt='%s %s %s')

但是我遇到了以下错误:

But I got following error:

ValueError:fmt的%格式数量错误:%s%s%s

ValueError: fmt has wrong number of % formats: %s %s %s

如何解决?

推荐答案

np.savetxt('/tmp/test.txt', np.column_stack((A, B, C)), fmt='%s %s %s')

收益

5.0 5.7 15.7
7.0 7.45 17.45
8912.0 8912.43 18912.143
44.0 44.99 144.99

请注意,fmt='%s'会产生相同的结果.

Note that fmt='%s' produces the same result.

如果您尝试

np.savetxt('/tmp/test.txt', (A, B, C))

您会看到NumPy在单独的一行(即水平)上写入每个1-D数组.由于fmt='%s %s %s'用作每行的格式,因此每行有4个值,就会引发错误.

you'll see that NumPy is writing each 1-D array on a separate line -- i.e. horizontally. Since fmt='%s %s %s' is used as the format for each line, an error was raised since each line had 4 values.

我们可以通过将二维数组np.column_stack((A, B, C))传递给np.savetxt来解决该问题.

We can get around that problem by passing a 2-D array, np.column_stack((A, B, C)) to np.savetxt.

这篇关于使用numpy.savetxt时出现值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆