Numpy詳解
列表轉我數組
np.array(list)
生成數組
np.zeros(10, dtype = int)
np.zeros((4, 4), dtype = int)
np.ones(9, dtype = int)
np.full((3, 3), 3.14) # 生成指定值3.14
每一個還有與之對應的like方法
np.zeros_like(nparray)
np.ones_like(nparray)
np.full_like(nparray)
生成隨機數
np. random.random((3, 3))
np.random.randint(2,5,(6,6)) 生成一個6*6矩陣,矩陣的每個元素2到5
range用法和np.arrange用法對比(知道歩長)
list(range(0, 10, 2))
np.arrange(0, 10, 2)
np.linespace() (不知道歩長)
np.linespace(0, 3, 100)
np.eye() # n維的單位矩陣
訪問np數組中的元素與列表中類似
數組的屬性
- nparray.ndim 維度
- nparray.shape
- nparray.size
- nparray.dtype
- nparray.itemsize
- nparray.nbytes
數組中元素運算
nparray+10 數組中所有元素均加10 等價於np.add(nparray, 10)
其他運算符類似
統計 np.sum(a, axis = 1)
注意: notebook中可以用%timeit 代碼 來判斷程序的執行效率
np數組中的比較 每個元素一一比較
變形
nparray.reshape(row, column) or 更高維
排序
nparray.sort()
拼接
np.concatenate([a, b], axis = 0)
axis = 0 按照行拼接 axis = 1 按照列拼接
Pandas詳解
首先我們瞭解一下.csv格式 以下是百度對csv格式的介紹
1.每條記錄佔一行 以逗號爲分隔符(逗號前後的空格會被忽略)
2.第一條記錄,可以是字段名
3.字段中包含有逗號,該字段必須用雙引號括起來
4.字段中包含有換行符,該字段必須用雙引號括起來
5.字段前後包含有空格,該字段必須用雙引號括起來
6.字段中的雙引號用兩個雙引號表示
7.字段中如果有雙引號,該字段必須用雙引號括起來
pandas中的dataframe的操作,很大一部分與numpy中二維數組的操作是近似的。
import pandas as pd
df = pd.read_csv('filename') # 讀取csv文件
df.head(3) # 取頭幾行
df.tail(3) #取尾幾行
#DataFrame是pandas的核心
df. column()
df.index()
df.loc[0] # 訪問第一行
df.[df.score>80] # b表格是成績名單的話,會將成績大於80的同學選出來
#還可複合篩選 通過 & 和 | 運算符
df. sort_values(['score', '...'])
df = pd.DataFrame(scores, index["..."]) # 修改索引
#修改索引之後用loc查的時候就要重新指定索引進行查詢
df.iloc[0] # 不管有沒有指定索引,都是取出第一行
#轉化爲數組
df.value()
df.score.value()
#提取多列
df[['數學', '語文']].head()
###map函數的用法
def func(score):
if score>90:
return '優秀'
elif score>80:
return '良好'
df.['數學分類'] = df.數學.map(func)
df.applymap( ) # 對所有的列均進行操作
###根據多列生成新列
df['new_column'] = df.apply(lambda x: x.score+x.score1, axis =1)
# **Pandas內置的繪圖**
df = pd.DataFrame(np.random.rand(100,4).cumsum(0), column = ['A', 'B', 'C', 'D'])
df.plot()
df.A.plot()
#柱狀圖
df.plot.bar()
df.plot(kind = 'bar')
df.plot(kind = 'bar', stacked = True)
#直方圖
df.hist()
#密度圖
df.plot.kde()
matplotlib
matplotlib是十分強大且專業的繪圖庫,以下列出其一些基本用法。詳細用法可查文檔。matplotlib繪圖的專業性可達到印刷製品的水平。
import matplotlib.pyplot as plt
%matplotlib.inline # 若要在jupyter中畫,此行必不可少
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.plot(x, np.cos(x), '--') #'--'表示以曲線畫出來
fig = plt.figure() # 獲取圖表
fig = savefig('file_address') # 可將繪製出來的圖形保存爲圖片格式
#將兩張圖花在兩個圖表上
plt.subplot(2, 1, 1)
plt.plot(x, y, '--')
plt.subplot(2, 1, 2)
plt.plot(x, y)
#樣式
plt.plot(x,y, '--') # 虛線樣式
plt.plot(x,y, 'o') # 點狀樣式
plt.plot(x,y, '--', color = 'red') # 顏色
#圖表中的註解
plt.plot(x,y, label = 'sin(x)')
plt.plot(x, np.cos(x), 'o', label = 'cos(x)')
plt.legend
#legend控制label的顯示效果,loc是控制label的位置顯示
#可定義的參數太多
plt.plot(x, y, '-p', color = 'blue', markersize = 10, linewidth = 6, markeredgecolor = 'gray', markeredgewidth = 6)
###控制繪製圖形的範圍
plt.ylim(start, end)
plt.xlim(start, end)
#散點圖函數
plt.scatter(x, y, x = 'gray')
plt.style.use('classic') #更換圖的樣式
繪製3D炫酷圖
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
fig = plt. figure()
ax = fig. gca( projection='3d')
# Make data.
X =np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y= np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z= np.sin(R)
# Plot the surface.
surf= ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,linewidth=0, antialiased=False )
# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter (FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig. colorbar(surf, shrink=0.5, aspect=5)
plt. show()