代码之家  ›  专栏  ›  技术社区  ›  David Waterworth

正在查找Pandas.DateTimeIndex.is\u dst()

  •  3
  • David Waterworth  · 技术社区  · 7 年前

    我有一个带有DateTimeIndex的日期框,即。

    import pandas as pd
    dates = pd.date_range('2018-04-01', periods=96, freq='15T', tz='Australia/Sydney', name='timestamp')
    df = dates.to_frame(index=False)
    df.set_index(dates.name, inplace=True)
    

    我想用0/1指示符列创建一个列,夏季为1,冬季为0,但找不到相关的dst/is\dst属性,例如

    df['is_dst'] = df.index.is_dst()
    

    谁能告诉我正确的方法/属性是什么。或者我需要转换到另一个“datetime”类?

    2 回复  |  直到 7 年前
        1
  •  6
  •   BENY    7 年前

    它已经在里面了 pandas

    df.index.map(lambda x : x.dst())
    

    在一个小的改变之后可以产生布尔值

    df.index.map(lambda x : int(x.dst().total_seconds()!=0))
    Out[104]: 
    Int64Index([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0],
               dtype='int64', name='timestamp')
    
        2
  •  3
  •   Brad Solomon    7 年前

    我猜温的方法可能要快一点,但下面是一种处理底层Python的方法 datetime 具有 isdst attribute from datetime.timetuple

    >>> is_dst = [x.timetuple().tm_isdst for x in df.index.to_pydatetime()]
    >>> pd.Series(is_dst).head()
    0    1
    1    1
    2    1
    3    1
    4    1
    dtype: int64
    >>> pd.Series(is_dst).tail()
    91    0
    92    0
    93    0
    94    0
    95    0
    dtype: int64
    

    单个值的示例:

    .timetuple() 返回一个 time.struct_time

    根据dst()方法设置结果的tmu isdst标志:tzinfo为None或dst()返回None,tmu isdst设置为-1;否则,如果dst()返回一个非零值,则tmu isdst设置为1;否则tm\U isdst设置为0。

    >>> df.index[0].to_pydatetime().timetuple()
    time.struct_time(tm_year=2018, tm_mon=4, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=91, tm_isdst=1)
    

    check 如果日期是 .dst()

        def timetuple(self):
            "Return local time tuple compatible with time.localtime()."
            dst = self.dst()
            if dst is None:
                dst = -1
            elif dst:
                dst = 1
            else:
                dst = 0