2017-08-16 44 views
3

我試圖找到所有的值,這是一個比我習慣的更復雜的查詢。我將會潛在地改變數百萬個值的值,所以找到滿足這些條件的行的最有效方式,以及如何改變它們的值將是非常有用的。字符串匹配加上熊貓中的布爾值重新分配

我試圖做的是以下幾點:

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

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