Python/Pandas基于DateTime值创建分类列

3

我有一个Pandas数据框(data),其中有一列['Date'],其值类似于“yyyy-mm-dd HH:MM:SS”,我已将其转换为Pandas Datetime格式。

data['Date'] = pd.to_datetime(data['Date'])

如何基于每天的小时数创建一个新的分类列['Time'],其中包含'Early','Mid-day','Late'等类别?

我尝试过以下方法:

def time(x):
    if '03:00:00' < x <= '11:00:00':
        return 'Early'
    elif '11:00:00' < x <= '17:00:00':
        return 'Mid-day'
    return 'Late'

data['Time'] = data['Date'].dt.time.apply(time)

但我遇到了这个错误:" TypeError: '<' not supported between instances of 'str' and 'datetime.time' "
非常感谢您的帮助!

调查 pd.to_datetime('03:00:00').time < x <= pd.to_datetime('11:00:00').time - jch
'03:00:00'只是一个字符串。虽然它在你看来像是一个时间,但对于Python来说,它不仅仅是一组字符。 - Acccumulation
3个回答

2
你可以使用pandas.cut。然而,它有点棘手,因为你需要先将你的日期时间转换为时间差(timedelta)。
df = pd.DataFrame({'date': ['2022-04-27 01:00:00', '2022-04-27 04:00:00',
                            '2022-04-27 12:00:00', '2022-04-27 17:00:00']})

# define bins and labels
bins = ['00:00:00', '03:00:00', '11:00:00', '17:00:00', '23:59:59']
labels = ['Late', 'Early', 'Mid-Day', 'Late']

# convert to timedelta
s = pd.to_timedelta(pd.to_datetime(df['date']).dt.time.astype(str))
df['time'] = pd.cut(s, bins=pd.to_timedelta(bins), labels=labels, ordered=False)

输出:

                  date     time
0  2022-04-27 01:00:00     Late
1  2022-04-27 04:00:00    Early
2  2022-04-27 12:00:00  Mid-Day
3  2022-04-27 17:00:00  Mid-Day

0
你可以尝试在函数中将所有条件都包装在 to_datetime() 中,这样怎么样?
def time(x):
    x=pd.to_datetime(x,format='%H:%M:%S')
    if pd.to_datetime('03:00:00') < x <= pd.to_datetime('11:00:00'):
        return 'Early'
    elif pd.to_datetime('11:00:00') < x <= pd.to_datetime('17:00:00'):
        return 'Mid-day'
    return 'Late'

df['Time'] = df['Date'].dt.time.apply(time)

1
将 format= '%H:%M:%S' 添加到所有情况中都起作用了! - rgatt

0
你可以使用 np.select 和 DatetimeIndex.indexer_between_time 功能一起创建标签。 indexer_between_time 返回时间在提供的端点之间的数组索引,因此您需要从与数据框长度相同的数组的 in 检查中形成布尔系列。
import pandas as pd
import numpy as np

df = pd.DataFrame({'Date': pd.date_range('2010-01-01', freq='3H', periods=11)},
                  index=list('ABCDEFGHIJK'))

idx = pd.DatetimeIndex(df['Date'])
ilocs = np.arange(len(df))

conds = [np.in1d(ilocs, idx.indexer_between_time('03:00:00', '11:00:00', include_start=False, include_end=True)),
         np.in1d(ilocs, idx.indexer_between_time('11:00:00', '17:00:00', include_start=False, include_end=True))]

choices = ['early', 'mid-day']

df['time_of_day'] = np.select(conds, choices, default='late')

                 Date time_of_day
A 2010-01-01 00:00:00        late
B 2010-01-01 03:00:00        late
C 2010-01-01 06:00:00       early
D 2010-01-01 09:00:00       early
E 2010-01-01 12:00:00     mid-day
F 2010-01-01 15:00:00     mid-day
G 2010-01-01 18:00:00        late
H 2010-01-01 21:00:00        late
I 2010-01-02 00:00:00        late
J 2010-01-02 03:00:00        late
K 2010-01-02 06:00:00       early

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接