Numpy(一)

2018-11-23  本文已影响0人  shadowflow
1. 数据读取

1.1:

world_alcohol = numpy.genfromtxt("world_alcohol.txt", delimiter=",",dtype=str)

读取文件名为world_alcohol.txt的文件,以“,”分割,以str类型读入

1.2:

print(type(world_alcohol))

结果:<class 'numpy.ndarray'>

1.3:

print(help(numpy.genfromtxt))

打印某个函数的帮助文档

1.4 生成数组或矩阵:

vector = numpy.array([5,10,15,20])
matrix = numpy.array([[5,10,15],[20,25,30],[35,40,45]])

numpy.ndarray结构

1.5 查看矩阵结构(行数,列数):

vector = numpy.array([1,2,3,4,5])
matrix = numpy.array([[5,10,15],[20,25,30]])
print(vector.shape)
print(matrix.shape)
结果:
(5,)
(2,3)

2. Numpy基础结构

2.1 numpy.array()里的数据应该为同一种数据类型:

numbers = numpy.array([1,2,3,4.0])
print(numbers)
print(numbers.dtype)
结果:
[1. 2. 3. 4.]
float64

只改变了4为浮点型,其他数据都成了浮点型

2.2 数据的选取:

world_alcohol = numpy.genfromtxt("world_alcohol.txt",delimiter=",",dtype=str, skip_header=1)
print(world_alcohol)
uruguay_other_1986 = world_alcohol[1,4]
print(uruguay_other_1986)
结果:
[['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']]


0.5

2.3 numpy中的切片:

vector = numpy.array([5,10,15,20])
print(vector[0:3])
结果:
[ 5 10 15]

print(matrix)
print(matrix[:,1])
结果:
[[ 5 10 15]
[20 25 30]]


[10 25]

print(matrix)
print(matrix[:,0:2])
结果:
[[ 5 10 15]
[20 25 30]]


[[ 5 10]
[20 25]]

2.4 判断:

print(vector)
vector == 10
equal_to_ten = (vector ==10)
print(vector[equal_to_ten])
结果:
[ 5 10 15 20]
array([False, True, False, False])
[False True False False]
[10]

上一篇 下一篇

猜你喜欢

热点阅读