pandas 看起来period.to_timestamp()和asfreq(“D”)有不同的行为,将每月的时间段转换为每月的第一天和最后一天,为什么?

yuvru6vn  于 2024-01-04  发布在  其他
关注(0)|答案(1)|浏览(177)

这可能看起来像是一个迂腐的问题,但这不是它的精神。考虑下面的代码:

  1. import pandas as pd
  2. period=pd.Period("2020-03-15","M") #This object ignores the specific day
  3. print(period.asfreq("D")) #converts to last of month
  4. print(period.to_timestamp()) #converts to first of month

字符串
这打印了2020-03-31,然后打印了2017-03-01 00:00:00.为什么会有不同的行为?我问这个问题的原因是因为Pandas似乎会因为特定的原因而做出特定的选择,所以可能这个原因对Pandas中的时间戳和周期之间的差异有一些具体或概念上的理解。

9ceoxa92

9ceoxa921#

Period.to_timestamp中使用参数how表示月份的最后一天:

  1. period=pd.Period("2020-03-15","M") #This object ignores the specific day
  2. print(period.asfreq("D")) #converts to last of month
  3. 2020-03-31
  4. print(period.to_timestamp(how='E')) #converts to last of month
  5. 2020-03-31 23:59:59.999999999

字符串
如果需要删除次数,则表示设置为00:00:00使用Timestamp.normalize

  1. print(period.to_timestamp(how='E').normalize())
  2. 2020-03-31 00:00:00


差异的原因是Period.asfreqPeriod.to_timestamp中的默认参数不同:

  1. print(period.asfreq("D", how='E'))
  2. 2020-03-31
  3. #default 'E' (end)
  4. print(period.asfreq("D"))
  5. 2020-03-31
  1. print(period.to_timestamp(how='S').normalize())
  2. 2020-03-01 00:00:00
  3. #default 'S' (start)
  4. print(period.to_timestamp().normalize())
  5. 2020-03-01 00:00:00

的字符串

展开查看全部

相关问题