一、数组常用属性
Dimension transformation
.reshape(shape) : 不改变当前数组,依shape生成
.resize(shape) : 改变当前数组,依shape生成
.swapaxes(ax1, ax2) : 将两个维度调换
.flatten(): 对数组进行降维,返回折叠后的一位数组
ndarray’s create
np.arange(n) : 元素从0到n-1的ndarray类型
np.ones(shape): 生成全1
np.zeros((shape), ddtype = np.int32) : 生成int32型的全0
np.full(shape, val): 生成全为val
np.eye(n) : 生成单位矩阵
array’s attribution
.ndim: 维度
.shape : 各维度的尺度 (2,5)
.size : 元素的个数 10
.dtype : 元素的类型 dtype(‘int32’)
.itemsize : 每个元素的大小,以字节为单位 ,每个元素占4个字节
array’s type
数据类型的转换 :a.astype(new_type) : eg, a.astype (np.float)
数组向列表的转换: a.tolist()
------------------------------------------------------------------------------------------------------
二、数组常用函数
np.ceil()
np.ceil 函数返回不小于输入值的最大整数,即对于输入 x ,返回最小的整数 i ,使得 i> = x。
import numpy as np
n = np.array([-1.7, -2.5, -0.2, 0.6, 1.2, 2.7, 11])
ceil = np.ceil(n)
print(ceil) # [ -1. -2. -0. 1. 2. 3. 11.]
np.floor()
np.floor 返回不大于输入参数的最大整数。 即对于输入值 x ,将返回最大的整数 i ,使得 i <= x。 注意在Python中,向下取整总是从 0 舍入。
import numpy as np
n = np.array([-1.7, -2.5, -0.2, 0.6, 1.2, 2.7, 11])
floor = np.floor(n)
print(floor) # [ -2. -3. -1. 0. 1. 2. 11.]
np.around()
np.around 返回四舍五入后的值,可指定精度。
import numpy as np
n = np.array([-0.746, 4.6, 9.4, 7.447, 10.455, 11.555])
around1 = np.around(n)
print(around1) # [ -1. 5. 9. 7. 10. 12.]
around2 = np.around(n, decimals=1)
print(around2) # [ -0.7 4.6 9.4 7.4 10.5 11.6]
around3 = np.around(n, decimals=-1)
print(around3) # [ -0. 0. 10. 10. 10. 10.]
np.where()
numpy.where(condition[ x, y])根据条件 condition 从 x 和 y 中选择元素,当 condition 为 True 时,选 x,否则选 y。
import numpy as np
data = np.random.random([2, 3])
print data
'''
[[ 0.93122679 0.82384876 0.28730977]
[ 0.43006042 0.73168913 0.02775572]]
'''
result = np.where(data > 0.5, data, 0)
print result
'''
[[ 0.93122679 0.82384876 0. ]
[ 0. 0.73168913 0. ]]
'''
math function
np.abs(x)、np.fabs(x) : 计算数组各元素的绝对值
np.sqrt(x) : 计算数组各元素的平方根
np.square(x) : 计算数组各元素的平方
np.log(x) 、np.log10(x)、np.log2(x) : 计算数组各元素的自然对数、10底对数和2底对数
np.sum(a, axis = None) : 依给定轴axis计算数组a相关元素之和,axis为整数或者元组
np.mean(a, axis = None) : 同理,计算平均值
np.average(a, axis =None, weights=None) : 依给定轴axis计算数组a相关元素的加权平均值
np.std(a, axis = None): 同理,计算标准差
np.var(a, axis = None: 计算方差
eg: np.mean(a, axis =1) : 对数组a的第二维度的数据进行求平均
a = np.arange(15).reshape(3, 5)
min(a) max(a) : 计算数组a的最小值和最大值
argmin(a) argmax(a) : 计算数组a的最小、最大值的下标(注:是一维的下标)
unravel_index(index, shape) : 根据shape将一维下标index转成多维下标
ptp(a) : 计算数组a最大值和最小值的差
median(a) : 计算数组a中元素的中位数(中值)
eg:a = [[15, 14, 13],
[12, 11, 10] ]
np.argmax(a) –> 0
np.unravel_index( np.argmax(a), a.shape) –> (0,0)