0%

python数据分析与机器学习实战-02.Numpy基础结构

1
2
3
4
import numpy
#数据运算
vector = numpy.array([3,6,7,89,90])
vector == 6
1
array([False,  True, False, False, False])
1
matrix = numpy.array([[12,3,67,9],[34,2,7,9],[3,8,9,6]])matrix == 3
1
2
3
array([[False,  True, False, False],
[False, False, False, False],
[ True, False, False, False]])
1
2
3
4
vector = numpy.array([3,6,7,89,90])
equal_to_six = (vector == 6)
print(equal_to_six)
print(vector[equal_to_six])
1
2
[False  True False False False]
[6]
1
2
3
4
matrix = numpy.array([[12,3,67,9],[34,2,7,9],[3,8,9,6]])
second_column_three = (matrix[:,1] == 3)
print(second_column_three)
print(matrix[second_column_three,:])
1
2
[ True False False]
[[12 3 67 9]]
1
2
3
4
#逻辑运算
vector = numpy.array([3,6,7,89,90])
equal_to_three_and_six = (vector == 3)&(vector == 6)
print(equal_to_three_and_six)
1
[False False False False False]
1
2
3
vector = numpy.array([3,6,7,89,90])
equal_to_three_or_six = (vector == 3)|(vector == 6)
print(equal_to_three_or_six)
1
[ True  True False False False]
1
#类型转换vector = numpy.array(['3','6','7','89','90'])print(vector.dtype)vector = vector.astype(float)print(vector.dtype)print(vector)
1
2
3
<U2
float64
[ 3. 6. 7. 89. 90.]
1
2
3
#最小值
vector = numpy.array([3,6,7,89,90])
print(vector.min())
1
2
3
#最大值
vector = numpy.array([3,6,7,89,90])
print(vector.max())
1
2
3
#列求和
matrix = numpy.array([[12,3,67,9],[34,2,7,9],[3,8,9,6]])
print(matrix.sum(axis=0))
1
[49 13 83 24]
1
2
3
#行求和
matrix = numpy.array([[12,3,67,9],[34,2,7,9],[3,8,9,6]])
print(matrix.sum(axis=1))
1
[91 52 26]