NumPy genfromext TypeError:数据类型不理解错误



我想在这个文件中读取(test.txt)

01.06.2015;00:00:00;0.000;0;-9.999;0;8;0.00;18951;(SPECTRUM)ZERO(/SPECTRUM)
01.06.2015;00:01:00;0.000;0;-9.999;0;8;0.00;18954;(SPECTRUM)ZERO(/SPECTRUM)
01.06.2015;00:02:00;0.000;0;-9.999;0;8;0.00;18960;(SPECTRUM)ZERO(/SPECTRUM)
01.06.2015;09:23:00;0.327;61;25.831;39;29;0.18;19006;01.06.2015;09:23:00;0.327;61;25.831;39;29;0.18;19006;(SPECTRUM);;;;;;;;;;;;;;1;1;;;1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1;;;;;;;;;;;;(/SPECTRUM)
01.06.2015;09:24:00;0.000;0;-9.999;0;29;0.00;19010;(SPECTRUM)ZERO(/SPECTRUM)

…我尝试使用numpy函数genfromtxt()(见下面的代码摘录)。

import numpy as np
col_names = ["date", "time", "rain_intensity", "weather_code_1", "radar_ref", "weather_code_2", "val6", "rain_accum", "val8", "val9"]
types = ["object", "object", "float", "uint8", "float", "uint8", "uint8", "float", "uint8","|S10"]
# Read in the file with np.genfromtxt
mydata = np.genfromtxt("test.txt", delimiter=";", names=col_names, dtype=types)

现在,当我执行代码时,我得到以下错误——>

raise ValueError(errmsg)ValueError: Some errors were detected !
    Line #4 (got 79 columns instead of 10)

现在我认为困难来自于最后一栏(val9)与许多;;;;;;;
很明显,最后一列;的等距和符号是一样的!

我如何在文件中读取而没有错误,也许有可能跳过最后一列,或者仅在最后一列中替换; ?

来自numpy文档

invalid_raise: bool,可选
方法中检测到不一致时将引发异常列数。如果为False,则发出警告并取消违规操作

mydata = np.genfromtxt("test.txt", delimiter=";", names=col_names, dtype=types, invalid_raise = False)

请注意,你的代码中有错误,我已经纠正了(分隔符拼写错误,types列表在函数调用中称为dtypes)

编辑:从你的评论,我看到我有点误解。您的意思是要跳过最后一个,而不是最后一个

请看下面的代码。我定义了一个生成器,它只返回每行的前十个元素。这将允许genfromtxt()无错误地完成,现在您将从所有行中获得列#3。

请注意,您仍然会丢失一些数据,如果您仔细观察,您会发现问题行实际上是两行与垃圾连接在一起,其他行具有ZERO。所以你仍然会失去第二条线。您可以修改生成器来解析每行并以不同的方式处理,但我将把它作为一个有趣的练习:)

import numpy as np
def filegen(filename):
    with open(filename, 'r') as infile:
        for line in infile:
            yield ';'.join(line.split(';')[:10])
col_names = ["date", "time", "rain_intensity", "weather_code_1", "radar_ref", "weather_code_2", "val6", "rain_accum", "val8", "val9"]
dtypes = ["object", "object", "float", "uint8", "float", "uint8", "uint8", "float", "uint8","|S10"]
# Read in the file with np.genfromtxt
mydata = np.genfromtxt(filegen('temp.txt'), delimiter=";", names=col_names, dtype = dtypes)

[('01.06.2015', '00:00:00', 0.0, 0, -9.999, 0, 8, 0.0, 7, '(SPECTRUM)')
 ('01.06.2015', '00:01:00', 0.0, 0, -9.999, 0, 8, 0.0, 10, '(SPECTRUM)')
 ('01.06.2015', '00:02:00', 0.0, 0, -9.999, 0, 8, 0.0, 16, '(SPECTRUM)')
 ('01.06.2015', '09:23:00', 0.327, 61, 25.831, 39, 29, 0.18, 62, '01.06.2015')
 ('01.06.2015', '09:24:00', 0.0, 0, -9.999, 0, 29, 0.0, 66, '(SPECTRUM)')]

usecols可用于忽略多余的分隔符,例如

In [546]: np.genfromtxt([b'1,2,3',b'1,2,3,,,,,,'], dtype=None,
    delimiter=',', usecols=np.arange(3))
Out[546]: 
array([[1, 2, 3],
       [1, 2, 3]])

最新更新