我正在使用 Python 2.7、PyCharm 和 Anaconda,
我有一个日期列表
,我想检索数组中每个月的最后一个日期。
是否有任何函数或库可以帮助我做到这一点?
我从 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)
为了清楚起见,假设我有:
Dates = [2015-01-20, 2015-01-15, 2015-01-17, 2015-02-21, 2015-02-06]
(假设它是 datetime
格式。)
我要检索的列表是:
[2015-01-20, 2015-02-21]
到目前为止,我已经四处搜索,尤其是在 Stack Overflow 中,但我只能找到有关如何获取每个月的最后日期的答案,而不是从用户指定的列表中找到答案。
最佳答案
Pandas可以很好地完成这项任务。将您的 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()
关于python - 在 Python 的日期列表中获取每个月的最后一个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32612150/