我想从数据框中的“时间戳”列中找出是白天还是晚上。时间戳列的值如下:
20:0、14:30、6:15、5:0、4:0 等
我使用了 for 循环,但它白天和晚上随机生成。
for x in data['timestamp']:
if x> '12:00':
print('Day')
else:
print('Night')
我想要在时间戳列旁边有一列,每当时间戳在上午 6:00 到 18:00 之间时,该列的值为“日”;当时间戳在上午 18:01 到上午 5:59 之间时,该列的值为“夜”。
将值转换为时间增量to_timedelta http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_timedelta.html并比较Series.between http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html,然后通过创建新列numpy.where https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html:
data = pd.DataFrame({
'timestamp' : ['6:00', '18:00', '18:01', '5:59'],
})
mask = (pd.to_timedelta(data['timestamp'] + ':00')
.between(pd.Timedelta('6h'),pd.Timedelta('18h')))
data['new'] = np.where(mask, 'Day', 'Night')
print (data)
timestamp new
0 6:00 Day
1 18:00 Day
2 18:01 Night
3 5:59 Night
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)