【问题标题】:How to split time data in Python?如何在 Python 中拆分时间数据?
【发布时间】:2021-01-06 17:58:01
【问题描述】:

我有一个如下的数据框:

d={
    'Date' :['2016-10-30','2016-10-30','2016-11-01','2016-10-30'],
    'Time':['09:58:11', '10:05:34', '10:07:57', '11:15:32'],
    'Transaction':[2,3,1,1]
}

df=pd.DataFrame(d, columns=['Date','Time','Transaction'])

我需要创建一个新变量作为 Time_Group。对于 Time_group 的数据,对于 (6,11] 是 'Morning',对于 (11,17] 是 'Afternoon',对于 (17,20] 是 'Evening'。如何使用 Time 列子创建此变量?

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    pd.cutpd.Timedelta 一起使用:

    u = df.assign(Time=pd.to_timedelta(df['Time']))
    bins = [6,11,17,20]
    labels = ['Morning','Afternoon','Evening']
    u = u.assign(Time_Group=pd.cut(u['Time'],[pd.Timedelta(hours=i) for i in bins],
                                   labels=labels))
    

    print(u)
             Date     Time  Transaction Time_Group
    0  2016-10-30 09:58:11            2    Morning
    1  2016-10-30 10:05:34            3    Morning
    2  2016-11-01 10:07:57            1    Morning
    3  2016-10-30 11:15:32            1  Afternoon
    

    【讨论】:

    • 您好,这里的第 4 次生应该是早上,但看起来是下午。如何解决这个问题?
    • @user14815110 在您的问题中您已经写到 11-17 应该是下午。因此,第 4 行是下午,因为它是 11 点过去 15 分钟。要更改时间,您可以简单地将垃圾箱列表从 11 更改为 12,例如从下午开始
    【解决方案2】:

    你可以用这个-

    d={
        'Date' :['2016-10-30','2016-10-30','2016-11-01','2016-10-30'],
        'Time':['09:58:11', '10:05:34', '10:07:57', '11:15:32'],
        'Transaction':[2,3,1,1]
    }
    
    df=pd.DataFrame(d, columns=['Date','Time','Transaction'])
    
    
    def time_group(inp):
        inp = datetime.datetime.strptime(inp[0], "%H:%M:%S")
        a = datetime.datetime.strptime("06:00:00", "%H:%M:%S")
        b = datetime.datetime.strptime("11:00:00", "%H:%M:%S")
        c = datetime.datetime.strptime("17:00:00", "%H:%M:%S")
        d = datetime.datetime.strptime("20:00:00", "%H:%M:%S")
        
        if a < inp <= b:
           return 'Morning'
        elif b < inp < c:
           return 'Afternoon'
        elif c < inp < d:
           return 'Night'
    
    >>> df[['Time']].apply(time_group,axis=1)
    0      Morning
    1      Morning
    2      Morning
    3    Afternoon
    dtype: object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 2021-10-16
      • 2021-02-13
      • 2023-01-20
      • 2018-12-06
      • 2020-03-07
      • 1970-01-01
      相关资源
      最近更新 更多