【问题标题】:What is the use of Periods in pandas大熊猫中的句号有什么用
【发布时间】:2021-01-05 07:16:26
【问题描述】:

我在 pandas 中经历了时期,找不到任何特殊用途,我认为它与日期没有任何不同,例如

  1. 为了获取日期时间,我使用

    日期时间(2012,1,1)

  2. 为了获取日期范围,我使用

    pd.date_range('1/1/2000', period=10)

我的问题是,为什么要使用 Period?根据定义

期间代表时间跨度,例如天、月、季度或年。

p = pd.Period(2007, freq='A-DEC')

在这种情况下,Period 对象表示从 2007 年 1 月 1 日至 2007 年 12 月 31 日(含)。 但是,如果我按照定义进行,我应该能够使用 Period 进行分组,因为我拥有一定的时间跨度,但是当我尝试分组时,我得到了错误

_period=pd.Period('2000',freq='M')
x = pd.date_range('1/1/2000', periods=14)
_result=pd.Series(range(len(x)),index=x)
_result.groupby(_period)

谁能帮我理解什么时候应该使用 Period 以及我可以使用它解决什么和所有问题

【问题讨论】:

    标签: pandas datetime period


    【解决方案1】:

    对于按期间汇总,请在此处将 DatetimeIndex 转换为 PeriodIndex DatetimeIndex.to_period

    print (_result.index.to_period('m'))
    PeriodIndex(['2000-01', '2000-01', '2000-01', '2000-01', '2000-01', '2000-01',
                 '2000-01', '2000-01', '2000-01', '2000-01', '2000-01', '2000-01',
                 '2000-01', '2000-01'],
                dtype='period[M]', freq='M')
    
    print (_result.groupby(_result.index.to_period('m')).sum())
    2000-01    91
    Freq: M, dtype: int64
    

    【讨论】:

    • 你能帮我看看什么时候使用 Period 或者 Period 和 Datetime 之间的主要区别是什么
    • @LijinDurairaj - 用于[Regular intervals of time are represented by Period objects in pandas while sequences of Period objects are collected in a PeriodIndex,](https://pandas.pydata.org/docs/user_guide/timeseries.html#time-span-representation)。这实际上意味着如果需要处理,例如按月和年的数据可以使用df.years with df.mothsdt.to_periods('m') 处理月期间。它应该是 pd.Grouper(freq='m') 的替代品。
    • 什么意思其实可以看到here
    • 我已经浏览了您提供的链接,现在我的问题是 Period 和 Datetime 之间有什么区别,当 Period 可以像 Datetime 一样添加年、月、日和时间时,谢谢您帮助
    猜你喜欢
    • 2015-01-30
    • 2017-05-05
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2016-01-25
    相关资源
    最近更新 更多