python

pip

7월 14, 2016 python No comments

pip?

python package index인데 손쉽게 python module을 설치 할 수 있습니다. https://pypi.python.org/pypi/pip

python module을 설치 할때 이전에는 version별로 검색을 통해 link 따라가면서 설치 하곤 했는데

pip가 활성화 되서 설치하기 쉬워졌네요

설치

c:>pip install numpy

제거

c:>pip uninstall numpy

목록 확인

c:>pip list

making pyd module

7월 14, 2016 python No comments

testpyd.pyd

주의 : 모든 source 및 출력은 소문자로

1.Visual Studio를 이용하여 win32 DLL Project 만들기

2.c/c++ -> include directory 추가

  • c:\python34\include
  • C:\python34\lib\site-packages\numpy\core\include

3.linker에서 library path 추가 및 종속성에 python lib추가

  • c:\python34\libs
  • python34.lib

4.linker에서 출력 파일을 testpyd.pyd 로 변경

5.기존 testpyd.cpp 파일은 삭제

6.testpyd.pyx 파일 생성

import ctypes
import numpy as np
cimport numpy as np

cpdef publiic int cy_sum(int a, int b):
    return a+b

7.cython을 이용하여 testpyd.cpp 파일 generate

cython -3 -o testpyd.cpp testpyd.pyx

-3 : python-3
-o : output source file

8.visual sutdio에서 rebuild 수행

9.test

C:\testpyd>ipython3 --pylab으로 실행 후

>import testpyd

>testpyd.cy_test(10)
55

numpy simple tip

7월 14, 2016 python No comments

hex 출력

import numpy as np
np.set_printoptions(formatter={'int':hex})
np.array([1,2,3,4,5])

import numpy as np
A = np.array([[1,2],[3,4]])

vhex = np.vectorize(hex)

vhex(A)
array([['0x1', '0x2'], ['0x3', '0x4']], dtype='<U8')

2차원 인경우 tuple로 전달(2차원 array삽입 및 ‘ ‘.join 출력)

data = np.ndarray((5,10), dtype=float) 
' '.join(['%f' % d for d in data[0]])

1로 채워진 ndarray 생성

v = np.ones(32,  dtype='uint32')

hjson module

7월 13, 2016 python No comments

hjson module ( https://hjson.org )

the Human JSON이라는 이름으로 json 파일을 setting 형태로 저장해서 사용 할 때

마지막 항목에 ,를 붙인다던가의 사소한 syntax error는 무시해 주는 확장형 json 입니다.

module간의 interface에서는 굳이 쓸 필요 없을 듯 하고,

주석도 지원해 주기는 하는데 추후 호환성을 위해서는 별로.. 안하는게 좋을듯 합니다.

1.pip로 hjson 설치

C:>pip instsall hjson

2.json과 동일하게 load

d = hjson.load(open('material.json', encoding='utf-8-sig'))

3.json 파일로 write

hson.dumpJSON(d, open('result,json', mode='x'), indent=2)

ipython plot test

7월 13, 2016 python No comments

1.ipython3를 –pylab parameter로 실행 c:>ipython3 –pylab

ipython_초기실행

2.numpy arange array 0~359 생성 d = np.arange(360)

3.sin 값으로 변환

d = np.sin(deg2rad(d))

4.matplotlib의 plot으로 sine graph출력 plot(d)

figure_1

ipython config

7월 13, 2016 python No comments

python config 파일 위치 확인

c:>ipython locate

python profile 생성 하기

c:/>ipython profile create  

ipython_config.py 파일에서 수정

c.TerminalInteractiveShell.editor = 'c:/program files/sublimetext3/sublimetext.exe'

ipython command에서 py파일 직접 수정 후 실행

IN]%edit test.py 

pandas excel file parsing

7월 13, 2016 python No comments

기존 time_zone data json형태로 변환

import json
records = [json.loads(line) for line in open('usagov.txt')]

records에서 timezone(‘tz’) 만 구하기

time_zones = [rec['tz'] for rec in records]

collections를 이용하여 각 timezone의 count 세기

from collections import defaultdict
def get_counts(sequence):
    counts = defaultdict(int)
    for x in sequence:
        counts[x] += 1
    return counts

Pandas로 DataFrame으로 Importing 하고 value_counts()를 통해 Series로 만든후 plot 출력

from pandas import DataFrame, Series
import numpy as npimport pandas as pd

frame = DataFrame(records)
tz_counts = frame['tz'].value_counts()
tz_counts.plot(kind='barh')

Load Excel File

  • excel 파일 load후 parse를 통해 해당 sheet DataFrame으로 변환
xls_file = pd.ExcelFile(exlFName)
xl = xls_file.parse(xls_file.sheet_names[sheetIdx])

loc를 이용하여 query 수행 및 특정 Series에 삽입

for i in range(len(xl)):    
    mt.loc[mt.id == xl.icol(idx)[i], ['price']] = xl.icol(amountIdx)[i]

원하는 colume순으로 재정렬

  • DataFrame 새로 생성시 columns에 원하는 array전달
cols = ['id', 'name', 'spec', 'remark', 'info'] 
mt = pd.DataFrame(mt, columns=cols)

records형태의 json으로 출력 후 json으로 parsing

j = json.loads(mt.to_json(orient='records'))

json load & save

7월 13, 2016 python No comments

import json

1.우선 json 파일 read

fs = open('L3-12.json')
data = fs.read()

2.read한 str을 json.loads() 수행

json.loads(data)

file pointer를 이용한 직접 전달은

json.load(fs)

또는

[json.loads(line) for line in open('L3-12.json')]

그런데 encoding 문제로 utf-8-sig로 변경

fs = open('L3-12.json', encoding='utf-8-sig')

하지만 이역시도 간혹 json 문법에 맞지 않으면 error발생됨

ex)

{
    "test" : 1,
}

마지막 element인데도 불구하고 , 가 있기에 error발생

  1. json file로 write하기

– mode=’x’ : create file의 file handle전달
– indent=2 : indent된 json output출력
– sort_keys=True : key 값으로 sort 후 출력

json.dump(j, open('result.json', mode='x'), indent=2, sort_keys=True)