gpt4 book ai didi

python - 通过其他列中的值高效替换值

转载 作者:行者123 更新时间:2023-11-28 20:40:16 25 4
gpt4 key购买 nike

如果一列中的值等于一个字符串,我将尝试用另一列替换该列。该字符串的值为“wo”。如果这出现在第 y 列中,请替换为第 x 列。目前我使用以下代码:

df.y.replace("wo",df.x) 

这会运行很长时间(数百万次观察,相当于几天的计算)。

有没有更高效的方法来替换?

以防万一,数据如下所示:

 y    x    other variables
1 mo something
2 2 something
3 3 something
wo >5 something
4 4 something
wo 7 something

它必须看起来像:

 y    x    other variables
1 mo something
2 2 something
3 3 something
>5 >5 something
4 4 something
7 7 something

最佳答案

试试这个:

df.loc[(df.y == 'wo'), 'y'] = df.x

它将首先只过滤那些 df.y == 'wo' 的行,并将 x 列的值分配给 'y' 列

时间报告:

In [304]: %timeit df.y.replace("wo",df.x)
100 loops, best of 3: 13.9 ms per loop

In [305]: %timeit df.loc[(df.y == 'wo'), 'y'] = df.x
100 loops, best of 3: 3.31 ms per loop

In [306]: %timeit df.ix[(df.y == 'wo'), 'y'] = df.x
100 loops, best of 3: 3.31 ms per loop

更新: 从 Pandas 0.20.1 开始 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers .

关于python - 通过其他列中的值高效替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36132973/

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