【问题标题】:Applying a function to dataframe column containing datetimes将函数应用于包含日期时间的数据框列
【发布时间】:2019-08-14 09:06:57
【问题描述】:

这是我尝试过的一段代码。我试图通过将 roundtime() 函数应用于我的数据框的“预订时间”列中的每个条目来将时间四舍五入到最近的时间。但是,四舍五入不适用于列,条目保持原样。

import datetime as dt
def roundtime(t):
    if t.minute >= 30:
        return t.replace(second=0, minute=0, hour=(t.hour+1)%24)
    else:
        return t.replace(second=0, minute=0)
df2= df.copy()
df2['Booking Time']= pd.to_datetime(df2['booking_created']).dt.time
df2['Booking Time'].apply(roundtime)
df2.head()

谁能指出错误?

【问题讨论】:

标签: python pandas time apply


【解决方案1】:

如果需要对日期时间应用函数:

df2['Booking Time']= pd.to_datetime(df2['booking_created']).apply(roundtime)

或者如果需要申请时间:

df2['Booking Time']= pd.to_datetime(df2['booking_created']).dt.time.apply(roundtime)

【讨论】:

  • 谢谢!这行得通。我可能没有在原地使用它。
  • 仅供参考 apply 不会就地执行。它将返回应用的系列或数据框。
【解决方案2】:

这可以在没有单独的函数的情况下完成

import numpy as np
df['Booking Time'] = (np.where(pd.to_datetime(df['booking_created'],format='%Y-%m-%d%H:%M:%S').dt.minute > 30 
                , pd.to_datetime(df['booking_created'],format='%Y-%m-%d%H:%M:%S').dt.ceil('30min')
                , pd.to_datetime(df['booking_created'],format='%Y-%m-%d%H:%M:%S')))

【讨论】:

    猜你喜欢
    • 2016-08-14
    • 1970-01-01
    • 2014-04-08
    • 2018-08-04
    • 1970-01-01
    • 2020-03-23
    • 2019-06-01
    • 2018-07-09
    相关资源
    最近更新 更多