Numpy array 객체.

Numpy는 다차원 배열 객체를 제공하며 ndarray로 불린다. ndarray는 2개의 파트로 구성되어 있다.

  • actual data
  • data 설명을 위한 메타 데이터

Numpy array의 이점

Numpy배열은 일반적으로 단일 타입으로 저장되어야 한다. 배열의 아이템이 동일한경우 이점은 배열을 위한 필요 크기를 확인하기 쉽게 해준다. NumPy 배열은 벡터 연산을 지원하며, 완벽한 배열 처리를 지원한다. 반면 Python의 배열을 이용하는 경우라면 각 엘리먼트를 순회하면서 처리를 해야한다. 또한 NumPy는 최적화된 C API를 이용하여 매우 빠른 처리를 지원한다.

NumPy배열은 Python에서와 같이 인덱스를 이용하며, 0에서 부터 시작한다. 데이터 타입은 특정 객체에 의해서 결정이 된다.

NumPy배열은 다음과 같은 타입을 가진다.

In: a = arange(5)
In: a.dtype
Out: dtype('int64')

상기 코드는 int64 를 가진다. 만약 당신의 머신이 32bit라면 int34가 될것이다.

벡터는 수학에서 공통으로 사용되는 것으로 높은 차원의 객체를 이요하고자 할때에는 반드시 필요하다. 다음 코드를 보자.

In: a
Out: array([0, 1, 2, 3, 4])
In: a.shape
Out: (5, )

보는바와 같이 위 코드는 5개의 컴포넌트를 가진다. 값의 범위는 0 ~ 4를 가진다. shape 속성은 tuple이며, 튜플의 1의 엘리먼트는 5의 값으로 각 차원의 길이를 가지고 있다.

다차원 배열 생성하기.

In: m = array([arange(2), arange(2)])
In: m
Out:
array([[0, 1],
	   [0, 1]])

In: m.shape
Out: (2, 2)

2 * 2 의 다차원 배열을 arange()를 이용하여 만들었다. array()함수는 객체로 부터 배열을 만들어내며, 이는 우리가 전달한 것이다. 객체는 배열이어야 하며, 이 예에서는 배열의 리스트가 전달 되었다.

NumPy 함수는 추가적인 아규먼트를 위한 힙을 가지려고 노력하며 이는 사전에 정의한 디폴트 옵션을 포함한다.

NumPy 배열 엘리먼트 선택하기.

In: a = array([[1,2], [3,4]])
In: a
Out:
array([[1, 2],
	   [3, 4]])

In: a[0, 0]
Out: 1

In: a[0,1]
Out: 2

In: a[1,0]
Out: 3

In: a[1,1]
Out: 4

보는바와 같이 엘리먼트를 선택하는 것은 매우 간단하다. 단순히 배열변수[m, n]으로 지정만 해주면 된다.

NumPy 수치 타입

NumPy는 과학 계산을 위한 도구이므로 다양한 타입이 있다.

Type Description
bool 참/거짓 값으로 True혹은 False값을 가진다. bit에 저장됨
int i 플랫폼 Integer값으로 일반적으로 int32 or int64를 가진다.
int8 Byte(-128 to 127)
int16 Integer(-32768 to 32767)
int32 Integer(-2 ** 31 to 2 ** 31-1)
int64 Integer(-2 ** 63 to 2 ** 63-1)
uint8 Unsigned integer (0 to 255)
uint16 Unsigned integer (0 to 65535)
uint32 Unsigned integer (0 to 2 ** 32 -1)
uint64 Unsigned integer (0 to 2 ** 64 -1)
float16 절반 정확도 float값을 가진다. sign bit과 5bit exponent, 10 bits mantissa
float32 단정도 정확도 float값을 가진다. sign bit, 8bit exponent, 23 bits mantiss
float64 or float 배정도 정확도 float값을 가진다. sign bit, 11bit exponent, 52 bits mantissa
complex64 복합수를 표현하며 32비트 플롯 형을 표현한다.
complex128 or complex 복합 수를 표현하며 64비트 플롯 형을 표현한다.

데이터타입 객체

Data type object는 numpy.dtype클래스의 인스턴스이다. 데이터타입 객체는 바이트 내에 존재하는 데이터의 크기를 알려준다. 바이트 크기는 itemsize속성으로 알 수 있다.

In: a.dtype.itemsize
Out: 8

캐릭터 코드

Character code는 Numeric과 함께 backward compatibility를 제공하기 위해 포함되었다. Numeric은 NumPy의 전신이며 추천하지 않는다.

Type Character code
integer i
Unsigned integer u
Single precision float f
Double precision float d
bool b
complex D
string S
unicode U
Void V

예제 )

In: arange(7, dtyp='f')
Out: array([0., 1., 2., 3., 4., 5., 6.], dtype=float32)

In: arange(7, dtype='D')
Out: array([0.+0.j, 1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j, 5.+0.j, 6.+0.j])

데이터타입 생성자.

데이터 타입을 생성하기 위한 다양한 방법이 있으며, dtype을 이용하여 생성한다.

예제 ) ch02/createDatatype.py

import numpy as num

type1 = num.dtype(float)
print("num.dtype(float) : ", type1)

type2 = num.dtype('f')
print("num.dtype('f') : ", type2)

type3 = num.dtype('d')
print("num.dtype('d') : ", type3)

type4 = num.dtype('f8')
print("num.dtype('f8') : ", type4)

# 모든 데이터 타입을 출력한다. 
print("num.sctypeDict.keys() : ", num.sctypeDict.keys())

데이터 타입 속성

dtype 클래스는 몇가지 유용한 프로퍼티 속성을 가지고 있다.

예제 ) ch02/typeattr.py

# -*- coding: utf-8 -*-
import numpy as num

# char 어트리뷰트의 사용 
t = num.dtype('Float64')
print("t.char of Float64 : ", t.char)

# type 어트리뷰트는 배열 엘리먼트의 객체 타입에 상응한다. 
print("t.tyep of Float64 : ", t.type)

# str 속성은 데이터타입을 string으로 표현한다. 
# 엔디안을 나타내는 표기식과 바이트의 수를 노출한다. 
# 엔디안은 32비트 혹은 64비트 내부에 바이트 순서를 표시한다. 
# 빅 엔디안의 경우 가장 중요한 바이트는 맨 처음에 저장된다. 그리고 '>'로 표기된다. 
# 리틀 엔디안의 경우 가장 최근의 바이트가 가장 먼저 저장된다. 그리고 '<'로 표기된다.

print("t.str of Float64 : ", t.str)

결과 :

('t.char of Float64 : ', 'd')
('t.tyep of Float64 : ', <type 'numpy.float64'>)
('t.str of Float64 : ', '<f8')

1차원 배열 slicing 하기

1차원 배열의 슬라이싱은 일반적인 파이선과 Numpy가 동일한 방식으로 수행한다.

/ch02/slicing.py

# -*- coding: utf-8 -*-
import numpy as num

a = num.arange(9)
print("a[3:7] of arange(9) : ", a[3:7])

# 다음으로 우리는 0 ~ 7 까지 2씩 증가하면서 데이터를 추출할 수 있다. 
print("a[:7:2] of arange(9) : ", a[:7:2])

# 음수 인덱스를 지정하여 역순 배열을 생성할 수 있다. 
print("a[::-1] of arange(9) : ", a[::-1])

결과

('a[3:7] of arange(9) : ', array([3, 4, 5, 6]))
('a[:7:2] of arange(9) : ', array([0, 2, 4, 6]))
('a[::-1] of arange(9) : ', array([8, 7, 6, 5, 4, 3, 2, 1, 0]))

배열 가지고 놀기.

배열을 flattening 하여 변환하는 작업을 제공한다. Flattening은 다차원 배열을 1차원 배열로 변환하는 작업을 포함한다.

/ch02/flattening.py

# -*- coding: utf-8 -*-
import numpy as num

print("In: b = arange(24).reshape(2,3,4)")
b = num.arange(24).reshape(2,3,4)

# reshape는 n차원의 배열을 다른 n차원의 배열로 변환할때 사용한다. 
# 아래 예는 1차원배열을 3차원 배열로 Z : 2, Y : 3, X : 4의 형태로 변환한 모양이다. 
print("result of reshape(2,3,4) : ", b)

# 우리는 3차원 배열을 기준으로 다음과 같은 작업을 한다. 
# 1. ravel() : 
# ravel은 n차원 배열을 1차원 배열로 풀어놓는다. 
print("result of b.ravel() : ", b.ravel())

# 2. flatten():
# flatten은 ravel()과 결과는 동일하게 나온다. 차이점은 항상 새로운 메모리를 할당하여 
# 새로운 객체를 만든다는 것이다. ravel은 배열의 뷰를 반환한다. 
print("result of b.flatten() : ", b.flatten())

# 3. shape()
# shape()는 reshape() 함수가 있지만 튜플을 직접적인 방법으로 정의할 수 있도록 한다. 
# 보는바와 같이 3차원 배열인 b가 2차원 배열로 변경이 되었다. 
b.shape = (6, 4)
print("result of b.shape = (6, 4) : ", b)

# 4. transpose()
# transpose()는 선형 대수에서 2차원 배열상에서 row --> column으로 column --> row로 변경하는 작업을 한다. 
print ("before trsnspose b : ", b)
print ("after trsnspose b : ", b.transpose())

# 5. resize()
# resize()는 배열을 새로운 차원의 배열로 변경한다. 
# 괄호가 하나더 있음을 확인하자...
b.resize( (2, 12) )
print ("result of b.resize( (2, 12) ) : ", b)

결과 :

In: b = arange(24).reshape(2,3,4)
('result of reshape(2,3,4) : ', array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]]))
('result of b.ravel() : ', array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23]))
('result of b.flatten() : ', array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23]))
('result of b.shape = (6, 4) : ', array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]]))
('before trsnspose b : ', array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]]))
('after trsnspose b : ', array([[ 0,  4,  8, 12, 16, 20],
       [ 1,  5,  9, 13, 17, 21],
       [ 2,  6, 10, 14, 18, 22],
       [ 3,  7, 11, 15, 19, 23]]))
('result of b.resize( (2, 12) ) : ', array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]]))

Stack 작업하기.

Stack은 vstack(), dstack(), hstack(), column_stack(), row_stack(), concatenate() 함수를 제공하고 있다.

Horizontal stacking :

horizontal stacking은 ndarrays의 튜플을 이용하여 hstack()함수를 실행한 결과를 반환한다.

예제) ch02/horizontalStack.py

# _*_ coding: utf-8 _*_
import numpy as num

a = num.arange(9).reshape(3, 3)
print ("num.arange(9).reshape(3, 3) : ", a)

b = 2 * a
print ("b = 2 * a : ", b)

# Horizontal Stack
print ("num.hstack( (a, b) ) : ", num.hstack( (a, b) ))

실행결과 :

('num.arange(9).reshape(3, 3) : ', 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]]))
('b = 2 * a : ', 
array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]]))
('num.hstack( (a, b) ) : ', 
array([[ 0,  1,  2,  0,  2,  4],
       [ 3,  4,  5,  6,  8, 10],
       [ 6,  7,  8, 12, 14, 16]]))

Vertical stacking :

vstack() 함수를 이용하여 주어진 배열을 수직으로 붙여준다.

예제) ch02/verticalStacking.py

# _*_ coding: utf-8 _*_
import numpy as num

a = num.arange(9).reshape(3, 3)
print ("num.arange(9).reshape(3, 3) : ", a)

b = 2 * a
print ("b = 2 * a : ", b)

# verticla Stack
print ("num.vstack( (a, b) ) : ", num.vstack( (a, b) ))

결과

('num.arange(9).reshape(3, 3) : ', array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]]))
('b = 2 * a : ', array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]]))
('num.vstack( (a, b) ) : ', array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]]))

concatenate

concatenate 함수에서 axis=0으로 인자를 부여하면 vstack()와 동일한 처리가 된다.

예제 : ch02/concatenateTest.py

# _*_ coding: utf-8 _*_
import numpy as num

a = num.arange(9).reshape(3, 3)
print ("num.arange(9).reshape(3, 3) : ", a)

b = 2 * a
print ("b = 2 * a : ", b)

# concatenate + axis=0 = vstack()
print ("concatenate( (a, b), axisx=0) : ", num.concatenate( (a, b), axis=0 ) )
print ("concatenate( (a, b), axisx=1) : ", num.concatenate( (a, b), axis=1 ) )

결과 :

('num.arange(9).reshape(3, 3) : ', array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]]))
('b = 2 * a : ', array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]]))
('concatenate( (a, b), axisx=0) : ', array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]]))
('concatenate( (a, b), axisx=1) : ', array([[ 0,  1,  2,  0,  2,  4],
       [ 3,  4,  5,  6,  8, 10],
       [ 6,  7,  8, 12, 14, 16]]))

Depth stacking:

dstack()함수를 이용하면 주어진 튜플을 깊이 기준으로 스택 처리를 수행한다.

예제 : ch02/depthStack.py

# _*_ coding: utf-8 _*_
import numpy as num

a = num.arange(9).reshape(3, 3)
print ("num.arange(9).reshape(3, 3) : ", a)

b = 2 * a
print ("b = 2 * a : ", b)

# depth stacking 
print ("dstack( (a, b) ) : ", num.dstack( (a, b) ) )

결과 :

('num.arange(9).reshape(3, 3) : ', array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]]))
('b = 2 * a : ', array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]]))
('dstack( (a, b) ) : ', array([[[ 0,  0],
        [ 1,  2],
        [ 2,  4]],

       [[ 3,  6],
        [ 4,  8],
        [ 5, 10]],

       [[ 6, 12],
        [ 7, 14],
        [ 8, 16]]]))

Column Stacking

column_stack()함수는 1차원 배열의 칼럼 기준으로 스택을 쌓는다. 즉 1차원배열 여러개를 칼럼 기준으로 쌓아가는 방식이다.

예제 : ch02/columnStack.py

# _*_ coding: utf-8 _*_
import numpy as num

oned = num.arange(2)

print ("num.arange(2) : ", oned)

twice_oned = 2 * oned

print ("2 * num.arange(2) : ", twice_oned)

columnStack = num.column_stack( (oned, twice_oned) )
print ("num.column_stack( (oned, twice_oned) ) : ", columnStack)

결과 :

('num.arange(2) : ', array([0, 1]))
('2 * num.arange(2) : ', array([0, 2]))
('num.column_stack( (oned, twice_oned) ) : ', array([[0, 0],
       [1, 2]]))

2차원 배열의 경우에는 hstack() 함수 처리 방법으로 쌓아간다.

예제 : ch02/columnStack2D.py

# _*_ coding: utf-8 _*_
import numpy as num

a = num.arange(9).reshape(3, 3)
print ("num.arange(9).reshape(3, 3) : ", a)

b = 2 * a
print ("b = 2 * a : ", b)

# column_stack 
print ("column_stack of 2D : column_stack( (a, b) ) : ", num.column_stack( (a, b) ) )

print ("compare column_stack of 2D and hstack : ", num.column_stack( (a, b) ) == num.hstack( (a, b) ) )

결과 :

('num.arange(9).reshape(3, 3) : ', array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]]))
('b = 2 * a : ', array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]]))
('column_stack of 2D : column_stack( (a, b) ) : ', array([[ 0,  1,  2,  0,  2,  4],
       [ 3,  4,  5,  6,  8, 10],
       [ 6,  7,  8, 12, 14, 16]]))
('compare column_stack of 2D and hstack : ', array([[ True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True]], dtype=bool))

Raw stacking

Numpy는 당연히 row기준의 stacking을 제공한다. row_stack()이며 1차원 배열과 2차원 배열에 대한 결과는 다음과 같다.

1차원 배열 예제 : ch02/rowStack.py

# _*_ coding: utf-8 _*_
import numpy as num

oned = num.arange(2)

print ("num.arange(2) : ", oned)

twice_oned = 2 * oned

print ("2 * num.arange(2) : ", twice_oned)

rowStack = num.row_stack( (oned, twice_oned) )
print ("num.row_stack( (oned, twice_oned) ) : ", rowStack)

결과 :

('num.arange(2) : ', array([0, 1]))
('2 * num.arange(2) : ', array([0, 2]))
('num.row_stack( (oned, twice_oned) ) : ', array([[0, 1],
       [0, 2]]))

2차원 배열 예제 : ch02/rowStack2D.py

# _*_ coding: utf-8 _*_
import numpy as num

a = num.arange(9).reshape(3, 3)
print ("num.arange(9).reshape(3, 3) : ", a)

b = 2 * a
print ("b = 2 * a : ", b)

# row_stack 
print ("row_stack of 2D : row_stack( (a, b) ) : ", num.row_stack( (a, b) ) )

print ("compare row_stack of 2D and vstack : ", num.row_stack( (a, b) ) == num.vstack( (a, b) ) )

결과 :

('num.arange(9).reshape(3, 3) : ', array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]]))
('b = 2 * a : ', array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]]))
('row_stack of 2D : row_stack( (a, b) ) : ', array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]]))
('compare row_stack of 2D and vstack : ', array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool))

Splitting arrays

numpy에서 split을 위한 메소드를 제공하며, 이는 수직, 수평, 깊이우선으로 스플릿을 수행할 수 있다. hsplit(), vsplit(), dsplit(), split() 함수를 제공한다.

Horizontal splitting

수평축을 기준으로 각 부분을 분리한다.

예제 : ch02/horizontalSplit.py

# _*_ coding: utf-8 _*_
import numpy as num

# make 3 * 3 narray
a = num.arange(9).reshape(3, 3)

print("num.arange(9).reshape(3, 3) : ", a)

# horizontal Split
print("num.hsplit(a, 3) : ", num.hsplit(a, 3)) 

# same horizontal split using split and axis
print("num.split(a, 3, axis=1) : ", num.split(a, 3, axis=1))

결과 :

('num.arange(9).reshape(3, 3) : ', array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]]))
('num.hsplit(a, 3) : ', [array([[0],
       [3],
       [6]]), array([[1],
       [4],
       [7]]), array([[2],
       [5],
       [8]])])
('num.split(a, 3, axis=1) : ', [array([[0],
       [3],
       [6]]), array([[1],
       [4],
       [7]]), array([[2],
       [5],
       [8]])])

Vertical splitting

vsplit()함수는 수직축을 기준으로 스플릿팅 한다.

예제 : ch02/verticalSplit.sh

# _*_ coding: utf-8 _*_
import numpy as num

a = num.arange(9).reshape(3, 3)

print("num.arange(9).reshape(3, 3) : ", a)

# vertical split using vsplit
print("num.vsplit(a, 3) : ", num.vsplit(a, 3) )

# vertical split using split with axis=0
print("num.split(a , 3, axis=0) : ", num.split(a, 3, axis=0))

결과 :

('num.arange(9).reshape(3, 3) : ', array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]]))
('num.vsplit(a, 3) : ', [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])])
('num.split(a , 3, axis=0) : ', [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])])

depth우선 스프리팅

dsplit()함수는 깊이 우선으로 스플리팅한다. 이 테스트를 위해서 3차원 배열을 만들어서 테스트 해보자.

예제 :
ch02/depthSplit.py

# _*_ coding:utf-8 _*_
import numpy as num

# make 3 * 3 * 3 array
a = num.arange(27).reshape(3, 3, 3)

print("num.arange(27).reshape(3, 3, 3) : ", a)

# depth-wise splitting
print("num.dsplit(a, 3) : ", num.dsplit(a, 3) )

결과 :

('num.arange(27).reshape(3, 3, 3) : ', array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]]))
('num.dsplit(a, 3) : ', [array([[[ 0],
        [ 3],
        [ 6]],

       [[ 9],
        [12],
        [15]],

       [[18],
        [21],
        [24]]]), array([[[ 1],
        [ 4],
        [ 7]],

       [[10],
        [13],
        [16]],

       [[19],
        [22],
        [25]]]), array([[[ 2],
        [ 5],
        [ 8]],

       [[11],
        [14],
        [17]],

       [[20],
        [23],
        [26]]])])

Numpy 배열 기능 더 알아보기.

Numpy배열 기능은 다음 예제를 통해서 확인해보자.

예제: ch02/moreArrayAttribute.py

# _*_ coding: utf-8 _*_
import numpy as num

a = num.arange(24).reshape(2, 12)
print("num.arange(24).reshape(2, 12) : ", a)

# ndim은 배열의 차수를 반환한다. 
print("a.ndim : ", a.ndim)

# size는 배열이 가지는 엘리먼트의 총 개수를 나타낸다. 
print("a.size : ", a.size)

# itemsize는 배열내에 각 엘리먼트가 가지는 바이트 수를 반환한다. 
print("a.itemsize : ", a.itemsize)

# nbyte는 전체 배열이 필요로 하는 총 바이트수이다. 이는 size * itemsize로 계산된다. 
print("a.nbytes : ", a.nbytes)

print("a.size * a.itemsize : ", (a.size * a.itemsize))

print("num.resize(6, 4) : ", num.resize(6, 4))

# T는 transpose()함수와 동일한 결과를 반환한다. 
print("a.T : ", a.T)

print("a.ndim after transform T : ", a.ndim)

print("a.T after transform T :", a.T)

# 복소수는 numpy에서 j로 표현된다. 
print("num.array([1.j + 1, 2.j + 3]) : ", num.array([1.j + 1, 2.j + 3]))

# real은 배열에서 숫자의 real파트를 반환한다. 
print("a.real : ", a.real)

# imag는 배열의 허수 영역을 출력한다. 
print("a.imag : ", a.imag)

# dtype은 배열이 저장하는 데이터 타입이며 복소수의 경우 complex가 반환된다. 
print("a.dtype : ", a.dtype)

print("a.dtype.str : ", a.dtype.str)

# flat속성은 numpy.flatiter객체를 나타낸다. flatiter 를 통해서만 flat객체에 접근할 수 있으며, 생성자로 생성할 수 없다. 
# flat 반복자는 flat 배열의 각 엘리먼트를 반복하면서 조회가능하다. 
b = num.arange(4).reshape(2,2)
print("num.arange(4).reshape(2,2) : ", b)

f = b.flat
print("b.flat : ", f)

print("for it in f: print it : ")
for it in f:
	print (it)

# 직접적으로 flatiter 객체의 특정 인덱스에 접근하여 object를 획득할 수 있다.  
print("b.flat[2] : ", b.flat[2])

# 또한 직접 엘리먼트를 조회할 수 있다. 
print("b.flat[[1, 3]] : ", b.flat[[1, 3]])

print("b : ", b)

# flat속성은 세팅이 가능하며 다음과 같이 세팅한다. 
b.flat[[1, 3]] = 1
print("b.flat[[1, 3]] = 1 : ", b)

결과 :

('num.arange(24).reshape(2, 12) : ', array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]]))
('a.ndim : ', 2)
('a.size : ', 24)
('a.itemsize : ', 8)
('a.nbytes : ', 192)
('a.size * a.itemsize : ', 192)
('num.resize(6, 4) : ', array([6, 6, 6, 6]))
('a.T : ', array([[ 0, 12],
       [ 1, 13],
       [ 2, 14],
       [ 3, 15],
       [ 4, 16],
       [ 5, 17],
       [ 6, 18],
       [ 7, 19],
       [ 8, 20],
       [ 9, 21],
       [10, 22],
       [11, 23]]))
('a.ndim after transform T : ', 2)
('a.T after transform T :', array([[ 0, 12],
       [ 1, 13],
       [ 2, 14],
       [ 3, 15],
       [ 4, 16],
       [ 5, 17],
       [ 6, 18],
       [ 7, 19],
       [ 8, 20],
       [ 9, 21],
       [10, 22],
       [11, 23]]))
('num.array([1.j + 1, 2.j + 3]) : ', array([ 1.+1.j,  3.+2.j]))
('a.real : ', array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]]))
('a.imag : ', array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]))
('a.dtype : ', dtype('int64'))
('a.dtype.str : ', '<i8')
('num.arange(4).reshape(2,2) : ', array([[0, 1],
       [2, 3]]))
('b.flat : ', <numpy.flatiter object at 0x7fc4cca14800>)
for it in f: print it : 
0
1
2
3
('b.flat[2] : ', 2)
('b.flat[[1, 3]] : ', array([1, 3]))
('b : ', array([[0, 1],
       [2, 3]]))
('b.flat[[1, 3]] = 1 : ', array([[0, 1],
       [2, 1]]))

배열 변환하기.

Numpy배열을 일반 파이선 리스트로 변환이 가능하다. tolist() 함수는 이러한 변환을 처리한다.

예제: ch02/convertArray.py

# _*_ coding: utf-8 _*_
import numpy as num

a = num.array([ 1. + 1.j, 3. + 2.j])
print("num.array([ 1. + 1.j, 3. + 2.j]) : ", a)

# tolist()함수를 이용하여 배열을 리스트로 변환한다.
print("a.tolist() : ", a.tolist())

# 배열을 특정 타입의 배열로 변환한다. 
print("a.astype(int) : ", a.astype(int))

# 배열을 복소수형 타입으로 변환한다. 
print("a.astype('complex') : ", a.astype('complex'))

결과:

/python-data/ch02/convertArray.py:11: ComplexWarning: Casting complex values to real discards the imaginary part
  print("a.astype(int) : ", a.astype(int))
('num.array([ 1. + 1.j, 3. + 2.j]) : ', array([ 1.+1.j,  3.+2.j]))
('a.tolist() : ', [(1+1j), (3+2j)])
('a.astype(int) : ', array([1, 3]))
("a.astype('complex') : ", array([ 1.+1.j,  3.+2.j]))