[Python] Scipy and Numpy(1)

import numpy as np

#Create an array of 1*10^7 elements
arr = np.arange(1e7)

#Converting ndarray to list
larr = arr.tolist()

#Create a 2D numpy array
arr = np.zeros((3,3))

#Converting a array to matrix
mat = np.matrix(arr)
np.matrix('1,2,3;4,5,6;7,8,9');

#Array Creation
#First we create a list and then
#wrap it with the np.array() function
alist = [1,2,3]
arr = np.array(alist)

#Creating an array of zeros with 5 elements
arr = np.zeros(5)

#Creating an array going from 0 to 100
#not include 100
arr = np.arange(100)

#from 10 to 100 (not include 100)
arr = np.arange(10, 100)

#100 steps form 1 to 100
#(start, end, step)
arr = np.linspace(0, 1, 100)

#Creating an 5X5 array of zeros
image = np.zeros((5,5))

#Creating a 5X5X5 cube of 1's
#The astype() method sets the array with integer elements
cube = np.zeros(5,5,5).astype(int) + 1

#Or even simpler with 16-bit floating-point precision
cube = np.ones((5,5,5)).astype(np.float16)

#Change Data type
#Use dtype: int numpy.float16, numpy.float32, numpy.float64
arr = np.zeros(2, dtype=int)
arr = np.zeros(2, dtype=np.float32)


'''
The restructured arrays are just different views
of the same data in memory.
If chang one of them, you will change all.
If you don't want this to happen, then use the numpy.copy function
to separete the arrays mamory-wise.
'''
#Created arrays and reshape them in many others ways
#Creating an array with elements from 0 to 999
arr1d = np.arange(1000)

#reshaping the array to a 10x10x10 3D array
arr3d = arr1d.reshape((10,10,10))
arr3d = np.reshape(arr1d, (10,10,10))

#Invesely, we can flatten arrays
arr4d = np.zeros((10,10,10,10))
arr1d = arr4d.ravel()
print arr1d.shape

recarr = np.zeros((2,), dtype('i4, f4, a10'))
#the type for the first to third columns
#i4 := 32-bit integer
#f4 := 32-bit float
#a10 := a string 10 characters long

#We can assign names to each column
recarr.dtype.names = ('Integers', 'Floats', 'Strings')


#Indexing and Slicing
alist = [[1,2],[3,4]]
arr = np.array(alist)
arr[0,1]#It's the same as arr[0][1]
arr[:,1]#return the last column
arr[1,:]#return the bottom row

  

转载于:https://www.cnblogs.com/KennyRom/p/6693954.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值