机器学习笔记 python numpy基础

import numpy as np
#numpy中存储数据类型应该相同
vector = np.array([5,10,15])#一维数组
matrix = np.array([[2,3,4],[3,4,5]])#矩阵

print(vector) #[ 5 10 15]
print(matrix)  #[[2 3 4]   [3 4 5]]

print(vector.shape)   #维度     (3,)
print(matrix.dtype)  #数据类型 int32 
#读入文件
world_alcohol = numpy.genfromtxt("C:/Users/TianYi ZHENG/Desktop/world_alcohol.txt",delimiter=",",dtype=str,skip_header=1)
#指定分隔符 类型 去掉第一行 
print(world_alcohol)
#读出数据为矩阵格式
'''
[['1986' 'Western Pacific' 'Viet Nam' 'Wine' '0']
 ['1986' 'Americas' 'Uruguay' 'Other' '0.5']
 ['1985' 'Africa' "Cte d'Ivoire" 'Wine' '1.62']
 ...
 ['1987' 'Africa' 'Malawi' 'Other' '0.75']
 ['1989' 'Americas' 'Bahamas' 'Wine' '1.5']
 ['1985' 'Africa' 'Malawi' 'Spirits' '0.31']]
'''
uruguay_other_1986 = world_alcohol[1:4]  

matrix = np.array([[5,10,15], [20,25,30],[35,40,45]])
print(matrix[:,0:2])    #所有行 第0列和第一列
'''
[[ 5 10]
 [20 25]
 [35 40]]
'''
a = np.arange(15).reshape(3,5) #产生0~14 并构造成3*5的矩阵
print(a)
'''
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
'''
print(a.shape) #(3,5)
c = np.zeros((3,4) )#全零矩阵float默认类型
d = np.ones((2,3,4),dtype=np.int32) #三维矩阵,数据类型为int
print(d)
'''
[[[1 1 1 1]
  [1 1 1 1]
  [1 1 1 1]]

 [[1 1 1 1]
  [1 1 1 1]
  [1 1 1 1]]]
'''
e = np.arange(0,20,5)
print(e) #[ 0  5 10 15] # 0- 起始值 20-终止值 5-间隔  不包含20
f = np.random.random((2,3))
print(f) #随机矩阵 0~1
g = np.linspace(0,5,100)
print(g)  #从0~5中获得100个数,平均的

a = np.array([10,20,30,40])
b = np.arange(4)
print(a)
print(b)
c = a-b
print(c)#对应位置做差
print(c-1)#每一个元素进行同样的操作

A = np.array([[1,1],[0,1]])

B = np.array([[2,0],[3,4]])

print(A)
print("*"*100)
print(B)

print(A*B) #内积 对应位置相乘
print("*"*100)
print(A.dot(B))#矩阵相乘
print("*"*100)
print(np.dot(A,B)) #与上面相同


import numpy as np
A = np.array([[1,2],[3,4]])
B = np.array([[5,6],[7,8]])
print(np.vstack((A,B))) #合并矩阵 按照行
print(np.hstack((A,B)))  #按照列


a = np.floor(10*np.random.random((2,12)))
print(a)
'''
[[5. 9. 0. 6. 2. 6. 4. 2. 4. 0. 5. 3.]
 [7. 9. 6. 3. 1. 6. 5. 2. 8. 2. 6. 7.]]
'''
print("*"*100)
print(np.hsplit(a,3))  #切分a 平均切成3份 按照列
'''
[array([[5., 9., 0., 6.],
       [7., 9., 6., 3.]]), array([[2., 6., 4., 2.],
       [1., 6., 5., 2.]]), array([[4., 0., 5., 3.],
       [8., 2., 6., 7.]])]
'''
print("*"*100)
print(np.hsplit(a,(3,4)))
'''
[array([[9., 0., 9.],
       [3., 3., 5.]]), array([[4.],
       [4.]]), array([[9., 3., 1., 1., 2., 9., 2., 3.],
       [1., 9., 7., 9., 9., 6., 1., 6.]])]'''

print("*"*100)
a = np.array([[4,3,5],[1,2,1]])
print(a)
b =  np.sort(a,axis=1)  #按照行排序
print(b)
b =  np.sort(a,axis=0)  #按照列排序
print(b)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值