Python 从文本文件中将数据读入 numpy 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20200353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:51:31  来源:igfitidea点击:

Reading data into numpy array from text file

pythonarraysfile-ionumpygenfromtxt

提问by Nirvan

I have a file with some metadata, and then some actual data consisting of 2 columns with headings. Do I need to separate the two types of data before using genfromtxt in numpy? Or can I somehow split the data maybe? What about placing the file pointer to the end of the line just above the headers, and then trying genfromtxt from there? Thanks The format of the file is shown below:

我有一个包含一些元数据的文件,然后是一些包含带有标题的 2 列的实际数据。在numpy中使用genfromtxt之前是否需要将两种类型的数据分开?或者我可以以某种方式拆分数据吗?将文件指针放在标题上方的行尾,然后从那里尝试 genfromtxt 怎么样?谢谢 文件格式如下图:

 &SRS
<MetaDataAtStart>
multiple=True
Wavelength (Angstrom)=0.97587
mode=assessment
background=True
issid=py11n2g
noisy=True
</MetaDataAtStart>
&END
Two Theta(deg)  Counts(sec^-1)
10.0    41.0
10.1    39.0
10.2    38.0
10.3    38.0
10.4    41.0
10.5    42.0
10.6    38.0
10.7    44.0
10.8    42.0
10.9    39.0
11.0    37.0
11.1    37.0
11.2    45.0
11.3    36.0
11.4    37.0
11.5    37.0
11.6    40.0
11.7    44.0
11.8    45.0
11.9    46.0
12.0    44.0
12.1    40.0
12.2    41.0
12.3    39.0
12.4    41.0

采纳答案by cm2

If you don't want the first nrows, try (if there is no missing data):

如果您不想要第一n行,请尝试(如果没有丢失数据):

data = numpy.loadtxt(yourFileName,skiprows=n)

or (if there are missing data):

或(如果有缺失数据):

data = numpy.genfromtxt(yourFileName,skiprows=n)    

If you then want to parse the header information, you can go back and openthe file parse the header, for example:

如果接下来要解析头信息,可以返回open文件解析头信息,例如:

fh = open(yourFileName,'r')
for i,line in enumerate(fh):
    if i is n: break
    do_other_stuff_to_header(line)
fh.close()