在datafram中为每个月选择特定的日期数据

2024-04-23 19:01:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧和日常数据,超过3年。 我想构建另一个包含每个月最后5天的数据的数据帧。 在这种情况下,“date”列的行将是(对于新构造的数据帧):

2013年1月27日 2013年1月28日
2013年1月29日
2013年1月30日
2013年1月31日
2013年2月23日
2013年2月25日
2013年2月26日
2013年2月27日
2013年2月28日

有人能告诉我我怎么做到的吗?在

非常感谢!在


Tags: 数据date情况行将
2条回答

假设您的列名为Date。在

df.groupby([df.Date.dt.month,df.Date.dt.year]).apply(lambda x: x[-5:]).reset_index(drop=True).sort_values('Date')

一种方法是使用布尔索引dt.day和{}:

df = pd.DataFrame({'Date':pd.date_range('2010-01-01','2013-12-31',freq='D'),
                   'Value':np.random.rand(1461)})

df_out = df[df['Date'].dt.day > df['Date'].dt.days_in_month-5]

print(df_out.head(20))

输出:

^{pr2}$

相关问题 更多 >