【问题标题】:How to create new column containing part of the day as ['morning' , 'afternoon' , 'evening', 'night' ] using time column?如何使用时间列创建包含部分时间的新列作为 ['morning' , 'afternoon' , 'evening', 'night' ]?
【发布时间】:2020-04-16 08:27:43
【问题描述】:
我正在处理时间序列数据,下面是前两列的外观。我想创建一个新列,其中包含一天中的部分时间或 4 个不同的数据框,分别只包含早上、下午、晚上和晚上的时间。
date time
0 2018-11-26 03:40:46.319000
1 2018-11-26 03:40:46.319999
2 2018-11-26 03:40:46.319999
3 2018-11-26 03:40:46.358000
4 2018-11-26 03:40:46.358000
【问题讨论】:
标签:
python
pandas
time-series
【解决方案1】:
你可以通过 dateutil:https://pypi.org/project/python-dateutil/ 或者直接 pandas 获取小时,如下图:
import dateutil
def get_part_of_day(hour):
return (
"morning" if 5 <= hour <= 11
else
"afternoon" if 12 <= hour <= 17
else
"evening" if 18 <= hour <= 22
else
"night"
)
df['part_of_day'] = df.time.apply(lambda x: get_part_of_day(dateutil.parser.parse(x).hour))
or without the import dateutil
df['part_of_day'] = df.apply(lambda x: get_part_of_day(pd.to_datetime(x.date + ' ' + x.time).hour), axis=1)
```
output
```
date time part_of_day
0 2018-11-26 03:40:46.319000 night
1 2018-11-26 03:40:46.319999 night
2 2018-11-26 03:40:46.319999 night
3 2018-11-26 03:40:46.358000 night
4 2018-11-26 03:40:46.358000 night
```
【解决方案2】:
您的时间列表示为 datetime.time 格式是否正确(例如your_df['time'][0] = datetime.time(3, 40, 46, 319000))?
在这种情况下,您真正需要做的就是应用 .hour 列中值的属性来创建一个新的(并应用一些 if 语句来确定哪些时间对应于上午、下午等)
像这样:
time_col_index = 1
your_df['part of the day'] = df.apply(lambda row: determine_time(row[time_col_index]), axis=1)
determine_time 函数可能看起来像这样:
def determine_time(time):
hr = time.hour
if hr <= 5:
return night
elif ...