【问题标题】:Pandas Create New Column from Time Comparsion in Datetime ColumnPandas 从日期时间列中的时间比较创建新列
【发布时间】:2021-01-30 14:28:32
【问题描述】:

我的数据框中有一个如下所示的日期时间列。

我想创建一个具有以下条件的新列。如果时间在 1100 之前,则新列中的值为早餐。如果时间是从 1100 到 1445,则值为午餐。如果时间在 1445 到 1730 之后,则值为茶。 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)

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

所以我从每个row["InvoiceDate"].dt.time 中删除了 dt。然后我收到另一条错误消息,指出'builtin_function_or_method'和'datetime.time'的实例之间不支持'

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

【问题讨论】:

  • 你在用熊猫吗?
  • 是的,我正在使用熊猫。

标签: python pandas datetime time


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-09-16
    • 2020-08-21
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多