gpt4 book ai didi

python - 检查最近n分钟内是否出现过一个值

转载 作者:行者123 更新时间:2023-11-30 22:39:40 26 4
gpt4 key购买 nike

如果我们有以下数据:

timestamp = ['2016-01-09_14-49-18','2016-01-10_09-48-59','2016-01-10_09-50-29','2016-01-10_09-59-08','2016-01-10_10-33-01','2016-01-10_10-35-01','2016-01-10_10-39-05','2016-01-10_10-40-38','2016-01-10_10-50-55','2016-01-10_12-28-35','2016-01-10_15-13-34','2016-01-10_17-02-44','2016-01-10_17-05-48','2016-01-10_17-13-44','2016-01-10_17-15-52']
feature = ['A','A','B','C','B','C','C','A','A','A','B','A','C','C','A']
df = pd.DataFrame({'timestamp':timestamp, 'feature':feature})

如何为每个特征创建一个新列来表示该类别是否出现在过去 15 分钟内?

结果:

   feature    timestamp              A    B    C
0 A 2016-01-09_14-49-18 1 0 0
1 A 2016-01-10_09-48-59 1 0 0
2 B 2016-01-10_09-50-29 1 1 0
3 C 2016-01-10_09-59-08 1 1 1
4 B 2016-01-10_10-33-01 0 1 0
5 C 2016-01-10_10-35-01 0 1 1
6 C 2016-01-10_10-39-05 0 1 1
7 A 2016-01-10_10-40-38 1 1 1
8 A 2016-01-10_10-50-55 1 0 1
9 A 2016-01-10_12-28-35 1 0 0
10 B 2016-01-10_15-13-34 0 1 0
11 A 2016-01-10_17-02-44 1 0 0
12 C 2016-01-10_17-05-48 1 0 1
13 C 2016-01-10_17-13-44 1 0 1
14 A 2016-01-10_17-15-52 1 0 1

其中 1 = 该类(class)在过去 15 分钟内出现,0 = 该类(class)未出现。

最佳答案

您可以使用:

df['timestamp'] = pd.to_datetime(df['timestamp'], format='%Y-%m-%d_%H-%M-%S')

for col in df['feature'].unique():
df[col] = df['timestamp'] - df['timestamp'].where(df['feature'] == col).ffill()
df[col] = (df[col] < pd.to_timedelta('15min')).astype(int)
print (df)

feature timestamp A B C
0 A 2016-01-09 14:49:18 1 0 0
1 A 2016-01-10 09:48:59 1 0 0
2 B 2016-01-10 09:50:29 1 1 0
3 C 2016-01-10 09:59:08 1 1 1
4 B 2016-01-10 10:33:01 0 1 0
5 C 2016-01-10 10:35:01 0 1 1
6 C 2016-01-10 10:39:05 0 1 1
7 A 2016-01-10 10:40:38 1 1 1
8 A 2016-01-10 10:50:55 1 0 1
9 A 2016-01-10 12:28:35 1 0 0
10 B 2016-01-10 15:13:34 0 1 0
11 A 2016-01-10 17:02:44 1 0 0
12 C 2016-01-10 17:05:48 1 0 1
13 C 2016-01-10 17:13:44 1 0 1
14 A 2016-01-10 17:15:52 1 0 1

关于python - 检查最近n分钟内是否出现过一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43090013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com