【发布时间】:2021-09-23 19:56:55
【问题描述】:
我有 2 个数组和一个 pandas 数据框。我想要完成的是: 使用具有 datetime64 值的一个数组、一个 3 个展平的 3D 数组(与时间相同的长度)和一个 pandas 数据帧(超过 6000 行)
我需要做的是: 使用时间数组上的时间戳,搜索数据框中匹配的时间戳,并使用这些值创建两个新数组(新时间和新 DF) 此外,展平数组的值与时间数组相同,所以我想将它们提取到一个新数组(new_flat)
一些sn-ps代码:
mini_time = ['2015-03-25T13:05:00.000000Z',
'2015-03-25T13:05:03.000000Z',
'2015-03-25T13:05:06.000000Z',
'2015-03-25T13:05:09.000000Z',
'2015-03-25T13:05:12.000000Z']
mini_flat=np.zeros((5,5,3750))
np.random.seed(5)
df = pd.DataFrame(np.random.randint(100, size=(5, 40)),
columns=list('ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMN'),
index=['2015-03-25T13:05:00.000000{}'.format(i) for i in range(5)])
我知道这里的索引是一个字符串,但是在我原来的 dtaframe 中,有一个名为“日期”的列,其中包含我制作成索引的一系列 6000 多个时间戳
这是我目前所拥有的:
df=df.set_index('Date')
这允许我将 DF 上的时间戳设置为索引
new_Time = []
new_Flat = []
new_DF = []
for t in range(len(time)):
s = df.loc[df.index.unique()[df.index.unique().get_loc(np.datetime64(time[mini_time]), method='nearest')]]
if (s.index - np.datetime64(time[mini_time])) < 0.2: #check this by hand
new_Time.append(time[mini_time])
new_DF.append(s)
new_Flat.mini_flat[mini_time]
UFuncTypeError: ufunc 'subtract' cannot use operands with types dtype('O') and dtype('<M8[us]')
如果我将 s.index 更改为 s.name,
TypeError: Cannot compare type Timedelta with type float
我至少得到了正确的方法吗?
【问题讨论】:
-
请始终包含最少的示例数据。 How to make good reproducible pandas examples
-
我认为我添加了我正在使用的较小规模
-
您的示例代码为
df=df.set_index('Date')行生成KeyError: "None of ['Date'] are in the columns"。请阅读并提供minimal reproducible example。 - 如果列表或系列应该是字符串以外的对象,请确保示例数据反映了这一点。请阅读How to Ask。
标签: python arrays pandas machine-learning