python - 根据最后一行获取新值并检查 ID
问题描述
当前日期范围。
ID Date Start Value Payment
111 1/1/2018 1000 0
111 1/2/2018 100
111 1/3/2018 500
111 1/4/2018 400
111 1/5/2018 0
222 4/1/2018 2000 200
222 4/2/2018 100
222 4/3/2018 700
222 4/4/2018 0
222 4/5/2018 0
222 4/6/2018 1000
222 4/7/2018 0
这是我想要得到的数据框。基本上,我正在尝试为每一行填充星值。如您所见,每个 ID 在第一天都有一个起始值。第二天的起始值=最后一天的起始值-最后一天的付款。
ID Date Start Value Payment
111 1/1/2018 1000 0
111 1/2/2018 1000 100
111 1/3/2018 900 500
111 1/4/2018 400 400
111 1/5/2018 0 0
222 4/1/2018 2000 200
222 4/2/2018 1800 100
222 4/3/2018 1700 700
222 4/4/2018 1000 0
222 4/5/2018 1000 0
222 4/6/2018 1000 1000
222 4/7/2018 0 0
现在,我使用 Excel 和这个公式。起始值 = if(本行 ID == 最后一行 ID,最后一行起始值 - 最后一行付款,起始值)
它运作良好,我想知道我是否可以在 Python/Pandas 中做到这一点。谢谢你。
解决方案
我们可以使用groupby
and shift
+ cumsum
,ffill
将为同一 Id 下的所有行设置初始值,然后我们只需要从该行中扣除累积付款直到开始 ,我们得到该点的剩余值
df.StartValue.fillna(df.groupby('ID').apply(lambda x : x['StartValue'].ffill()-x['Payment'].shift().cumsum()).reset_index(level=0,drop=True))
Out[61]:
0 1000.0
1 1000.0
2 900.0
3 400.0
4 0.0
5 2000.0
6 1800.0
7 1700.0
8 1000.0
9 1000.0
10 1000.0
11 0.0
Name: StartValue, dtype: float64
通过添加将其分配回来inplace=Ture
df.StartValue.fillna(df.groupby('ID').apply(lambda x : x['StartValue'].ffill()-x['Payment'].shift().cumsum()).reset_index(level=0,drop=True),inplace=True)
df
Out[63]:
ID Date StartValue Payment
0 111 1/1/2018 1000.0 0
1 111 1/2/2018 1000.0 100
2 111 1/3/2018 900.0 500
3 111 1/4/2018 400.0 400
4 111 1/5/2018 0.0 0
5 222 4/1/2018 2000.0 200
6 222 4/2/2018 1800.0 100
7 222 4/3/2018 1700.0 700
8 222 4/4/2018 1000.0 0
9 222 4/5/2018 1000.0 0
10 222 4/6/2018 1000.0 1000
11 222 4/7/2018 0.0 0
推荐阅读
- python - 为什么我的烧瓶应用程序没有连接到正确的房间
- javascript - 如何在具有可点击下拉菜单的反应中制作带有标签的文本区域
- javascript - 如何在 gtm 自定义模板中读取特定的 dataLayer obj
- python - 字符串索引超出范围,解决方案工作正常
- php - 将 Elixir 加密和解密逻辑映射到 PHP,反之亦然
- sql - 在表中查找所有父母或孩子
- java - 使用spring数据进行mongodb junit测试
- flutter - 如何更改 ButtonStyle 中 onPrimary 的不透明度?
- java - Java计算列表中的出现次数并在更新字数时从结构中删除添加/重复项
- npm - 为什么我可以使用 npm i tailwindcss@npm:@tailwindcss/postcss7-compat 而我只能使用 npm i tailwind?