字符串匹配以及Pandas中的布尔值重新分配

时间:2017-08-16 15:16:13

标签: python pandas numpy

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

我要做的是以下内容:

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'

2 个答案:

答案 0 :(得分:2)

我们可以使用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

答案 1 :(得分:0)

你能不能只使用df.apply()

def get_new_a(x):
    if ('9' in x.a or '10' in x.a) and x.b == False:
        return '8'
    else:
        return x.a

example['a_2'] = example.apply(get_new_a, axis=1)

所以你的数据框变为:

    a      b   a_2
 0  9+  False   8