【问题标题】:how to optimize these pandas apply functions?如何优化这些 pandas 应用功能?
【发布时间】:2021-07-03 15:44:31
【问题描述】:
train["gender"] = train.apply(lambda x: 1 if x["gender"] == "F" else 0, axis=1) 
train["car"] = train.apply(lambda x: 1 if x["car"] == "Y" else 0, axis=1) 
train["reality"] = train.apply(lambda x: 1 if x["reality"] == "Y" else 0, axis=1) 

这3个代码即使是简单的更改也需要很多时间。
我想,访问每一行 3 次会导致效率低下。 所以,如果我可以 1 访问行并应用函数更改 3 数据,它可以比现在快 2~3 倍。

喜欢.....

# it is my imaginary code. not works
train[["gender","car", "reality"]] =  train.apply(lambda x: 1 if x["gender"] == "F" else 0, axis=1,
                                                  lambda y: 1 if y["car"] == "Y" else 0, axis=1,
                                                  lambda z: 1 if z["reality"] == "Y" else 0, axis=1) 

如何优化这些代码?

============================ tdy的测试结果

【问题讨论】:

    标签: pandas lambda apply


    【解决方案1】:

    您可以尝试 3x np.where()generally the fastest option

    train['gender'] = np.where(train.gender == 'F', 1, 0)
    train['car'] = np.where(train.car == 'Y', 1, 0)
    train['reality'] = np.where(train.reality == 'Y', 1, 0)
    

    或 2x np.where() 稍慢:

    train['gender'] = np.where(train.gender == 'F', 1, 0)
    train[['car', 'reality']] = np.where(train[['car', 'reality']] == 'Y', 1, 0)
    

    1000 万行的时序:

    method %timeit
    3x np.where() 152 ms ± 8.86 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    2x np.where() 198 ms ± 39.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    3x apply() 8.91 s ± 495 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

    【讨论】:

    • 哦,我会试试这个。但我认为这个解决方案也有同样的问题。每行访问 3 次
    • @LaserCho 我编辑了答案以结合carreality。由于gender 的条件不同,我不知道有什么方法可以同时包含所有 3 个。
    • 非常有趣。您的原始答案“np.where 3 times”是最快的。第二个是当前答案。我原来的 3 次申请是最慢的。最快的方式比第二快将近 16 倍。第二个当前答案比我的代码快 35 倍。
    • @LaserCho 我添加了另一个选项来一次性完成所有操作,但我不确定它是否真的更快。
    • 从头开始,其中的一些错误我还没有弄清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多