python - Pandas 相当于 sql 的月份日期时间
问题描述
我有一个 pandas 数据框,我需要像特定月份的 sql 查询一样过滤它。每次我运行代码时,我都希望它从上个月获取数据,无论当月的具体日期是什么。
我的 SQL 代码在这里,但我需要 pandas 等价物。
WHERE DATEPART(m, logged) = DATEPART(m, DATEADD(m, -1, getdate()))
df = pd.DataFrame({'month': ['1-05-01 00:00:00','1-06-01 00:00:00','1-06-01 00:00:00','1-05-01 00:00:00']})
df['month'] = pd.to_datetime(df['month'])```
In this example, I only want the data from June.
Would definitely appreciate the help! Thanks.
解决方案
根据问题编辑修改:
df = pd.DataFrame({'month': ['1-05-01 00:00:00','1-06-01 00:00:00','1-06-01 00:00:00','1-05-01 00:00:00']})
df['month'] = pd.to_datetime(df['month'])
## To get it to the right format
import datetime as dt
df['month'] = df['month'].apply(lambda x: dt.datetime.strftime(x, '%Y-%d-%m'))
df['month'] = pd.to_datetime(df['month'])
## Extract the month from this date
df['month_ex'] = df.month.dt.month
## Get current month to get the latest month from the dataframe, which is the previous month of the current month
from datetime import datetime
currentMonth = datetime.now().month
newDf = df[df.month_ex == currentMonth - 1]
输出:
month month_ex
1 2001-06-01 6
2 2001-06-01 6
推荐阅读
- android - 将两个 LiveData 合并为一个 Android
- pandoc - 添加题为“我的出版物”的二级参考书目列表
- python - 读取二进制文件只打印零
- asp.net - 在 asp.net 中四舍五入价格
- java - 如何在android的sqlite查询中使用sqrt函数
- javascript - 为什么我的 React 代码没有显示在浏览器中?
- angular - CKeditor 5 Angular 11 与自定义插件的集成
- spring-boot - SpringBoot Rest Controller 使用 JAXB Pojos + 自定义 Http 消息转换器 + Swagger-UI 同时支持 xml 和 json
- python - 在排序期间使用多个字段进行键评估的pythonic方法是什么?
- git - 如何将外部 git 添加到正在运行的结构集合中