返回 pandas 中每个月的最后一个日期和值

Ale*_*lex 3 python python-3.x pandas

我在 pandas 中有一个包含每日数据的 df 。我想返回每个月的最后一个值。然而,我认为简单的解决方案是.resample("M").apply(lambda ser: ser.iloc[-1,]),似乎resample实际上计算了月结束日期,而不是返回该月出现的实际日期。这是有意的行为吗?微量元素:

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
Run Code Online (Sandbox Code Playgroud)

虽然最后出现的日期df2000-04-10

WeN*_*Ben 5

您可能需要查看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
Run Code Online (Sandbox Code Playgroud)