2016-06-18 6 views
4

Я ищу подстроку или несколько подстрок в dataframe из 4 миллионов строк.Как сделать pandas dataframe str.contains быстрее искать

df[df.col.str.contains('Donald',case=True,na=False)] 

или

df[df.col.str.contains('Donald|Trump|Dump',case=True,na=False)] 

DataFrame (ДФ) выглядит, как показано ниже (4 миллиона строк строк)

df = pd.DataFrame({'col': ["very definition of the American success story, continually setting the standards of excellence in business, real estate and entertainment.", 
         "The myriad vulgarities of Donald Trump—examples of which are retailed daily on Web sites and front pages these days—are not news to those of us who have", 
         "While a fearful nation watched the terrorists attack again, striking the cafés of Paris and the conference rooms of San Bernardino"]}) 

Есть ли наконечник, чтобы сделать эту строку поиска быстрее? Например, сначала сортировка данных, определенный способ индексирования, изменение имен столбцов на номера, сброс «na = False» из запроса и т. Д.? Даже миллисекунды увеличения скорости будут очень полезны!

ответ

3

Если число подстрок невелико, то, возможно, быстрее выполнить поиск по одному, поскольку вы можете передать аргумент regex=False в contains, что ускоряет его.

На образце DataFrame около 6000 строк, которые я тестировал на двух подстроках, blah.contains("foo", regex=False) | blah.contains("bar", regex=False) был примерно в два раза быстрее, чем blah.contains("foo|bar"). Вам нужно будет протестировать его своими данными, чтобы узнать, как он масштабируется.

2

Вы можете преобразовать его в список. Кажется, что поиск в списке, а не применение строковых методов к серии, значительно быстрее.

Пример кода:

import timeit 
df = pd.DataFrame({'col': ["very definition of the American success story, continually setting the standards of excellence in business, real estate and entertainment.", 
         "The myriad vulgarities of Donald Trump—examples of which are retailed daily on Web sites and front pages these days—are not news to those of us who have", 
         "While a fearful nation watched the terrorists attack again, striking the cafés of Paris and the conference rooms of San Bernardino"]}) 



def first_way(): 
    df["new"] = pd.Series(df["col"].str.contains('Donald',case=True,na=False)) 
    return None 
print "First_way: " 
%timeit for x in range(10): first_way() 
print df 

df = pd.DataFrame({'col': ["very definition of the American success story, continually setting the standards of excellence in business, real estate and entertainment.", 
         "The myriad vulgarities of Donald Trump—examples of which are retailed daily on Web sites and front pages these days—are not news to those of us who have", 
         "While a fearful nation watched the terrorists attack again, striking the cafés of Paris and the conference rooms of San Bernardino"]}) 


def second_way(): 
    listed = df["col"].tolist() 
    df["new"] = ["Donald" in n for n in listed] 
    return None 

print "Second way: " 
%timeit for x in range(10): second_way() 
print df 

Результаты:

First_way: 
100 loops, best of 3: 2.77 ms per loop 
               col new 
0 very definition of the American success story,... False 
1 The myriad vulgarities of Donald Trump—example... True 
2 While a fearful nation watched the terrorists ... False 
Second way: 
1000 loops, best of 3: 1.79 ms per loop 
               col new 
0 very definition of the American success story,... False 
1 The myriad vulgarities of Donald Trump—example... True 
2 While a fearful nation watched the terrorists ... False 
Смежные вопросы