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

发布于 2025-01-24 15:31:28 字数 580 浏览 2 评论 0原文

我有一个带有列['date']的pandas dataframe(数据),其值是“ yyyy-mm-dd hh:mm:ss”,我将我转换为pandas dateTime格式。

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

如何使用类别'早期','mid--创建一个新的分类列['time']一天,“迟到”,根据每天的时间?

我尝试了以下错误:

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:'&lt;'在“ str”和“ dateTime”实例之间不支持“时间”。“

感谢您的帮助!

I have a Pandas Dataframe (data) with a column ['Date'] with values like "yyyy-mm-dd HH:MM:SS" that I converted into Pandas Datetime format.

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

How can I create a new categorical column ['Time'] with categories 'Early', 'Mid-day', 'Late' based on the hour of each day?

I tried this:

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)

But I get this error: " TypeError: '<' not supported between instances of 'str' and 'datetime.time' "

I would appreciate your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浮萍、无处依 2025-01-31 15:31:28

您可以使用 pandas.cut.cut.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

You can use pandas.cut. It is however a bit tricky as you need to convert first your datetime to 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)

output:

                  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
假扮的天使 2025-01-31 15:31:28

如何将所有条件包装在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)

How about just wrapping all of your conditions in your function in a 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)
空袭的梦i 2025-01-31 15:31:28

您可以将np.selectdateTimeIndex.indexer_between_time功能一起创建标签。 indexer_between_time返回所提供端点之间的时间的数组索引,因此您需要从 in 使用dataframe的阵列中核对 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

You can use np.select together with the DatetimeIndex.indexer_between_time functionality to create the labels. indexer_between_time returns the array indices where the time is between the provided endpoints, so you need to form the Boolean series from an in check with an array the length of the DataFrame.

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文