gpt4 book ai didi

python - 当为另一列指定一个条件时如何填充前向值?

转载 作者:太空宇宙 更新时间:2023-11-03 20:50:03 27 4
gpt4 key购买 nike

我正在分析如下一张表。 offer_id 中有几个 None 值当事件列显示 transaction 时的列。仅当前一个事件是 offer viewed 时,我才会通过值forward 填充 None ,否则,将 None 值填充为 0 或将其保留为 none。

数据框是:

df = pd.DataFrame({'event': ['offer_received', 'offer_viewed','transaction', 'transaction', 'offer_received', 'transaction'], 'user':['A','A','A','A','A','A'], 'value':[0, 0, 1.09, 2.55, 0, 3.02], 'offer_id': ['0b1e1539f2cc45b7b9fa7c272da2e1d7', '0b1e1539f2cc45b7b9fa7c272da2e1d7', 'None', 'None', '3f207df678b143eea3cee63160fa8bed', 'None'], 'days':[0, 0.25, 9.75, 11, 0,9.75]})
event           user   value    offer_id                            days
offer received A 0.00 0b1e1539f2cc45b7b9fa7c272da2e1d7 0.00
offer viewed A 0.00 0b1e1539f2cc45b7b9fa7c272da2e1d7 0.25
transaction A 1.09 None 9.75
transaction A 2.55 None 11
offer received A 0.00 3f207df678b143eea3cee63160fa8bed 0.00
transaction A 3,02 None 9.75

我尝试使用df.offer_id.fillna(method = 'ffill')但我只是不知道当上一个事件是 offer_viewed 时如何将条件放在事件列上然后填写offer_idtransaction通过使用(method = 'ffill') .

我的预期结果是这样的:

event           user   value    offer_id                            days
offer received A 0.00 0b1e1539f2cc45b7b9fa7c272da2e1d7 0.00
offer viewed A 0.00 0b1e1539f2cc45b7b9fa7c272da2e1d7 0.2
transaction A 1.09 0b1e1539f2cc45b7b9fa7c272da2e1d7 9.75
transaction A 2.55 0b1e1539f2cc45b7b9fa7c272da2e1d7 11
offer received A 0.00 3f207df678b143eea3cee63160fa8bed 0.00
transaction A 3,02 None 9.75

最佳答案

我认为你可以使用 shift()ffill()where() 来实现:

df = pd.DataFrame({'e': ['r', 'v', 't', 'r', 't'], 'oid': [1, 1, np.nan, 2, np.nan]})
df
# e oid
# 0 r 1.0
# 1 v 1.0
# 2 t NaN
# 3 r 2.0
# 4 t NaN
df.oid = df.oid.ffill().where(df.e.shift() == 'v', df.oid)
df
# e oid
# 0 r 1.0
# 1 v 1.0
# 2 t 1.0
# 3 r 2.0
# 4 t NaN

您甚至可以跳过 ffill() 并使用 shift() 两次:

df = pd.DataFrame({'e': ['r', 'v', 't', 'r', 't'], 'oid': [1, 1, np.nan, 2, np.nan]})

df.oid = df.oid.shift().where(df.e.shift() == 'v', df.oid)
df
# e oid
# 0 r 1.0
# 1 v 1.0
# 2 t 1.0
# 3 r 2.0
# 4 t NaN

关于python - 当为另一列指定一个条件时如何填充前向值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56327292/

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