Data Science FAQ | https://www.kaggle.com/rounakbanik/data-science-faq
Novice to Grandmaster | https://www.kaggle.com/ash316/novice-to-grandmaster
-복잡한 코드 리뷰 형식으로
-더보기에 jupyter노트북으로 했던거 있음
#missingno는 NaN 데이터들에 대해 시각화를 해준다.
# NaN 데이터의 컬럼이 많아 아래 그래프만으로는 내용을 파악하기 어렵다.
#pip install missingno 로 먼저 설치
import missingno as msno
msno.matrix(mcq, figsize=(12,5))
설문통계부분
#국가별 응답수
con_df = pd.DataFrame(mcq['Country'].value_counts())
#'country' column 인덱스로 지정
con_df['국가']=con_df.index
#컬럼의 순서대로 응답수, 국가 지정
con_df.columns=['응답 수','국가']
# index 컬럼을 삭제하고 순위를 알기위해 reset_index()를 해준다.
con_df = con_df.reset_index().drop('index', axis=1)
#index column 삭제는 drop()을 이용하여. column을 삭제하기 때문에 axis=1
#reset_index()로 새로운 index 세팅(0,1,2,3,... 이런거)
con_df.head(20)
- mcq의 Country컬럼만 뽑아 나라별로 갯수를 세고 그것을 데이터 프레임으로 만든다.
- 국가 이름은 인덱스가 되며 '국가'라는 컬럼을 만들어 국가 이름(인덱스)을 넣어준다.
- 컬럼을 순서대로 응답수, 국가 로 지정한다
- drop()을 이용하여 index 컬럼을 삭제한다. 컬럼을 삭제하기 때문에 axis=1로 해준다.
- reset_index()로 새로운 index 세팅
전공분석
mcq_major_count = pd.DataFrame(
mcq['MajorSelect'].value_counts())
mcq_major_percent = pd.DataFrame(
mcq['MajorSelect'].value_counts(normalize=True))
#normalize=True를 사용하면 퍼센트로 나타낼 수 있음
mcq_major_df = mcq_major_count.merge(
mcq_major_percent, left_index=True, right_index=True)
mcq_major_df.columns = ['응답 수', '비율']
mcq_major_df
- mcq의 MajorSelect 컬럼만 뽑아 전공별로 개수를 새고 그것을 데이터 프레임으로 만든다.
- mcq의 MajorSelect 컬럼만 뽑아 전공별로 개수를 새고 normalize=True를 이용하여 퍼센트로 나타낸 후 그것을 데이터 프레임으로 만든다.
- merge()를 이용하여 mcq_major_count와 mcq_major_percent를 합친다. 이때 count, percent에 존재하는 인덱스를 조인키로 사용하기 위해서 left_index와 right_index를 True로 한다.
- 컬럼을 순서대로 응답수, 비율 로 지정
(취업 여부도 이와 비슷)
프로그래밍 경험
korea = mcq.loc[(mcq['Country']=='South Korea')]
print('The number of interviewees in Korea: ' + str(korea.shape[0]))
sns.distplot(korea['Age'].dropna())
plt.title('Korean')
plt.show()
- .loc[] 를 이용하여 특정 데이터만 추출. Country 컬럼에서 South Korea인 것만 추출
- dropna()를 이용하여 Age 컬럼에서 NaN 제거하여 distplot 그리기
figure, (ax1, ax2) = plt.subplots(ncols=2)
figure.set_size_inches(12,5)
sns.distplot(korea['Age'].loc[korea['GenderSelect']=='Female'].dropna(),
norm_hist=False, color=sns.color_palette("Paired")[4], ax=ax1)
plt.title('korean Female')
sns.distplot(korea['Age'].loc[korea['GenderSelect']=='Male'].dropna(),
norm_hist=False, color=sns.color_palette("Paired")[0], ax=ax2)
plt.title('korean Male')
- 나이 + 성별(남여 따로)을 그래프로 출력해본다.
- 두 개의 그래프를 각각 어디에 보여줄 것인지 선택. ncols는 열의 추가이므로 가로로 배열되고 nrows는 행의 추가이므로 세로로 배열된다. ncols=2이므로 가로로 2개 배열 됨
- figure.set_size_inches()는그래프의 (넓이, 높이)를 설정한다.
- >>https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html
- distplot의 옵션
- norm_hist: True면 히스토그램 높이가 수가 아닌 밀도를 표시한다.
- color: 색 지정. .color_palette()는 seaborn에 존재하는 함수로 deep, muted, bright, pastel, dark, colorblind를 쓸 수 있다.
- ax: 위에서 지정한 figure에 ax1으로 이 설정을 집어넣는다.
- loc를 이용하여 GenderSelect가 Female인것만 추출하고 그것의 Age 데이터를 이용하여 그래프를 그린다. 이때 dropna()를 통해 결측치가 제거 되었다. ax=ax1을 통해 첫번째에 그려진다.
- loc를 이용하여 GenderSelect가 Female인것만 추출하고 그것의 Age 데이터를 이용하여 그래프를 그린다. 이때 dropna()를 통해 결측치가 제거 되었다. ax=ax2을 통해 두번째에 그려진다.
#취업 현황
sns.barplot(x=korea['EmploymentStatus'].unique(), y=korea['EmploymentStatus'].value_counts()/len(korea))
plt.xticks(rotation=30, ha='right')
plt.title('Employment status of the korean')
plt.ylabel('')
plt.show()
- x에는 사람들이 응답한 문항이 들어가야 하기 때문에 .unique() 메서드를 사용해서 사람들이 답변한 내용 도메인을 리스트로 만든다. y에는 x도메인의 상대도수를 구해 넣어준다.
참고 URL :
Data Science FAQ | https://www.kaggle.com/rounakbanik/data-science-faq
Novice to Grandmaster | https://www.kaggle.com/ash316/novice-to-grandmaster
캐글을 시작한지 두 달정도 된 초보자로, 이 설문조사의 결과를 바탕으로 데이터사이언스와 머신러닝과 관련 된 인사이트를 얻어볼 수 있지 않을까 가설을 세워본다.
schema.csv : 설문 스키마가있는 CSV 파일입니다. 이 스키마에는 multipleChoiceResponses.csv 및 freeformResponses.csv의 각 열 이름에 해당하는 질문이 포함되어 있습니다.
multipleChoiceResponses.csv : 객관식 및 순위 질문에 대한 응답자의 답변, 각 행이 한 응답자의 응답
freeformResponses.csv : Kaggle의 설문 조사 질문에 대한 응답자의 주관식 답변입니다. 임의로 지정되어 각 행이 같은 응답자를 나타내지 않음
conversionRates.csv : R 패키지 "quantmod"에서 2017 년 9 월 14 일에 액세스 한 통화 변환율 (USD)
RespondentTypeREADME.txt : schema.csv 파일의 "Asked"열에 응답을 디코딩하는 스키마입니다.
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
#창 맞추기위함
# 노트북 안에서 그래프를 그리기 위해
%matplotlib inline
# Import the standard Python Scientific Libraries
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns
# Suppress Deprecation and Incorrect Usage Warnings
import warnings
warnings.filterwarnings('ignore')
#multipleChoiceResponses.csv 및 freeformResponses.csv의 각 열 이름에 해당하는 질문이 포함
question = pd.read_csv("data/schema.csv")
question.shape
(290, 3)
question.head()
Column | Question | Asked | |
---|---|---|---|
0 | GenderSelect | Select your gender identity. - Selected Choice | All |
1 | GenderFreeForm | Select your gender identity. - A different ide... | All |
2 | Country | Select the country you currently live in. | All |
3 | Age | What's your age? | All |
4 | EmploymentStatus | What's your current employment status? | All |
# 판다스로 선다형 객관식 문제에 대한 응답을 가져 옴
mcq = pd.read_csv("data/multipleChoiceResponses.csv", encoding="ISO-8859-1")
mcq.shape
(16716, 228)
mcq.columns
Index(['GenderSelect', 'Country', 'Age', 'EmploymentStatus', 'StudentStatus',
'LearningDataScience', 'CodeWriter', 'CareerSwitcher',
'CurrentJobTitleSelect', 'TitleFit',
...
'JobFactorExperienceLevel', 'JobFactorDepartment', 'JobFactorTitle',
'JobFactorCompanyFunding', 'JobFactorImpact', 'JobFactorRemote',
'JobFactorIndustry', 'JobFactorLeaderReputation', 'JobFactorDiversity',
'JobFactorPublishingOpportunity'],
dtype='object', length=228)
mcq.tail()
GenderSelect | Country | Age | EmploymentStatus | StudentStatus | LearningDataScience | CodeWriter | CareerSwitcher | CurrentJobTitleSelect | TitleFit | ... | JobFactorExperienceLevel | JobFactorDepartment | JobFactorTitle | JobFactorCompanyFunding | JobFactorImpact | JobFactorRemote | JobFactorIndustry | JobFactorLeaderReputation | JobFactorDiversity | JobFactorPublishingOpportunity | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16711 | Female | Other | 24.0 | Not employed, but looking for work | NaN | NaN | NaN | NaN | NaN | NaN | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
16712 | Male | Indonesia | 25.0 | Employed full-time | NaN | NaN | Yes | NaN | Programmer | Fine | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
16713 | Female | Taiwan | 25.0 | Employed part-time | NaN | NaN | No | Yes | NaN | NaN | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
16714 | Female | Singapore | 16.0 | I prefer not to say | Yes | Yes, but data science is a small part of what ... | NaN | NaN | NaN | NaN | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
16715 | Male | Japan | 27.0 | Employed full-time | NaN | NaN | No | Yes | Programmer | Fine | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
5 rows × 228 columns
mcq.head()
GenderSelect | Country | Age | EmploymentStatus | StudentStatus | LearningDataScience | CodeWriter | CareerSwitcher | CurrentJobTitleSelect | TitleFit | ... | JobFactorExperienceLevel | JobFactorDepartment | JobFactorTitle | JobFactorCompanyFunding | JobFactorImpact | JobFactorRemote | JobFactorIndustry | JobFactorLeaderReputation | JobFactorDiversity | JobFactorPublishingOpportunity | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | Non-binary, genderqueer, or gender non-conforming | NaN | NaN | Employed full-time | NaN | NaN | Yes | NaN | DBA/Database Engineer | Fine | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
1 | Female | United States | 30.0 | Not employed, but looking for work | NaN | NaN | NaN | NaN | NaN | NaN | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | Somewhat important | NaN | NaN |
2 | Male | Canada | 28.0 | Not employed, but looking for work | NaN | NaN | NaN | NaN | NaN | NaN | ... | Very Important | Very Important | Very Important | Very Important | Very Important | Very Important | Very Important | Very Important | Very Important | Very Important |
3 | Male | United States | 56.0 | Independent contractor, freelancer, or self-em... | NaN | NaN | Yes | NaN | Operations Research Practitioner | Poorly | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
4 | Male | Taiwan | 38.0 | Employed full-time | NaN | NaN | Yes | NaN | Computer Scientist | Fine | ... | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
5 rows × 228 columns
# missingno는 NaN 데이터들에 대해 시각화를 해준다.
# NaN 데이터의 컬럼이 많아 아래 그래프만으로는 내용을 파악하기 어렵다.
#pip install missingno
import missingno as msno
msno.matrix(mcq, figsize=(12,5))
<AxesSubplot:>
설문통계¶
#성별
sns.countplot(data=mcq, y='GenderSelect')
<AxesSubplot:xlabel='count', ylabel='GenderSelect'>
#국가별 응답수
con_df = pd.DataFrame(mcq['Country'].value_counts())
#'country' column 인덱스로 지정
con_df['국가']=con_df.index
#컬럼의 순서대로 응답수, 국가 지정
con_df.columns=['응답 수','국가']
# index 컬럼을 삭제하고 순위를 알기위해 reset_index()를 해준다.
con_df = con_df.reset_index().drop('index', axis=1)
#index column 삭제는 drop()을 이용하여. column을 삭제하기 때문에 axis=1
#reset_index()로 새로운 index 세팅(0,1,2,3,... 이런거)
con_df.head(20)
응답 수 | 국가 | |
---|---|---|
0 | 4197 | United States |
1 | 2704 | India |
2 | 1023 | Other |
3 | 578 | Russia |
4 | 535 | United Kingdom |
5 | 471 | People 's Republic of China |
6 | 465 | Brazil |
7 | 460 | Germany |
8 | 442 | France |
9 | 440 | Canada |
10 | 421 | Australia |
11 | 320 | Spain |
12 | 277 | Japan |
13 | 254 | Taiwan |
14 | 238 | Italy |
15 | 205 | Netherlands |
16 | 196 | Ukraine |
17 | 194 | South Korea |
18 | 184 | Singapore |
19 | 184 | Poland |
#연령에 대한 정보
mcq['Age'].describe()
count 16385.000000
mean 32.372841
std 10.473487
min 0.000000
25% 25.000000
50% 30.000000
75% 37.000000
max 100.000000
Name: Age, dtype: float64
sns.distplot(mcq[mcq['Age']>0]['Age'])
<AxesSubplot:xlabel='Age', ylabel='Density'>
학력¶
sns.countplot(data=mcq, y='FormalEducation')
<AxesSubplot:xlabel='count', ylabel='FormalEducation'>
전공¶
mcq_major_count = pd.DataFrame(
mcq['MajorSelect'].value_counts())
mcq_major_percent = pd.DataFrame(
mcq['MajorSelect'].value_counts(normalize=True))
#normalize=True를 사용하면 퍼센트로 나타낼 수 있음
mcq_major_df = mcq_major_count.merge(
mcq_major_percent, left_index=True, right_index=True)
mcq_major_df.columns = ['응답 수', '비율']
mcq_major_df
응답 수 | 비율 | |
---|---|---|
Computer Science | 4397 | 0.331074 |
Mathematics or statistics | 2220 | 0.167156 |
Engineering (non-computer focused) | 1339 | 0.100821 |
Electrical Engineering | 1303 | 0.098110 |
Other | 848 | 0.063851 |
Physics | 830 | 0.062495 |
Information technology, networking, or system administration | 693 | 0.052180 |
A social science | 531 | 0.039982 |
Biology | 274 | 0.020631 |
Management information systems | 237 | 0.017845 |
A humanities discipline | 198 | 0.014909 |
A health science | 152 | 0.011445 |
Psychology | 137 | 0.010315 |
I never declared a major | 65 | 0.004894 |
Fine arts or performing arts | 57 | 0.004292 |
# 재학중인 사람들의 전공 현황
plt.figure(figsize=(6,8))
sns.countplot(y='MajorSelect', data=mcq)
<AxesSubplot:xlabel='count', ylabel='MajorSelect'>
취업 여부¶
mcq_es_count = pd.DataFrame(
mcq['EmploymentStatus'].value_counts())
mcq_es_percent = pd.DataFrame(
mcq['EmploymentStatus'].value_counts(normalize=True))
mcq_es_df = mcq_es_count.merge(
mcq_es_percent, left_index=True, right_index=True)
mcq_es_df.columns = ['응답 수', '비율']
mcq_es_df
응답 수 | 비율 | |
---|---|---|
Employed full-time | 10897 | 0.651890 |
Not employed, but looking for work | 2110 | 0.126226 |
Independent contractor, freelancer, or self-employed | 1330 | 0.079564 |
Not employed, and not looking for work | 924 | 0.055276 |
Employed part-time | 917 | 0.054858 |
I prefer not to say | 420 | 0.025126 |
Retired | 118 | 0.007059 |
sns.countplot(y='EmploymentStatus', data=mcq)
<AxesSubplot:xlabel='count', ylabel='EmploymentStatus'>
프로그래밍 경험¶
sns.countplot(y='Tenure', data=mcq)
<AxesSubplot:xlabel='count', ylabel='Tenure'>
korea = mcq.loc[(mcq['Country']=='South Korea')]
print('The number of interviewees in Korea: ' + str(korea.shape[0]))
sns.distplot(korea['Age'].dropna())
plt.title('Korean')
plt.show()
The number of interviewees in Korea: 194
pd.DataFrame(korea['GenderSelect'].value_counts())
GenderSelect | |
---|---|
Male | 156 |
Female | 37 |
A different identity | 1 |
sns.countplot(x='GenderSelect', data=korea)
plt.title('Korean')
Text(0.5, 1.0, 'Korean')
figure, (ax1, ax2) = plt.subplots(ncols=2)
figure.set_size_inches(12,5)
sns.distplot(korea['Age'].loc[korea['GenderSelect']=='Female'].dropna(),
norm_hist=False, color=sns.color_palette("Paired")[4], ax=ax1)
plt.title('korean Female')
sns.distplot(korea['Age'].loc[korea['GenderSelect']=='Male'].dropna(),
norm_hist=False, color=sns.color_palette("Paired")[0], ax=ax2)
plt.title('korean Male')
Text(0.5, 1.0, 'korean Male')
sns.barplot(x=korea['EmploymentStatus'].unique(), y=korea['EmploymentStatus'].value_counts()/len(korea))
plt.xticks(rotation=30, ha='right')
plt.title('Employment status of the korean')
plt.ylabel('')
plt.show()
korea['StudentStatus'] = korea['StudentStatus'].fillna('No')
sns.countplot(x='StudentStatus', data=korea)
plt.title('korean')
plt.show()