Как извлечь несколько ключевых слов по определенным описаниям - PullRequest
0 голосов
/ 28 января 2019

Вот мой набор данных

No   Description
1    Paying Google ads
2    Purchasing Facebook Ads
3    Purchasing Ads
4    AirBnB repayment

У меня есть txt файлы с именем entity.txt

0, Google
1, Facebook
2, Ads

Мне нужно обнаружить все ключевые слова на entity.txt в моем фрейме данных либотолько одно или несколько ключевых слов, и если ни одно ключевое слово не обнаружено, мы называем это Other, поэтому мое ожидание вывода:

No   Description                 Keyword
1    Paying Google ads           Google
2    Purchasing Facebook Ads     Facebook Ads
3    Purchasing LinkedIn Ads     LinkedIn Ads
4    AirBnB repayment            Other

Вот что я сделал

with open('entity.txt') as f: 
    content = f.readlines()
content = [x.strip() for x in content ]
df['keyword'] = df['description'].apply(lambda x: ' '.join([i for i in content if i in x]))
df['keyword'] = df['keyword'].replace('', 'Other')

Но результат

1018 *

Ответы [ 3 ]

0 голосов
/ 28 января 2019

Использование str.extract()

df['Keyword']=df.Description.str.extract(r'({})'.format('|'.join(df1[1],)))
print(df)

  No              Description    Keyword
0   1        Paying Google ads     Google
1   2  Purchasing Facebook Ads   Facebook
2   3  Purchasing LinkedIn Ads        Ads
3   4         AirBnB repayment        NaN
0 голосов
/ 28 января 2019

Используйте str.findall для извлечения всех значений из df1 в списки, затем преобразуйте пустые списки в Other, и все заполненные списки объединяются пробелом с str.join:

df1 = pd.DataFrame({'entity':['Google','Facebook','Ads']})

s = df['Description'].str.findall(r'({})'.format('|'.join(df1['entity'])))
df['Keyword'] = np.where(s.astype(bool), s.str.join(' '), 'Other')
print (df)

   No              Description       Keyword
0   1        Paying Google ads        Google
1   2  Purchasing Facebook Ads  Facebook Ads
2   3  Purchasing LinkedIn Ads           Ads
3   4         AirBnB repayment         Other

Ваше решение:

s = df['Description'].apply(lambda x: [i for i in set(df1['entity']) if i in x])
df['Keyword'] = np.where(s.astype(bool), s.str.join(' '), 'Other')
print (df)
   No              Description       Keyword
0   1        Paying Google ads        Google
1   2  Purchasing Facebook Ads  Facebook Ads
2   3  Purchasing LinkedIn Ads           Ads
3   4         AirBnB repayment         Other

Альтернатива:

out = []
for x in df['Description']:
    L = [i for i in set(df1['entity']) if i in x]
    if bool(L):
        out.append(' '.join(L))
    else:
        out.append('Other')
df['Keyword'] = out
print (df)
   No              Description       Keyword
0   1        Paying Google ads        Google
1   2  Purchasing Facebook Ads  Facebook Ads
2   3  Purchasing LinkedIn Ads           Ads
3   4         AirBnB repayment         Other
0 голосов
/ 28 января 2019

Использование findall

df.Description.str.findall(('|'.join(s.tolist()))).str[0]
0      Google
1    Facebook
2         Ads
3         NaN
Name: Description, dtype: object
df['Keyword']=df.Description.str.findall(('|'.join(s.tolist()))).str[0]

Ввод данных

s
0      Google
1    Facebook
2         Ads
Name: s, dtype: object
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...