数组类型转换:.astype(),改变数组元素的类型,可设为整形,浮点型等,在pandas中更改DataFrame的数据类型也会用到。
ar1=np.arange(10,dtype=float)
ar2=ar1.astype(np.int64)#转换为整形
print(ar1,ar1.dtype)
print(ar2,ar2.dtype)
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.] float64
[0 1 2 3 4 5 6 7 8 9] int64
数据堆叠:.hstack()横向连接,vstack()竖向连接
a=np.arange(5)
b=np.arange(5,9)
print(a)
print(b)
[0 1 2 3 4]
[5 6 7 8]
print(np.hstack((a,b)))#横向连接a,b
[0 1 2 3 4 5 6 7 8]
a=np.array([[1],[2],[3]])
b=np.array([['a'],['b'],['c']])#a,b均为1*3结构
print(a)
print(b)
[[1]
[2]
[3]]
[['a']
['b']
['c']]
print(np.vstack((a,b)))#竖向连接a,b
[['1']
['2']
['3']
['a']
['b']
['c']]
数组拆分:.hsplit()拆分列,.vsplit()拆分行
ar=np.arange(16).reshape(4,4)
print(ar)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
print(np.hsplit(ar,2))#按列拆分成两部分
[array([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]]), array([[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])]
print(np.vsplit(ar,2))#按行拆分成两部分
[array([[0, 1, 2, 3],
[4, 5, 6, 7]]), array([[ 8, 9, 10, 11],
[12, 13, 14, 15]])]