唐宇迪-python计算库numpy

python计算库numpy

  • 导入numpy
  • 读取文件
  • 创建numpy数组
  • 查看数组大小
  • 查看数组类型
  • numpy数组的访问
  • 作比较
  • 类型转换
  • 矩阵的和
  • numpy生成等差数列
  • 访问数组的维度
  • 数组总元素
  • 生成全1、全0的数组
  • 生成等差数列(np.arange)
  • 生成随机数
  • 生成等差数列 (np.linspace)
  • 数组运算
  • numpy的常用方法
    • np.exp和np.sqrt
    • np.floor和.resize和.ravel和np.random
    • np.floor和np.hstack和np.random.random()
    • np.vsplit
    • id
    • view方法
    • copy方法
    • np.tile
    • np.argsort

导入numpy

import numpy

读取文件

xxx=numpy.genfromtxt("xxx.txt", delimiter=",")
# numpy.genfromtxt("xxx.txt", delimiter=",",dtype="U75", skip_header=1)
print(type(xxx))
# 

创建numpy数组

#The numpy.array() function can take a list or list of lists as input. When we input a list, we get a one-dimensional array as a result:
vector = numpy.array([5, 10, 15, 20])
#When we input a list of lists, we get a matrix as a result:
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
print(vector)
print(matrix)

#[ 5 10 15 20]
#[[ 5 10 15]
# [20 25 30]
# [35 40 45]]

查看数组大小

#We can use the ndarray.shape property to figure out how many elements are in the array
vector = numpy.array([1, 2, 3, 4])
print(vector.shape)
#For matrices, the shape property contains a tuple with 2 elements.
matrix = numpy.array([[5, 10, 15], [20, 25, 30]])
print(matrix.shape)
# (4,)
#(2, 3)

查看数组类型

#Each value in a NumPy array has to have the same data type
#NumPy will automatically figure out an appropriate data type when reading in data or converting lists to arrays. 
#You can check the data type of a NumPy array using the dtype property.
numbers = numpy.array([1, 2, 3, 4])
numbers.dtype

numpy数组的访问

与list访问方法相同

matrix = numpy.array([
                    [5, 10, 15], 
                    [20, 25, 30],
                    [35, 40, 45]
                 ])
print(matrix[:,1])
matrix = numpy.array([
                    [5, 10, 15], 
                    [20, 25, 30],
                    [35, 40, 45]
                 ])
print(matrix[:,0:2])

作比较

import numpy
#it will compare the second value to each element in the vector
# If the values are equal, the Python interpreter returns True; otherwise, it returns False
vector = numpy.array([5, 10, 15, 20])
vector == 10
# array([False,  True, False, False], dtype=bool)
#Compares vector to the value 10, which generates a new Boolean vector [False, True, False, False]. It assigns this result to equal_to_ten
vector = numpy.array([5, 10, 15, 20])
equal_to_ten = (vector == 10)
print(equal_to_ten)
print(vector[equal_to_ten])
# [False  True False False]
# [10]

类型转换

#We can convert the data type of an array with the ndarray.astype() method.
vector = numpy.array(["1", "2", "3"])
print(vector.dtype)
print(vector)
vector = vector.astype(float)
print(vector.dtype)
print(vector)

矩阵的和

# The axis dictates which dimension we perform the operation on
#1 means that we want to perform the operation on each row, and 0 means on each column
matrix = numpy.array([
                [5, 10, 15], 
                [20, 25, 30],
                [35, 40, 45]
             ])
matrix.sum(axis=1)
# array([ 30,  75, 120])

numpy生成等差数列

import numpy as np
a = np.arange(15).reshape(3, 5)
a
# array([[ 0,  1,  2,  3,  4],
#       [ 5,  6,  7,  8,  9],
#       [10, 11, 12, 13, 14]])

访问数组的维度

#the number of axes (dimensions) of the array
a.ndim
# 2

数组总元素

#the total number of elements of the array
a.size

生成全1、全0的数组

np.zeros ((3,4)) 
#array([[ 0.,  0.,  0.,  0.],
#       [ 0.,  0.,  0.,  0.],
#       [ 0.,  0.,  0.,  0.]])
np.ones( (2,3,4), dtype=np.int32 )
#array([[[1, 1, 1, 1],
#        [1, 1, 1, 1],
#        [1, 1, 1, 1]],
#
#       [[1, 1, 1, 1],
#        [1, 1, 1, 1],
#        [1, 1, 1, 1]]])

生成等差数列(np.arange)

#To create sequences of numbers
np.arange( 10, 30, 5 )
# array([10, 15, 20, 25])
np.arange(12).reshape(4,3)
# array([[ 0,  1,  2],
#       [ 3,  4,  5],
#       [ 6,  7,  8],
#       [ 9, 10, 11]])

生成随机数

np.random.random((2,3))
# array([[ 0.40130659,  0.45452825,  0.79776512],
#        [ 0.63220592,  0.74591134,  0.64130737]])

生成等差数列 (np.linspace)

from numpy import pi
np.linspace( 0, 2*pi, 100 )
#array([ 0.        ,  0.06346652,  0.12693304,  0.19039955,  0.25386607,
#        0.31733259,  0.38079911,  0.44426563,  0.50773215,  0.57119866,
#        0.63466518,  0.6981317 ,  0.76159822,  0.82506474,  0.88853126,
#        0.95199777,  1.01546429,  1.07893081,  1.14239733,  1.20586385,
#        1.26933037,  1.33279688,  1.3962634 ,  1.45972992,  1.52319644,
#        1.58666296,  1.65012947,  1.71359599,  1.77706251,  1.84052903,
#        1.90399555,  1.96746207,  2.03092858,  2.0943951 ,  2.15786162,
#        2.22132814,  2.28479466,  2.34826118,  2.41172769,  2.47519421,
#        2.53866073,  2.60212725,  2.66559377,  2.72906028,  2.7925268 ,
#        2.85599332,  2.91945984,  2.98292636,  3.04639288,  3.10985939,
#        3.17332591,  3.23679243,  3.30025895,  3.36372547,  3.42719199,
#        3.4906585 ,  3.55412502,  3.61759154,  3.68105806,  3.74452458,
#        3.8079911 ,  3.87145761,  3.93492413,  3.99839065,  4.06185717,
#        4.12532369,  4.1887902 ,  4.25225672,  4.31572324,  4.37918976,
#        4.44265628,  4.5061228 ,  4.56958931,  4.63305583,  4.69652235,
#        4.75998887,  4.82345539,  4.88692191,  4.95038842,  5.01385494,
#        5.07732146,  5.14078798,  5.2042545 ,  5.26772102,  5.33118753,
#        5.39465405,  5.45812057,  5.52158709,  5.58505361,  5.64852012,
#        5.71198664,  5.77545316,  5.83891968,  5.9023862 ,  5.96585272,
#        6.02931923,  6.09278575,  6.15625227,  6.21971879,  6.28318531])

数组运算

#the product operator * operates elementwise in NumPy arrays
a = np.array( [20,30,40,50] )
b = np.arange( 4 )
#print a 
#print b
#b
c = a-b
#print c
b**2
#print b**2
print(a<35)
#The matrix product can be performed using the dot function or method
A = np.array( [[1,1],
               [0,1]] )
B = np.array( [[2,0],
               [3,4]] )
print(A)
print(B)
#print A*B
print(A.dot(B))
print(np.dot(A, B)) 

numpy的常用方法

np.exp和np.sqrt

import numpy as np
B = np.arange(3)
print(B)
#print np.exp(B)
print(np.sqrt(B))

np.floor和.resize和.ravel和np.random

#Return the floor of the input
a = np.floor(10*np.random.random((3,4)))
#print(a)

#a.shape
## flatten the array
#print(a.ravel())
#a.shape = (6, 2)
#print(a)
#print(a.T)
print(a.resize((2,6)))
print(a)

#If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated:
#a.reshape(3,-1)

np.floor和np.hstack和np.random.random()

np.random.random():Return random floats in the half-open interval [0.0, 1.0).
np.hstack:Stack arrays in sequence horizontally (column wise).

a = np.floor(10*np.random.random((2,2)))
b = np.floor(10*np.random.random((2,2)))
print(a)
print('---')
print(b)
print('---')
print(np.hstack((a,b)))
#np.hstack((a,b))

np.vsplit

Split an array into multiple sub-arrays vertically (row-wise).

a = np.floor(10*np.random.random((2,12)))
#print a
#print np.hsplit(a,3)
#print np.hsplit(a,(3,4))   # Split a after the third and the fourth column
a = np.floor(10*np.random.random((12,2)))
print(a)
np.vsplit(a,3)

id

Return the identity of an object.

#Simple assignments make no copy of array objects or of their data.
a = np.arange(12)
b = a
# a and b are two names for the same ndarray object
b is a
b.shape = 3,4
print(a.shape)
print(id(a))
print(id(b))

view方法

a.view(dtype=None, type=None)
New view of array with the same data.

#The view method creates a new array object that looks at the same data.
c = a.view()
c is a
c.shape = 2,6
#print a.shape
c[0,4] = 1234
a

copy方法

a.copy(order=‘C’)
Return a copy of the array.

#The copy method makes a complete copy of the array and its data.
d = a.copy() 
d is a
d[0,0] = 9999
print(d)
print(a)

np.tile

Construct an array by repeating A the number of times given by reps.

a = np.arange(0, 40, 10)
b = np.tile(a, (3, 5)) 
print(a)
print(b)
#[ 0 10 20 30]
#[[ 0 10 20 30  0 10 20 30  0 10 20 30  0 10 20 30  0 10 20 30]
# [ 0 10 20 30  0 10 20 30  0 10 20 30  0 10 20 30  0 10 20 30]
# [ 0 10 20 30  0 10 20 30  0 10 20 30  0 10 20 30  0 10 20 30]]

np.argsort

Returns the indices that would sort an array.

a = np.array([[4, 3, 5], [1, 2, 1]])
#print(a)
#b = np.sort(a, axis=1)
#print(b)
#b
#a.sort(axis=1)
#print(a)
a = np.array([4, 3, 1, 2])
j = np.argsort(a)
print(j)
print(a[j])
#[2 3 1 0]
#[1 2 3 4]

你可能感兴趣的:(唐宇迪机器学习)