无法将numpy二维数组保存到文件中 [英] Can't save a numpy 2-d array into a file

查看:292
本文介绍了无法将numpy二维数组保存到文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下2维numpy矩阵,它是两个矩阵的串联:

I have the following 2-d numpy matrix, which was a concatenation of two matrices:

     >>> mnist1_train_final_data=np.hstack((y_train_mnist_ni,features_train_mnist1))
     >>> type(mnist1_train_final_data)
     <type 'numpy.ndarray'>
     >>> mnist1_train_final_data.dtype
     dtype('S32')
     >>> mnist1_train_final_data.shape
      (1149, 129)

如您所见,它是一个二维numpy数组.但是,当我尝试使用以下命令保存它时:

As you can see, it is a 2-d numpy array. However, when I try to save it using the following command:

>>> np.savetxt('test.txt', mnist1_train_final_data, delimiter=',', fmt='%5.2f') 

它显示了以下错误:

Traceback (most recent call last):   File "<stdin>", line 1, in
<module>   File "/usr/lib/python2.7/site-packages/numpy/lib/npyio.py",
line 1162, in savetxt
    % (str(X.dtype), format)) TypeError: Mismatch between array dtype ('|S32') and format specifier
('%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f,%5.2f')

如何保存二维numpy矩阵?

How can I save a 2-d numpy matrix in my case?

推荐答案

S32是字符串类型.您指定的格式适用于浮点类型.要保存字符串类型,请使用savetxt传递"%s"格式化程序.请注意,默认格式对于字符串类型无效,因此您必须传递有效的字符串格式器,例如"%s"

S32 is a string type. The format you're specifying is for float types. To save a string type, with savetxt you need to pass the "%s" formatter. Note that the default format is not valid for string types so you must pass a valid string formatter such as "%s"

np.savetxt('test.txt', mnist1_train_final_data, delimiter=',', fmt='%s')

这篇关于无法将numpy二维数组保存到文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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