gpt4 book ai didi

python - Pandas,根据数据间隔创建列值

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:35 26 4
gpt4 key购买 nike

我对 python 相当陌生,并且有一个包含数据的 panda,需要根据获取时间进行标记。panda 有一个时间戳列,包含 datetime64 类型的时间戳。

我想评估列中的所有值,并测试它们是否在特定时间范围内,并根据日期所属的时间间隔在新列中分配标签 1-5。

timestamp:             interval:
2017-03-22 13:12:00 1
2017-03-23 13:12:00 1
2017-03-24 13:12:00 2
2017-03-25 13:12:00 2
2017-03-26 13:12:00 2

我尝试了一个函数,可以使用如下所示的数据框调用

def classifyRunHours(series):
if [(series['index_time'] > PERIOD_1) & (series['index_time'] <= PERIOD_2)]:
return 1
elif [(series['index_time'] > PERIOD_2) & (series['index_time'] <= PERIOD_3)]:
return 2
elif [(series['index_time'] > PERIOD_3) & (series['index_time'] <= PERIOD_4)]:
return 3
elif [(series['index_time'] > PERIOD_4) & (series['index_time'] <= PERIOD_5)]:
return 4
else:
return 0

并且间隔定义为

PERIOD_1 = '2017-05-20 11:00:00'

这给我带来了一些麻烦,因为我正在比较字符串和时间戳。这可能是可以解决的,但我不确定这是否是在专栏上工作的正确方法。我应该使用 lambda 函数来处理整个列吗?或者如何有效地做到这一点

欢迎任何意见

最佳答案

我认为你需要cut + add_categoriesfillna用于替换 NaN:

rng = pd.date_range('2017-04-03', periods=15)
series = pd.DataFrame({'index_time': rng, 'a': range(15)})

PERIOD_1 = '2017-04-05'
PERIOD_2 = '2017-04-08'
PERIOD_3 = '2017-04-10'
PERIOD_4 = '2017-04-11'
PERIOD_5 = '2017-04-13'

bins = pd.DatetimeIndex([PERIOD_1,PERIOD_2,PERIOD_3,PERIOD_4, PERIOD_5])
labels = [1,2,3,4]
series['interval'] = pd.cut(series['index_time'], bins=bins, labels=labels)
series['interval'] = series['interval'].cat.add_categories([0]).fillna(0)
print (series)
a index_time interval
0 0 2017-04-03 0
1 1 2017-04-04 0
2 2 2017-04-05 0
3 3 2017-04-06 1
4 4 2017-04-07 1
5 5 2017-04-08 1
6 6 2017-04-09 2
7 7 2017-04-10 2
8 8 2017-04-11 3
9 9 2017-04-12 4
10 10 2017-04-13 4
11 11 2017-04-14 0
12 12 2017-04-15 0
13 13 2017-04-16 0
14 14 2017-04-17 0

另一个解决方案 searchsorted :

bins = pd.DatetimeIndex(['1678-01-01',PERIOD_1,PERIOD_2,PERIOD_3,PERIOD_4, PERIOD_5, '2226-01-01'])
labels = [0,1,2,3,4,0]
series['interval'] = np.array(labels)[np.array(bins).searchsorted(series['index_time'].values) - 1]
print (series)
a index_time interval
0 0 2017-04-03 0
1 1 2017-04-04 0
2 2 2017-04-05 0
3 3 2017-04-06 1
4 4 2017-04-07 1
5 5 2017-04-08 1
6 6 2017-04-09 2
7 7 2017-04-10 2
8 8 2017-04-11 3
9 9 2017-04-12 4
10 10 2017-04-13 4
11 11 2017-04-14 0
12 12 2017-04-15 0
13 13 2017-04-16 0
14 14 2017-04-17 0

关于python - Pandas,根据数据间隔创建列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46976410/

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