gpt4 book ai didi

python - 在数据框中选择每个月的特定日期数据

转载 作者:行者123 更新时间:2023-12-01 02:33:11 25 4
gpt4 key购买 nike

我有一个包含每日数据的数据框,已有 3 年多了。我想构建另一个包含每个月最后 5 天数据的数据框。在这种情况下,“日期”列的行(对于新构建的数据框):

2013-01-27
2013-01-28
2013-01-29
2013-01-30
2013-01-31
2013-02-23
2013-02-25
2013-02-26
2013-02-27
2013-02-28

有人可以告诉我如何做到这一点吗?

非常感谢!

最佳答案

一种方法是使用 bool 索引对 dt.daydt.days_in_month 进行操作:

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))

输出:

          Date     Value
26 2010-01-27 0.097695
27 2010-01-28 0.236572
28 2010-01-29 0.910922
29 2010-01-30 0.777657
30 2010-01-31 0.943031
54 2010-02-24 0.217144
55 2010-02-25 0.970090
56 2010-02-26 0.658967
57 2010-02-27 0.189376
58 2010-02-28 0.229299
85 2010-03-27 0.986992
86 2010-03-28 0.980633
87 2010-03-29 0.258102
88 2010-03-30 0.827310
89 2010-03-31 0.813219
115 2010-04-26 0.135519
116 2010-04-27 0.263941
117 2010-04-28 0.120624
118 2010-04-29 0.993652
119 2010-04-30 0.901466

关于python - 在数据框中选择每个月的特定日期数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46554930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com