【问题标题】:Pandas Dataframe datetime conditionPandas Dataframe 日期时间条件
【发布时间】:2022-02-12 22:12:54
【问题描述】:

我有以下数据框,并想根据条件创建一个新列。新列应包含 20:00 到 06:00 之间的“夜间”,06:00 到 14:30 之间的“早晨”和 14:30 到 20:00 之间的“下午”。如何以最佳方式制定和应用这样的条件?

import pandas as pd

df = {'A' : ['test', '2222', '1111', '3333', '1111'],
        'B' : ['aaa', 'aaa', 'bbbb', 'ccccc', 'aaa'],
        'Date' : ['15.07.2018 06:23:56', '15.07.2018 01:23:56', '15.07.2018 06:40:06', '15.07.2018 11:38:27', '15.07.2018 21:38:27'],
        'Defect': [0, 1, 0, 1, 0]
        }

df = pd.DataFrame(df)
df['Date'] = pd.to_datetime(df['Date'])

【问题讨论】:

    标签: python pandas date datetime


    【解决方案1】:

    你可以使用np.select:

    from datetime import time
    
    condlist = [df['Date'].dt.time.between(time(6), time(14, 30)),
                df['Date'].dt.time.between(time(14,30), time(20))]
    
    df['Time'] = np.select(condlist, ['Morning', 'Afternoon'], default='Night')
    

    输出:

    >>> df
          A      B                Date  Defect     Time
    0  test    aaa 2018-07-15 06:23:56       0  Morning
    1  2222    aaa 2018-07-15 01:23:56       1    Night
    2  1111   bbbb 2018-07-15 06:40:06       0  Morning
    3  3333  ccccc 2018-07-15 11:38:27       1  Morning
    4  1111    aaa 2018-07-15 21:38:27       0    Night
    

    注意,'Night'不需要条件:

    df['Date'].dt.time.between(time(20), time(23,59,59)) \
    | df['Date'].dt.time.between(time(0), time(6))
    

    因为np.select 可以将default 值作为参数。

    【讨论】:

    • 谢谢,对我来说很好:)!
    【解决方案2】:

    您可以创建日期字段的索引,然后使用indexer_between_time

    idx = pd.DatetimeIndex(df["Date"])
    conditions = [
        ("20:00", "06:00", "Night"),
        ("06:00", "14:30", "Morning"),
        ("14:30", "20:00", "Afternoon"),
    ]
    
    for cond in conditions:
        start, end, val = cond
        df.loc[idx.indexer_between_time(start, end, include_end=False), "Time_of_Day"] = val
    
          A      B                Date  Defect Time_of_Day
    0  test    aaa 2018-07-15 06:23:56       0     Morning
    1  2222    aaa 2018-07-15 01:23:56       1       Night
    2  1111   bbbb 2018-07-15 06:40:06       0     Morning
    3  3333  ccccc 2018-07-15 11:38:27       1     Morning
    4  1111    aaa 2018-07-15 21:38:27       0       Night
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      • 2016-08-05
      • 2014-06-05
      相关资源
      最近更新 更多