numpy之数组属性与方法

# coding=utf-8
import numpy as np
import random
# nan是一个float类型 ,not a num不是一个数字;inf,infinite 无穷
# 轴的概念---(3,2) 3为0轴,2为1轴; (3,2,1)3为0轴,2为1轴,1为2轴

#一、读取CSV数据----csv文件内容以逗号进行分割
#t = np.loadtxt("path",delimiter=",",dtype="int")
'''
fname文件
dtype数据类型
delimiter分割符
skiprows跳过前几行
usecols读取指定的列
unpack 矩阵转置---默认为False,不进行转置
'''

#二、转置 --->建议使用transpose()或者T
t2 = t8.transpose()
t3 = t8.T
t4 = t8.swapaxes(1,0)

#三、索引与切片----取行和列
t8 = np.random.randint(3,12,(4,8))
#取行
print(t8[1,:])
#取多行
print(t8[1:,:])
#取不连续的多行
print(t8[[0,1],:])

#取列
print(t8[:,1])
#取连续的多列
print(t8[:,1:])
#取不连续的多列
print(t8[:,[1,3]])


#取行和列,取第三行四列
print(t8[2,3])
#取多行多列,取3-5行,2-4列----取交叉点的数据
print(t8[2:5,1:4])
#取多个不相邻的点
print(t8[[0,2],[0,1]])  #即(0,0),(2,1)两个点

'''
四、裁剪
'''
#裁剪----返回的数据为一维数组
print("*"*20)
print(t8[t8<10])
print("*"*20)

#布尔判断--->转为boolean类型,大于5为True,小于5为False,返回的数据为一维数组
print(t8>5)

#元素替换---三元运算符,小于10为0,大于10的为10 ,返回一维数组
print(np.where(t>10,0,10))

#clip裁剪 ----clip(10,18)将小于10的替换为10,大于18的替换为18  返回的数据为一维数组
t8 = t8.clip(10,18)
print(t8)

'''
五、数组拼接与交换
'''
t1 = np.array([1,2,3])
t2 = np.array([4,5,6])
t51 = np.vstack((t1,t2))   #竖直拼接
t61 = np.hstack((t1,t2))   #水平拼接
#np.vsplit() #竖直分割
#np.hsplit() #水平分割

#行交换
t8[[1,2],:] = t8[[2,1],:]
#列交换
t8[:,[1,2]] = t8[:,[2,1]]

猜你喜欢

转载自www.cnblogs.com/ywjfx/p/10827050.html
今日推荐