Допустим, у меня есть фрейм данных, назовем его A.
И у меня есть еще один Data Frame, назовем его B.
Я хотел бы найти способ динамически обновлять фрейм данных B, чтобы он проходил через каждое предложение b. и записывал A.Code, если он находит экземпляр A.Key_word. Если ключевое слово появляется в A более одного раза, я хотелось бы, чтобы он появлялся только один раз в B.Components_from_A. Если появляется несколько ключевых слов, я бы хотел, чтобы они были записаны как Код1+Код2+Код3.....
Я предполагаю, что я мог бы построить что-то вроде
import pandas as pd
import numpy as np
A=pd.read_csv('A.csv')
B=pd.read_csv('B.csv')
Dict=dict(zip(A.Key_Word,A.Code))
То, с чем я борюсь, - это динамическое обновление столбца в B и логика, которая мне понадобится, чтобы сделать это так, как я описал.






Вы можете сделать это, создав словарь кадра данных A и перебирая каждое предложение B. Проверьте, являются ли ключевые слова важными, и соберите информацию.
import pandas as pd
data_A = {'Key_Word': ['Market', 'Theater'], 'Code': ['A1', 'A2']}
data_B = {'Sentence': [
'John went to the theater',
'Mary went to the Market and then the theater',
'Jack decided to go to the theater now as opposed to going to the theater later'
]}
A = pd.DataFrame(data_A)
B = pd.DataFrame(data_B)
keyword_to_code = dict(zip(A.Key_Word, A.Code))
def update_components(sentence, keyword_to_code):
codes = set()
for keyword, code in keyword_to_code.items():
if keyword.lower() in sentence.lower():
codes.add(code)
return '+'.join(sorted(codes))
B['Components_from_A'] = B['Sentence'].apply(lambda x: update_components(x, keyword_to_code))
print(B)
что дает вам
Sentence Components_from_A
0 John went to the theater A2
1 Mary went to the Market and then the theater A1+A2
2 Jack decided to go to the theater now as oppos... A2
Вы можете создать регулярное выражение, извлечь все ключевые слова, объединить , чтобы получить совпадающие коды, наконец, drop_duulates , чтобы сохранить только уникальные коды в строке и groupby.agg, чтобы объединить коды в одну строку :
import re
# make the comparison case insensitive
A['Key_Word'] = A['Key_Word'].str.casefold()
# craft a regex
pattern = '(%s)' % '|'.join(map(re.escape, A['Key_Word']))
# '(Market|Theater)'
# extract keywords, match the codes, aggregate, assign to A
B['Components_from_A'] = (B['Sentence']
.str.casefold().str.extractall(pattern) # case insensitive extraction
.droplevel('match').reset_index(0) # keep index
.merge(A, left_on=0, right_on='Key_Word') # match codes
.drop_duplicates(['index', 'Code']) # keep unique codes per row
.groupby('index')['Code'].agg('+'.join) # aggregate as single string
)
Выход:
Sentence Components_from_A
0 John went to the theater A2
1 Mary went to the Market and then the theater A1+A2
2 Jack decided to go to the theater now as oppos... A2
Спасибо. Сэкономил мне часы утомительного труда