【发布时间】:2016-01-16 11:24:48
【问题描述】:
我正在尝试将一个 numpy 矩阵导出为 ASCII 格式,但我想先为其添加一个标头。
我的代码概念是这样的:
- 将 ASCII 文件导入为 np.ndarray,比如矩阵 A
- 获取 A 的标题(前 6 行)。标头包含浮点值和字符
- 取 A 中不是标题的行(从第 6 行到最后一行),给出数组 B
- 在B上应用一些功能
- 另存为ASCII格式:header(A) + B
我尝试了以下方法:
尝试1:
import numpy as np
A = np.genfromtxt('......Input\chm_plot_1.txt', dtype=None, delimiter='\t')
header = A[0:6]
B = A[6:]
mat_out = np.concatenate([A,B])
np.savetxt('........out.txt', mat_out, delimiter='\t')
,但给出错误:
TypeError: 数组 dtype ('|S3973') 和格式不匹配 说明符('%.18e')
尝试2:
import numpy as np
A = np.genfromtxt('......Input\chm_plot_1.txt', dtype=None, delimiter='\t')
header = A[0:6]
headers = np.vstack(header)
head_list = headers.tolist()
head_str = ''.join(str(v) for v in head_list)
B = A[6:]
np.savetxt('\out.txt', B, header = head_str, delimiter='\t')
,给出同样的错误:
TypeError: 数组 dtype ('|S3973') 和格式不匹配 说明符('%.18e')
尝试 3:
import numpy as np
import linecache
A = np.genfromtxt('.............\Input\chm_plot_1.txt', dtype=None, delimiter='\t')
line1 = linecache.getline('.............Input\chm_plot_1.txt', 1)
line2 = linecache.getline('.............Input\chm_plot_1.txt', 2)
line3 = linecache.getline('.............Input\chm_plot_1.txt', 3)
line4 = linecache.getline('.............Input\chm_plot_1.txt', 4)
line5 = linecache.getline('.............Input\chm_plot_1.txt', 5)
line6 = linecache.getline('.............Input\chm_plot_1.txt', 6)
header2 = line1
header2 += line2
header2 += line3
header2 += line4
header2 += line5
header2 += line6
B = A[6:]
np.savetxt('........\out.txt', B , header = header2, delimiter='\t')
,这给了我同样的错误:
TypeError: 数组 dtype ('|S3973') 和格式不匹配 说明符('%.18e')
A 数组的第一行是这样的:
print A[0:8] #从第 6 行开始,行有 100+ 个值,标题是前 6 行
['ncols 371' 'nrows 435' 'xllcorner 520298.0053'
'yllcorner 436731.3065' 'cellsize 1' 'NODATA_value -9999'
'16.52002 15.90161 15.96692 20.32922 20.59827 18.28137 18.83533 17.66 .......
'13.16687 17.09497 7.309204 20.83655 19.05078 17.68591 17.88464 ...... ']
任何帮助将不胜感激!谢谢:)
编辑:我从输入数据 (chm_plot_1.txt) 上传了一个样本。链接如下:http://we.tl/mjgBe4QIRM
Edit2:在回答之后,问题是它在标题行的开头插入了“#”字符,如下图所示。此外,还有一个补充行,即第 7 行,应该删除。
编辑3:我认为错误
ValueError: float() 的文字无效
是由于示例文件与完整文件中的数据格式不同。虽然都是.txt,但排列方式不同,如下图。
【问题讨论】:
-
您能否提供
chm_plot_1.txt样本的链接?看来A.ndim=1,不是“矩阵”。 -
我编辑了主帖。链接在这里:we.tl/mjgBe4QIRM