gpt4 book ai didi

python-3.x - lambda pandas 数据框中的行减法

转载 作者:行者123 更新时间:2023-12-04 19:30:33 26 4
gpt4 key购买 nike

我有一个包含多列的数据框。其中一栏是累计收入栏。如果这一年没有结束,那么剩余时间里的收入将保持不变,因为接下来的每日收入为 0。

数据框看起来像这样

enter image description here

现在我想创建一个新列,其中该行被最后一行减去,如果结果为 0,则在新列中为该行打印 0。如果不为零,则使用行值。新的数据框应如下所示:

enter image description here

我的想法是使用 apply lambda 方法来做到这一点。所以这就是想法:

{df['2017new'] = df['2017'].apply(lambda x: 0 if row - lastrow == 0 else x)}

但我不知道如何编写代码的 row-lastrow 部分。这个怎么做?提前致谢!

最佳答案

通过使用np.where

df2['New']=np.where(df2['2017'].diff().eq(0),0,df2['2017'])
df2
Out[190]:
2016 2017 New
0 10 21 21
1 15 34 34
2 70 40 40
3 90 53 53
4 93 53 0
5 99 53 0

关于python-3.x - lambda pandas 数据框中的行减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46284644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com