numpy基础1多维数组对象

 1 # coding: utf-8
 2 # numpy ndarry:多维数组对象
 3 import numpy as np
 4 # 生成随机数组
 5 data = np.random.randn(2, 3)
 6 data
 7 
 8 # 给data加一系列数学操作
 9 data * 10
10 data + data
11 
12 # 数组的dtype属性,用来描述数组的数据类型
13 data.shape
14 data.dtype
15 # 生成数组ndarray
16 data1 = [6, 7.5, 8, 0, 1]
17 arr1 = np.array(data1)
18 arr1
19 
20 data2 = [[1, 2, 3, 4], [5, 6, 7, 8]]
21 arr2 = np.array(data2)
22 arr2
23 
24 # 通过ndim shape 检查数组属性
25 arr2.ndim
26 arr2.shape
27 arr1.dtype
28 arr2.dtype
29 
30 # 其他生成函数的数组
31 np.zeros(10)
32 np.zeros((3, 6))
33 np.empty((2, 3, 2))
34 np.arange(15)
35 np.ones((2, 3))
36 
37 # ndarry数据类型
38 import numpy as np
39 arr1 = np.array([1, 2, 3], dtype = np.float64)
40 arr2 = np.array([1, 2, 3], dtype=np.int32)
41 
42 arr1.dtype
43 arr2.dtype
44 
45 #  astype方法转换数组的数据类型
46 
47 # 整型转换为浮点型
48 arr = np.array([1, 2, 3, 4, 5])
49 arr
50 
51 arr.dtype
52 float_arr = arr.astype(np.float64)
53 float_arr.dtype
54 
55 # 浮点型转换为整型
56 arr = np.array([1.2, 2.4, 0.3, -1.4, 15.6])
57 arr
58 arr.astype(np.int32)
59 
60 # 字符串转换为数字
61 numeric_strings = np.array(['1.25', '-9.6', '42'], dtype=np.string_)
62 numeric_strings.astype(float)
63 
64 #使用另一数组的dtype属性
65 int_array = np.arange(10)
66 calibers = np.array([.22, .270, .357, .380, .44, .50], dtype=np.float64)
67 int_array.astype(calibers.dtype)
68 
69 # 使用类型代码传入数据类型
70 empty_uint32 = np.empty(8, dtype='u4')
71 empty_uint32
72 
73 #  numpy数组算术
74 arr = np.array([[1., 2., 3.], [4., 5., 6.]])
75 arr
76 
77 # 相乘
78 arr*arr
79 # 相减
80 arr-arr
81 
82 # 带有标量计算的算术操作
83 1 / arr
84 arr **0.5
85 
86 # 同尺寸数组之间的比较
87 arr2 = np.array([[0., 4., 1.], [7., 2., 12.]])
88 arr2
89 arr2 >arr

参考书籍:利用 python 进行数据分析

作者:舟华520

出处:https://www.cnblogs.com/xfzh193/

本文以学习,分享,研究交流为主,欢迎转载,请标明作者出处!

原文地址:https://www.cnblogs.com/xfzh193/p/11221895.html