2016-01-28 3 views
1

У меня есть Dataframe, df с столбцом Account Number. Я пытаюсь бросить строки, где первые две буквы Счете 'AA' или 'BB'Выбрасывание строки Pandas на основе префикса значения в столбце

import pandas as pd 

df = pd.DataFrame(data=["AA121", "AB1212", "BB121"],columns=['Account']) 
print df 
df = df[df['Account Number'][2:] not in ['AA', 'BB']] 

Ошибка:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

ответ

2

Вы можете попробовать contains:

import pandas as pd 

df = pd.DataFrame(data=["AA121", "AB1212", "BB121"],columns=['Account']) 
print df 
    Account 
0 AA121 
1 AB1212 
2 BB121 

print df['Account'].str[:2] 
0 AA 
1 AB 
2 BB 
Name: Account, dtype: object 

print df['Account'].str[:2].str.contains('AA|BB') 
0  True 
1 False 
2  True 
Name: Account, dtype: bool 


df = df[~(df['Account'].str[:2].str.contains('AA|BB'))] 
print df 
    Account 
1 AB1212 

Или с startswith:

print ((df['Account'].str[:2].str.startswith('AA')) | 
     (df['Account'].str[:2].str.startswith('BB'))) 
0  True 
1 False 
2  True 
Name: Account, dtype: bool 

print ~((df['Account'].str[:2].str.startswith('AA')) | 
     (df['Account'].str[:2].str.startswith('BB'))) 
0 False 
1  True 
2 False 
Name: Account, dtype: bool 

df = df[~((df['Account'].str[:2].str.startswith('AA')) | 
      (df['Account'].str[:2].str.startswith('BB')))] 
print df 
    Account 
1 AB1212 
+0

Th anks. Что делать? – user2242044

+0

Он работает как 'not', инвертирует булевскую маску. – jonchar

+0

Я добавляю образец для '~' – jezrael

Смежные вопросы