我正在使用 Python 2.7、PyCharm 和 Anaconda,
我有一个list
日期,我想检索数组中存在的每个月的最后一个日期。
有没有任何函数或库可以帮助我做到这一点?
我从 CSV 文件中读取日期并将其存储为datetime
.
我有以下代码:
Dates=[]
Dates1=[]
for date in dates:
temp=xlrd.xldate_as_tuple(int(date),0)
Dates1.append(datetime.datetime(temp[0],temp[1],temp[2]))
for date in Dates1:
if not (date<startDate or date>endDate):
Dates.append(date)
Run Code Online (Sandbox Code Playgroud)
为了说清楚,假设我有:
Dates = [2015-01-20, 2015-01-15, 2015-01-17, 2015-02-21, 2015-02-06]
Run Code Online (Sandbox Code Playgroud)
(考虑它是datetime
格式化的。)
我想要检索的列表是:
[2015-01-20, 2015-02-21]
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经用谷歌搜索过,尤其是在 Stack Overflow 中,但我只能找到如何获取每个月最后日期的答案,而不能从用户指定的列表中找到答案。
熊猫可以很好地完成这项任务。将 csv 加载到数据框,然后按月运行一组并使用聚合函数查找最大日期:
import pandas as pd
import numpy as np
df = pd.read_csv('/path/to/file/') # Load a dataframe with your file
df.index = df['my_date_field'] # set the dataframe index with your date
dfg = df.groupby(pd.TimeGrouper(freq='M')) # group by month / alternatively use MS for Month Start / referencing the previously created object
# Finally, find the max date in each month
dfg.agg({'my_date_field': np.max})
# To specifically coerce the results of the groupby to a list:
dfg.agg({'my_date_field': np.max})['my_date_field'].tolist()
Run Code Online (Sandbox Code Playgroud)