文件多行,逗号分隔,每行3个数字,最后一个只有2个
In [182]: fname='../Downloads/pastie-10860707.txt'
In [183]: np.fromregex(fname,regexp=pattern,dtype=float)
...
np.fromregex(fname,regexp=pattern,dtype=float)
/usr/lib/python3/dist-packages/numpy/lib/npyio.py in fromregex(file, regexp, dtype)
1240 # Create the new array as a single data-type and then
1241 # re-interpret as a single-field structured array.
-> 1242 newdtype = np.dtype(dtype[dtype.names[0]])
1243 output = np.array(seq, dtype=newdtype)
1244 output.dtype = dtype
TypeError: 'NoneType' object is not subscriptable
通过简单的“br”读取加载,文件如下所示:
In [184]: txt
Out[184]: b'2.75386225e+00,1.80508078e+00,2.95729122e+00,\n-4.21413726e+00, -3.38139076e+00, -4.22751379e+00,\n ... 4.23010784e-01, -1.14839331e+00, -9.56098910e-01,\n -1.15019836e+00, 1.13845303e-06'
最后一行缺少的数字会给genfromtxt 带来问题。
您选择的模式是错误的。它看起来像一个分隔符模式。但是fromregex docs 中的模式会产生组:
regexp = r"(\\d+)\\s+(...)"
fromregex 会
seq = regexp.findall(file.read()) # read whole file and group it
output = np.array(seq, dtype=dtype) # make array from seq
如果你想使用fromregex,你需要想出一个模式来生成一个可以直接转换成数组的元组列表。
=================
虽然再次查看错误消息,但我发现当前的问题在于dtype。 dtype=float 不是此函数的有效 dtype 规范。它需要一个复合 dtype(结构化)。
此操作会产生错误,其中float 是您的dtype 参数:
In [189]: np.dtype(float).names[0]
...
TypeError: 'NoneType' object is not subscriptable
但它正在尝试这样做,因为模式已经产生了
In [194]: pattern.findall(txt)
Out[194]:
[b',',
b',',
b',',
b'\n',
b',',
b' ',
b' ',
....]
不是它预期的元组列表。
===================
我可以加载文件
In [213]: np.genfromtxt(txt.splitlines(),delimiter=',',usecols=[0,1])
Out[213]:
array([[ 2.75386225e+00, 1.80508078e+00],
[ -4.21413726e+00, -3.38139076e+00],
[ 7.46991792e-01, -1.08010066e+00],
...
[ 4.23010784e-01, -1.14839331e+00],
[ -1.15019836e+00, 1.13845303e-06]])
我正在使用usecols 暂时解决最后一行只有 2 个数字的问题。
如果我删除 \n 并将其拆分为逗号,我可以直接使用 np.array 解析生成的文本字段。
In [231]: txt1=txt.replace(b'\n',b'').split(b',')
In [232]: np.array(txt1,float)
Out[232]:
array([ 2.75386225e+00, 1.80508078e+00, 2.95729122e+00,
-4.21413726e+00, -3.38139076e+00, -4.22751379e+00,
...
4.23010784e-01, -1.14839331e+00, -9.56098910e-01,
-1.15019836e+00, 1.13845303e-06])
此模式包括十进制和科学记数法:
In [266]: pattern=re.compile(br"(\d+\.\d+e[\+\-]\d+)")
In [267]: np.fromregex(fname,regexp=pattern,dtype=np.dtype([('f0',float)]))['f0']
Out[267]:
array([ 2.75386225e+00, 1.80508078e+00, 2.95729122e+00,
4.21413726e+00, 3.38139076e+00, 4.22751379e+00,
...
4.23010784e-01, 1.14839331e+00, 9.56098910e-01,
1.15019836e+00, 1.13845303e-06])
现在我正在创建一个结构化数组并提取该字段。可能有办法解决这个问题。但fromregex 似乎更倾向于使用结构化数据类型。