gpt4 book ai didi

python - 乘以包含 NaN 的 Pandas 系列行

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:40 25 4
gpt4 key购买 nike

给出这个数据框:

import pandas as pd
import numpy as np

data = {'column1': [True,False, False, True, True],
'column2' : [np.nan,0.21, np.nan, 0.2222, np.nan],
'column3': [1000, 0, 0, 0, 0 ]}


df = pd.DataFrame.from_dict(data)

print(df)

   column1  column2  column3
0 True NaN 1000
1 False 0.2100 0
2 False NaN 0
3 True 0.2222 0
4 True NaN 0

column2 行不是 NaN 时,如何将 column2 的结果与 column3 的先前值相乘,否则只返回column3 的先前值 ?

结果应该是这样的:

   column1  column2  column3
0 True NaN 1000
1 False 0.2100 210
2 False NaN 210
3 True 0.2222 46.662
4 True NaN 46.662

我一直在浏览类似的问题,但我就是无法理解它..

非常感谢您的意见:)

最佳答案

你可以试一试:

#replace 0 with nan and create a copy of the df
m=df.assign(column3=df.column3.replace(0,np.nan))
#ffill on axis 1 where column2 is not null , and filter the last col then cumprod
final=(df.assign(column3=m.mask(m.column2.notna(),m.ffill(1)).iloc[:,-1].cumprod().ffill()))

   column1  column2   column3
0 True NaN 1000.000
1 False 0.2100 210.000
2 False NaN 210.000
3 True 0.2222 46.662
4 True NaN 46.662

关于python - 乘以包含 NaN 的 Pandas 系列行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57588604/

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