从数字列表中查找和标记步进函数的最佳方法是什么?

2024-04-20 04:46:17 发布

您现在位置:Python中文网/ 问答频道 /正文

查找和标记包含多个步骤且必须按顺序排列的步骤函数的最佳方法是什么?下面的示例包含3个步骤,步骤1、2和3介于两个数字之间,其中

15 <= step 1 <= 20

21 <= step 2 <= 30

31 <= step 3 <= 40

而每一步都必须至少有一定的时间长度,比如说,第一步30分钟,第二步60分钟,第三步30分钟

import pandas as pd
import numpy as np

x = np.random.randint(0, 100, 20)
step1 = np.random.randint(15, 20, 36)
step2 = np.random.randint(21, 30, 70)
step3 = np.random.randint(31, 40, 40)
y = np.random.randint(0, 100, 20)

df = pd.DataFrame({
'z': np.concatenate((x, step1, step2, step3, y)),
'time': pd.date_range(start='10/20/2019', periods=(20+36+70+40+20), freq='T')
})

预期结果将是:

outcome = pd.DataFrame({
'z': np.concatenate((x, step1, step2, step3, y)),
'time': pd.date_range(start='10/20/2019', periods=(20+36+70+40+20), freq='T'),
'cond': [False]*20 + [True]*(36+70+40) + [False]*20
})

我试过np.piecewise但是如果下一步(比如第2步)落在前一步(比如第1步)中,就会失败:

x = np.random.randint(0, 100, 20)
step1 = np.random.randint(15, 20, 36)
step2new = np.random.randint(15, 30, 70)
step3 = np.random.randint(31, 40, 40)
y = np.random.randint(0, 100, 20)

df = pd.DataFrame({
'z': np.concatenate((x, step1, step2new, step3, y)),
'time': pd.date_range(start='10/20/2019', periods=(20+36+70+40+20), freq='T')
})

Tags: dataframedatetimestepnp步骤rangerandom