我有一个类似这样的numpy数组:
A=[(datetime.datetime(2016, 6, 8, 12, 37, 27, 826000), 3.0)
(datetime.datetime(2016, 6, 8, 12, 37, 27, 827000), nan)
(datetime.datetime(2016, 6, 8, 12, 37, 27, 832000), nan)
(datetime.datetime(2016, 6, 8, 12, 37, 27, 833000), nan)
(datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 3.0)
(datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 35.0)]
我想把它分成两个numpy数组:
B=[(datetime.datetime(2016, 6, 8, 12, 37, 27, 826000),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 827000),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 832000),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 833000),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 837000),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 837000)]
C=[3.0,nan,nan,nan,3.0,35.0]
为了给你更多的细节,这个numpy数组最初是一个dictionary,我已经将其转换为numpy数组,你可以找到下面的代码:
def convertarray(dictionary):
names=['id','data']
formats=['datetime64[ms]','f8']
dtype=dict(names=names, formats=formats)
result=np.array(dictionary.items(),dtype)
return result
如果你只是有一个带有dtype=object
的普通数组,我认为你最好的办法是通过在几个列表中迭代旧数组来构建新数组:
将numpy导入为np来自numpy进口nan导入日期时间
A=np.array([(datetime.datetime(2016, 6, 8, 12, 37, 27, 826000), 3.0),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 827000), nan),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 832000), nan),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 833000), nan),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 3.0),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 35.0)])
print(A.dtype)
times = np.array([x[0] for x in A])
values = np.array([x[1] for x in A])
print(times)
print(values)
话虽如此,使用记录数组可能会稍微干净一些:
import numpy as np
from numpy import nan
import datetime
A=np.array([(datetime.datetime(2016, 6, 8, 12, 37, 27, 826000), 3.0),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 827000), nan),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 832000), nan),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 833000), nan),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 3.0),
(datetime.datetime(2016, 6, 8, 12, 37, 27, 837000), 35.0)],
dtype=[('time', object), ('value', float)])
print(A.dtype)
print(A['time'])
print(A['value'])
您可能想要对数据进行切片。为该维度插入:
将选择该维度的所有元素。
B = A[:, 0]
C = A[:, 1]