Skip to main content
 首页 » 编程设计

python之将标题添加到 np.matrix

2025年05月04日7sharpest

我正在尝试将一个 numpy 矩阵导出为 ASCII 格式,但我想先为其添加一个标题。

我的代码概念是这样的:

  1. 将 ASCII 文件导入为 np.ndarray,比如矩阵 A
  2. 取 A 的标题(前 6 行)。 header 包含浮点值和字符
  3. 取 A 中不是标题的行(从第 6 行到最后一行),给出数组 B
  4. 在B上应用一些函数
  5. 以这种形式保存为 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: Mismatch between array dtype ('|S3973') and format specifier ('%.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: Mismatch between array dtype ('|S3973') and format specifier ('%.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: Mismatch between array dtype ('|S3973') and format specifier ('%.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: invalid literal for float()

是由于示例文件与完整文件中的数据格式不同。虽然都是.txt,但是排列方式不同,如下图。

请您参考如下方法:

问题是您的 header 与数据的格式不同。

解决该问题的方法:将标题视为普通文件文本,将数据视为数字。

with open('chm_plot_1_sample.txt') as f :  
      header="".join([f.readline() for i in range(6)])[:-1] 
a=np.loadtxt('chm_plot_1_sample.txt',delimiter='\t',skiprows=6) 
a=a/2  # some treatement 
np.savetxt('out.txt',a,delimiter='\t',header=header,comments='')