数据挖掘工具numpy(七)Numpy数组的拼接、行列交换、转置

一,数组的拼接

1,竖直拼接
import numpy as np

t1 = np.arange(30).reshape(6,5).astype(float)
t2 = np.arange(30,60).reshape(6,5).astype(float)
t1[:,3] = np.nan
t2[3,:] = np.nan
# 竖直拼接
t = np.vstack((t1,t2))
print(t)
2,水平拼接
import numpy as np

t1 = np.arange(30).reshape(6,5).astype(float)
t2 = np.arange(30,60).reshape(6,5).astype(float)
t1[:,3] = np.nan
t2[3,:] = np.nan
# 水平拼接
t = np.hstack((t1,t2))
print(t)

二,数组的行列交换

1,行交换
import numpy as np

t = np.arange(30).reshape(6,5).astype(float)
t[:,3] = np.nan
# 行交换
t[[1,2],:] = t[[2,1],:]

print(t)
2,列交换
import numpy as np

t = np.arange(30).reshape(6,5).astype(float)
t[:,3] = np.nan
# 列交换
t[:,[0,2]]] = t[:,[2,0]]

print(t)

三,维数组中进行转置

# 第一种转置方法
import numpy as np

temp = np.arange(30).reshape(6,5)
print(temp)
print('-'*50)
# 当不传参的时候和T是同等效果
# 参数默认为(0,1,2),可根据传入参数对应更改维度值
# 例如temp = temp.transpose(1,0)
temp = temp.transpose()

print(temp)

第二种转置方法

import numpy as np

temp = np.arange(30).reshape(6,5)
print(temp)
print('-'*50)

temp = temp.T

print(temp)

第三种转置方法

import numpy as np

temp = np.arange(30).reshape(6,5)
print(temp)
print('-'*50)

# 与transpose类似,将传入的维度参数交换
temp = temp.swapaxes(1,0)

print(temp)

四,翻转90度

import numpy as np

temp = np.arange(20).reshape(4,5)
print(temp)
temp = temp.T
temp[:,:] = temp[:,[3,2,1,0]]
print(temp)

# -------------output---------------------
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]
[[15 10  5  0]
 [16 11  6  1]
 [17 12  7  2]
 [18 13  8  3]
 [19 14  9  4]]

五,拼接实例

import numpy as np

# dtype为int保证数组为十进制
number1 = np.loadtxt('./number1.csv',delimiter=',',dtype=int)
number2 = np.loadtxt('./number2.csv',delimiter=',',dtype=int)

# dtype为int保证数组为十进制
# zeros、ones中传入数组shape
num0 = np.zeros((number1.shape[0],1)).astype(int)
num1 = np.ones((number2.shape[0],1)).astype(int)

number1 = np.hstack((number1,num0))
number2 = np.hstack((number2,num1))

totle_num = np.vstack((number1,number2))
print(totle_num)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章