반응형

 

csv 포멧의 파일을 Parsing 하는 과정에서 다음과 같은 코드를 실행 할 경우 문제가 발생합니다.

 

import pandas as pd
import os
encoding = 'latin1'

mpath = os.path.expanduser('movielens/movies.dat')
rpath = os.path.expanduser('movielens/ratings.dat')
upath = os.path.expanduser('movielens/users.dat')

unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
mnames = ['movie_id', 'title', 'genres']

users = pd.read_csv(upath, sep='::', header=None, names=unames, encoding=encoding)
ratings = pd.read_csv(rpath, sep='::', header=None, names=rnames, encoding=encoding)
movies = pd.read_csv(mpath, sep='::', header=None, names=mnames, encoding=encoding) 

 

[Error]

C:\Python27\lib\site-packages\ipykernel\__main__.py:13: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators; you can avoid this warning by specifying engine='python'.
C:\Python27\lib\site-packages\ipykernel\__main__.py:14: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators; you can avoid this warning by specifying engine='python'.
C:\Python27\lib\site-packages\ipykernel\__main__.py:15: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators; you can avoid this warning by specifying engine='python'.

 

이럴 경우 engine='python'을 추가해주면 오류가 발생하지 않습니다.

 

import pandas as pd
import os
encoding = 'latin1'

mpath = os.path.expanduser('movielens/movies.dat')
rpath = os.path.expanduser('movielens/ratings.dat')
upath = os.path.expanduser('movielens/users.dat')

unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
mnames = ['movie_id', 'title', 'genres']

users = pd.read_csv(upath, sep='::', header=None, names=unames, encoding=encoding, engine='python')
ratings = pd.read_csv(rpath, sep='::', header=None, names=rnames, encoding=encoding, engine='python')
movies = pd.read_csv(mpath, sep='::', header=None, names=mnames, encoding=encoding, engine='python')

 

데이터 파일이 여러개일 경우 다음과 같이 pandas의 merge함수를 활용하면 손쉽게 합칠 수 있습니다.

아래의 merge는 ratings 파일과 users 파일을 합치고 movies 파일을 합치는 과정을 나타내는 명령어 입니다.

(※ pd = import pandas as pd)

 

 data = pd.merge(pd.merge(ratings, users), movies)

 

테이블로 만들어진 Data는 .ix 메소드를 활용하여 컬럼을 사용할 수 있다.

 

data.ix[0] - index 0 컬럼의 데이터를 출력

 

 

반응형
반응형

 

IPython을 사용하다보면 %matplotlib inline을 사용 해야 하는 상황이 발생합니다.

도형이나 그래프로 output을 출력 하는 라이브러리 이므로 Qtconsole 환경이 필요합니다.

 

그럴 때, IPython qtconsole을 실행 하면 다음과 같은 에러가 발생할 수도 있습니다.

이럴 경우 에러 코드의 마지막을 보면 다음과 같이 필요한 라이브러리가 있습니다.

해당 라이브러리를 설치해주시면 문제 없이 실행 됩니다.

 

 

[에러코드]

 

[TerminalIPythonApp] WARNING | Subcommand `ipython qtconsole` is deprecated and will be removed in future versions.
[TerminalIPythonApp] WARNING | You likely want to use `jupyter qtconsole` in the  future
Error in sys.excepthook:
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\qtconsole\qtconsoleapp.py", line 49, in gui_excepthook
    old_excepthook(exctype, value, tb)
TypeError: 'NoneType' object is not callable
 .........................

    Could not load requested Qt binding. Please ensure that
    PyQt4 >= 4.7, PyQt5 or PySide >= 1.0.3 is available,
    and only one is imported per session.

    Currently-imported Qt library:   None
    PyQt4 installed:                 False
    PyQt5 installed:                 False
    PySide >= 1.0.3 installed:       False
    Tried to load:                   ['pyqt5', 'pyside', 'pyqt']

 

pip install PySide

pip install PyQt4

pip install PyQt5

 

필자의 경우는 PySide만 설치가 가능했으며, PySide를 설치한 이후 문제 없이 qtconsole이 실행 되었습니다.

 

 

Jupyter QtConsole 4.2.1
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.

IPython 4.2.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
 

In [1]:

 

그래픽 라이브러리를 사용하기 위해서는 console에서 동작하기엔 옵션이 필요하다.

그럴땐 notebook을 활용해야 한다.

 

ipython notebook

 

E:\Temp\Data_Science\IPython\chapter\02>ipython notebook
[TerminalIPythonApp] WARNING | Subcommand `ipython notebook` is deprecated and will be removed in future versions.
[TerminalIPythonApp] WARNING | You likely want to use `jupyter notebook` in the future
C:\Python27\lib\site-packages\widgetsnbextension\__init__.py:30: UserWarning: To use the jupyter-js-widgets nbextension, you'll need to update the Jupyter notebook to version 4.2 or later.
  the Jupyter notebook to version 4.2 or later.""")
[I 10:15:53.674 NotebookApp] Serving notebooks from local directory: E:\Temp\Data_Science\IPython\chapter\02
[I 10:15:53.674 NotebookApp] 0 active kernels
[I 10:15:53.674 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/
[I 10:15:53.674 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). 

 





Plot을 사용하는데 다음과 같은 오류가 발생할 경우 32bit 환경에서 사용하였기 때문입니다.

따라서, 64bit로 다시 진행 해 보세요.

 

 

total_births.plot(title='Total births by sex and year') 

error >

c:\python27\lib\lib-tk\Tkinter.py in <module>()
     36 if sys.platform == "win32":
     37     # Attempt to configure Tcl/Tk without requiring PATH
---> 38     import FixTk
     39 import _tkinter # If this fails your Python may not be configured for Tk
     40 tkinter = _tkinter # b/w compat for export

c:\python27\lib\lib-tk\FixTk.py in <module>()
     63     # Compute TK_LIBRARY, knowing that it has the same version
     64     # as Tcl
---> 65     import _tkinter
     66     ver = str(_tkinter.TCL_VERSION)
     67     if "TK_LIBRARY" not in os.environ:

ImportError: DLL load failed: %1은(는) 올바른 Win32 응용 프로그램이 아닙니다.

 

추가적으로 plot이 정상적으로 동작하지 않을 경우 다음과 같이 진행 하면 그래프가 출력 됩니다.

 

 

total_births.plot(title='total births by sex and year')

 

error>

<matplotlib.axes._subplots.AxesSubplot at 0xf05df60>
[이후 아무것도 출력 되지 않음]

 

[해결책]

 

%matplotlib inline 

<matplotlib.axes._subplots.AxesSubplot at 0xf05df60>

[이후 정상적으로 출력 됨.]

 



반응형
반응형

python을 활용한 Data Science를 하기 위해서는 다음과 같은 환경에서 업무는 하는 것이 좋습니다.

(출처 : Python for Data Analysis)

 

1. Numpy (pip install numpy)

과학계산용 파운데이션 패키지

· 빠르고 효율적인 다차원 배열 객체 ndarry

· 배열 원소를 다루거나 배열 간의 수학 계산을 수행하는 함수

· 디스크로부터 배열 기반의 데이터를 읽거나 쓸 수 있는 도구

· 선형대수 계산, 푸리에 변환, 난수 발생기

· 파이썬과 c, c++ 그리고 포트란 코드를 통합하는 도구

 

2. pandas (pip install pandas)

구조화된 데이터를 빠르고 쉬우면서도 다양한 형식으로 가공할 수 있는 풍부한 자료 구조와 함수를 제공

 

3. matplotlib (pip install matplotlib [or] pip install -m matpoltlib)

그래프나 2차원 데이터 시각화를 생성하는 유명한 파이썬 라이브러리

 

4. IPython (pip install IPython)

표준 과학계산용 파이썬 도구 모음에 포함된 컴포넌트

· IPython을 웹브라우저와 연결할 수 있는 Mathematica 스타일의 HTML 노트북 기능

· 그래프를 즉시 그려보거나 여러 줄을 편집할 수 있는 기능 그리고 문법 강조 기능을 가진 Qt 프레임워크 기반의 GUI 콘솔

· 병렬 분산 컴퓨팅을 위한 기반 구조

· Tutorial : https://plot.ly/python/ipython-notebook-tutorial/

 

5. SciPy (pip install SciPy)

과학계산 컴퓨팅 영역의 여러 기본 문제를 다루는 패키지 모음

· scipy.integrate : 수치적분 루틴과 미분방정식 해법기

· scipy.linalg : numpy.linalg에서 제공하는 것보다 더 확장된 선형대수 루틴과 매트릭스 분해

· scipy.optimize : 함수 최적화기와 방정식의 근을 구하는 알고리즘

· scipy.signal : 시그널 프로세싱 도구

· scipy.sparse : 희소 행렬과 희소 선형 시스템 풀이법

· scipy.special : 감마 함수처럼 흔히 사용되는 수학 함수를 구현한 포트란 라이브러리인 SPECFUN 확장

· scipy.stats : 표준 연속/이산 확률 분포(집적도 함수, 샘플러, 연속 분포 함수)와 다양한 통계 테스트 그리고 좀 더 기술적인 통계 도구

· scipy.weave : 배열 계산을 빠르게 하기 위한 인라인 c++ 코드를 사용하는 도구

 

6. jupyter (pip install jupyter)

matplotlib을 활용하기 위해서 설치해야 하는 라이브러리

ipython notebook을 사용하려면 jupyter를 설치해야 합니다.

notebook은 Interative IDE이며, 향후 활용해야 하므로 미리 설치 합니다.

 

7. Matplotlib (pip install Matplotlib)

그래프를 활용하기 위해서 사용하는 필수 라이브러리

설치 할 경우 대소문자를 구문하니 반드시 "M"을 대 문자로 표시 해야 합니다.

 

이 모든 것이 포함된 도구는 아나콘다(Anaconda)라는 시스템이 있습니다.

 

https://www.continuum.io/downloads#_windows

 

 

추가적으로 프롬포트상의 highlighting을 적용하고 싶다면 다음의 패키지를 설치하면 됩니다.

distribute (pip install distribute)

pyreadline (pip install pyreadline)

반응형

+ Recent posts