我使用genfromtxt
从txt文件导入数据。
根据genfromtxt
通常,这个文本文件有许多行数据要导入,这意味着narray是这样的:
array([ ('2016-04-17T00:08:42.273000Z', '2016-04-17T00:08:50.595000Z', '2016-04-17T00:08:58.378391Z', '2016-04-17T00:08:58.840273Z', '2016-04-17T00:09:05.670000Z', '2016-04-17T00:09:06.115000Z', '2016-04-17T00:09:07.155000Z', '2016-04-17T00:09:06.804999Z', '2016-04-17T00:09:08.488391Z', '2016-04-17T00:09:14.890273Z', '2016-04-17T00:09:11.648393Z', 1.702756, 10, 3.959),
('2016-04-17T01:11:11.393000Z', '2016-04-17T01:11:19.715000Z', '2016-04-17T01:11:27.498391Z', '2016-04-17T01:11:27.960273Z', '2016-04-17T01:11:34.790000Z', '2016-04-17T01:11:35.235000Z', '2016-04-17T01:11:36.275000Z', '2016-04-17T01:11:35.924999Z', '2016-04-17T01:11:37.608391Z', '2016-04-17T01:11:44.010273Z', '2016-04-17T01:11:40.768393Z', 3.084912, 10, 3.423),
('2016-05-20T19:10:42.883000Z', '2016-05-20T19:10:51.205000Z', '2016-05-20T19:10:58.978393Z', '2016-05-20T19:10:59.441114Z', '2016-05-20T19:11:06.280000Z', '2016-05-20T19:11:06.705000Z', '2016-05-20T19:11:07.725000Z', '2016-05-20T19:11:07.405000Z', '2016-05-20T19:11:09.108393Z', '2016-05-20T19:11:15.481160Z', '2016-05-20T19:11:12.258393Z', 1.956513, 10, 3.078)],
dtype=[('origintime', 'S27'), ('JAMA', 'S27'), ('FLF1', 'S27'), ('MAG1', 'S27'), ('AV18', 'S27'), ('AV21', 'S27'), ('AMA1', 'S27'), ('BV15', 'S27'), ('PPLP', 'S27'), ('HPAL', 'S27'), ('ILLI', 'S27'), ('stackedcorr', '<f8'), ('totalstations', '<i8'), ('magestimate', '<f8')])
但是当文本文件只有一行时,narray是这样的(注意前面的例子缺少方括号):
array(('2016-05-08T03:13:02.841000Z', '2016-05-08T03:13:10.705000Z', '1900-01-01T00:00:00.000000Z', '2016-05-08T03:13:14.099997Z', '2016-05-08T03:13:14.938393Z', '2016-05-08T03:13:29.228391Z', '2016-05-08T03:13:31.868393Z', '2016-05-08T03:13:31.909995Z', '2016-05-08T03:13:36.920000Z', '2016-05-08T03:13:37.080000Z', '2016-05-08T03:13:37.635000Z', 9.0, 9, 3.41),
dtype=[('origintime', 'S27'), ('JAMA', 'S27'), ('CABP', 'S27'), ('MAG1', 'S27'), ('FLF1', 'S27'), ('PAC1', 'S27'), ('GGPT', 'S27'), ('PINO', 'S27'), ('SUCR', 'S27'), ('BNAS', 'S27'), ('SLOR', 'S27'), ('stackedcorr', '<f8'), ('totalstations', '<i8'), ('magestimate', '<f8')])
区别在于多行输入是数组,而单行输入不是。
这会导致索引混乱,因为我不能循环results['origintime'][i]
,因为只有一行输入的可能性。
我如何将单行输入(没有方括号)的ndarray转换为len=1列表,这意味着它具有与多行ndarray相同的格式?
谢谢
Numpy实际上是作为一个数组在文件中加载的,但它是一个"0维"数组。也就是说,results.ndim
将返回0
。您可以通过执行results.reshape((1,))
将其转换为具有1个元素的一维数组。
如果你正在读取一个文件,并且你不知道它是有一行还是多行,你可以这样做:
results = np.genfromtxt(filename)
if results.ndim==0:
results.reshape((1,))