ndarray创建方式
# 1.从列表、元组等类型创建ndarray
x1 = np.array([1,2,3,4])
[1 2 3 4]
x2 = np.array((5,6,7,8))
[5 6 7 8]
x3 = np.array([[1,2],[3,4],(0.2,0.5)])
[[1. 2. ]
[3. 4. ]
[0.2 0.5]]
2.arange ones zeros等函数
y1 = np.arange(10)
[0 1 2 3 4 5 6 7 8 9]
##ones zeros eye默认为浮点数类型,除非指定
y2 = np.ones((2,3,6))
[[[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]]
[[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]]]
y3 = np.zeros((3,6),dtype=np.int32)
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]]
y4 = np.eye(5)
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
3.linspace concatenate
z1 = np.linspace(1,10,4) #从1到10等间距取4个元素
[ 1. 4. 7. 10.]
z2 = np.linspace(1,10,4,endpoint=False) # endpoint表示最后的数是否可取
[1. 3.25 5.5 7.75]
z = np.concatenate((z1,z2)) # 合并z1,z2
[ 1. 4. 7. 10. 1. 3.25 5.5 7.75]
ndarray维度变换
# 维度变换
# 1.reshape(shape) 返回shape形状的数组,原数组不变
# 2.resize(shape) 与reshape功能一致,但改变原数组
# 3.swapeaxes(ax1,ax2) 将两个维度调换
# 4. flatten() 对数据进行降维,返回一维数组,原数组不变
a = np.ones((2,3,4),dtype=np.int32)
print(a.reshape((3,8)))
[[1 1 1 1 1 1 1 1]
[1 1 1 1 1 1 1 1]
[1 1 1 1 1 1 1 1]]
print(a.flatten())
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
ndarray转为列表
print(a.tolist())
[[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]
待更新…
来源:oschina
链接:https://my.oschina.net/u/4332788/blog/3225340