爬虫没学两天,数据分析课就来了。
使用numpy创建数组
介绍numpy数组的属性和简单操作
import numpy
#delimiter设置定界符
world_alcohol = numpy.genfromtxt("world_alcohol.txt", delimiter=",")
print(type(world_alcohol))#类型是多维数组
<type 'numpy.ndarray'>
#The numpy.array() function can take a list or list of lists as input. When we input a list, we get a one-dimensional array as a result:
#(输入一维列表,得到一位数组。)
vector = numpy.array([5, 10, 15, 20])#创建数组
#When we input a list of lists, we get a matrix as a result:,
#输入多维列表,得到多维数组。
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
print vector#一维数组
print matrix#二维数组
[ 5 10 15 20]
[[ 5 10 15]
[20 25 30]
[35 40 45]]
#We can use the ndarray.shape property to figure out how many elements are in the array
#使用.shape属性来判断数组中有多少个元素)
vector = numpy.array([1, 2, 3, 4])
print(vector.shape)#数组(矩阵结构),通过结构我们可以看到数据的特征。
#For matrices, the shape property contains a tuple with 2 elements.
#一般矩阵是二维,所以shape属性值是一个两个元素组成的元组。
matrix = numpy.array([[5, 10, 15], [20, 25, 30]])
print(matrix.shape)
(4,)
(2, 3)
#Each value in a NumPy array has to have the same data type
#numpy数组中所有元素的类型必须相同
#NumPy will automatically figure out an appropriate data type when reading in data or converting lists to arrays.
#numpy创建数组时会自适应的指定数组类型。
#You can check the data type of a NumPy array using the dtype property.
#使用dtype属性查看数组的元素的数据类型
numbers = numpy.array([1, 2, 3, 4])
numbers.dtype#data type 数据元素结构必须相同
dtype('int32')
#When NumPy can't convert a value to a numeric data type like float or integer, it uses a special nan value that stands for Not a Number。
#非数字值以nan代替
#nan is the missing data(nan代表数据缺失)
#1.98600000e+03 is actually 1.986 * 10 ^ 3(科学计数法)
world_alcohol#文件读取
array([[ nan, nan, nan,
nan, nan],
[ 1.98600000e+03, nan, nan,
nan, 0.00000000e+00],
[ 1.98600000e+03, nan, nan,
nan, 5.00000000e-01],
...,
[ 1.98700000e+03, nan, nan,
nan, 7.50000000e-01],
[ 1.98900000e+03, nan, nan,
nan, 1.50000000e+00],
[ 1.98500000e+03, nan, nan,
nan, 3.10000000e-01]])
world_alcohol = numpy.genfromtxt("world_alcohol.txt", delimiter=",", dtype="U75", skip_header=1)
print(world_alcohol)
[[u'1986' u'Western Pacific' u'Viet Nam' u'Wine' u'0']
[u'1986' u'Americas' u'Uruguay' u'Other' u'0.5']
[u'1985' u'Africa' u"Cte d'Ivoire" u'Wine' u'1.62']
...,
[u'1987' u'Africa' u'Malawi' u'Other' u'0.75']
[u'1989' u'Americas' u'Bahamas' u'Wine' u'1.5']
[u'1985' u'Africa' u'Malawi' u'Spirits' u'0.31']]
uruguay_other_1986 = world_alcohol[1,4]
third_country = world_alcohol[2,2]
print uruguay_other_1986
print third_country
0.5
Cte d'Ivoire
vector = numpy.array([5, 10, 15, 20])
print(vector[0:3]) #数组的切片,找出索引为0,1,2的元素
[ 5 10 15]
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
print(matrix[:,1])
#打印所有行的索引为1的元素
[10 25 40]
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
print(matrix[:,0:2])
#打印所有行的索引为0,1的元素
[[ 5 10]
[20 25]
[35 40]]
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
print(matrix[1:3,0:2])
#打印索引为1,2的行的列索引为0,1的元素
[[20 25]
[35 40]]
网友评论