1. 程式人生 > >Python常用模組(time、numpy、pandas、matplotlib)之簡單使用

Python常用模組(time、numpy、pandas、matplotlib)之簡單使用

一、time模組

  • 常用的一種獲取當前時間以及格式化模組,模組名稱:time
    匯入方式:import time

1. 時間元祖屬性

這裡寫圖片描述

這裡寫圖片描述

2. 常用方法

這裡寫圖片描述

3. 使用

3.1 導包

import time

3.2 顯示時間戳

print(time.time()) # 顯示時間戳,1937年1月1日0:0:0至今的描述

# time.localtime(timetamp) timetamp 時間戳,這個引數不填預設為當前的時間戳

3.3 顯示時間元祖

print(time.localtime()) # 顯示時間元祖

3.4 time.altzone 表示返回格林威治西部夏令時區的偏移秒數

print(time.altzone)

3.5 時間元祖轉換為時間字串

# time.strftime(fmt,tupletime)
# 時間的格式化fmt
# %Y 四位數的年 %y兩位數的年
print(time.strftime('%Y',time.localtime()))
print(time.strftime('%y',time.localtime()))
# %m 月份  %d 日
# %H 24進位制的小時   %I 12進位制小時
# %M 分鐘 %S 秒數
# %a 本地簡化星期名稱 %A 本地星期名稱
print(time.strftime('%Y/%m/%d %H:%M:%S %A',time.localtime()))

3.6 時間字串轉換為時間元祖

# time,strptime(timestr,fmt)
print(time.strptime('2018-03-27 13:11:30','%Y-%m-%d %H:%M:%S'))

二、scipy模組

  • Scipy庫是基於Python生態的一款開源數值計算、科學與工程應用的開源軟體,主要包括NumPy、Scipy、pandas、matplotlib等

這裡寫圖片描述

三、numpy模組

1. 簡介

  • 主要包括:

  • 一個具有向量算術運算和複雜廣播能力的快速且節省空間多維陣列,稱為 ndarray (N -dimensional array object)
  • 用於對整組資料進行快速運算的標準數學函式:ufunc(universal function object) object)
  • 實用的線性代數、傅立葉變換和隨機數生成函式
  • Numpy和稀疏矩陣的運算包Scipy配合使用更加方便、

匯入方式:import numpy as np

2. 核心資料結構 : ndarray

  • ndarray(N-dimensional array):N維陣列
  • 一種由相同型別的元素組成多維陣列,元素數量是實現給定好的
  • 元素的資料型別有dtype(data-type)物件來指定,每個ndarray只有一種dtype型別
  • ndarray的大小固定,建立好陣列後陣列的大小是不會發生改變的

3. Numpy基本資料型別

這裡寫圖片描述

這裡寫圖片描述

4. 使用

4.1 約定匯入方式

import numpy as np

4.2 建立Narry多維陣列

arr=np.array(
    [
        [1,2,3,4],
        [2,3,4,5],
    ]
)

4.3 維度數量

arr.ndim

4.4 陣列的形狀,陣列的每個維度的資料量

arr.shape

4.5 陣列的資料型別

arr.dtype

np.array(
    [
        ['1','2','3','4']
    ]
)

4.6 陣列中元素個數

arr.size

4.7 zeros函式 填充0

np.zeros(5) # 一維
np.zeros((3,2,2)) # 多維
np.zeros((2,1)) #第一個維度為2,第二個維度為1

4.8 ones函式 用1進行填充

np.ones((5,6)) # 預設資料型別是浮點數
np.ones((5,6),dtype=np.int) # 定義資料型別

4.9 empty函式 填充隨機值

np.empty((2,4))

4.10 幫助文件

help(np.array)

4.11 ndarray建立方式

# 1. array函式
a =  np.array(
    [
        [89,95,83],
        [79,75,77],
        [74,51,88]
    ] 
)
print(a)

# 2. arange
np.arange(2,20,3) # 從2到20,取不到20,步長為3

# 3. linspace函式 生成以等差數列 
# 第一個值代表起始位置,第二個代表結束數,第三個生成元素的個數
np.linspace(2,20,3)
np.linspace(1,10,5,endpoint=False) # 相當於生成6個數,只顯示前五個

# 4. logspace函式 生成一個等比數列
# 第一個值代表10的2次方,第二個數代表10的20次方,第三個數代表生成的元素的個數
np.logspace(2,20,6)
np.logspace(2,20,5,endpoint=False)

# 5. random函式 生成[0,1)隨機數
np.random.random((2,3,4))

4.12 ndarray 屬性

  • 1) dtype:一個用於說明陣列元素資料型別的物件
  • 2) shape:一個數組的各維度大小的元祖,即陣列的形狀
  • 3) size:元素總個數,即shape中各個數的相乘
  • 4) ndim:一個數組的維度數量
arr=np.array(
    [
        [1,2,3,4],
        [2,3,4,5],
    ]
)
print("維度的數量",arr.ndim)
print("陣列的形狀",arr.shape)
print("陣列的元素型別",arr.dtype)
print("陣列的元素數量",arr.size)

4.13 改變array形狀reshape函式

1.reshape函式不會改變原來的ndarray,但是得到的新的ndarray是原陣列的檢視

  • 檢視:多個變數使用(指向)一個記憶體地址(空間)
  • arr2 = arr1.reshape((2,10))
  • 副本:把原來的內容複製(拷貝)以一份新的資料,放到新的記憶體地址(空間)
  • 即使修改了其中一個變數的元素值,並不會影響另外一個變數

    2.對於ndarray的一些方法操作,首先要區分是否會改變原變數,以此來判斷是檢視還是副本

    arr = np.arange(20)
    arr.reshape((4,5))
    arr2 = arr.reshape((2,-1))
    arr2

    形狀可變,元素總數不可變

    arr3 = arr.copy() #拷貝,生成副本

4.14 Numpy算術運算

arr = np.arange(1,20,2)
arr + 2
arr ** 2
arr / 2
arr2 = np.arange(1,40,4)
arr + arr2
arr * arr2
arr / arr2

4.15 陣列算術運算,必須保證兩邊的陣列的形狀一致

arr = np.random.random((2,3))
arr2 = np.random.random((3,2))

# arr + arr2 # 報錯

arr2 + arr.reshape((3,2))

4.16 矩陣相乘必須滿足第一個矩陣的列軸等於第二個矩陣的行軸值

new_arr1 = np.array(
    [
        [89,95,83],
        [79,75,77],
        [74,51,88]
    ] 
)

new_arr2 = np.array(
    [
        [10,1],
        [6,10],
        [9,1]
    ] 
)

new_arr1.dot(new_arr2)

4.17 切片(取元素,切片是一個檢視)

arr3 = np.random.random((2,3,4))
arr3
arr3[0,1:]
arr3[0,[0,2]]
arr3[0,[0,2],1:3]

比如:

這裡寫圖片描述

4.18 布林型索引(篩選作用)

arr3>0.5
arr3[arr3>0.5]

4.19 花式索引

arr = np.arange(32).reshape((8,4))
arr
arr[[0,3,5]]
arr[[0,3,5],[0,3,2]] #前一個取出行,後一個按位取出對應的列

arr4 = np.array([
    'Tom','Day','Jack'
])
arr4[arr4=='Tom']=1
arr4

arr5 = np.arange(32).reshape((8,4))
arr5
np.ix_([0,3,5],[0,2,3])
arr5[np.ix_([0,3,5],[0,2,3])] #第一個表示取的行數,第二個表示取的列數
arr5[np.ix_([0,3,5],[0,2,1,3])] # ix_函式 生成一個索引器

4.20 陣列轉置與軸對換

arr7 = np.arange(32).reshape((8,4))
arr7
arr8 = arr7.T  # 陣列轉置   T屬性為檢視
arr8

arr7.transpose() # 陣列軸對換
arr = np.random.random((3,4,5))
np.abs(arr)
np.sqrt(arr)

4.21 ndarray常用函式

一元函式

這裡寫圖片描述

這裡寫圖片描述

二元函式

這裡寫圖片描述

# 1. abs
arr = np.random.random((3,4,5))
np.abs(arr)

# 2. sqrt
np.sqrt(arr)

# 3. power
arr = np.arange(10).reshape(2,-1)
arr1 = np.arange(10).reshape(2,-1)
np.power(arr,arr1) # 按位做power x的y次方

# 4. isnan
arr2 = np.empty((2,3,3))
arr2[1][1] = 'nan'
arr2
np.isnan(arr2)

# 5. add
arr3 = ([
    [1,2,3],
    [2,3,4],
    [3,4,5]
])
arr4 = ([
    [1,2,3],
    [2,3,4],
    [3,4,5]
])
np.add(arr3,arr4)

4.22 ndarray聚合函式

  • 聚合函式是對一組值(eg一個數組)進行操作,返回一個單一值作為結果的函式。
  • 當然聚合函式也可以指定對某個具體的軸進行資料聚合操作;
  • 常用的聚合操作有:平均值、最大值、最小值、方差等
arr = np.array([[1,2,3,4],[7,8,9,10]])
print(arr)
print("min=",arr.min())
print("max=",arr.max())
print("mean=",arr.mean())
print("max=",arr.max(axis=0)) # 對同列的元素進行聚合
print("max=",arr.max(axis=1)) # 對同行的元素進行聚合

4.23 三元表示式where

滿足True則顯示第一個陣列的對應位置的元素,否則顯示第二個陣列的對應位置的元素

xarr = np.array([1.1,2.2,3.3,4.4])
yarr = np.array([1.2,2.3,3.4,4.5])
bool_arr = np.array([True,False,False,True])
zip_arr = zip(xarr,yarr,bool_arr) # 數組合並
result = ['%.2f' %x if bl else '%.2f' %y for x,y,bl in zip_arr]result

np.where(bool_arr,xarr,yarr)

4.24 np.unique求陣列非重複值

arr = np.array(['中國','美國','英國','美國','英國','中國'])
arr
# Python2不能直接輸出,直接輸出會亂碼可用for迴圈列印
arr1 = np.unique(arr) # 取出唯一值
arr1

4.25 存取文字檔案

#  1.讀取文字資料
arr4 = np.loadtxt('1.txt',delimiter=',')
arr4
from io import StringIO
c = StringIO(u'0 1\n2 3')
c
np.loadtxt(c)
arr5 = np.genfromtxt('1.txt',delimiter=',') # 類似與loadtxt
arr5

# 2.資料寫入文字檔案
np.savetxt('arr.txt',arr5,delimiter=',')
np.savetxt('arr.txt',arr5,delimiter=',',fmt='%d')
arr3 = np.random.random((2,3,4)) # 如果是二維以上的陣列,需要轉換成二維的才能進行儲存
np.savetxt('arr1.txt',arr3.reshape((4,6)),delimiter=',')

四、pandas模組

1. 簡介

  • pandas是一種Python資料分析的利器,是一個開源的資料分析包,最初是應用於金融資料分析工具而開發出來的,因此pandas為時間序列分析提供了很好的支援。 pandas是PyData專案的一部分。

引入約定

  • from pandas import Series,DataFrame
  • import pandas as pd

pandas中主要有兩種資料結構,分別是:Series和DataFrame

  • Series:一種類似於一維陣列的物件,是由一組資料(各種NumPy資料型別)以及一組與之相關的資料標籤 (即索引)組成。僅由一組資料也可產生簡單的Series物件。注意:Series中的索引值是可以重複。
  • DataFrame:一個表格型的資料結構,包含有一組有序的列,每列可以是不同的值型別 (數值、字串、布林型等),DataFrame即有行索引也有列索引,可以被看做是由Series組成的字典。

2. 使用

2.1 引入方式

import numpy as np # 用於配合使用

import pandas as pd
from pandas import DataFrame,Series # 資料框、一維陣列

2.1 Series 一維陣列建立

arr = np.arange(5) # 建立一個數組
series = Series(arr)
series

series.index  # 檢視索引列
series.values # 檢視資料列
series.dtype  # 檢視資料型別

2.2 資料index繫結

series1 = Series([70,89,67],index=['張三','李四','王五'])
series1
series1.values  # 檢視資料列
series1.index

2.3 通過字典的方式建立Series

a_dict = {'1':80,'2':90,'3':89}
series2 = Series(a_dict)
series2
series2.index

2.4 Series應用NumPy陣列運算

b_dict = {'語文':80,'數學':90,'英語':89}
series3 = Series(b_dict)
series3[series3>89]
series3 / 10

2.5 Series缺失值

c_dict = {'語文':80,'數學':90,'英語':89}
series4 = Series(c_dict)
new_index = ['語文','數學','英語','地理','政治']
series4 = Series(series4,index=new_index)
series4

2.6 Series缺失值檢測

pd.isnull(series4) # 為空的元素返回True

pd.notnull(series4) # 不為空的元素返回True

series4[pd.isnull(series4)] # 過濾出缺失值的項

2.7 Series自動對齊

num1 = Series([1,2,3,4,5],index=['a','b','c','d','e'])
num2 = Series([1,2,3,4,5],index=['c','a','e','b','d'])
total = num1 * num2
num1
num2
total

2.8 通過索引從Series中取值

num3 = Series([1,2,3,4,5],index=['a','b','c','d','e'])
num3
num3['a']
num3['b':'d'] # 邊界,包含頭尾
num3['c':]
num3[:'d'] = [2,3,4,5]

2.9 通過二維陣列建立DataFrame

df1 = DataFrame([['Tom','Marry','John'],[76,78,80]])
df1
df2 = DataFrame([['Tom',76],['Marry',80],['John',90]])
df2

2.10 定義行索引和列索引

arr = np.array([['Tom',76],['Marry',80],['John',90]])
df3 = DataFrame(arr,columns=['name','score']) 
df3
df4 = DataFrame(arr,index=['1','2','3'],columns=['name','score'])
df4

2.11 通過字典的方式建立DataFrame

data = {'name':['Tom','Jack','Dany'],
       'age':[23,24,22],
       'sal':[3000,5000,2800]}
df = DataFrame(data)
df
df.index
df.columns
df.values
df5 = DataFrame(data,index=['1','2','3'])
df5

2.12 通過索引從DataFrame中取值

data1 = {'name':['Tom','Jack','Dany'],
       'age':[23,24,22],
       'sal':[3000,5000,2800]}
df6 = DataFrame(data1) 
df6
df6['age']

df6.loc[0]

2.13 通過傳遞值進行位置選擇(選擇的是行)

df6.iloc[0]

2.14 通過數值進行切片

df6.iloc[1:3] # 切片 行
df6.iloc[:,1:3] # 切片 列
df6.iloc[1:3,1:2] # 切片 行和列
df6.iloc[[1,2],[1,2]] # 1,2行,1,2列
df6['age'][0]  # 取出age列,第0行資料,從列開始取值
df6[1:]  # 如果使用切片,那麼從行開始取值

2.15 獲取指定位置的值

df6.iloc[2,2]

df6.iat[2,2]

2.16 布林索引

# 1. 使用一個單獨列的值來獲取值
df6[df6.age > 23]

# 2. 整體過濾
df7 = DataFrame([[1,2,3,4,5,4,3,5],[2,3,4,2,3,6,7,4]])
df7
df7[df7 > 4] # 把所有不滿足條件的全部置空(NaN)

# 3. isin() 過濾資料
df8 = df7.copy()
df8
df8[df8[1].isin(['3'])] # 檢索1列中的資料,將滿足3資料的行返回出來

2.17 資料檔案讀取

data1.csv

這裡寫圖片描述

# 讀取csv檔案
df = pd.read_csv('data1.csv')
df

這裡寫圖片描述

data2.txt

這裡寫圖片描述

# 讀取文字資料
# 指定屬性分隔符為":",不讀取頭部資料
df = pd.read_csv("data2.txt", sep=':',header=None)
df

這裡寫圖片描述

2.18 去除包含缺失值的行

s4 = DataFrame(np.array([
    [2,3,4,6,np.nan],
    [2,np.nan,3,4,6],
    [2,3,4,6,5]
]))
s4
s4.dropna(how = 'any')

2.19 對缺失值的替換

s5 = DataFrame(np.array([
    [2,3,4,6,np.nan],
    [2,np.nan,3,4,6],
    [2,3,4,6,5]
]))
s5
s5.fillna(value = 0)

2.20 對資料進行布林填充,空值的判斷

s6 = DataFrame(np.array([
    [2,3,4,6,np.nan],
    [2,np.nan,3,4,6],
    [2,3,4,6,5]
]))
pd.isnull(s6)

2.21 資料描述性統計

s6 = DataFrame(np.array([
    [2,3,4,6,np.nan],
    [2,np.nan,3,4,6],
    [2,3,4,6,5]
]))
s6.mean()
s6.describe()
s6.mean(1) # 對固定的軸進行統計操作

這裡寫圖片描述

2.22 apply()對資料應用函式

s4 = DataFrame(np.array([
    [2,3,4,6,np.nan],
    [2,np.nan,3,4,6],
    [2,3,4,6,5]
]))
s4.apply(np.cumsum) # apply()對資料應用函式  應用累積和函式
s4.apply(lambda x:x.max()-x.min()) # 應用最大值-最小值

2.21 常見的數學統計方法

這裡寫圖片描述

這裡寫圖片描述

2.22 相關係數與協方差

  • 相關係數(Correlation coefficient):反映兩個樣本/樣本之間的相互關係以及之間的相關程度。在COV的基礎上進行了無量綱化操作,也就是進行了標準化操作。
  • 協方差(Covariance, COV):反映兩個樣本/變數之間的相互關係以
    及之間的相關程度。

這裡寫圖片描述

2.23 資料元素頻率統計

n1 = np.random.randint(0,10,size=100)
n1
s1 = pd.Series(n1)
s1.value_counts() # 資料元素頻率統計

五、matplotlib模組

1. 簡介

  • Python最常用的繪相簿,提供了一整套十分適合互動式命令API ,比較方便的就可以將其嵌入到GUI應用程式中。

2. Figure和Subplot

  • Figure:面板(圖),matplotlib中的所有影象都是位於figure物件中,一個影象只能有一個figure物件
  • Subplot:子圖,figure物件下建立一個或多個subplot物件(即axes)用於繪製圖像

3. 約定命名

import matplotlib.pyplot as plt

4. 使用

4.1 畫cos和sin圖

import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-np.pi,np.pi,256,endpoint=True)
C = np.cos(X)
S = np.sin(X)
plt.plot(X,C)
plt.plot(X,S)
plt.show()

這裡寫圖片描述

4.2 修改版

%matplotlib inline

# 建立一個8*6點(point)的圖,並設定分別率為80
plt.figure(figsize=(8,6),dpi=80)

# 建立一個新的1*1的子圖,接下來繪製在這個區域裡
plt.subplot(1,1,1) # 1*1的子圖繪製在第一塊裡

這裡寫圖片描述

# 繪製餘弦曲線,使用藍色的、連續的、寬度為1(畫素)的線條
plt.plot(X,C,color='blue',linewidth=1.0,linestyle='-.')
# 儲存為圖片
plt.savefig('1.png',dpi = 72)

這裡寫圖片描述

# 設定橫軸的上下限
plt.xlim(-2.0,2.0)
plt.plot(X,C,color='blue',linewidth=1.0,linestyle='-.')
# 顯示圖表
plt.show()

這裡寫圖片描述

# 設定橫軸記號
plt.xticks(np.linspace(-1,1,3,endpoint=True))
plt.plot(X,C,color='blue',linewidth=1.0,linestyle='-.')
plt.show()

這裡寫圖片描述

# 移動脊柱
ax = plt.gca()
# 去除右邊和上邊的邊框
ax.spines['right'].set_color('None')
ax.spines['top'].set_color('None')
# 繪製餘弦曲線,使用藍色的、連續的、寬度為1(畫素)的線條
plt.plot(X,C,color='blue',linewidth=1.0,linestyle='-.')
plt.show()

這裡寫圖片描述

# 解決中文輸出問題
def show_word():
    from pylab import mpl
    mpl.rcParams['font.sans-serif']='FangSong' # 指定預設字型
    mpl.rcParams['axes.unicode_minus']=False
show_word()

4.3 詳細版

# 解決中文輸出問題
def show_word():
    from pylab import mpl
    mpl.rcParams['font.sans-serif']='FangSong' # 指定預設字型
    mpl.rcParams['axes.unicode_minus']=False
show_word()

# 移動脊柱
ax = plt.gca()
# 去除右邊和上邊的邊框
ax.spines['right'].set_color('None')
ax.spines['top'].set_color('None')
# 設定x軸的位置
ax.xaxis.set_ticks_position('bottom')        # 設定座標軸繫結的邊框
ax.spines['bottom'].set_position(('data',0)) # 重新定義中心點
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
# 設定x軸名,如果是中文,會無法顯示
ax.set_xticklabels(['中','b','c','中文','-e','f','g','h','i'])
# 繪製餘弦曲線,使用藍色的、連續的、寬度為1(畫素)的線條
plt.plot(X,C,color='blue',linewidth=1.0,linestyle='-.',label='cos')
# label 設定線段的描述
plt.plot(X,S,color='green',linewidth=1.0,linestyle='-',label='sin')
# 在圖表中顯示線段的描述
plt.legend(loc='upper left')
# 給特殊點做註釋
t = 2*np.pi/3  # 定義120度
# 設定cos描述
# 設定一個從(t,0)到(t,np.con(t))的一個線段
plt.plot([t,t],[0,np.cos(t)],color='blue',linewidth=2.0,linestyle='-.')
# 設定描述文字
# 第一個引數描述顯示文字
# xy這個引數,傳入顯示文字的座標
# xycoords 顯示資料的模式
plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',xy=(t,np.cos(t)),
             xycoords='data',xytext=(2,-0.5),textcoords='offset points',
             fontsize=16)

# 設定sin描述
# 設定一個從(t,0)到(t,np.con(t))的一個線段
plt.plot([t,t],[0,np.sin(t)],color='green',linewidth=2.0,linestyle='-')
# 設定描述文字
# 第一個引數描述顯示文字
# xy這個引數,傳入顯示文字的座標
# xycoords 顯示資料的模式
plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',xy=(t,np.sin(t)),
             xycoords='data',xytext=(2,-0.5),textcoords='offset points',
             fontsize=16)
plt.show()

這裡寫圖片描述

4.4 樣式

import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline  
# 上一行必不可少,在notebook中畫圖

x = np.linspace(0,10,20)
y = np.sin(x)

plt.plot(x,y)
plt.plot(x,np.cos(x))

這裡寫圖片描述

plt.plot(x,y,'--')

這裡寫圖片描述

fig = plt.figure()
plt.plot(x,y,'--')

這裡寫圖片描述

# 儲存圖
fig.savefig('./data.png')

# 虛線樣式
plt.subplot(2,1,1)
plt.plot(x,np.sin(x),'--')
# 實線樣式
plt.subplot(2,1,2)
plt.plot(x,np.cos(x))

這裡寫圖片描述

# 點狀樣式
x = np.linspace(0,10,20)
plt.plot(x,np.sin(x),'o',color='red')

這裡寫圖片描述

# 加label
x = np.linspace(0,10,100)
y = np.sin(x)

plt.plot(x,y,label='sin(x)')
plt.plot(x,np.cos(x),'o',label='cos(x)')
# legend控制label的顯示位置
plt.legend(loc = 1)

這裡寫圖片描述

這裡寫圖片描述

x = np.linspace(0,10,10)
y = np.sin(x)
plt.plot(x,y,'-p',color='orange',markersize=16,linewidth=4)

這裡寫圖片描述

# xlim ylim限定範圍
x = np.linspace(0,10,10)
y = np.sin(x)
plt.plot(x,y,'-p',color='orange',markersize=16,linewidth=4)
plt.ylim(-0.5,0.8)
plt.xlim(2,8)

這裡寫圖片描述

# 散點圖
plt.scatter(x,y,s=100)

這裡寫圖片描述

x = np.random.randn(100)
y = np.random.randn(100)
colors = np.random.rand(100)
sizes = 100 * np.random.rand(100)
plt.scatter(x,y,c=colors,s=sizes,alpha=0.4)
plt.colorbar()

這裡寫圖片描述

4.5 線性圖

df = pd.DataFrame(np.random.rand(100,4).cumsum(0),columns=['A','B','C','D'])
df.plot()

這裡寫圖片描述

df.A.plot()

這裡寫圖片描述

4.6 柱狀圖

df = pd.DataFrame(np.random.randint(10,50,(3,4)),columns=['A','B','C','D'], index=['one','two','three'])
df.plot.bar()

這裡寫圖片描述

df.A.plot.bar()

這裡寫圖片描述

# 等價於上面的繪製
df.plot(kind='bar')

這裡寫圖片描述

4.7 直方圖

df = pd.DataFrame(np.random.rand(100,4),columns=['A','B','C','D'])
df.hist()

這裡寫圖片描述

4.8 密度圖

df.plot.kde()

這裡寫圖片描述