python - Pandas 从系列中获取月末值
问题描述
我需要从一系列条目中获取月末余额。
样本数据:
date contrib totalShrs
0 2009-04-23 5220.00 10000.000
1 2009-04-24 10210.00 20000.000
2 2009-04-27 16710.00 30000.000
3 2009-04-30 22610.00 40000.000
4 2009-05-05 28909.00 50000.000
5 2009-05-20 38409.00 60000.000
6 2009-05-28 46508.00 70000.000
7 2009-05-29 56308.00 80000.000
8 2009-06-01 66108.00 90000.000
9 2009-06-02 78108.00 100000.000
10 2009-06-12 86606.00 110000.000
11 2009-08-03 95606.00 120000.000
输出看起来像这样:
2009-04-30 40000
2009-05-31 80000
2009-06-30 110000
2009-07-31 110000
2009-08-31 120000
有没有简单的熊猫方法?
我不明白如何使用 groupby 之类的东西来做到这一点?
还是我必须做类似 iterrows 的事情,找到所有每月条目,按日期排序并选择最后一个?
谢谢。
解决方案
使用Grouper
with ,通过withGroupBy.last
前向填充缺失值:ffill
Series.reset_index
#if necessary
#df['date'] = pd.to_datetime(df['date'])
df = df.groupby(pd.Grouper(freq='m',key='date'))['totalShrs'].last().ffill().reset_index()
#alternative
#df = df.resample('m',on='date')['totalShrs'].last().ffill().reset_index()
print (df)
date totalShrs
0 2009-04-30 40000.0
1 2009-05-31 80000.0
2 2009-06-30 110000.0
3 2009-07-31 110000.0
4 2009-08-31 120000.0
推荐阅读
- hashtable - ConvertFrom-StringData 值存储在变量中
- mysql - 一列字段如何引用来自两个不同表的 ID?
- clang-tidy - Clang-Tidy 检查别名是否重复相同的检查?
- jhipster - JHipster 使用 Angular 进行外部导航
- amazon-web-services - 最近有没有人处理过 AWS Rekognition 自定义标签?尝试分析通过 CLI(Windows 机器)创建的模型时收到错误
- excel - 使用 excel vba 自动填充 web 表中的列
- javascript - 收到来自 post 请求的 404 错误:邮递员
- python - Python:Reduce() 和函数作为函数的参数
- sql - 如何使用一对一选择两个关系表来创建视图,并用父值填充所有空值 - postgreSQL
- docker - 如何在 docker-machine 中使用本地镜像作为服务