gpt4 book ai didi

python - 如何使用 np.where 使用前面的行和公式创建新列?

转载 作者:行者123 更新时间:2023-12-04 22:17:59 27 4
gpt4 key购买 nike

这是我的问题的延续,或者与我最初的问题“如何使用 np.where 使用先前行创建新列?”有些相关。
我正在将一个 excel 文件转换为 python,因为 excel 无法再运行(或者运行数十万行需要一段时间)。这是我要转换的示例表。
Table from Excel
其中我将此公式运行到 C 列

=IF(B2="new",A2,C3+1)
A 列和 B 列是输入,C 列是输出。
如果 B2 等于"new",则可以导出 C 列,这将导致 A 列的值
如果不等于"new",它将导致上一个值(或下一个值)+1。
我尝试将 1 添加到建议的先前代码并产生不同的结果。这是代码。
df['Previous'] = np.where(df['Status']=='new', df['Count'], np.nan)    
df['Previous'] = df['Previous'].bfill().astype(int) +1
这个快照是我运行它时代码的结果。
Result 2
非常感谢。
特别提到@SeaBean 帮助我。

最佳答案

让我们用额外的 groupby带有 cumsum 的键

df['new'] = df.groupby(df.Status.eq('new').iloc[::-1].cumsum()).cumcount(ascending=False) + df.Count.where(df.Status.eq('new')).bfill()
df
Out[219]:
Count Status Previous new
0 4 old 4 4.0
1 3 old 3 3.0
2 2 old 2 2.0
3 1 new 1 1.0
4 40 old 13 13.0
5 30 old 12 12.0
6 20 old 11 11.0
7 10 new 10 10.0
8 400 old 103 103.0
9 300 old 102 102.0
10 200 old 101 101.0
11 100 new 100 100.0

关于python - 如何使用 np.where 使用前面的行和公式创建新列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67046353/

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