在 pandas 数据框中过滤和操作日期时间

Filtering and manipulating datetime in pandas dataframe

好的,伙计们,我想知道发生了什么事。我有一个从 MySQL.

中提取的 pandas dataframe

实际上这是我的查询语法:

query = "SELECT * FROM mywebsite.com WHERE date BETWEEN '2019-12-01' AND '2020-03-31'"

websitedata = pd.read_sql(query,con=engine)

然后我exported数据为CSV。现在今天 reading 来自 CSV 并尝试拆分 dates

chunks 中的数据
Dec2019 = df.loc[(df.date >= "2019-12-01") & (df.date <= "2019-12-31")]
Jan2020 = df.loc[(df.date >= "2020-01-01") & (df.date <= "2020-01-31")]
Feb2020 = df.loc[(df.date >= "2020-02-01") & (df.date <= "2020-02-29")]
Mar2020 = df.loc[(df.date >= "2020-03-01") & (df.date <= "2020-03-31")]


len(df) == len(Dec2019) + len(Jan2020) + len(Feb2020) + len(Mar2020) # gives me False

事实上 len(Dec2019) + len(Jan2020) + len(Feb2020) + len(Mar2020) 给出 376440

len(df)给出384274

如何预览框架以查看哪里出了问题?喜欢2019年12月,2020年1月,...,2020年3月,了解一下问题?

PS: 日期已经是pandas datetime

所以我找到了最有效的方法来做到这一点,它为我提供了没有日期泄漏的准确框架。

使用datetime dt accessor

Jan2020 = df[df.date.dt.month == 1]
Dec2019 = df[df.date.dt.month == 12]
Feb2020 = df[df.date.dt.month == 2]
Mar2020 = df[df.date.dt.month == 3]

事实上现在这样 returns True

len(df) == len(Dec2019) + len(Jan2020) + len(Feb2020) + len(Mar2020)

来源:How to filter a dataframe of dates by a particular month/day?