Numpy_1基础结构

numpy库基础结构

  • 可以通过打印help(numpy.XXX函数)看相应的帮助文档
import numpy as np
#读取一个文件,并且以XX作为分隔符
f = np.genfromtxt('./data/world_alcohol.txt',delimiter = ',',dtype = str)
print(type(f))
print(f)
<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']]
  • 创建一维向量和矩阵,以及打印其维度
vector = np.array([1,2,3])
matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(vector)
print(matrix)
[1 2 3]
[[1 2 3]
 [4 5 6]
 [7 8 9]]
print(vector.shape)
print(matrix.shape)
(3,)
(3, 3)
vector.dtype
dtype('int32')
  • Numpy array中数据类型要保持一致
numbers = np.array([1,2,3,4])
print(numbers)
numbers.dtype
[1 2 3 4]





dtype('int32')
numbers = np.array([1,2,3,4.5])
print(numbers)
numbers.dtype
[1.  2.  3.  4.5]





dtype('float64')
world_alcohol = np.genfromtxt('./data/world_alcohol.txt',delimiter = ',',dtype = str)
print(world_alcohol)
[['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']]
second_country = world_alcohol[1,1]
print(second_country)
Western Pacific
  • array数组同样可以切片操作
numbers = np.array([1,2,3,4,5])
num1 = numbers[0:4]
print(num1)
[1 2 3 4]
matrix = np.array([[1,2,3],
                   [4,5,6],
                   [7,8,9]])
mat1 = matrix[:,1]
print(mat1)
[2 5 8]
mat2 = matrix[:,0:2]
print(mat2)
[[1 2]
 [4 5]
 [7 8]]

重要

  • Numpy array数组可以直接判断是否包含某个值,且相应的结果可以当做索引
vector = np.array([1,2,3,4,5,6,7])
vector == 5
array([False, False, False, False,  True, False, False])
matrix = np.array([[1,2,3],
                   [4,5,6],
                   [7,8,9]])
matrix == 5
array([[False, False, False],
       [False,  True, False],
       [False, False, False]])
vector = np.array([1,2,3,4,5,6,7])
equal_to_five = (vector == 5)
print(equal_to_five)
print(vector[equal_to_five])
[False False False False  True False False]
[5]
matrix = np.array([[1,5,3],
                   [4,5,6],
                   [7,8,9]])
second_column_5 = (matrix[:,1] == 5)
print(second_column_5)
print(matrix[second_column_5,:])
[ True  True False]
[[1 5 3]
 [4 5 6]]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值