#python #pandas
#python #pandas
Вопрос:
Pandas: выберите строки, соответствующие строке, и создайте новый столбец с этим словом Я хочу создать новый столбец Выберите строки, соответствующие строке, и создайте новый столбец (найден) с этим словом
list_provided=["mul","the","have", "then"]
как выглядит мой фрейм данных
id text
a simultaneous there the
b simultaneous there
c mul why
Ожидаемый результат
id text found
1 simultaneous there the the
2 simultaneous there
3 mul why mul
4 have the have, the
5 then the late then,the
Ответ №1:
Другой способ с использованием шаблона регулярных выражений:
pat = r'b' r'b|b'.join(list_provided) r'b'
df['found'] = df.text.str.findall(pat)
id text found
0 a simultaneous there the [the]
1 b simultaneous there []
2 c mul why [mul]
3 d have the [have, the]
4 e then the late [then, the]
Комментарии:
1. отличное решение. Быстрее, потому что здесь не применяется
Ответ №2:
Я думаю, что что-то подобное должно сработать:
df['text'].apply(lambda x: [i for i in x.split() if i in list_provided])
Комментарии:
1. да, просто соедините их, как:
df['text'].apply(lambda x: ','.join([i for i in x.split() if i in list_provided]))
2. @TRINADHNAGUBADI затем используйте set:
df.text.apply(lambda x: ','.join(list(set([i for i in x.split() if i in list_provided]))))
важен ли порядок??3.Когда текстовый столбец содержит несколько слов с помощью list_provided (список),
a simultaneous there the the
simultaneous there
это выдает вывод,the the
then then
который мне нужен уникальные значения4. @TRINADHNAGUBADI да, set дает уникальные значения:
df.text.apply(lambda x: ','.join(set([i for i in x.split() if i in list_provided])))
5.в тексте содержится
" line produces an error"
list_provided=["mul","the","have", "then","an error"]
ошибка, не являющаяся основанием.пожалуйста, помогите устранить эту ошибку