#This code shows basic np.array usage with several basic functions #Print() is used for print result. #Written by Princess Liatris in 2017-01-11 import numpy as np # import numpy lib as np to use np.array #01. random nparray declaration data = 2 + np.random.randn(5,5) + 0 # 5x5 random array declaration. np array need initialization/ sigma * np.random.randn(...) + mu(avg) print(data) # print random variables #02. nparray numeric operations data2 = data * 10 print('') print(data2) # print random variables data3 = data + data print('') print(data3) # print random variables #03. show array shape print('') print(data.shape) # shows 5x5 (5,5) print('') print(data.dtype) # shows numpy data types(result is float64) #04. generate ndarray & array copy data4 = [6,7.5,8,0,1] arr1 = np.array(data4) #generate new np.array with array function #print copied dataset print('') print(arr1) #05. list array to multi - dimention array data5 = [[1,2,3,4],[5,6,7,8]] # generate list array print('') print(data5) # print list array arr2 = np.array(data5)#copy and change as multi-dimention array print('') print(arr2) #print changed result with arr2 print('') print(arr2.ndim) # print dimention with arr2 print('') print(arr2.shape) # result is (2,4) #06. np.array initialization print('') zeros = np.zeros((2,5))#need 2 (()), filled with 0 print(zeros) #generate 2x5 array with 0 print('') zeros = np.ones((2,5)) # filled with 1 print(zeros) #generate 2x5 array with 1 print('') zeros2 = np.empty([2,4])# filled with non initialized, can give([size], dtype=,order) print(zeros2)#generate 2x4 array with 'non initialized' data, not empty #print arranged data print(np.arange(20)) #07 np.array data types arr3 = np.array([1,2,3],dtype = np.float64) #numpy's basic dtype is float64 arr4 = np.array([1,2,3],dtype = np.int32) print('') print(arr3.dtype) #float64 print(arr4.dtype) #int32 #08. change np.array data type arr5 = np.array([3.7,1.2,2.6,0.5,12.9]) print('') print(arr5) print('') print(arr5.astype(np.int32))#change data type as int32 arr5 = arr5.astype(np.int32) arr5 = arr5.astype(np.float64 )#change data type as float64(roleback) print('') print(arr5)#changed datatype, loses are not recovered int_array = np.arange(10) calibers = np.array([.22,.270,.357,.380,.44,.50],dtype =np.float64) int_array = int_array.astype(calibers.dtype)#get another array datatype ans assign target array with dtype) print('') print(int_array)#changed datatype, float64 type #09. calc with array and skalar arr10 = np.array([[1,2,3],[4,5,6]]) print('') print(arr10) print('') print(arr10*arr10) print('') print(arr10-arr10) print('') print(1/arr10)#broadcasting, skalar values are affect to all variables print('') print(arr10 ** 0.5) #10. slicing ang index arr10 = np.arange(10) print(arr10[5])#print 6th element of arr10 print(arr10[5:8])#print 6 - 8th element of arr10 arr10[5:8]=12 print(arr10)#6 - 8th changed to 12 arr_slice = np.array([[1,2,3],[4,5,6],[7,8,9]]) print(arr_slice[2]) # print 1th dimention array with line 3 print(arr_slice[2][2])#print 1 element with 2,2(last element) arr_slice[2] = 0 print(arr_slice)#all line 2 were changed to 0 print(arr_slice[:2])# :number is remove with : over print(arr_slice[2:])# number: is eremove with : under print(arr_slice[:,2:])# : means seelct all, reduce dimentionality #11. boolean indexing names = np.array(['bob','joe','will','bob','will','joe','joe'])#generate name index data = np.random.randn(7,4)# random generate 7 x 4 print(names) print(data) print(names == 'bob')# find bob in names print(data[names =='bob']) # it can use by print other index print(data[~(names =='bob')]) # choose that not 'bob' print(data[(names =='bob') | (names =='joe')]) # can use &(and) | (or) #12. fancy indexing arr = np.empty((8,4))#generate 8x4 for i in range(8): arr[i] = i # imput ith line with i to arr print(arr)# print arr print('') print(arr[[4,3,0,6]])# show 4,3,0,6th row with arr if use - index, reversed print(arr[[3,3,0,2],[3,3,0,2]])# show (3,3) (3,3) (0,0) (2,2) eleemnts print(arr[[3,3,0,2]][:,[3,3,0,2]])# show 3,3,0,2 cols and rows, same with arr[np.ix_[3,3,0,2],[3,3,0,2]] # 13. transpose arr = np.arange(15).reshape((3,5))# generate 15 list to 3x5 dimention print(arr) print(arr.T)#transpose np.dot(arr.T,arr)# calculate X^tX print(arr.transpose(1,0))#change lines with 0,1 -> 1,0 line #print(arr.swapaxes(1,2))# exchange cach rows #14 universal functions arr = np.arange(10) arr2 = np.arange(10) +10 print(np.sqrt(arr))#sqrt print(np.exp(arr))#exponential print(np.maximum(arr,arr2))#maximum between 2 arrays print(np.modf(arr))#used for div result and others #15 array data processing points = np.arange(-5,5,0.01)# -5 to 5 with 0.01 increase xs,ys = np.meshgrid(points, points)#shows with meshgrid form print(ys) print(np.where([[True, False], [True, True]], [[1, 2], [3, 4]], [[9, 8], [7, 6]]))#generate new array from old array print(arr.mean()) # np mean print(arr.sum()) # np sum print(arr.mean(axis = 0)) # np mean wit 1 level low dimentionality #16 boolean methods arr = np.random.randn(100) print((arr > 0).sum()) # number of positive values(print conditional sum) bools = np.array([False,True,False,False]) #fnd out true print(bools.any())# there is true print(bools.all())# there are all true arr.sort() # sorting array in(), choose dimentionality print(arr) #17. np.unique names = np.array(['bob','bob','angel']) print(np.unique(names))#find out unique values values = np.array([6,0,0,3,2,5,6,]) print(np.in1d(values,[2,3,6]))# return true if there is element # 18 . np.array load and save arr = np.arange(10) np.save('some_array',arr) # np.save array with .npy formay np.savez('array_archive.npz',a = arr, b = arr)#several array saving with compressed npz file format np.load('some_array.npy')#load .npy format #np.loadtxt(name, delimiter) - numpy text loader #np.savetxt(name, delimiter) - numpy text saver #19. calculus x = np.array([[1,2],[3,4]]) y = np.array([[1,2],[3,4]]) print(np.dot(x,y))#matrix mul calculation print(np.random.normal(size =(4,4)))# np randopm with 4x4
np.array 코드 요약
Numpy array프로그래밍과 연산에 사용되는 기초 코드들을 하나의 예제 코드로 정리했습니다. 도움이 되시기를 바래요.
댓글 없음:
댓글 쓰기
글에 대한 의문점이나 요청점, 남기고 싶은 댓글이 있으시면 남겨 주세요. 단 악성 및 스팸성 댓글일 경우 삭제 및 차단될 수 있습니다.
모든 댓글은 검토 후 게시됩니다.