python - 每个月在 Pandas 中返回最后一个日期和值

标签 python python-3.x pandas

我在 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/

相关文章:

python - 在Python(Pandas)中,如何生成这样的分类值的交叉表?

python - 为什么我的代码不根据字典解码加密字符串?

python - 在Python3中逐一读取列表的元素

python - 将日期时间戳转换为本地纪元日期时间

python-3.x - 模拟具有不同返回值的相同方法

python - 分组 Pandas : incompatible index of inserted column with frame index

Python 负二项式回归 - 结果与 R 中的结果不匹配

python - 无法从网页中抓取标题

python - 如何使用书签运行 python?

python - pandas 数据帧中的时间戳