numpy库基础结构
- 可以通过打印help(numpy.XXX函数)看相应的帮助文档
import numpy as np
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')
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
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]]