Извлечение 2-граммовых строк из столбца, присутствующего в списке - PullRequest
2 голосов
/ 20 марта 2019

У меня есть датафрейм с именем df

Gender  Country      Comments
male    USA        machine learning and fraud detection are a must learn
male    Canada     monte carlo method is great and so is hmm,pca, svm and neural net
female  USA        clustering and cloud computing
female  Germany    logistical regression and data management and fraud detection
female  Nigeria    nltk and supervised machine learning
male    Ghana      financial engineering and cross validation and time series

и список алгоритмов

algorithms = ['machine learning','fraud detection', 'monte carlo method', 'time series', 'cross validation', 'supervised machine learning', 'logistical regression', 'nltk','clustering', 'data management','cloud computing','financial engineering']

Технически, для каждой строки столбца комментариев я пытаюсь извлечь слова, которые появляются в списке алгоритмов. Это то, чего я пытаюсь достичь

Gender  Country      algorithms
male    USA        machine learning, fraud detection 
male    Canada     monte carlo method, hmm,pca, svm, neural net
female  USA        clustering, cloud computing
female  Germany    logistical regression, data management, fraud detection
female  Nigeria    nltk, supervised machine learning
male    Ghana      financial engineering, cross validation, time series

Тем не менее, это то, что я получаю

Gender  Country      algorithms
male    USA         
male    Canada     hmm pca svm  
female  USA        clustering
female  Germany    
female  Nigeria    nltk
male    Ghana      

слова, такие как машинное обучение и обнаружение мошенничества, не отображаются. в основном все 2 грамма слова

Это код, который я использовал

df['algorithms'] = df['Comments'].apply(lambda x: " ".join(x for x in x.split() if x in algorithms)) 

Ответы [ 4 ]

2 голосов
/ 21 марта 2019

Вы можете pandas.Series.str.findall в сочетании с join.

import pandas as pd
import re

df['algo_new'] = df.algo.str.findall(f"({ '|'.join(ml) })")

>> out

    col1    gender  algo                                                algo_new
0   usa     male    machine learning and fraud detection are a mus...   [machine learning, fraud detection, clustering]
1   fr      female  monte carlo method is great and so is hmm,pca,...   [monte carlo method]
2   arg     male    logistical regression and data management and ...   [logistical regression, data management, fraud..

мы используем join, чтобы объединить ваши строки в списке ml и добавить | между каждой строкой для захвата значения 1 OR значение 2 и т. д. Затем мы используем findall, чтобы найти все вхождения.

Обратите внимание, что в нем используется f-строка, поэтому вам потребуется Python 3.6+,Дайте мне знать, если у вас более низкая версия python.


Для всех, кто интересуется тестами (поскольку у нас есть 3 ответа), используйте каждое решение с 9,6M строками и выполняйте каждое 10 раз подряд.дать нам следующие результаты:

  • AlexK:
    • означает: 14,94 с
    • мин: 12,43 с
    • макс: 17,08 с
  • Тедди:
    • означает: 22,67 с
    • мин: 18,25 с
    • макс: 27,64 с
  • AbsoluteSpace
    • означает: 24,12 с
    • мин: 21,25 с
    • макс: 27,53 с
0 голосов
/ 01 июля 2019

Flashtext также может быть использован для этого процесса для извлечения ключевых слов, будь то биграмма или любой ngram ...

import pandas as pd
from flashtext import KeywordProcessor
df=pd.DataFrame(data = [['male', 'USA', 'machine learning and fraud detection are a must learn'],
                  ['male', 'Canada','monte carlo method is great and so is hmm,pca, svm and neural net'],
                  ['female','USA','clustering and cloud'],
                  ['female','Germany', 'logistical regression and data management and fraud detection']] ,columns = ['Gender', 'Country','Comments'])


algorithms = ['machine learning','fraud detection', 'monte carlo method', 'time series', 'cross validation', 'supervised machine learning', 'logistical regression', 'nltk','clustering', 'data management','cloud computing','financial engineering']


 kp = KeywordProcessor()
 kp.add_keywords_from_list(algorithms)


df['algorithm'] = df['Comments'].apply(lambda x : kp.extract_keywords(x))

#o/p
df['algorithm']
Out[20]: 
0                  [machine learning, fraud detection]
1                                 [monte carlo method]
2                                         [clustering]
3    [logistical regression, data management, fraud...
Name: algorithm, dtype: object
0 голосов
/ 21 марта 2019

Другое возможное решение:

#function to convert Comments field into a list of terms found in Algorithms list
#it searches Comments field for occurrences of algorithm substrings
def make_algo_list(comment):
    algo_list = []
    for algo in algorithms:
        if algo in comment:
            algo_list.append(algo)
    return algo_list

#apply function to create new column
df['algorithms'] = df['Comments'].apply(lambda x: make_algo_list(x))
0 голосов
/ 21 марта 2019

Это может работать для вас:

def f(stringy):
    contained = filter((lambda x: x in stringy), algorithms)
    return ",".join(contained)

df['algorithms'] = df['Comments'].apply(f)

И вы можете перебрать все входные строки с этим.

...