过滤元组的numpy数组

Filter numpy array of tuples

Scikit-learn 图书馆有一个出色的数据聚类示例 - stock market structure。它在美国股票中运作良好。但是当添加来自其他市场的代码时,numpy 的错误出现是数组应该具有相同的大小 - 这是事实,例如,德国股票具有不同的交易日历。

好的,报价下载后我添加共享日期的准备:

quotes = [quotes_historical_yahoo_ochl(symbol, d1, d2, asobject=True)
          for symbol in symbols]


def intersect(list_1, list_2):
    return list(set(list_1) & set(list_2))

dates_all = quotes[0].date
for q in quotes:
    dates_symbol = q.date
    dates_all = intersect(dates_all, dates_symbol)

然后我无法过滤 numpy 元组数组。下面是一些尝试:

# for index, q in enumerate(quotes):
#     filtered = [i for i in q if i.date in dates_all]

#     quotes[index] = np.rec.array(filtered, dtype=q.dtype)
#     quotes[index] = np.asanyarray(filtered, dtype=q.dtype)
#
#     quotes[index] = np.where(a.date in dates_all for a in q)
#
#     quotes[index] = np.where(q[0].date in dates_all)

如何将过滤器应用于 numpy 数组或如何真正将记录列表(过滤后)转换回 numpyrecarray

引用[0].dtype:

'(numpy.record, [('date', 'O'), ('year', '<i2'), ('month', 'i1'), ('day', 'i1'), ('d', '<f8'), ('open', '<f8'), ('close', '<f8'), ('high', '<f8'), ('low', '<f8'), ('volume', '<f8'), ('aclose', '<f8')])'

引用[0].形状:

<class 'tuple'>: (261,)

所以quotes是一个recarrays列表,在date_all中你收集了date字段中所有值的交集。

我可以重新创建一个这样的数组:

In [286]: dt=np.dtype([('date', 'O'), ('year', '<i2'), ('month', 'i1'), ('day', 
     ...:
     ...: ), ('low', '<f8'), ('volume', '<f8'), ('aclose', '<f8')])
In [287]: 
In [287]: arr=np.ones((2,), dtype=dt)  # 2 element structured array
In [288]: arr
Out[288]: 
array([(1, 1, 1, 1,  1.,  1.,  1.,  1.,  1.,  1.,  1.),
       (1, 1, 1, 1,  1.,  1.,  1.,  1.,  1.,  1.,  1.)], 
      dtype=[('date', 'O'), ('year', '<i2'), ('month', 'i1'), ('day', 'i1'), ... ('aclose', '<f8')])
In [289]: type(arr[0])
Out[289]: numpy.void

把它变成一个 recarray(我不像普通结构化数组那样经常使用它们):

In [291]: np.rec.array(arr)
Out[291]: 
rec.array([(1, 1, 1, 1,  1.,  1.,  1.,  1.,  1.,  1.,  1.),
 (1, 1, 1, 1,  1.,  1.,  1.,  1.,  1.,  1.,  1.)], 
          dtype=[('date', 'O'), ('year', '<i2'), ('month', 'i1'), ('day', 'i1'), .... ('aclose', '<f8')])

dtype 的 recarray 显示略有不同:

In [292]: _.dtype
Out[292]: dtype((numpy.record, [('date', 'O'), ('year', '<i2'), ('month', 'i1'), ....('aclose', '<f8')]))
In [293]: __.date
Out[293]: array([1, 1], dtype=object)

在任何情况下,date 字段都是一个对象数组,可能是 datetime?

q 是这些数组之一; i是元素,i.date是日期字段。

 [i for i in q if i.date in dates_all]

所以 filtered 是 recarray 元素的列表。 np.stack 在将它们重新组装成数组方面做得更好(也适用于 recarray)。

np.stack([i for i in arr if i['date'] in alist])

或者您可以收集匹配记录的索引,并索引引用数组

In [319]: [i for i,v in enumerate(arr) if v['date'] in alist]
Out[319]: [0, 1]
In [320]: arr[_]

或者先拉出日期字段:

In [321]: [i for i,v in enumerate(arr['date']) if v in alist]
Out[321]: [0, 1]

in1d 也可以用于搜索

In [322]: np.in1d(arr['date'],alist)
Out[322]: array([ True,  True], dtype=bool)
In [323]: np.where(np.in1d(arr['date'],alist))
Out[323]: (array([0, 1], dtype=int32),)