Python Programming for Data Analysis

1. 데이터 분석을 위한 환경 구성 (패키지 설치 포함)


In [1]:
# 운영체제
!ver


Microsoft Windows [Version 10.0.10586]

In [2]:
# 현재 위치 및 하위 디렉토리 구조
!dir


 C 드라이브의 볼륨에는 이름이 없습니다.
 볼륨 일련 번호: D68D-E2A9

 C:\GitHub\kookmin-1 디렉터리

2016-04-23  오전 08:39    <DIR>          .
2016-04-23  오전 08:39    <DIR>          ..
2016-04-10  오전 12:33                61 .floo
2016-04-10  오전 12:33                63 .flooignore
2016-04-10  오전 12:33               826 .gitignore
2016-04-22  오후 11:18    <DIR>          .ipynb_checkpoints
2016-04-16  오후 04:31               801 CRM 노트
2016-04-16  오전 09:13               208 globalvar.py
2016-04-22  오후 11:48    <DIR>          images
2016-04-10  오전 12:33             1,102 LICENSE
2016-04-17  오전 12:22    <DIR>          numpy
2016-04-23  오전 02:10            22,696 Python 중간 발표_정인환.ipynb
2016-04-10  오전 12:33               472 README.md
2016-04-10  오전 12:33               481 requirements.txt
2016-04-17  오전 12:51    <DIR>          scipy
2016-04-10  오전 12:33    <DIR>          source
2016-04-23  오전 01:57             3,294 TicTaeToe.py
2016-04-10  오전 12:33         1,203,361 w01_data_science.pdf
2016-04-10  오전 12:33            21,564 w02_python_primer.ipynb
2016-04-10  오전 12:33         4,013,493 w02_python_primer.pdf
2016-04-10  오전 12:33           772,863 w03_python_101_git.ipynb
2016-04-10  오전 12:33         2,870,682 w03_python_101_git.pdf
2016-04-16  오전 09:13           686,274 w04_exercies_indexing&slicing_function.ipynb
2016-04-10  오전 12:33           624,792 w04_exercies_indexing&slicing_function.pdf
2016-04-16  오전 09:13         3,140,402 w06_scope_package&module.ipynb
2016-04-16  오후 10:50         1,989,348 w07_numpy_pandas_primer.ipynb
              19개 파일          15,352,783 바이트
               7개 디렉터리  237,906,771,968 바이트 남음

In [3]:
# 파이선 버전

!python --version


Python 3.4.4

In [4]:
# 가상환경 버전

!virtualenv --version


15.0.0

In [5]:
# 존재하는 가상환경 목록

!workon


Pass a name to activate one of the following virtualenvs:
==============================================================================
kookmin1

In [6]:
# 가상환경 kookmin1에 진입
# workon kookmin1

In [6]:
# 가상환경 kookmin1에 설치된 패키지
# 데이터 분석 : numpy, pandas
# 시각화 : matplotlib

!pip freeze


atlas==0.27.0
backports-abc==0.4
cycler==0.10.0
decorator==4.0.9
entrypoints==0.2
ipykernel==4.3.1
ipython==4.1.2
ipython-genutils==0.1.0
ipywidgets==4.1.1
Jinja2==2.8
jsonschema==2.5.1
jupyter-client==4.2.2
jupyter-core==4.1.0
MarkupSafe==0.23
matplotlib==1.5.1
mistune==0.7.2
nbconvert==4.2.0
nbformat==4.0.1
notebook==4.2.0
numpy==1.11.0
pandas==0.18.0
pickleshare==0.7.2
Pygments==2.1.3
pyparsing==2.1.1
python-dateutil==2.5.2
pytz==2016.3
pyzmq==15.2.0
scikit-learn==0.17.1
scipy==0.17.0
simplegeneric==0.8.1
six==1.10.0
sklearn==0.0
Tempita==0.5.2
threadpool==1.3.2
tornado==4.3
traitlets==4.2.1

TicTaeToe 게임

print("출처: http://www.practicepython.org") print("==================================") print("가로, 세로, 대각선 방향으로 ") print("세점을 먼저 이어 놓으면 이기는 ") print("게임으로 사용자(U)와 Computer(C)가") print("번갈아 놓습니다. ") print("==================================\n")

In [8]:
from IPython.display import Image
Image(filename='images/TicTaeToe.png')


Out[8]:

TicTaeToe게임을 간단 버젼으로 구현한 것으로 사용자가 먼저 착수하여 승부를 겨루게 됩니다. 향후에는 기계학습으로 발전시켜 실력을 키워 보려 합니다.


In [ ]:
# %load TicTaeToe.py
import sys
import random

# 게임 방범 설명
print("출처: http://www.practicepython.org")
print("==================================")
print("가로, 세로, 대각선 방향으로                   ")
print("세점을 먼저 이어 놓으면 이기는")
print("게임으로 사용자(U)와 Computer(C)가")
print("번갈아 놓습니다.")
print("==================================\n")

# 3 x 3 정보를 담기 위한 저장소 선언
# 0 은 초기 상태
# 1 은 사용자가 선택한 곳
# 2 는 컴퓨터가 선택한 곳
dim=3
list4 = [0,0,0,0,0,0,0,0,0]

# 사용자 안내를 위한 박스를 그리고 그 안에 번호 넣기
def graph():
    k = 1
    for i in range(dim+1):
        print(" ---"*dim)
        for j in range(dim):
            if (i < dim):
                print("| "+str(k), end=" ")
                k = k + 1
        if (i != 3):
            print("|")

# 사용자 또는 컴퓨터가 수를 둘때 마다,
# 누가 이겼는지 체크
def game_wins(list4):
    #print(list4)
    for i in range(dim): 
        #checks to see if you win in a column
        if list4[i] == list4[i+3] == list4[i+6] == 1:
            print("You Won")
        elif list4[i] == list4[i+3] == list4[i+6] == 2:
            print("You Lost")
        #checks to see if you win in a row
        if list4[dim*i] == list4[dim*i+1] == list4[dim*i+2] == 1:
            print ("You Won")
        elif list4[dim*i] == list4[dim*i+1] == list4[dim*i+2] == 2:
            print("You Lost")
        #checks to see if you win in a diagonal
        if list4[0] == list4[4] == list4[8] == 1:
            print ("You Won")
        elif list4[0] == list4[4] == list4[8] == 2:
            print("You Lost")
        if list4[2] == list4[4] == list4[6] == 1:
            print ("You Won")
        elif list4[2] == list4[4] == list4[6] == 2:
            print("You Lost")

# 사용자 안내를 위한 박스를 그리고 그 안에 번호 또는 둔 수 표기
def graph_pos(list4):
    for idx in range(len(list4)):
        if (idx % 3 == 0):
            print(" ---"*dim)
        if (list4[idx] == 0):
            print("| "+str(idx+1), end=" ")
        elif (list4[idx] == 1):
            print("| "+"U", end=" ")
        else:
            print("| "+"C", end=" ")   
        if (idx % 3 == 2):
            print("|")
    print("\n")

# 게임 시작
go = input("Play TicTaeToe? Enter, or eXit?")
if (go == 'x' or go == 'X'):
    sys.exit(0)
graph()
print("\n")

while(1):  # 보드게임이 승부가 날때까지 무한 반복
        # 빈곳 선택
        pos = int(input("You : ")) - 1
        while (pos < 0 or pos > 8 or list4[pos] != 0):
            pos = int(input("Again : ")) - 1
        list4[pos] = 1
         
        # 보드를 갱신하여 그리고, 승부 체크
        graph_pos(list4)
        game_wins(list4)

        # 컴퓨터 차례로, 빈곳을 랜덤하게 선택하여 List에 저장
        pos = random.randrange(9)
        while (list4[pos] != 0):
            pos = random.randrange(9)
        print("Computer : " + str(pos+1))
        list4[pos] = 2
        
        # 보드를 갱신하여 그리고, 승부 체크
        graph_pos(list4)
        game_wins(list4)


출처: http://www.practicepython.org
==================================
가로, 세로, 대각선 방향으로                   
세점을 먼저 이어 놓으면 이기는
게임으로 사용자(U)와 Computer(C)가
번갈아 놓습니다.
==================================

write/save %%writefile myfile.py

write/save cell contents into myfile.py (use -a to append). Another alias: %%file myfile.py run %run myfile.py

run myfile.py and output results in the current cell load/import %load myfile.py

load "import" myfile.py into the current cell for more magic and help %lsmagic

list all the other cool cell magic commands. %COMMAND-NAME?

for help on how to use a certain command. i.e. %run?


In [ ]: