파이썬

Python3. 설문조사를 위한 데이터 수집 및 전처리

dltmfdltmf 2025. 2. 18. 23:30

설문조사를 통한 데이터 활용

: 그로스마케팅(Growth Marketing)에서는 고객의 구매 행동, 제품 인식, 마케팅 캠페인 효과 등을 분석하기 위해 설문조사를 활용할 수 있음

 

목적

  • 고객 페르소나 구축: 고객의 연령, 성별, 직업, 관심사 등 파악
  • 제품/서비스 만족도 조사: 고객이 제품을 어떻게 평가하는지 조사
  • 광고/캠페인 효과 분석: 특정 광고나 마케팅 캠페인이 효과가 있었는지 평가
  • 구매 의사결정 과정 분석: 고객이 제품을 구매하기까지 어떤 요인이 영향을 미쳤는지 확인
  • NPS(Net Promoter Score) 분석: 고객의 브랜드 추천 의향 평가

 

survey process

  1. 설문 기획(대상)
  2. 설계(질문)
  3. 배포(응답)
  4. 엑셀로 정리
  5. CSV로 추출
  6. pandas로 분석

 

설문결과 분석 e.g.

  • 응답자 수 확인: df[ ].value_counts()
  • 평균 값 계산: df[ ].mean()
  • 상관관계 계산: df[ ].corr()
  • 비율 계산: df[ ].value_counts(narmalize = True) * 100

 

※ 참고 코드

import pandas as pd

# 예제 설문 데이터 생성
data = {
    "연령대": ["20대", "30대", "40대", "20대", "50대"],
    "성별": ["남성", "여성", "여성", "남성", "남성"],
    "광고_시청": ["예", "예", "아니오", "예", "예"],
    "광고_채널": ["유튜브", "인스타그램", "없음", "페이스북", "네이버 블로그"],
    "광고_영향": [5, 4, 0, 3, 2],
    "제품_만족도": [4, 5, 3, 5, 2],
    "재구매_의향": ["예", "예", "아니오", "예", "아니오"]
}

df = pd.DataFrame(data)

# 광고 시청 여부별 응답자 수 확인
ad_view_counts = df["광고_시청"].value_counts()
print("광고 시청 여부 분포:\n", ad_view_counts)

# 광고 채널별 응답자 수 확인
ad_channel_counts = df["광고_채널"].value_counts()
print("\n광고 채널별 분포:\n", ad_channel_counts)

# 제품 만족도 평균 값 계산
avg_satisfaction = df["제품_만족도"].mean()
print("\n제품 만족도 평균 값:", avg_satisfaction)

# 광고 영향도와 제품 만족도의 상관관계 확인
correlation = df[["광고_영향", "제품_만족도"]].corr()
print("\n광고 영향도와 제품 만족도의 상관관계:\n", correlation)

# 연령대별 광고 시청 여부 확인
age_ad_view = df.groupby("연령대")["광고_시청"].value_counts()
print("\n연령대별 광고 시청 여부:\n", age_ad_view)

# 재구매 의향 비율 계산
repurchase_rate = df["재구매_의향"].value_counts(normalize=True) * 100
print("\n재구매 의향 비율(%):\n", repurchase_rate)

# 광고 영향도 평균값
avg_ad_influence = df["광고_영향"].mean()
print("\n광고 영향도 평균 값:", avg_ad_influence)

 


 

 

실습: 설문 문항 만들고, 답변 만들고, 분석 코드로 마케팅 전략 제안

 

실습1) 제품 만족도 조사

 

(1) 설문 문항 설계

 

 [ 제품 만족도 조사 설문 문항 (Product Satisfaction Survey Questions for Colab Analysis) ]

Q1.제품 사용 경험 여부 (Product Usage Experience)
1 예 (Yes)0 아니오 (No)

Q2.전반적인 제품 만족도 (Overall Product Satisfaction)
1 매우 불만족 (Very Dissatisfied)2 불만족 (Dissatisfied)3 보통 (Neutral)4 만족 (Satisfied)5 매우 만족 (Very Satisfied)

Q3. 가장 만족스러웠던 부분 (Most Satisfying Aspect)
1 가격 (Price)2 품질 (Quality)3 디자인 (Design)4 기능 (Functionality)5 기타 (Others)

Q4. 가장 개선이 필요한 부분 (Needs Improvement - Multiple Choice Possible)
1 가격 (Price)2 품질 (Quality)3 디자인 (Design)4 기능 (Functionality)5 기타 (Others)

Q5. 제품 사용 중 불편했던 점 (Inconveniences While Using the Product)
1 없음 (None)2 배송 지연 (Delivery Delay)3 품질 문제 (Quality Issues)4 사용 설명 부족 (Lack of Instructions)5 고객 서비스 문제 (Customer Service Issues)

Q6. 제품 내구성 평가 (Durability Rating)
1 매우 약함 (Very Weak)2 약함 (Weak)3 보통 (Neutral)4 강함 (Strong)5 매우 강함 (Very Strong)

Q7. 가성비 평가 (Value for Money)
1 매우 낮음 (Very Low)2 낮음 (Low)3 보통 (Neutral)4 높음 (High)5 매우 높음 (Very High)

Q8. 제품 디자인 만족도 (Satisfaction with Product Design)
1 매우 불만족 (Very Dissatisfied)2 불만족 (Dissatisfied)3 보통 (Neutral)4 만족 (Satisfied)5 매우 만족 (Very Satisfied)

Q9. 주변에 제품 추천 의향 (Willingness to Recommend the Product)
1 전혀 추천하지 않음 (Not at All)2 추천하지 않음 (Not Likely)3 보통 (Neutral)4 추천함 (Likely)5 적극 추천함 (Highly Likely)

Q10. 동일 브랜드 재구매 의향 (Likelihood to Repurchase from the Same Brand)
1 전혀 구매하지 않을 것 (Will Not Purchase Again)2 구매하지 않을 가능성이 큼 (Unlikely to Purchase Again)3 잘 모르겠음 (Neutral)4 구매할 가능성이 큼 (Likely to Purchase Again)5 반드시 구매할 것 (Will Definitely Purchase Again)

 

 

(2) 설문 문항 코딩

import pandas as pd

# 설문조사 데이터 생성 (하드코딩된 응답 포함)
survey_data = pd.DataFrame({
    "Product Usage Experience": ["y", "y", "n", "y", "n"],
    "Overall Product Satisfaction": [1,1,2,5,4],
    "Most Satisfying Aspect": [3,3,5,4,2],
    "Needs Improvement - Multiple Choice Possible": [2,2,4,5,5],
    "Inconveniences While Using the Product": [2,2,2,5,5],
    "Durability Rating": [5, 4, 3, 3, 2],
    "Value for Money": [4, 5, 3, 5, 2],
    "Satisfaction with Product Design": [1,1,1,2,3],
    "Willingness to Recommend the Product": [5,5,4,3,4],
    "Likelihood to Repurchase from the Same Brand": [2,2,3,2,1]
})

# CSV 파일로 저장
csv_filename = "growth_marketing_survey(제품 만족도).csv"
survey_data.to_csv(csv_filename, index=False, encoding='utf-8-sig')


# 저장된 CSV 파일 불러오기
loaded_data = pd.read_csv(csv_filename)

# 데이터 개요 출력
print("데이터 개요:\n", loaded_data.info())

# 제품 사용 여부별 응답자 수 확인
Product_usage_counts = loaded_data["Product Usage Experience"].value_counts()
print("\n제품 사용 여부 분포:\n", Product_usage_counts)


# 제품 만족도 평균 값 계산
avg_satisfaction = loaded_data["Overall Product Satisfaction"].mean()
print("\n제품 만족도 평균 값:", avg_satisfaction)


# 개선 필요한 부분 확인
Needs_Improvement_counts = loaded_data["Needs Improvement - Multiple Choice Possible"].value_counts()
print("\n개선 필요한 부분:\n", Needs_Improvement_counts)

# 가성비 평가 평균 계산
value_for_money = loaded_data["Value for Money"].mean()
print("\n가성비 평가 평균:\n", value_for_money)

# 가성비 평가와 동일 브랜드 재구매 의향의 상관관계 확인
correlation_b = loaded_data[["Value for Money", "Likelihood to Repurchase from the Same Brand"]].corr()
print("\n가성비 평가와 동일 브랜드 재구매 의향의 상관관계:\n", correlation_b)

# 재구매 의향 비율 계산
repurchase_rate = loaded_data["Likelihood to Repurchase from the Same Brand"].value_counts(normalize=True) * 100
print("\n재구매 의향 비율(%):\n", repurchase_rate)

# 주변 추천 의향과 동일 브랜드 재구매 의향의 상관관계 확인
correlation_a = loaded_data[["Willingness to Recommend the Product", "Likelihood to Repurchase from the Same Brand"]].corr()
print("\n주변 추천 의향과 동일 브랜드 재구매 의향의 상관관계:\n", correlation_a)

분석 코드 출력 결과

 


 

실습2) 학습 프로그램 만족도 조사

(1) 설문 문항 설계

[멋사 프로그램 만족도 설문조사 문항 설계]

1. 수강하는 멋사 프로그램 (enrolled_program)
GM, JAVA, data analysis, ux/ui, python

2. 수강생 본인의 현 상황 (participant_current_status)
휴학(Leave of Absence), 졸업 유예Graduation Postponement, 졸업Graduation, 퇴사Resignation, 이직 준비Preparing for Job Change

3. 전반적인 프로그램 만족도 (overall_program_satisfaction)
   - 1 매우 불만족 (Very Dissatisfied)  
   - 2 불만족 (Dissatisfied)  
   - 3 보통 (Neutral)  
   - 4 만족 (Satisfied)  
   - 5 매우 만족 (Very Satisfied)  

4. 강사진 만족도 (instructor_satisfaction)
   - 1 매우 불만족 (Very Dissatisfied)  
   - 2 불만족 (Dissatisfied)  
   - 3 보통 (Neutral)  
   - 4 만족 (Satisfied)  
   - 5 매우 만족 (Very Satisfied)  

5. 커리큘럼 적절성 (curriculum_appropriateness)
   - 1 매우 불만족 (Very Dissatisfied)  
   - 2 불만족 (Dissatisfied)  
   - 3 보통 (Neutral)  
   - 4 만족 (Satisfied)  
   - 5 매우 만족 (Very Satisfied)  

6. 프로젝트 및 실습 기회 만족도 (project_and_practice_opportunities_satisfaction)
   - 1 매우 불만족 (Very Dissatisfied)  
   - 2 불만족 (Dissatisfied)  
   - 3 보통 (Neutral)  
   - 4 만족 (Satisfied)  
   - 5 매우 만족 (Very Satisfied)  

7. 과제 및 평가 방식 만족도 (assignment_and_evaluation_satisfaction)
   - 1 매우 불만족 (Very Dissatisfied)  
   - 2 불만족 (Dissatisfied)  
   - 3 보통 (Neutral)  
   - 4 만족 (Satisfied)  
   - 5 매우 만족 (Very Satisfied)  

8. 운영진 및 멘토 지원 시스템 만독도 (admin_and_mentor_support_satisfaction)
   - 1 매우 불만족 (Very Dissatisfied)  
   - 2 불만족 (Dissatisfied)  
   - 3 보통 (Neutral)  
   - 4 만족 (Satisfied)  
   - 5 매우 만족 (Very Satisfied)  


9. 수업 진행 방식에 대한 선호 (preferred_learning_method)
   - 1 실시간 강의 (Live Lecture)
   - 2 녹화 강의 (Recorded Lecture)
   - 3 1:1멘토링 (1:1 Mentoring)
   - 4 팀플 (Team Project)
   - 5 보충강의 (Supplementary Lecture)

10. 다른 사람에게 추천 의향 정도 (recommendation_intent)
   - 1 매우 불만족 (Very Dissatisfied)  
   - 2 불만족 (Dissatisfied)  
   - 3 보통 (Neutral)  
   - 4 만족 (Satisfied)  
   - 5 매우 만족 (Very Satisfied)

 

 

(2) 설문 문항 코딩

[설문조사 데이터 생성 및 분석]

import pandas as pd

# 설문조사 데이터 생성 (하드코딩된 응답 포함)
survey_data = pd.DataFrame({
    "enrolled_program": [1,1,1,3,5],
    "participant_current_status": [3,3,2,5,4],
    "overall_program_satisfaction": [3,3,5,4,2],
    "instructor_satisfaction": [2,2,4,5,5],
    "curriculum_appropriateness": [2,2,2,5,5],
    "project_and_practice_opportunities_satisfaction": [5, 4, 3, 3, 2],
    "assignment_and_evaluation_satisfaction": [4, 5, 3, 5, 2],
    "admin_and_mentor_support_satisfaction": [1,1,1,2,3],
    "preferred_learning_method": [5,5,4,3,4],
    "recommendation_intent": [2,2,3,2,1]
})

# CSV 파일로 저장
csv_filename = "growth_marketing_survey(멋사 만족도).csv"
survey_data.to_csv(csv_filename, index=False, encoding='utf-8-sig')

# 저장된 CSV 파일 불러오기
loaded_data = pd.read_csv(csv_filename)

# 데이터 개요 출력
print("데이터 개요:\n", loaded_data.info())

# 수강하는 멋사 프로그램 분포
enrolled_program = loaded_data["enrolled_program"].value_counts()
display("\n수강하는 멋사 프로그램 분포:\n", enrolled_program)


# 수강생 분포
participant_current_status = loaded_data["participant_current_status"].value_counts()
display("\n수강생 분포:\n", participant_current_status)


# 프로그램 만족도 평균 값 계산
overall_program_satisfaction = loaded_data["overall_program_satisfaction"].mean()
display("\n프로그램 만족도 평균 값:", overall_program_satisfaction)

# 프로젝트 및 실습 기회 만족도과 과제 및 평가 방식 만족도의 상관관계 확인
correlation_a = loaded_data[["project_and_practice_opportunities_satisfaction", "assignment_and_evaluation_satisfaction"]].corr()
display("\n프로젝트 및 실습 기회 만족도과 과제 및 평가 방식 만족도의 상관관계:\n", correlation_a)

#수업 진행 방식에 대한 선호도 확인
preferred_learning_method = loaded_data["preferred_learning_method"].value_counts()
display("\n수업 진행 방식에 대한 선호도:\n", preferred_learning_method)

# 강사진 만족도와 동일 브랜드 다른 사람에게 추천 의향 정도의 상관관계 확인
correlation_b = loaded_data[["instructor_satisfaction", "recommendation_intent"]].corr()
display("\n강사진 만족도와 동일 브랜드 다른 사람에게 추천 의향 정도의 상관관계:\n", correlation_b)


# 커리큘럼 적절성와 동일 브랜드 다른 사람에게 추천 의향 정도의 상관관계 확인
correlation_c = loaded_data[["curriculum_appropriateness", "recommendation_intent"]].corr()
display("\n커리큘럼 적절성와 동일 브랜드 다른 사람에게 추천 의향 정도의 상관관계:\n", correlation_c)

# 운영진 및 멘토 지원 시스템 만독도와 동일 브랜드 다른 사람에게 추천 의향 정도의 상관관계 확인
correlation_d = loaded_data[["admin_and_mentor_support_satisfaction", "recommendation_intent"]].corr()
display("\n운영진 및 멘토 지원 시스템 만독도와 동일 브랜드 다른 사람에게 추천 의향 정도의 상관관계:\n", correlation_d)

+) 설문조사 데이터 생성(랜덤)

import pandas as pd
import numpy as np

# 랜덤 데이터 생성
np.random.seed(42)

# 가능한 값 정의
campaigns = ["SNS Ad", "YouTube Ad", "Email Marketing", "Influencer Collab", "Search Ad"]
age_groups = ["10s", "20s", "30s", "40s", "50s+"]
genders = ["Male", "Female"]
ad_viewed = ["Yes", "No"]
ad_channels = ["YouTube", "Instagram", "Facebook", "Google Search", "Twitter", "None"]
scores = [1, 2, 3, 4, 5]
repurchase_intent = ["Yes", "No"]

# 데이터 생성
survey_data = pd.DataFrame({
    "Campaign": np.random.choice(campaigns, 30),
    "Age Group": np.random.choice(age_groups, 30),
    "Gender": np.random.choice(genders, 30),
    "Ad Viewed": np.random.choice(ad_viewed, 30),
    "Ad Channel": np.random.choice(ad_channels, 30),
    "Ad Influence": np.random.choice(scores, 30),
    "Product Satisfaction": np.random.choice(scores, 30),
    "Repurchase Intent": np.random.choice(repurchase_intent, 30)
})

# CSV 저장
csv_filename = "/mnt/data/growth_marketing_survey.csv"
survey_data.to_csv(csv_filename, index=False, encoding='utf-8-sig')

 

 

 

[분석결과 시각화]

import matplotlib.pyplot as plt

# 1. 수강하는 멋사 프로그램 분포
plt.figure(figsize=(6, 4))
plt.bar(enrolled_program.index.astype(str), enrolled_program.values, color=['red', 'green', 'purple', 'blue', 'orange'])
plt.title("enrolled_program Distribution")
plt.xlabel("program (1: GM, 2: JAVA, 3: data anlysis, 4: ux, 5: python)")
plt.ylabel("Number of Respondents")
plt.xticks(rotation=0)
plt.show()

# 2. 수강생 분포
plt.figure(figsize=(6, 4))
plt.bar(participant_current_status.index.astype(str), participant_current_status.values, color=['red', 'green', 'purple', 'blue', 'orange'])
plt.title("participant_current_status Distribution")
plt.xlabel("status (1:Leave of Absence , 2: Graduation Postponement, 3: Graduation, 4: Resignation, 5: Preparing for Job Change)")
plt.ylabel("Number of Respondents")
plt.xticks(rotation=0)
plt.show()

# 4. 프로젝트 및 실습 기회 만족도과 과제 및 평가 방식 만족도의 상관관계 확인
plt.figure(figsize=(6, 4))
sns.heatmap(correlation_a, annot=True, cmap="Blues", linewidths=0.5, fmt=".2f")
plt.title("correlation_a: project_and_practice_opportunities_satisfaction vs. assignment_and_evaluation_satisfaction")
plt.show()

#5. 수업 진행 방식에 대한 선호도 확인
plt.figure(figsize=(6, 4))
plt.pie(preferred_learning_method, labels=preferred_learning_method.index.astype(str), autopct='%1.1f%%', colors=['lightblue', 'salmon','pink', 'blue','orange'])
plt.title("preferred_learning_method")
plt.show()


# 6. 강사진 만족도와 동일 브랜드 다른 사람에게 추천 의향 정도의 상관관계 확인
plt.figure(figsize=(6, 4))
sns.heatmap(correlation_b, annot=True, cmap="Blues", linewidths=0.5, fmt=".2f")
plt.title("correlation_b: instructor_satisfaction vs. recommendation_intent")
plt.show()

# 7. 커리큘럼 적절성와 동일 브랜드 다른 사람에게 추천 의향 정도의 상관관계 확인
plt.figure(figsize=(6, 4))
sns.heatmap(correlation_c, annot=True, cmap="Blues", linewidths=0.5, fmt=".2f")
plt.title("correlation_c: curriculum_appropriateness vs. recommendation_intent")
plt.show()

# 8. 운영진 및 멘토 지원 시스템 만독도와 동일 브랜드 다른 사람에게 추천 의향 정도의 상관관계 확인
plt.figure(figsize=(6, 4))
sns.heatmap(correlation_d, annot=True, cmap="Blues", linewidths=0.5, fmt=".2f")
plt.title("correlation_d: admin_and_mentor_support_satisfaction vs. recommendation_intent")
plt.show()

 

 

[분석결과 시각화_ 한 col 기준으로 여러 상관관계 보고 싶을 때 ]

import pandas as pd
import matplotlib.pyplot as plt

# 상관관계 계산
correlation_matrix = loaded_data[[
    "instructor_satisfaction", 
    "curriculum_appropriateness", 
    "admin_and_mentor_support_satisfaction", 
    "recommendation_intent"
]].corr()

# 'recommendation_intent'와 다른 변수들의 상관관계 추출
correlation_with_recommendation = correlation_matrix["recommendation_intent"].drop("recommendation_intent")

# 데이터프레임 생성
correlation_df = pd.DataFrame({
    "Variable": correlation_with_recommendation.index,
    "Correlation with Recommendation Intent": correlation_with_recommendation.values
})

# 데이터프레임 출력
print("\nCorrelation Results:\n", correlation_df)

# 시각화
plt.figure(figsize=(8, 5))
plt.barh(correlation_df["Variable"], correlation_df["Correlation with Recommendation Intent"], color="skyblue")
plt.xlabel("Correlation with Recommendation Intent")
plt.ylabel("Variable")
plt.title("Correlation Analysis with Recommendation Intent")
plt.xlim(-1, 1)
plt.grid(axis="x", linestyle="--", alpha=0.7)

# 그래프 출력
plt.show()

 

 

(3) 설문 데이터 시나리오화