Python科学计算库-Numpy的使用基础

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/while10/article/details/78585889

python科学计算库-numpy的使用
一、NumPy 是什么
NumPy 是 Python 科学计算的基础包,它专为进行严格的数字处理而产生。在之前的随笔里已有更加详细的介绍,这里不再赘述。 利用 Python 进行数据分析

二、ndarray 是什么
ndarray 是一个多维的数组对象,具有矢量算术运算能力和复杂的广播能力,并具有执行速度快和节省空间的特点。

import numpy#这句话的意思是用来将numpy的库引用进来
#下面是打开数据的语句,从txt中读取数据,用逗号作为分隔符,取出来的类型是str
#但是他好像是每一行又作为一个元素(自己理解的,不知道对不对)
shuju = numpy.genfromtxt("world_alcohol.txt", delimiter = ",",dtype = str)
print(type(shuju))#打印数据类型 numpy。ndarray所有的numpy都是ndarray结构
print(shuju)#打印数据
print(help(numpy.genfromtxt))#打印帮助文档,可以开两个编译器,一个用于打印帮助文档
<class 'numpy.ndarray'>
[['Year' 'WHO region' 'Country' 'Beverage Types' 'Display Value']
 ['1986' 'Western Pacific' 'Viet Nam' 'Wine' '0']
 ['1986' 'Americas' 'Uruguay' 'Other' '0.5']
 ..., 
 ['1987' 'Africa' 'Malawi' 'Other' '0.75']
 ['1989' 'Americas' 'Bahamas' 'Wine' '1.5']
 ['1985' 'Africa' 'Malawi' 'Spirits' '0.31']]
Help on function genfromtxt in module numpy.lib.npyio:

genfromtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=None, replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None)
    Load data from a text file, with missing values handled as specified.


None
vector = numpy.array([5,10,15,20])#定义一个一维向量
matrix = numpy.array([[5,10],[6,20]])#定义一个二维矩阵,看起来好像是list中有list
#相应的定义三维的矩阵就用三个中括号。
print(vector)
print(vector.shape)#注意一维的输出格式
print(matrix.shape)#打印shape看看矩阵的行和列
[ 5 10 15 20]
(4,)
(2, 2)
import numpy
numbers = numpy.array([1,2,3,4])#注意list中元素可以是不同类型的但是numpy.array中元素必须为相同类型的
print(numbers)
print(type(numbers))#输出的是numbers的类型
numbers.dtype#输出的是numbers中data(也叫元素)的类型
[1 2 3 4]
<class 'numpy.ndarray'>





dtype('int32')
shuju = numpy.genfromtxt("world_alcohol.txt", delimiter = ",",dtype = str)
print(shuju)
#如果我想取某一行某一列
er_si = shuju[2,4]#将shuju中第二行第四列数据提取出来
print(er_si)
[['Year' 'WHO region' 'Country' 'Beverage Types' 'Display Value']
 ['1986' 'Western Pacific' 'Viet Nam' 'Wine' '0']
 ['1986' 'Americas' 'Uruguay' 'Other' '0.5']
 ..., 
 ['1987' 'Africa' 'Malawi' 'Other' '0.75']
 ['1989' 'Americas' 'Bahamas' 'Wine' '1.5']
 ['1985' 'Africa' 'Malawi' 'Spirits' '0.31']]
0.5
[2 5 8]
matrix = numpy.array([
    [1,2,3],
    [4,5,6],
    [7,8,9]
])
print(matrix[:,1])#输出第1列,:代表全部
print(matrix[0,:])#输出第0行
print(matrix[:,0:2])#取两列的方式:也代表到
[2 5 8]
[1 2 3]
[[1 2]
 [4 5]
 [7 8]]
import numpy
vector = numpy.array([1,2,3,4])
vector == 3#注意输出结果是bool型的,最后也标注出来了
array([False, False,  True, False], dtype=bool)
#二维的也一样
matrix = numpy.array([
    [1,2,3],
    [4,5,6],
    [7,8,9]
])
matrix == 3
array([[False, False,  True],
       [False, False, False],
       [False, False, False]], dtype=bool)
#得到了一堆bool的类型有什么用
import numpy
vector = numpy.array([1,2,3,4])
equal_to_three = (vector == 3)
print(equal_to_three)
print(vector[equal_to_three])#如果为真才返回值,可以这样作为索引下标
[False False  True False]
[3]
#输出有3元素的那一行
matrix = numpy.array([
    [1,2,3],
    [4,5,6],
    [7,8,9]
])
print_c = (matrix[:,1] == 2)#从第1列中寻找哪一个等于2
print(matrix[2])#这样缺省是输出矩阵的第2行
print(print_c)#因为是从第一列中找的,所以这个地方输出第一列中找的值
print(matrix[print_c,:])#此时print_c返回的是true的值,也就是第0行,所以这输出的是第0行的所有值
[7 8 9]
[ True False False]
[[1 2 3]]
import numpy
vector = numpy.array([1,2,3,4])
bool_panduan = (vector == 1) & (vector == 2)#向量中的值即等于1又等于2的,,,,显然没有
print(bool_panduan)#所以输出结果都是false
bool_panduan = (vector == 1) | (vector == 2)#向量中额值等于1或者等于2的,,,,显然有两个
print(bool_panduan)#所以输出结果有两个true
[False False False False]
[ True  True False False]
#对numpy。array的类型进行改变
import numpy
vector = numpy.array(["1","2","3","4"])#因为带双引号所以是str类型的
print(vector.dtype)#输出当前类型看看
print(vector)
vector = vector.astype(float)#assert type 将类型转换为float
print(vector.dtype)#输出当前类型看看
print(vector)#以前带引号现在不带了,说明转换了类型
print(vector.max())#这样可以用函数直接输出array中的最大值
<U1
['1' '2' '3' '4']
float64
[ 1.  2.  3.  4.]
4.0
#对行求和
matrix = numpy.array([
    [1,2,3],
    [4,5,6],
    [7,8,9]
])
matrix.sum(axis = 1)#对行求和
array([ 6, 15, 24])
#对列求和:区别就只有axis的值
matrix = numpy.array([
    [1,2,3],
    [4,5,6],
    [7,8,9]
])
matrix.sum(axis = 0)#对列求和
array([12, 15, 18])
import numpy as np#意思就是对numpy重新命名为np
print(np.arange(15))
a = np.arange(15).reshape(3,5)#对这15个元素进行一个reshape,reshape成三行五列的数组array
a#打印出来看看

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]





array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
a.shape
(3, 5)
a.ndim#打印看看是几维的数组
2
a.dtype#打印元素类型
dtype('int32')
a.size#打印元素个数
15
#初试化一个空矩阵,初始化都为0用np。zeros函数
np.zeros((3,4))
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
#定义三维数组,每个元素的类型为int32
a = np.ones((3,2,3),dtype = np.int32)
print(a.dtype)
print(a)
int32
[[[1 1 1]
  [1 1 1]]

 [[1 1 1]
  [1 1 1]]

 [[1 1 1]
  [1 1 1]]]
#可以这样构建数组,数组的值为10到50,间隔值为5
np.arange(10,50,5)
array([10, 15, 20, 25, 30, 35, 40, 45])
np.random.random((2,3))#numpy中调用random结再调用random函数,所以后面是两个括号。
#目的是为了产生两行三列的随机值
array([[ 0.57987265,  0.53664261,  0.0996795 ],
       [ 0.95114989,  0.62315414,  0.75531816]])
from numpy import pi#从numpy中将π取出来
np.linspace(0,pi,100)#将π从零开始分成100份
array([ 0.        ,  0.03173326,  0.06346652,  0.09519978,  0.12693304,
        0.1586663 ,  0.19039955,  0.22213281,  0.25386607,  0.28559933,
        0.31733259,  0.34906585,  0.38079911,  0.41253237,  0.44426563,
        0.47599889,  0.50773215,  0.53946541,  0.57119866,  0.60293192,
        0.63466518,  0.66639844,  0.6981317 ,  0.72986496,  0.76159822,
        0.79333148,  0.82506474,  0.856798  ,  0.88853126,  0.92026451,
        0.95199777,  0.98373103,  1.01546429,  1.04719755,  1.07893081,
        1.11066407,  1.14239733,  1.17413059,  1.20586385,  1.23759711,
        1.26933037,  1.30106362,  1.33279688,  1.36453014,  1.3962634 ,
        1.42799666,  1.45972992,  1.49146318,  1.52319644,  1.5549297 ,
        1.58666296,  1.61839622,  1.65012947,  1.68186273,  1.71359599,
        1.74532925,  1.77706251,  1.80879577,  1.84052903,  1.87226229,
        1.90399555,  1.93572881,  1.96746207,  1.99919533,  2.03092858,
        2.06266184,  2.0943951 ,  2.12612836,  2.15786162,  2.18959488,
        2.22132814,  2.2530614 ,  2.28479466,  2.31652792,  2.34826118,
        2.37999443,  2.41172769,  2.44346095,  2.47519421,  2.50692747,
        2.53866073,  2.57039399,  2.60212725,  2.63386051,  2.66559377,
        2.69732703,  2.72906028,  2.76079354,  2.7925268 ,  2.82426006,
        2.85599332,  2.88772658,  2.91945984,  2.9511931 ,  2.98292636,
        3.01465962,  3.04639288,  3.07812614,  3.10985939,  3.14159265])
a = np.array([10,20,30,40])
b = np.arange(4)
print(a)
print(b)
c = a - b#同维的数组可以相减
print(c)
print(b**2)
print(c<20)
[10 20 30 40]
[0 1 2 3]
[10 19 28 37]
[0 1 4 9]
[ True  True False False]
A = np.array([[1,1],
            [0,1]])
B = np.array([[2,0],
            [3,4]])
print(A)
print("------")
print(B)
print("------")
print(A*B)#对应位置进行相乘
print("------")
print(A.dot(B))#传统的A和B相乘
print(np.dot(A,B))#这种相乘的形式我更容易接受
[[1 1]
 [0 1]]
------
[[2 0]
 [3 4]]
------
[[2 0]
 [0 4]]
------
[[5 4]
 [3 4]]
[[5 4]
 [3 4]]

B = np.arange(3)
print(B)
print(np.exp(B))#代表e的B次幂,比如这就是e的0次幂,1次幂,2次幂
print(np.sqrt(B))#代表对B求根号
[0 1 2]
[ 1.          2.71828183  7.3890561 ]
[ 0.          1.          1.41421356]
#注意这个地方用random.random结构取到的值是-1到1的
#乘以10的目的就是为了扩大倍数
#floor的目的是为了向下取整
a = np.floor(10*np.random.random((3,4)))
print(a)
a.shape
print("------")
print(a.ravel())#将多维矩阵变为一维向量  ravel磨损的意思
print("------")
a.shape = (6,2)#再将向量变为多维矩阵   shape使变形的意思
print(a)
print("------")
a.shape = (3,-1)#-1代表另一维度自己计算即可
print(a)
[[ 0.  8.  9.  8.]
 [ 7.  6.  0.  6.]
 [ 0.  7.  8.  7.]]
------
[ 0.  8.  9.  8.  7.  6.  0.  6.  0.  7.  8.  7.]
------
[[ 0.  8.]
 [ 9.  8.]
 [ 7.  6.]
 [ 0.  6.]
 [ 0.  7.]
 [ 8.  7.]]
------
[[ 0.  8.  9.  8.]
 [ 7.  6.  0.  6.]
 [ 0.  7.  8.  7.]]
a = np.floor(10*np.random.random((2,2)))
b = np.floor(10*np.random.random((2,2)))
print(a)
print(b)
print(np.hstack((a,b)))#将两个矩阵横着拼接在一起  stack就是拼接操作的函数
print(np.vstack((a,b)))#将两个矩阵竖着拼接在一起
[[ 7.  2.]
 [ 1.  1.]]
[[ 6.  1.]
 [ 6.  1.]]
[[ 7.  2.  6.  1.]
 [ 1.  1.  6.  1.]]
[[ 7.  2.]
 [ 1.  1.]
 [ 6.  1.]
 [ 6.  1.]]
a = np.floor(10*np.random.random((2,12)))
print(a)
print("-----")
print(np.hsplit(a,3))#对数组进行切分,切分三等份
print("-----")
print(np.hsplit(a,(3,4)))#对数组进行切分,切分段为3和4
[[ 2.  6.  8.  7.  0.  2.  3.  3.  8.  2.  2.  8.]
 [ 9.  1.  6.  5.  8.  6.  9.  1.  6.  6.  1.  3.]]
-----
[array([[ 2.,  6.,  8.,  7.],
       [ 9.,  1.,  6.,  5.]]), array([[ 0.,  2.,  3.,  3.],
       [ 8.,  6.,  9.,  1.]]), array([[ 8.,  2.,  2.,  8.],
       [ 6.,  6.,  1.,  3.]])]
-----
[array([[ 2.,  6.,  8.],
       [ 9.,  1.,  6.]]), array([[ 7.],
       [ 5.]]), array([[ 0.,  2.,  3.,  3.,  8.,  2.,  2.,  8.],
       [ 8.,  6.,  9.,  1.,  6.,  6.,  1.,  3.]])]
import numpy as np
a = np.arange(12)
print(a)
b = a
print(b)
b.shape = 3,4   #这句话就可以将b设置成三行四列的矩阵
print(b)
print("------")
print(a)#打印a发现a也变了
print(id(a))
print(id(b))#打印发现他们两个,a和b的地址是一样的
[ 0  1  2  3  4  5  6  7  8  9 10 11]
[ 0  1  2  3  4  5  6  7  8  9 10 11]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
------
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
124842832
124842832
c = a.view()#这样就不是指向同一个地方了
print(c)
print(c.shape)#三行四列的
c.shape = 2,6
print(c)
print(c.shape)
c[0,4] = 1234#
print(a)#但是对c赋值,依旧能改变a中的值
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
(3, 4)
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]]
(2, 6)
[[   0    1    2    3]
 [1234    5    6    7]
 [   8    9   10   11]]
d = a.copy()
print(d is a)#打印发现d不是a,说明这两个也不是指向同一个地方
d[0,0] = 9999
print(d)#相应的d的值改变也不会改变a的值
print("--------")
print(a)
False
[[9999    1    2    3]
 [1234    5    6    7]
 [   8    9   10   11]]
--------
[[   0    1    2    3]
 [1234    5    6    7]
 [   8    9   10   11]]
data = np.random.random((5,4))
print(data)
ind = data.argmax(axis=0)
print(ind)#每一列中哪个数最大,如果axis=1就是每一行中哪个数最大
data_max = data[ind,range(data.shape[1])]#ind为找出行,然后再找出列。找列的时候用data中第二个属性就为他的列
print(data_max)
[[ 0.67684773  0.44593787  0.44244423  0.76992239]
 [ 0.87015584  0.24594329  0.82728904  0.24265102]
 [ 0.07925658  0.92387252  0.04531156  0.87333059]
 [ 0.2723402   0.93362859  0.48617785  0.50714169]
 [ 0.73610068  0.09922339  0.39593682  0.38077017]]
[1 3 1 2]
[ 0.87015584  0.93362859  0.82728904  0.87333059]
a = np.arange(0,40,10)
print(a)
b = np.tile(a,(2,2))#可以指定a的行变为两倍列变为两倍 tile英文为覆盖的意思
print(b)
[ 0 10 20 30]
[[ 0 10 20 30  0 10 20 30]
 [ 0 10 20 30  0 10 20 30]]
#对adarry进行排序
a = np.array([[1,2,3],[3,6,5],[2,9,8]])
print(a)
print("按照列进行排序")
b = np.sort(a,axis=1)#按照列进行排序
print(b)
print("按照行排序")
a.sort(axis=0)#按照行排序
print(a)
print("*******")
c = np.array([4,3,1,2])
j = np.argsort(c)
print("最小值的索引,第一个最小值是1,索引是2,依次类推")
print(j)
print("依据索引输出值")
print(c[j])
[[1 2 3]
 [3 6 5]
 [2 9 8]]
按照列进行排序
[[1 2 3]
 [3 5 6]
 [2 8 9]]
按照行排序
[[1 2 3]
 [2 6 5]
 [3 9 8]]
*******
最小值的索引,第一个最小值是1,索引是2,依次类推
[2 3 1 0]
依据索引输出值
[1 2 3 4]

猜你喜欢

转载自blog.csdn.net/while10/article/details/78585889