gpt4 book ai didi

python - 将值乘以仅一半的行 python pandas

转载 作者:行者123 更新时间:2023-12-04 07:21:23 25 4
gpt4 key购买 nike

Pandas 1.1.4
雷:

mre_df = pd.DataFrame({"dates":["2021-05-01", "2021-05-02", "2021-05-03","2021-05-04"],
"click":[3,2,3,4],
"imps":[123,122,444,443]})
mre_df["dates"] = pd.to_datetime(mre_df["dates"], format="%Y-%m-%d")
mre_df.set_index("dates", inplace=True)
mre_df["ctr"] = mre_df["click"]/mre_df["imps"]
mre_df:
         click  imps    ctr
dates
2021-05-01 3 123 0.024390
2021-05-02 2 122 0.016393
2021-05-03 3 444 0.006757
2021-05-04 4 443 0.009029
我想将 ctr 乘以一个值,但是只有在“2021-05-02”进入新列之后。
这是我的看法,但我正在寻找更稳定、更干净、更有效的方法。
编辑:由于 HenryEcker,SettingWithCopyWarning 部分已被编辑
mre_df["rel_ctr"] = mre_df["ctr"]
mre_df.loc["2021-05-03":, "rel_ctr"] = mre_df.loc["2021-05-03":, "rel_ctr"] * 1.2
输出
          click imps    ctr     rel_ctr
dates
2021-05-01 3 123 0.024390 0.024390
2021-05-02 2 122 0.016393 0.016393
2021-05-03 3 444 0.006757 0.008108
2021-05-04 4 443 0.009029 0.010835

最佳答案

试试 Pandas where :

mre_df.assign(rle_ctr = mre_df.ctr.where(mre_df.index<="2021-05-02", 
mre_df.ctr*1.2)
)

click imps ctr rle_ctr
dates
2021-05-01 3 123 0.024390 0.024390
2021-05-02 2 122 0.016393 0.016393
2021-05-03 3 444 0.006757 0.008108
2021-05-04 4 443 0.009029 0.010835

关于python - 将值乘以仅一半的行 python pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68478453/

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