python - 在熊猫中返回每个月的最后日期和值
问题描述
我有一个带有每日数据的熊猫 df。我想返回每个月的最后一个值。但是,我认为简单的解决方案是.resample("M").apply(lambda ser: ser.iloc[-1,])
,似乎resample
实际上是在计算月末日期,而不是返回该月出现的实际日期。这是预期的行为吗?MWE:
import pandas as pd
import numpy as np
df = pd.Series(np.arange(100), index=pd.date_range(start="2000-01-02", periods=100)).to_frame()
df.sort_index().resample("M").apply(lambda ser: ser.iloc[-1,])
# 0
#2000-01-31 29
#2000-02-29 58
#2000-03-31 89
#2000-04-30 99
虽然最后出现的日期df
是2000-04-10
解决方案
您可能需要查看groupby
+tail
df.groupby(df.index.month).tail(1)
Out[18]:
0
2000-01-31 29
2000-02-29 58
2000-03-31 89
2000-04-10 99