我在 Pandas 中有一个每日数据的 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
关于python - 每个月在 Pandas 中返回最后一个日期和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51604967/