У меня есть фрейм данных pandas со столбцом.
id text_col
1 Was it Accurate?: Yes\n\nReasoning: This is a sample : text
2 Was it Accurate?: Yes\n\nReasoning: This is a :sample 2 text
3 Was it Accurate?: No\n\nReasoning: This is a sample: 1. text
Мне нужно разбить text_col на два столбца "Was it accurate?" и "Reasoning".
Окончательный фрейм данных должен выглядеть так:
id Was it Accurate? Reasoning
1 Yes This is a sample : text
2 Yes This is a :sample 2 text
3 No This is a sample: 1. text
Текстовые значения могут содержать несколько «двоеточий».
Я попытался разделить text_col с помощью «\n\nReasoning:», но не получил желаемого результата. Текст после второго двоеточия (:) отсутствует.
df[['Was it Accurate?', 'Reasoning']] = df['text_col'].str.extract(r'Was it Accurate\?: (Yes|No)\n\nReasoning: (.*)')
Редактировать:
Я применил эту функцию к столбцу LLM_response моего фрейма данных sample_100. и напечатал первую строку. если вы внимательно посмотрите, sample_100.iloc[0]['Reasoning'] удалил весь текст после:
Temp dict obj для проверки:
{'id_no': [8736215],
'Notes': [' Temp Notes Sample xxxxxxxxxxxxx [4/21/23, 2:10 PM] Work started -work complete-'],
'ProblemDescription': ['Sample problem description xxxxxxxxxxxxxxxxxxxxxxxx'],
'LLM_response': ['Accurate & Understandable: Yes\n\nReasoning: The Technician notes are accurate and understandable as:\n1) The technician provided detailed steps on how they addressed the mold issue by removing materials, treating surfaces, priming, and painting them.\n2) Additionally, even though there was non-repair related information (toilet repairs), the main issue of mold growth was addressed.\n3) The process described logically follows the process for remedying a mold issue, which aligns with the problem description.'],
'Accurate & Understandable': ['Yes'],
'Reasoning': ['The Technician notes are accurate and understandable as:']}
Можете ли вы предоставить результат df.to_dict('list')? Это хорошо работает для меня
попробуйте df['text_col'].str.extract(r'Was it Accurate\?: (Yes|No)\\n\\nReasoning: (.*)'): добавьте еще 1 обратную косую черту вместо \n
@mozway Я обновил вопрос, проверьте, пожалуйста. добавлен объект dict вывода после того, как я запустил ваш ответ.






один из способов справиться с этим может быть с помощью функции разделения.
# deal with the first column by splitting on '\n' and take the first value then split on ':' and take the second one
df['Was it Accurate ?'] = df.apply(lambda x:x.split('\n')[0].split(':')[1],axis=1)
# again split on '\n' then on ':' but put back the ':' if you have many colons in the text.
df['Reasoning'] = df.apply(lambda x: ':'.join(x.split('\n)[2].split(':')[1:]), axis = 1)
Проблема связана не с двоеточиями, а с символами новой строки в вашем примере текста. По умолчанию они не совпадают с .. Вам следует добавить флаг re.DOTALL.
Пример:
import re
import pandas as pd
df = pd.DataFrame({'id': [1, 2, 3],
'text_col': ['Was it Accurate?: Yes\n\nReasoning: This is a sample: text',
'Was it Accurate?: Yes\n\nReasoning: This is a sample:\n with newline',
'Was it Accurate?: No\n\nReasoning: This is a sample text']})
df[['Was it Accurate?', 'Reasoning']] = (df['text_col']
.str.extract(r'Was it Accurate\?: (Yes|No)\n\nReasoning: (.*)',
flags=re.DOTALL)
)
Выход:
id text_col Was it Accurate? Reasoning
0 1 Was it Accurate?: Yes\n\nReasoning: This is a sample: text Yes This is a sample: text
1 2 Was it Accurate?: Yes\n\nReasoning: This is a sample:\n with newline Yes This is a sample:\n with newline
2 3 Was it Accurate?: No\n\nReasoning: This is a sample text No This is a sample text
Меня устраивает.