索引ndarray - 1项目的存储方式与> 1不同

时间:2016-10-07 20:43:07

标签: python multidimensional-array indexing genfromtxt

我使用genfromtxt从txt文件导入数据。

根据genfromtxt

将此数据导入到ndarray中

通常,这个文本文件有多行数据输入,这意味着ndarray是这样的:

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')])

但是当文本文件只有一行时,ndarray就像这样(注意缺少方括号,如上例所示):

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列表,这意味着它具有与多行ndarrays相同的格式? < / p>

由于

1 个答案:

答案 0 :(得分:1)

Numpy实际上是作为数组加载到文件中,但它是一个“0维”数组。也就是说,results.ndim将返回0。您可以通过执行results.reshape((1,))将其转换为包含1个元素的1维数组。

如果您正在阅读某个文件并且您不知道它是否预先有一行或多行,您可以这样做:

results = np.genfromtxt(filename)
if results.ndim==0:
    results.reshape((1,))