【问题标题】:Pandas: How to select values from this month and the last two months?Pandas:如何选择本月和最近两个月的值?
【发布时间】:2021-01-01 17:18:47
【问题描述】:

我有一个包含以下列但没有 NaN 的多年财务预算数据的数据框:

Index
Dates (datetime) with data for each day of the month
Category (object) with several different names
Amount (float) in USD

如何声明“本月”值,然后过滤数据框以查找“本月”和“上个月”或“两个月前”之间的所有值?

【问题讨论】:

  • 能否请您分享代码,以便我们复制您需要的内容?

标签: python pandas dataframe datetime timedelta


【解决方案1】:

您可以使用 datetime 模块中的 .today() 方法获取实际时间戳,然后应用 .month 将月份提取为“int”。您也可以使用 .month 进行过滤:

import datetime as dt

this_month = dt.datetime.today().month
two_months_ago = this_month - 2 if this_month - 2 > 0 else this_month - 2 + 12
filter = df['Dates'].dt.month == two_month_ago

【讨论】:

  • 谢谢,@kasper。但是 df['Dates'] 列是 datetime64[ns] 并且您推荐的所有内容都是整数。当我尝试:df2 = df[(df['Date'] >= two_months_ago) & (df['Date']
  • 尝试在过滤器中使用 .dt.month ,它也会产生整数。在您的示例中: df2 = df[(df['Date'].dt.month >= two_months_ago) & (df['Date'].dt.month
  • 这种工作,但问题是,如果我今天(1 月 23 日)运行代码,那么它只包括上个月到 12 月 23 日和两个月前到 11 月 23 日的数据。甚至虽然我使用整数 12 和 11 访问月份的数据,但它考虑了这一天。很困惑如何避免这种情况!
  • 意识到将日期列转换为日期时间时出现错误,但不知道如何解决:df['Date'] = df['Date'].apply(dateutil.parser.解析)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2014-11-19
  • 1970-01-01
  • 2022-11-10
  • 2015-01-28
  • 2016-12-28
  • 1970-01-01
相关资源
最近更新 更多