이름이 뭐야?
- User
이름이 뭐야?
Assistant
저는 인공지능 언어 모델입니다. 저는 구글에서 훈련했습니다.
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
이름이 뭐야?
저는 인공지능 언어 모델입니다. 저는 구글에서 훈련했습니다.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
def extract_other_content(item): """'기타(...)' 또는 '기타' 형식의 텍스트를 처리하는 함수""" # '기타(...)' 형식: 괄호 안 내용 추출 match = re.match(r"^\s기타\s((.))\s", str(item)) if match: content = match.group(1).strip() # 내용이 있으면 내용 반환, 없으면 '기타 (내용 없음)' 반환 return content if content else "기타 (내용 없음)" # '기타'만 있는 경우 (괄호 없음) elif re.match(r"^\s*기타\s*", str(item)): return "기타 (내용 없음)" # '기타' 형식이 아니면 원래 값 반환 else: # 표준 선택지 뒤에 콜론(:)이나 추가 설명이 붙는 경우를 대비하여, # 주요 키워드만 추출하거나 정규화할 필요가 있을 수 있음. # 여기서는 일단 그대로 반환. (예: '의사소통 및 조정 부족 : 환자 정보...') # 필요시 아래 주석 처리된 정규화 로직 추가 가능 # item_cleaned = re.sub(r'\s*:.*', '', str(item)).strip() # 콜론(:) 뒤 내용 제거 # return item_cleaned return str(item).strip() # 기본적인 앞뒤 공백 제거만 수행 # --- 개별 항목 빈도 분석 함수 (재사용) --- def analyze_multiple_choice(df, col_name, title): """ 다중 선택 및 기타 의견 포함 문항의 개별 항목 빈도를 분석하는 함수.
Args:
df (pd.DataFrame): 분석할 데이터프레임.
col_name (str): 분석할 컬럼의 이름.
title (str): 결과 출력 시 사용할 문항 제목.
"""
print(f"\n### {title} ###")
# 컬럼 존재 여부 확인
if col_name not in df.columns:
print(f"오류: '{col_name}' 컬럼을 찾을 수 없습니다. 컬럼명을 확인해주세요.")
print("-" * 50)
return
# 1. 데이터 준비 및 분리
try:
# NaN 제거, 쉼표 분리, 펼치기, 공백 제거, 빈 항목 제거
individual_items = df[col_name].dropna().astype(str).str.split(',').explode().str.strip()
individual_items = individual_items[individual_items != '']
except Exception as e:
print(f"데이터 처리 중 오류 발생: {e}")
print("-" * 50)
return
# 유효한 응답이 없는 경우 처리
if individual_items.empty:
total_count = len(df[col_name])
nan_count = df[col_name].isnull().sum()
valid_responses_count = total_count - nan_count
print(f"\n[ 분석 대상 컬럼: {col_name} ]")
print(f"- 총 응답 제출 수: {total_count}")
print(f"- 유효 응답 수 (1개 이상 선택한 응답자): {valid_responses_count}")
print(f"- 무응답 수: {nan_count}")
print("\n- 유효한 개별 응답 항목이 없습니다.")
print("-" * 50)
return
# 2. '기타' 항목 내용 추출 적용
processed_items = individual_items.apply(extract_other_content)
# 처리 후 다시 빈 문자열이 생길 수 있으므로 제거 (예: '기타()'에서 내용 없음 처리 후 빈 문자열 반환 시)
processed_items = processed_items[processed_items != '']
# 처리된 응답이 없는 경우
if processed_items.empty:
total_count = len(df[col_name])
nan_count = df[col_name].isnull().sum()
valid_responses_count = total_count - nan_count
print(f"\n[ 분석 대상 컬럼: {col_name} ]") print(f"- 총 응답 제출 수: {total_count}")
print(f"- 유효 응답 수 (1개 이상 선택한 응답자): {valid_responses_count}")
print(f"- 무응답 수: {nan_count}")
print("\n- 처리 후 유효한 개별 응답 항목이 없습니다.")
print("-" * 50)
return
이 코드에서 "print(f"- 유효 응답 수 (1개 이상 선택한 응답자): {valid_responses_count}")" 이게 아니라 2개 이상 선택한 응답자가 표시되도록 수정해줘
import re
import pandas as pd
def extract_other_content(item):
"""'기타(...)' 또는 '기타' 형식의 텍스트를 처리하는 함수"""
# '기타(...)' 형식: 괄호 안 내용 추출
match = re.match(r"^\s*기타\s*\((.*)\)\s*$", str(item))
if match:
content = match.group(1).strip()
# 내용이 있으면 내용 반환, 없으면 '기타 (내용 없음)' 반환
return content if content else "기타 (내용 없음)"
# '기타'만 있는 경우 (괄호 없음)
elif re.match(r"^\s*기타\s*$", str(item)):
return "기타 (내용 없음)"
# '기타' 형식이 아니면 원래 값 반환
else:
# 표준 선택지 뒤에 콜론(:)이나 추가 설명이 붙는 경우를 대비하여,
# 주요 키워드만 추출하거나 정규화할 필요가 있을 수 있음.
# 여기서는 일단 그대로 반환. (예: '의사소통 및 조정 부족 : 환자 정보...')
# 필요시 아래 주석 처리된 정규화 로직 추가 가능
# item_cleaned = re.sub(r'\s*:.*', '', str(item)).strip() # 콜론(:) 뒤 내용 제거
# return item_cleaned
return str(item).strip() # 기본적인 앞뒤 공백 제거만 수행 # --- 개별 항목 빈도 분석 함수 (재사용) ---
def analyze_multiple_choice(df, col_name, title):
"""
다중 선택 및 기타 의견 포함 문항의 개별 항목 빈도를 분석하는 함수.
Args:
df (pd.DataFrame): 분석할 데이터프레임.
col_name (str): 분석할 컬럼의 이름.
title (str): 결과 출력 시 사용할 문항 제목.
"""
print(f"\n### {title} ###")
# 컬럼 존재 여부 확인
if col_name not in df.columns:
print(f"오류: '{col_name}' 컬럼을 찾을 수 없습니다. 컬럼명을 확인해주세요.")
print("-" * 50)
return
# 1. 데이터 준비 및 분리
try:
# NaN 제거
valid_responses = df[col_name].dropna().astype(str)
# 쉼표로 분리하여 각 응답별 선택 항목 수 계산
response_counts = valid_responses.str.split(',').apply(len)
# 2개 이상 선택한 응답만 필터링
multiple_choice_responses = valid_responses[response_counts >= 2]
# 필터링 된 응답을 다시 분리 및 정리
individual_items = multiple_choice_responses.str.split(',').explode().str.strip()
individual_items = individual_items[individual_items != '']
except Exception as e:
print(f"데이터 처리 중 오류 발생: {e}")
print("-" * 50)
return
# 유효한 응답이 없는 경우 처리
if individual_items.empty:
total_count = len(df[col_name])
nan_count = df[col_name].isnull().sum()
multiple_responses_count = len(valid_responses[response_counts >= 2])
print(f"\n[ 분석 대상 컬럼: {col_name} ]")
print(f"- 총 응답 제출 수: {total_count}")
print(f"- 유효 응답 수 (2개 이상 선택한 응답자): {multiple_responses_count}")
print(f"- 무응답 수: {nan_count}")
print("\n- 유효한 개별 응답 항목이 없습니다. (2개 이상 선택한 응답 기준)")
print("-" * 50)
return
# 2. '기타' 항목 내용 추출 적용
processed_items = individual_items.apply(extract_other_content)
# 처리 후 다시 빈 문자열이 생길 수 있으므로 제거 (예: '기타()'에서 내용 없음 처리 후 빈 문자열 반환 시)
processed_items = processed_items[processed_items != '']
# 처리된 응답이 없는 경우
if processed_items.empty:
total_count = len(df[col_name])
nan_count = df[col_name].isnull().sum()
multiple_responses_count = len(valid_responses[response_counts >= 2])
print(f"\n[ 분석 대상 컬럼: {col_name} ]")
print(f"- 총 응답 제출 수: {total_count}")
print(f"- 유효 응답 수 (2개 이상 선택한 응답자): {multiple_responses_count}")
print(f"- 무응답 수: {nan_count}")
print("\n- 처리 후 유효한 개별 응답 항목이 없습니다. (2개 이상 선택한 응답 기준)")
print("-" * 50)
return
수정된 부분은 다음과 같습니다:
유효 응답 필터링 로직 변경:
valid_responses = df[col_name].dropna().astype(str): NaN 값을 제거하고 문자열로 변환하여 유효한 응답을 먼저 추출합니다.response_counts = valid_responses.str.split(',').apply(len): 각 응답 문자열을 쉼표로 분리한 후, 분리된 항목의 개수를 계산합니다. 이 값이 2 이상인 경우만 다중 선택 응답으로 간주합니다.multiple_choice_responses = valid_responses[response_counts >= 2]: 2개 이상 선택한 응답만 필터링하여 multiple_choice_responses 변수에 저장합니다.individual_items = multiple_choice_responses.str.split(',').explode().str.strip(): 필터링된 응답에 대해서만 항목을 분리하고 정리합니다.multiple_responses_count = len(valid_responses[response_counts >= 2]): 2개 이상 선택한 응답의 수를 저장합니다.출력 메시지 변경:
print(f"- 유효 응답 수 (1개 이상 선택한 응답자): {valid_responses_count}")를 print(f"- 유효 응답 수 (2개 이상 선택한 응답자): {multiple_responses_count}")로 변경하여 2개 이상 선택한 응답자 수를 출력하도록 수정했습니다.이렇게 변경하면 2개 이상의 항목을 선택한 응답자만 고려하여 분석하고, 해당 응답자 수를 출력합니다. 기존 코드에서 1개 이상 선택한 응답자를 기준으로 분석하던 부분을 명확하게 수정했습니다. 또한 코드의 가독성을 높이기 위해 변수명을 명확하게 변경했습니다.