numpy.savetxt保存array时TypeError: must be real number, not str 问题

在用numpy.savetxt() 保存一个字符串array时出现了TypeError: must be real number, not str的报错。在百度搜索了一下,全是乱七八糟的解释,没看到靠谱的。以前在国外用google,任何报错基本很快找到解决办法,百度真是无语了。没办法,用bing搜索了下,在 stack overflow中找到了解决办法:

import numpy as np

# array 为字符换性质
>>> holdon_id 
array(['1000568.3', '1000568.3', '1000568.3', ..., 'AFEU01000007',
       'CP002601', 'AP010906'], dtype='<U12')
# 直接np.savetext 保存
>>> np.savetxt("holdon_id.txt",holdon_id)
Traceback (most recent call last):
  File "/homes/xiaohuizou/anaconda3/lib/python3.7/site-packages/numpy/lib/npyio.py", line 1422, in savetxt
    v = format % tuple(row) + newline
TypeError: must be real number, not str

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/homes/xiaohuizou/anaconda3/lib/python3.7/site-packages/numpy/lib/npyio.py", line 1426, in savetxt
    % (str(X.dtype), format))
TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e')

直接用默认的numpy.savetxt()出现报错,看报错原因TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e')是因为array是‘object’字符型,存储的类型是浮点型'%.18e'所以不匹配。

修改存储类型为字符串解决问题

>>> np.savetxt("holdon_id.txt",holdon_id,fmt="%s")

猜你喜欢

转载自blog.csdn.net/weixin_44022515/article/details/104962204