python - Pandas:如何选择本月和最近两个月的值?
问题描述
我有一个包含以下列但没有 NaN 的多年财务预算数据的数据框:
Index
Dates (datetime) with data for each day of the month
Category (object) with several different names
Amount (float) in USD
我将如何声明“本月”值,然后过滤数据框以查找“本月”和“上个月”或“两个月”前之间的所有值?
解决方案
您可以使用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
推荐阅读
- elasticsearch - elasticsearch-certutil 创建的证书在生产中不可用?
- docker - 如何在 Alpine docker 容器中接收 UDP 消息?
- html - 为什么我使用 % 时背景图像会消失?
- python - 如何在 HTML 中呈现和显示来自 Django 的变量和值
- shell - 如何从一个新添加的列中的第一行更改值
- python - 在 Python 中规范化深度嵌套的 JSON 错误地产生数百列
- iphone - NotificationCenter addObserver forreachabilityChanged 不起作用
- python - 在python中生成一个随机句子
- flutter - 如何从另一个飞镖文件中获取对象
- python - multiprocessing.shared_memory 是否需要锁定?