假设我有一个开始日期和结束日期,如下所示:
start_d = datetime.date(2017, 7, 20)
end_d = datetime.date(2017, 9, 10)
我希望获得一个如下所示的 Pandas DataFrame:
Month NumDays
2017-07 12
2017-08 31
2017-09 10
它显示了我的范围内每个月的天数。
到目前为止,我可以生成每月系列pd.date_range(start_d, end_d, freq='MS')
.
您可以使用date_range http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html默认情况下day
先频率,再创建Series
and resample http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.resample.html with size http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.resample.Resampler.size.html。最后转换为month
期间由to_period http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.to_period.html:
import datetime as dt
start_d = dt.date(2017, 7, 20)
end_d = dt.date(2017, 9, 10)
s = pd.Series(index=pd.date_range(start_d, end_d), dtype='float64')
df = s.resample('MS').size().rename_axis('Month').reset_index(name='NumDays')
df['Month'] = df['Month'].dt.to_period('m')
print (df)
Month NumDays
0 2017-07 12
1 2017-08 31
2 2017-09 10
谢谢Zero https://stackoverflow.com/questions/46319852/pandas-monthly-date-range-with-number-of-days/46319991?noredirect=1#comment79600857_46319991为了简化解决方案:
df = s.resample('MS').size().to_period('m').rename_axis('Month').reset_index(name='NumDays')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)