熊猫通过日期时间列中的时间比较创建新列

时间:2020-10-16 04:14:57

标签: python pandas datetime time

我的数据框中有一个类似这样的日期时间列。

enter image description here

我要创建一个具有以下条件的新列。如果时间在1100之前,则新列中的值为早餐。如果时间是从1100到1445,则值为午餐。如果时间在1445到1730之间,则值为tea。 1730年之后,值是晚餐。

这是我的代码。

def meal(row):
    if (row["InvoiceDate"].dt.time < pd.to_datetime("11:00:00").time()):
        meal="breakfast"
    elif (row["InvoiceDate"].dt.time >= pd.to_datetime("11:00:00").time())&(row["InvoiceDate"].dt.time <= pd.to_datetime("14:45:00").time()):
        meal="lunch"
    elif (row["InvoiceDate"].dt.time > pd.to_datetime("14:45:00").time())&(row["InvoiceDate"].dt.time <= pd.to_datetime("17:30:00").time()):
        meal="tea"
    else:
        meal="dinner"

df["meal"]=df.apply(lambda row:meal(row),axis=1)

当我运行上面的函数时,我收到一条错误消息,指出“ Timestamp”对象没有属性“ dt”。

因此,我从row["InvoiceDate"].dt.time的每一个中删除了dt。然后,我又收到一条错误消息,指出“ builtin_function_or_method”实例与“ datetime.time”实例之间不支持“ <”。

我应该怎么做?有没有更好的方法来编写我的进餐功能?谢谢。

1 个答案:

答案 0 :(得分:0)

看起来列InvoiceDate的类型不是datetime。 您可以使用以下代码将其转换为这种类型:

df['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'])