문자열에서 특정 값을 뽑아내고 input을 받는 함수

Kaggle Survey Data Transformation

2021 Kaggle Machine Learning & Data Science Survey 에서 질문지를 나누는 작업 중 여러 part로 다수의 칼럼명을 가진 question number 부분의 칼럼명을 뽑아내는 함수를 찾았고, 이 함수에 대응할 수 있으며 질문의 A,B type을 특정해낼 수 있는 input 함수를 짜봤다.

데이터 칼럼명 나누기

1
2
3
4
5
import numpy as np
import pandas as pd

from warnings import filterwarnings
filterwarnings('ignore')

우선 모든 Question 칼럼명을 추출해낸다.
물론 데이터를 나누는 작업 전에 나눌 데이터와 데이터 명을 학습해야한다.
kaggle_survey_2021_responses.csv의 칼럼명 형식은 다음과 같다.

  • 'Q'(num1)
  • 'Q'(num1)'_Part_'(num2)
  • 'Q'(num1)'_'(type)'_Part_'(num2)

각각을 Question, sub_Qustion, type_Qustion(sub 포함)으로 볼 수 있다.

1
2
3
4
#df = pd.read_csv("D:/_Bdata/Codding-base-Python/Python/Python-jupyter/Kaggle Survey - 2021 Analysis - Plotly/kaggle_survey_2021_responses.csv")
df = pd.read_csv("E:/Fear/Univ/Big_data/Training/Github/Codding-base-Python/Python/Python-jupyter/Kaggle Survey - 2021 Analysis - Plotly/kaggle_survey_2021_responses.csv")
df_col_name = df.columns[1:]
df_col_name
Index(['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7_Part_1', 'Q7_Part_2',
       'Q7_Part_3', 'Q7_Part_4',
       ...
       'Q38_B_Part_3', 'Q38_B_Part_4', 'Q38_B_Part_5', 'Q38_B_Part_6',
       'Q38_B_Part_7', 'Q38_B_Part_8', 'Q38_B_Part_9', 'Q38_B_Part_10',
       'Q38_B_Part_11', 'Q38_B_OTHER'],
      dtype='object', length=368)

문자열을 인식해서 input 값을 특정해주는 함수 만들기

questions_count에 대응할 수 있는 input 함수를 짜낸다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def input_num():
print("input Question no.: ")
Qnum = input()
Qnum_subQ = [s for s in df_col_name if "Q"+Qnum+"_" in s]

if Qnum_subQ == []:
return "Q"+Qnum+" has not part_Q"

Question_type = None
if [s for s in Qnum_subQ if ("A"or"B") in s]:
print("input Q"+Qnum+"'s type")
Question_type = input().upper()

if Qnum_subQ:
print("input Q"+Qnum+"'s last part no.: ")
part_num = input()


return questions_count(Qnum,part_num,Question_type)

위 함수는
Question number(Qnum)을 입력받은 뒤 이전에 정의한 칼럼명을 추출해 낸 df_col_name 객체내에서 "Q"+Qnum+"_" 문자열이 있는 sub_Question 형식을 찾아낸다.

Data Transformation에서 얻어낸 코드는 Qnum 만 있는 경우에 대한 작업이 없으므로 이 경우는 line6 조건문에서 함수를 종료한다.

line 9의 if문에선 'A' or 'B' 문자가 들어있는 문자열을 list에서 식별해 해당하는 경우엔 Question_type 객체에 type을 입력 받게 되는 조건문을 작성했다.
이 때, upper() 함수를 이용해 소문자로 입력받아도 대문자로 자동변환되게 설정했다.

line 14의 조건문은 sub Question의 마지막 열을 입력받는 조건문으로 사용자가 ‘kaggle_survey’에서 직접 확인해서 input 값을 정해야한다.

칼럼명 리스트로 뽑아내기

Data Transformation에서 가져온 코드로, 원하는 sub_Question들을 뽑아낼 수 있는 함수다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def questions_count(question_num, part_num, Question_type = False):
part_questions = []

if Question_type in ["A","B"]:
part_questions = ['Q'+question_num+"_"+Question_type+"_Part_"+str(j) for j in range(1,int(part_num))]
part_questions.append("Q"+question_num+"_"+Question_type+"_OTHER")
else:
part_questions = ['Q'+question_num+'_Part_'+str(j) for j in range(1,int(part_num))]
part_questions.append('Q'+question_num+'_OTHER')

categories = []
counts = []
for i in part_questions:
category = df[i].value_counts().index[0]
val = df[i].value_counts()[0]
categories.append(category)
counts.append(val)

combined_df = pd.DataFrame()
combined_df['Category'] = categories
combined_df['Count'] = counts

combined_df = combined_df.sort_values(['Count'], ascending = False)
return combined_df

part_question List를 만들어서 칼럼명을 저장하는데, Question_type이 입력되었을 경우와 아닌경우로 조건문이 나뉜다.

  • type이 있는 경우: "Q(num)_(type)_Part_(part_num)"
  • type이 없는 경우: "Q(num)_Part_(part_num)"

csv 파일을 보면 알 수 있지만, sub_qustion의 마지막 칼럼은 Q(num)_OTHER로 구성된다.
위 예외에 대응하기 위해 append함수를 이용해서 list에 Q(num)_OTHER 값을 추가한다.

남은 작업은 기존 df에서 칼럼명과 칼럼에 응답한 합을 구하기 위해value_counts함수의 indexvalues를 사용해서 만든 dataframe을 반환하면 Data Transformation 작업이 끝난다.

1
input_num()
input Question no.: 
1





'Q1 has not part_Q'
1
input_num()
input Question no.: 
7
input Q7's last part no.: 
12
Category Count
0 Python 21860
2 SQL 10756
4 C++ 5535
1 R 5334
5 Java 4769
3 C 4709
6 Javascript 4332
10 MATLAB 2935
11 Other 2575
9 Bash 2216
7 Julia 305
8 Swift 242
1
input_num()
input Question no.: 
27
input Q27's type
a
input Q27's last part no.: 
11
Category Count
0 Amazon Web Services (AWS) 3721
2 Google Cloud Platform (GCP) 3142
1 Microsoft Azure 2450
3 IBM Cloud / Red Hat 572
4 Oracle Cloud 454
7 VMware Cloud 390
10 Other 337
5 SAP Cloud 290
6 Salesforce Cloud 275
8 Alibaba Cloud 259
9 Tencent Cloud 172

외부 링크

기억이 안날 때는 응애..

문자열에서 특정 값을 뽑아내고 input을 받는 함수

https://hangack.github.io/2021/11/11/Codding/Python/kaggle_survey/Data-Transformation-input-num/

Author

Hangack

Posted on

2021-11-11

Updated on

2022-02-14

Licensed under

댓글