python数据分析笔记——第二章 Numpy数组

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28467367/article/details/89249127

2.1-2.6

import numpy as np

b=np.arange(24).reshape(2,3,4)
b.ravel() #将多维数组变成一维数组
b.flatten()  #将数组拉直,功能同上

#指定数组形状
b.reshape(4,6)
b.shape=(6,4)  
b.resize(2,12)

#转置
b.transpose()
b.T
#堆叠数组
a=np.arange(9).reshape(3,3)
b=2*a

#水平叠加
np.hstack((a,b))
np.concatenate((a,b),axis=1)
#垂直叠加
np.vstack((a,b))
np.concatenate((a,b),axis=0)

#深度叠加
np.dstack((a,b))
#列式叠加,类似于hstack
np.column_stack((a,b))
#行式堆叠,类似于vstack
np.row_stack((a,b))


#拆分数组
#横向拆分
np.hsplit(a,3)
np.split(a,3,axis=1)
#纵向拆分
np.vsplit(a,3)
np.split(a,3,axis=0)

#深度拆分
c=np.arange(27).reshape(3,3,3)
np.dsplit(c,3)
c.flat[b]

#ndim维度数
#b.size 元素个数
#b.itemsize各个元素的字节数
#b.nbytes=b.size*b.itemsize 总字节数
#b.flat[[1,2]]=9 将b中1,2替换为9

2.7 创建数组的视图和拷贝

import scipy.misc
import matplotlib.pyplot as plt 
# 加载 Lena 图像
lena = scipy.misc.ascent()
# copy 创建副本,Python 对象复制,内部内存复制
acopy = lena.copy() 
# view 创建视图,Python 对象复制,内部内存共享
aview = lena.view()
# 绘制 Lena 图像(左上角)
plt.subplot(221) 
plt.imshow(lena)
# 绘制副本(右上角) 
plt.subplot(222) 
plt.imshow(acopy)
# 绘制视图(左下角)
plt.subplot(223) 
plt.imshow(aview)
# 通过flat迭代器将视图中的所有值设为0
# 由于数组的数据保存在内部内存中
# 副本不受影响,视图(以及引用)会跟着变化
aview.flat = 0 
# 绘制修改后的视图(右下角)
plt.subplot(224) 
plt.imshow(aview)
https://www.jianshu.com/p/414f086f7dde

2.8 花式索引

# 这个代码通过将数组对角线上的元素设为 0 ,来展示花式索引
# 花式索引就是使用数组作为索引来索引另一个数组
import scipy.misc 
import matplotlib.pyplot as plt
# 加载图像
lena = scipy.misc.ascent() 
# 取图片的宽和高
height = lena.shape[0] 
width = lena.shape[1]
# 使用花式索引将对角线上的元素设为 0
# x 为 0 ~ width - 1 的数组
# y 为 0 ~ height - 1 的数组
lena[range(height), range(width)] = 0
# 将副对角线上元素也设为 0
# x 为 width - 1 ~ 0 的数组
# y 为 0 ~ height - 1 的数组
lena[range(height), range(width - 1, -1, -1)] = 0
# 画出带对角线的 Lena 图像
plt.imshow(lena) 
plt.show()

2.9 将位置列表用于索引

#利用ix_()函数将像素全部打乱
import scipy.misc 
import matplotlib.pyplot as plt 
import numpy as np
# 加载ascent图像 
lena = scipy.misc.ascent() 
# 取图像宽高
xmax = lena.shape[0] 
ymax = lena.shape[1]
def shuffle_indices(size):   
    '''   
    生成 0 ~ size - 1 的数组并打乱   
    '''
    arr = np.arange(size)   
    np.random.shuffle(arr)
    return arr
# 生成 x 随机索引和 y 随机索引
xindices = shuffle_indices(xmax) 
np.testing.assert_equal(len(xindices), xmax) 
yindices = shuffle_indices(ymax) 
np.testing.assert_equal(len(yindices), ymax)
# 画出打乱后的图像
# ix_ 函数将 yindices 转置,xindices 不变
# 结果是一个 y x 1 的数组和一个 1 x  x 的数组
# 用于索引时,都会扩展为 y * x 的数组
plt.imshow(lena[np.ix_(yindices, xindices)]) 
plt.show()

2.10 布尔索引

import scipy.misc 
import matplotlib.pyplot as plt 
import numpy as np
# 加载 Lena 图像
lena = scipy.misc.ascent()
# 取大小为 size 的数组
# 4 的倍数的下标为 True,其余为 False
def get_indices(size):   
    arr = np.arange(size)   
    return arr % 4 == 0
# 绘制 Lena
# 对角线上被4整除的元素清零 
lena1 = lena.copy() 
yindices = get_indices(lena.shape[0]) 
xindices = get_indices(lena.shape[1]) 
lena1[yindices, xindices] = 0 
#plt.subplot(211) 
plt.imshow(lena1)
plt.show()
lena2 = lena.copy() 
# 最大值 1/4 ~ 3/4 之间的元素清零
# 这里用到了数组广播
lena2[(lena > lena.max()/4) & (lena < 3 * lena.max()/4)] = 0 
#plt.subplot(212) 
plt.imshow(lena2)
plt.show()

2.11 Numpy数组广播

import scipy.io.wavfile 
import matplotlib.pyplot as plt 
import urllib.request #爬虫库
import numpy as np
# 下载音频文件
response = urllib.request.urlopen('http://www.thesoundarchive.com/austinpowers/smashingbaby.wav') 
print(response.info())
# 将文件写到磁盘
WAV_FILE = 'smashingbaby.wav' 
filehandle = open(WAV_FILE, 'wb') 
filehandle.write(response.read()) 
filehandle.close() 
# 使用 SciPy 读取音频文件
sample_rate, data = scipy.io.wavfile.read(WAV_FILE)
print("Data type", data.dtype, "Shape", data.shape)
# ('Data type', dtype('uint8'), 'Shape', (43584L,))
# 绘制原始音频文件(上方)
# y 值是数据,x 值是数据的下标
plt.subplot(2, 1, 1) 
plt.title("Original") 
plt.plot(data)
# 使音频更安静
# 数组广播的意思是,两个数组进行运算时
# 较小尺寸的数组会扩展自身,与较大数组对齐
# 如果数组与标量运算,那么将标量与数组的每个元素运算
# 所以这里数组的每个元素都 x 0.2
newdata = data * 0.2 
newdata = newdata.astype(np.uint8) 
print("Data type:", newdata.dtype, "Shape:", newdata.shape)
# ('Data type', dtype('uint8'), 'Shape', (43584L,))
# 保存更安静的音频
scipy.io.wavfile.write("quiet.wav", sample_rate, newdata)
# 绘制更安静的音频文件(下方)
plt.subplot(2, 1, 2) 
plt.title("Quiet") 
plt.plot(newdata)
plt.show()

猜你喜欢

转载自blog.csdn.net/qq_28467367/article/details/89249127