【发布时间】:2017-03-02 03:15:22
【问题描述】:
我有一个没有每个日期(即交易日期)的时间序列。系列可以在这里复制。
dates=pd.Series(np.random.randint(100,size=30),index=pd.to_datetime(['2010-01-04', '2010-01-05', '2010-01-06', '2010-01-07',
'2010-01-08', '2010-01-11', '2010-01-12', '2010-01-13',
'2010-01-14', '2010-01-15', '2010-01-19', '2010-01-20',
'2010-01-21', '2010-01-22', '2010-01-25', '2010-01-26',
'2010-01-27', '2010-01-28', '2010-01-29', '2010-02-01',
'2010-02-02', '2010-02-03', '2010-02-04', '2010-02-05',
'2010-02-08', '2010-02-09', '2010-02-10', '2010-02-11',
'2010-02-12', '2010-02-16']))
我想在我的日期列表中显示该月的最后一天,即:“2010-01-29”和“2010-02-16”
我看过Get the last date of each month in a list of dates in Python
更具体地说...
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()
...但不能完全弄清楚如何使其适应我的应用程序。提前致谢。
【问题讨论】:
-
dates.groupby(dates.index.month).apply(pd.Series.tail,1)怎么样? -
dfg = data.groupby(pd.TimeGrouper(freq='M')).max() 在您的数据上返回包含两行的数据框 - 2010-01-31、2010-02-28