gpt4 book ai didi

python - Pandas 中的字符串匹配和 bool 值重新分配

转载 作者:行者123 更新时间:2023-11-28 17:13:34 25 4
gpt4 key购买 nike

我正在尝试查找所有值,这是一个比我以前更复杂的查询。我可能会更改数百万个值的值,因此找到满足这些条件的行的最有效方法以及如何更改它们的值将非常有帮助。

我想做的是:

import pandas as pd

example = pd.DataFrame({'a': ['9+'],
'b': [False]})

# If example['a'] contains a '9' or a '10' AND example['b'] is 'False' then change example['a'] to '8'

最佳答案

我们可以使用Pandas boolean indexing :

In [126]: example
Out[126]:
a b
0 9+ False
1 10- False
2 9 True
3 1 True
4 2 False

In [127]: example.loc[example['a'].str.contains('9|10') & ~example['b'], 'a'] = '8'

In [128]: example
Out[128]:
a b
0 8 False
1 8 False
2 9 True
3 1 True
4 2 False

关于python - Pandas 中的字符串匹配和 bool 值重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45717328/

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