python-day18(正式學習)

numpy模塊

numpy簡介

numpy官方文檔:https://docs.scipy.org/doc/numpy/reference/?v=20190307135750python

numpy是Python的一種開源的數值計算擴展庫。這種庫可用來存儲和處理大型numpy數組,比Python自身的嵌套列表結構要高效的多(該結構也能夠用來表示numpy數組)。mysql

numpy庫有兩個做用:正則表達式

  1. 區別於list列表,提供了數組操做、數組運算、以及統計分佈和簡單的數學模型
  2. 計算速度快,甚至要因爲python內置的簡單運算,使得其成爲pandas、sklearn等模塊的依賴包。高級的框架如TensorFlow、PyTorch等,其數組操做也和numpy很是類似。

爲何要用numpy

lis1=[1,2,3]
lis2=[4,5,6]

當咱們想讓兩個列表內的元素相乘時,若是不用numpy模塊,就須要用一個for循環來進行元素的相乘並從新建一個列表來賦值。而使用了numpy則徹底不同了,接下來就讓咱們欣賞一下numpy模塊的功能。sql

建立numpy數組

numpy數組即numpy的ndarray對象,建立numpy數組就是把一個列表傳入np.array()方法數據庫

arr=np.array([1,2,3])
print(arr)
arr1=np.array([[1,2,3],[4,5,6]])
print(arr1)
arr2=np.array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
print(arr2)

建立一維二維和三維的numpy數組,在numpy中通常用二位比較多,三維及以上用其餘模塊json

numpy數組的基本屬性

屬性 解釋
dtype 數組元素的數據類型
size 數組元素的個數
ndim 數組的維度
shape 數組的維度大小(以元組形式)
astype 類型轉換

dtype種類:bool_,int(8,16,32,64),float(16,32,64)數組

arr=np.array([[1,2,3],[4,5,6]])
print(arr,arr.dtype)
print(arr.T)
print(arr.size)
print(arr.ndim)
print(arr.shape)

[[1 2 3]
[4 5 6]] int32
[[1 4]
[2 5]
[3 6]]
6
2
(2, 3)數據結構

獲取numpy數組的行列數

因爲numpy數組是多維的,對於維的數組而言,numpy數組就是既有行又有列app

arr=np.array([[1,2,3],[4,5,6]])
print(arr)
print(arr.shape)
print(arr.shape[0])
print(arr.shape[1])

[[1 2 3]
[4 5 6]]
(2, 3)
2
3

切割numpy數組

切分numpy數組相似於列表的切割,但與列表的切割不一樣的是,numpy數組的切割涉及到行和列的切割,可是二者的切割方式都是從索引0開始,而且取頭不取尾

arr=np.array([[1,2,3],[4,5,6]])
print(arr)
print(arr[:,:])
print(arr[:1,1:])
print(arr[0,:])
print(arr[:,0])
print(arr[arr>5])

[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]
[[2 3]]
[1 2 3]
[1 4]
[6]

numpy數組元素替換

numpy數組元素的替換,相似於列表元素的替換,而且numpy數組也是一個可變類型的數據,即若是對numpy數組進行替換操做,會修改原numpy數組的元素,因此下面咱們用.copy()方法舉例numpy數組元素的替換。

arr=np.array([[1,2,3],[4,5,6]])
arr1=arr.copy()
arr1[:1,:]=0
print(arr1)
arr2=arr.copy()
arr2[arr2>5]=0
print(arr2)
arr[:,:]=0
print(arr)

[[0 0 0]
[4 5 6]]
[[1 2 3]
[4 5 0]]
[[0 0 0]
[0 0 0]]

numpy數組的合併

arr1 = np.array([[1, 2], [3, 4], [5, 6]])
print(arr1)
[[1 2]
 [3 4]
 [5 6]]
arr2 = np.array([[7, 8], [9, 10], [11, 12]])
print(arr2)
[[ 7  8]
 [ 9 10]
 [11 12]]
# 合併兩個numpy數組的行,注意使用hstack()方法合併numpy數組,numpy數組應該有相同的行,其中hstack的h表示horizontal水平的
print(np.hstack((arr1, arr2)))
[[ 1  2  7  8]
 [ 3  4  9 10]
 [ 5  6 11 12]]
# 合併兩個numpy數組,其中axis=1表示合併兩個numpy數組的行
print(np.concatenate((arr1, arr2), axis=1))
[[ 1  2  7  8]
 [ 3  4  9 10]
 [ 5  6 11 12]]
# 合併兩個numpy數組的列,注意使用vstack()方法合併numpy數組,numpy數組應該有相同的列,其中vstack的v表示vertical垂直的
print(np.vstack((arr1, arr2)))
[[ 1  2]
 [ 3  4]
 [ 5  6]
 [ 7  8]
 [ 9 10]
 [11 12]]
# 合併兩個numpy數組,其中axis=0表示合併兩個numpy數組的列
print(np.concatenate((arr1, arr2), axis=0))
[[ 1  2]
 [ 3  4]
 [ 5  6]
 [ 7  8]
 [ 9 10]
 [11 12]]
方法 詳解
array() 將列表轉換爲數組,可選擇顯式指定dtype
arange() range的numpy版,支持浮點數
linspace() 相似arange(),第三個參數爲數組長度
zeros() 根據指定形狀和dtype建立全0數組
ones() 根據指定形狀和dtype建立全1數組
eye() 建立單位矩陣
empty() 建立一個元素全隨機的數組
reshape() 重塑形狀

array

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

arange

# 構造0-9的ndarray數組
print(np.arange(10))
[0 1 2 3 4 5 6 7 8 9]
# 構造1-4的ndarray數組
print(np.arange(1, 5))
[1 2 3 4]
# 構造1-19且步長爲2的ndarray數組
print(np.arange(1, 20, 2))
[ 1  3  5  7  9 11 13 15 17 19]

linspace/logspace

# 構造一個等差數列,取頭也取尾,從0取到20,取5個數
print(np.linspace(0, 20, 5))
[ 0.  5. 10. 15. 20.]
# 構造一個等比數列,從10**0取到10**20,取5個數
print(np.logspace(0, 20, 5))
[1.e+00 1.e+05 1.e+10 1.e+15 1.e+20]

zeros/ones/eye/empty

# 構造3*4的全0numpy數組
print(np.zeros((3, 4)))
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
# 構造3*4的全1numpy數組
print(np.ones((3, 4)))
[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]
# 構造3個主元的單位numpy數組
print(np.eye(3))
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
# 構造一個4*4的隨機numpy數組,裏面的元素是隨機生成的
print(np.empty((4, 4)))
[[ 2.31584178e+077 -1.49457545e-154  3.95252517e-323  0.00000000e+000]
 [ 0.00000000e+000  0.00000000e+000  0.00000000e+000  0.00000000e+000]
 [ 0.00000000e+000  0.00000000e+000  0.00000000e+000  0.00000000e+000]
 [ 0.00000000e+000  0.00000000e+000  1.29074055e-231  1.11687366e-308]]

reshape

arr = np.ones([2, 2], dtype=int)
print(arr.reshape(4, 1))
[[1]
 [1]
 [1]
 [1]]

fromstring/fromfunction(瞭解)

# fromstring經過對字符串的字符編碼所對應ASCII編碼的位置,生成一個ndarray對象
s = 'abcdef'
# np.int8表示一個字符的字節數爲8
print(np.fromstring(s, dtype=np.int8))
[ 97  98  99 100 101 102]


/Applications/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:4: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
  after removing the cwd from sys.path.
def func(i, j):
    """其中i爲numpy數組的行,j爲numpy數組的列"""
    return i * j


# 使用函數對numpy數組元素的行和列的索引作處理,獲得當前元素的值,索引從0開始,並構造一個3*4的numpy數組
print(np.fromfunction(func, (3, 4)))
[[0. 0. 0. 0.]
 [0. 1. 2. 3.]
 [0. 2. 4. 6.]]

numpy數組的運算

運算符 說明
+ 兩個numpy數組對應元素相加
- 兩個numpy數組對應元素相減
* 兩個numpy數組對應元素相乘
/ 兩個numpy數組對應元素相除,若是都是整數則取商
% 兩個numpy數組對應元素相除後取餘數
**n 單個numpy數組每一個元素都取n次方,如**2:每一個元素都取平方
arrarr1 = np.array([[1, 2], [3, 4], [5, 6]])
print(arr1)
[[1 2]
 [3 4]
 [5 6]]
arr2 = np.array([[7, 8], [9, 10], [11, 12]])
print(arr2)
[[ 7  8]
 [ 9 10]
 [11 12]]
print(arr1 + arr2)
[[ 8 10]
 [12 14]
 [16 18]]
print(arr1**2)
[[ 1  4]
 [ 9 16]
 [25 36]]

numpy數組運算函數

numpy數組函數 詳解
np.sin(arr) 對numpy數組arr中每一個元素取正弦,sin(x)sin(x)
np.cos(arr) 對numpy數組arr中每一個元素取餘弦,cos(x)cos(x)
np.tan(arr) 對numpy數組arr中每一個元素取正切,tan(x)tan(x)
np.arcsin(arr) 對numpy數組arr中每一個元素取反正弦,*arcsi**n(x*)arcsin(x)
np.arccos(arr) 對numpy數組arr中每一個元素取反餘弦,*arcco**s(x*)arccos(x)
np.arctan(arr) 對numpy數組arr中每一個元素取反正切,*arcta**n(x*)arctan(x)
np.exp(arr) 對numpy數組arr中每一個元素取指數函數,*e**x*ex
np.sqrt(arr) 對numpy數組arr中每一個元素開根號x

一元函數:abs, sqrt, exp, log, ceil, floor, rint, trunc, modf, isnan, isinf, cos, sin, tan

二元函數:add, substract, multiply, divide, power, mod, maximum, mininum

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(arr)
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
# 對numpy數組的全部元素取正弦
print(np.sin(arr))
[[ 0.84147098  0.90929743  0.14112001 -0.7568025 ]
 [-0.95892427 -0.2794155   0.6569866   0.98935825]
 [ 0.41211849 -0.54402111 -0.99999021 -0.53657292]]
# 對numpy數組的全部元素開根號
print(np.sqrt(arr))
[[1.         1.41421356 1.73205081 2.        ]
 [2.23606798 2.44948974 2.64575131 2.82842712]
 [3.         3.16227766 3.31662479 3.46410162]]
# 對numpy數組的全部元素取反正弦,若是元素不在定義域內,則會取nan值
print(np.arcsin(arr * 0.1))
[[0.10016742 0.20135792 0.30469265 0.41151685]
 [0.52359878 0.64350111 0.7753975  0.92729522]
 [1.11976951 1.57079633        nan        nan]]


/Applications/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in arcsin
  
# 判斷矩陣元素中是否含有np.nan值
print(np.isnan(arr))
[[False False False]
 [False False False]]

numpy數組矩陣化

numpy數組點乘

numpy數組的點乘必須知足第一個numpy數組的列數等於第二個numpy數組的行數,即mnnm=mmm∗n·n∗m=m∗m 。

arr1 = np.array([[1, 2, 3], [4, 5, 6]])
print(arr1.shape)
(2, 3)
arr2 = np.array([[7, 8], [9, 10], [11, 12]])
print(arr2.shape)
(3, 2)
assert arr1.shape[0] == arr2.shape[1]
# 2*3·3*2 = 2*2
print(arr2.shape)
(3, 2)

numpy數組轉置

numpy數組的轉置,至關於numpy數組的行和列互換。

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
[[1 2 3]
 [4 5 6]]
print(arr.transpose())
[[1 4]
 [2 5]
 [3 6]]
print(arr.T)
[[1 4]
 [2 5]
 [3 6]]

nummpy數組的逆

numpy數組行和列相同時,numpy數組纔可逆。

arr = np.array([[1, 2, 3], [4, 5, 6], [9, 8, 9]])
print(arr)
[[1 2 3]
 [4 5 6]
 [9 8 9]]
print(np.linalg.inv(arr))
[[ 0.5        -1.          0.5       ]
 [-3.          3.         -1.        ]
 [ 2.16666667 -1.66666667  0.5       ]]
# 單位numpy數組的逆是單位numpy數組自己
arr = np.eye(3)
print(arr)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
print(np.linalg.inv(arr))
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

numpy數組數學和統計方法

方法 詳解
sum 求和
cumsum 累加求和
mean 求平均數
std 求標準差
var 求方差
min 求最小值
max 求最大值
argmin 求最小值索引
argmax 求最大值索引
sort 排序
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr)
[[1 2 3]
 [4 5 6]
 [7 8 9]]
# 獲取numpy數組全部元素中的最大值
print(arr.max())
9
# 獲取numpy數組全部元素中的最小值
print(arr.min())
1
# 獲取舉着每一行的最大值
print(arr.max(axis=0))
[7 8 9]
# 獲取numpy數組每一列的最大值
print(arr.max(axis=1))
[3 6 9]
# 獲取numpy數組最大元素的索引位置
print(arr.argmax(axis=1))
[2 2 2]

numpy.random生成隨機數

函數名稱 函數功能 參數說明
rand(d0,d1,⋯,*d**n*d0,d1,⋯,dn ) 產生均勻分佈的隨機數 *d**n*dn 爲第n維數據的維度
randn(d0,d1,⋯,*d**n*d0,d1,⋯,dn ) 產生標準正態分佈隨機數 *d**n*dn 爲第n維數據的維度
randint(low[, high, size, dtype]) 產生隨機整數 low:最小值;high:最大值;size:數據個數
random_sample([size]) 在[0,1)[0,1) 內產生隨機數 size爲隨機數的shape,能夠爲元祖或者列表
choice(a[, size]) 從arr中隨機選擇指定數據 arr爲1維數組;size爲數組形狀
uniform(low,high [,size]) 給定形狀產生隨機數組 low爲最小值;high爲最大值,size爲數組形狀
shuffle(a) 與random.shuffle相同 a爲指定數組

點擊查看源網頁

pandas模塊

pandas官方文檔:https://pandas.pydata.org/pandas-docs/stable/?v=20190307135750

pandas基於Numpy,能夠當作是處理文本或者表格數據。pandas中有兩個主要的數據結構,其中Series數據結構相似於Numpy中的一維數組,DataFrame相似於多維表格數據結構。

pandas是python數據分析的核心模塊。它主要提供了五大功能:

  1. 支持文件存取操做,支持數據庫(sql)、html、json、pickle、csv(txt、excel)、sas、stata、hdf等。
  2. 支持增刪改查、切片、高階函數、分組聚合等單表操做,以及和dict、list的互相轉換。
  3. 支持多表拼接合並操做。
  4. 支持簡單的繪圖操做。
  5. 支持簡單的統計分析操做。

1、Series數據結構

Series是一種相似於一維數組的對象,由一組數據和一組與之相關的數據標籤(索引)組成。

Series比較像列表(數組)和字典的結合體

import numpy as np
import pandas as pd
df = pd.Series(0, index=['a', 'b', 'c', 'd'])
print(df)
a    0
b    0
c    0
d    0
dtype: int64
print(df.values)
[0 0 0 0]
print(df.index)
Index(['a', 'b', 'c', 'd'], dtype='object')

1.1 Series支持NumPy模塊的特性(下標)

詳解 方法
從ndarray建立Series Series(arr)
與標量運算 df*2
兩個Series運算 df1+df2
索引 df[0], df[[1,2,4]]
切片 df[0:2]
通用函數 np.abs(df)
布爾值過濾 df[df>0]
arr = np.array([1, 2, 3, 4, np.nan])
print(arr)
[ 1.  2.  3.  4. nan]
df = pd.Series(arr, index=['a', 'b', 'c', 'd', 'e'])
print(df)
a    1.0
b    2.0
c    3.0
d    4.0
e    NaN
dtype: float64
print(df**2)
a     1.0
b     4.0
c     9.0
d    16.0
e     NaN
dtype: float64
print(df[0])
1.0
print(df['a'])
1.0
print(df[[0, 1, 2]])
a    1.0
b    2.0
c    3.0
dtype: float64
print(df[0:2])
a    1.0
b    2.0
dtype: float64
np.sin(df)
a    0.841471
b    0.909297
c    0.141120
d   -0.756802
e         NaN
dtype: float64
df[df > 1]
b    2.0
c    3.0
d    4.0
dtype: float64

1.2 Series支持字典的特性(標籤)

詳解 方法
從字典建立Series Series(dic),
in運算 ’a’ in sr
鍵索引 sr['a'], sr[['a', 'b', 'd']]
df = pd.Series({'a': 1, 'b': 2})
print(df)
a    1
b    2
dtype: int64
print('a' in df)
True
print(df['a'])
1

1.3 Series缺失數據處理

方法 詳解
dropna() 過濾掉值爲NaN的行
fillna() 填充缺失數據
isnull() 返回布爾數組,缺失值對應爲True
notnull() 返回布爾數組,缺失值對應爲False
df = pd.Series([1, 2, 3, 4, np.nan], index=['a', 'b', 'c', 'd', 'e'])
print(df)
a    1.0
b    2.0
c    3.0
d    4.0
e    NaN
dtype: float64
print(df.dropna())
a    1.0
b    2.0
c    3.0
d    4.0
dtype: float64
print(df.fillna(5))
a    1.0
b    2.0
c    3.0
d    4.0
e    5.0
dtype: float64
print(df.isnull())
a    False
b    False
c    False
d    False
e     True
dtype: bool
print(df.notnull())
a     True
b     True
c     True
d     True
e    False
dtype: bool

2、DataFrame數據結構

DataFrame是一個表格型的數據結構,含有一組有序的列。

DataFrame能夠被看作是由Series組成的字典,而且共用一個索引。

2.1 產生時間對象數組:date_range

date_range參數詳解:

參數 詳解
start 開始時間
end 結束時間
periods 時間長度
freq 時間頻率,默認爲'D',可選H(our),W(eek),B(usiness),S(emi-)M(onth),(min)T(es), S(econd), A(year),…
dates = pd.date_range('20190101', periods=6, freq='M')
print(dates)
DatetimeIndex(['2019-01-31', '2019-02-28', '2019-03-31', '2019-04-30',
               '2019-05-31', '2019-06-30'],
              dtype='datetime64[ns]', freq='M')
np.random.seed(1)
arr = 10 * np.random.randn(6, 4)
print(arr)
[[ 16.24345364  -6.11756414  -5.28171752 -10.72968622]
 [  8.65407629 -23.01538697  17.44811764  -7.61206901]
 [  3.19039096  -2.49370375  14.62107937 -20.60140709]
 [ -3.22417204  -3.84054355  11.33769442 -10.99891267]
 [ -1.72428208  -8.77858418   0.42213747   5.82815214]
 [-11.00619177  11.4472371    9.01590721   5.02494339]]
df = pd.DataFrame(arr, index=dates, columns=['c1', 'c2', 'c3', 'c4'])
df
c1 c2 c3 c4
2019-01-31 16.243454 -6.117564 -5.281718 -10.729686
2019-02-28 8.654076 -23.015387 17.448118 -7.612069
2019-03-31 3.190391 -2.493704 14.621079 -20.601407
2019-04-30 -3.224172 -3.840544 11.337694 -10.998913
2019-05-31 -1.724282 -8.778584 0.422137 5.828152
2019-06-30 -11.006192 11.447237 9.015907 5.024943

3、DataFrame屬性

屬性 詳解
dtype是 查看數據類型
index 查看行序列或者索引
columns 查看各列的標籤
values 查看數據框內的數據,也即不含表頭索引的數據
describe 查看數據每一列的極值,均值,中位數,只可用於數值型數據
transpose 轉置,也可用T來操做
sort_index 排序,可按行或列index排序輸出
sort_values 按數據值來排序
# 查看數據類型
print(df2.dtypes)
0    float64
1    float64
2    float64
3    float64
dtype: object
df
c1 c2 c3 c4
2019-01-31 16.243454 -6.117564 -5.281718 -10.729686
2019-02-28 8.654076 -23.015387 17.448118 -7.612069
2019-03-31 3.190391 -2.493704 14.621079 -20.601407
2019-04-30 -3.224172 -3.840544 11.337694 -10.998913
2019-05-31 -1.724282 -8.778584 0.422137 5.828152
2019-06-30 -11.006192 11.447237 9.015907 5.024943
print(df.index)
DatetimeIndex(['2019-01-31', '2019-02-28', '2019-03-31', '2019-04-30',
               '2019-05-31', '2019-06-30'],
              dtype='datetime64[ns]', freq='M')
print(df.columns)
Index(['c1', 'c2', 'c3', 'c4'], dtype='object')
print(df.values)
[[ 16.24345364  -6.11756414  -5.28171752 -10.72968622]
 [  8.65407629 -23.01538697  17.44811764  -7.61206901]
 [  3.19039096  -2.49370375  14.62107937 -20.60140709]
 [ -3.22417204  -3.84054355  11.33769442 -10.99891267]
 [ -1.72428208  -8.77858418   0.42213747   5.82815214]
 [-11.00619177  11.4472371    9.01590721   5.02494339]]
df.describe()
c1 c2 c3 c4
count 6.000000 6.000000 6.000000 6.000000
mean 2.022213 -5.466424 7.927203 -6.514830
std 9.580084 11.107772 8.707171 10.227641
min -11.006192 -23.015387 -5.281718 -20.601407
25% -2.849200 -8.113329 2.570580 -10.931606
50% 0.733054 -4.979054 10.176801 -9.170878
75% 7.288155 -2.830414 13.800233 1.865690
max 16.243454 11.447237 17.448118 5.828152
df.T
2019-01-31 00:00:00 2019-02-28 00:00:00 2019-03-31 00:00:00 2019-04-30 00:00:00 2019-05-31 00:00:00 2019-06-30 00:00:00
c1 16.243454 8.654076 3.190391 -3.224172 -1.724282 -11.006192
c2 -6.117564 -23.015387 -2.493704 -3.840544 -8.778584 11.447237
c3 -5.281718 17.448118 14.621079 11.337694 0.422137 9.015907
c4 -10.729686 -7.612069 -20.601407 -10.998913 5.828152 5.024943
# 按行標籤[c1, c2, c3, c4]從大到小排序
df.sort_index(axis=0)
c1 c2 c3 c4
2019-01-31 16.243454 -6.117564 -5.281718 -10.729686
2019-02-28 8.654076 -23.015387 17.448118 -7.612069
2019-03-31 3.190391 -2.493704 14.621079 -20.601407
2019-04-30 -3.224172 -3.840544 11.337694 -10.998913
2019-05-31 -1.724282 -8.778584 0.422137 5.828152
2019-06-30 -11.006192 11.447237 9.015907 5.024943
# 按列標籤[2019-01-01, 2019-01-02...]從大到小排序
df.sort_index(axis=1)
c1 c2 c3 c4
2019-01-31 16.243454 -6.117564 -5.281718 -10.729686
2019-02-28 8.654076 -23.015387 17.448118 -7.612069
2019-03-31 3.190391 -2.493704 14.621079 -20.601407
2019-04-30 -3.224172 -3.840544 11.337694 -10.998913
2019-05-31 -1.724282 -8.778584 0.422137 5.828152
2019-06-30 -11.006192 11.447237 9.015907 5.024943
# 按c2列的值從大到小排序
df.sort_values(by='c2')
c1 c2 c3 c4
2019-02-28 8.654076 -23.015387 17.448118 -7.612069
2019-05-31 -1.724282 -8.778584 0.422137 5.828152
2019-01-31 16.243454 -6.117564 -5.281718 -10.729686
2019-04-30 -3.224172 -3.840544 11.337694 -10.998913
2019-03-31 3.190391 -2.493704 14.621079 -20.601407
2019-06-30 -11.006192 11.447237 9.015907 5.024943

4、DataFrame取值

df
c1 c2 c3 c4
2019-01-31 16.243454 -6.117564 -5.281718 -10.729686
2019-02-28 8.654076 -23.015387 17.448118 -7.612069
2019-03-31 3.190391 -2.493704 14.621079 -20.601407
2019-04-30 -3.224172 -3.840544 11.337694 -10.998913
2019-05-31 -1.724282 -8.778584 0.422137 5.828152
2019-06-30 -11.006192 11.447237 9.015907 5.024943

4.1 經過columns取值

df['c2']
2019-01-31    -6.117564
2019-02-28   -23.015387
2019-03-31    -2.493704
2019-04-30    -3.840544
2019-05-31    -8.778584
2019-06-30    11.447237
Freq: M, Name: c2, dtype: float64
df[['c2', 'c3']]
c2 c3
2019-01-31 -6.117564 -5.281718
2019-02-28 -23.015387 17.448118
2019-03-31 -2.493704 14.621079
2019-04-30 -3.840544 11.337694
2019-05-31 -8.778584 0.422137
2019-06-30 11.447237 9.015907

4.2 loc(經過行標籤取值)

# 經過自定義的行標籤選擇數據
df.loc['2019-01-01':'2019-01-03']
c1 c2 c3 c4
df[0:3]
c1 c2 c3 c4
2019-01-31 16.243454 -6.117564 -5.281718 -10.729686
2019-02-28 8.654076 -23.015387 17.448118 -7.612069
2019-03-31 3.190391 -2.493704 14.621079 -20.601407

4.3 iloc(相似於numpy數組取值)

df.values
array([[ 16.24345364,  -6.11756414,  -5.28171752, -10.72968622],
       [  8.65407629, -23.01538697,  17.44811764,  -7.61206901],
       [  3.19039096,  -2.49370375,  14.62107937, -20.60140709],
       [ -3.22417204,  -3.84054355,  11.33769442, -10.99891267],
       [ -1.72428208,  -8.77858418,   0.42213747,   5.82815214],
       [-11.00619177,  11.4472371 ,   9.01590721,   5.02494339]])
# 經過行索引選擇數據
print(df.iloc[2, 1])
-2.493703754774101
df.iloc[1:4, 1:4]
c2 c3 c4
2019-02-28 -23.015387 17.448118 -7.612069
2019-03-31 -2.493704 14.621079 -20.601407
2019-04-30 -3.840544 11.337694 -10.998913

4.4 使用邏輯判斷取值

df[df['c1'] > 0]
c1 c2 c3 c4
2019-01-31 16.243454 -6.117564 -5.281718 -10.729686
2019-02-28 8.654076 -23.015387 17.448118 -7.612069
2019-03-31 3.190391 -2.493704 14.621079 -20.601407
df[(df['c1'] > 0) & (df['c2'] > -8)]
c1 c2 c3 c4
2019-01-31 16.243454 -6.117564 -5.281718 -10.729686
2019-03-31 3.190391 -2.493704 14.621079 -20.601407

5、DataFrame值替換

df
c1 c2 c3 c4
2019-01-31 16.243454 -6.117564 -5.281718 -10.729686
2019-02-28 8.654076 -23.015387 17.448118 -7.612069
2019-03-31 3.190391 -2.493704 14.621079 -20.601407
2019-04-30 -3.224172 -3.840544 11.337694 -10.998913
2019-05-31 -1.724282 -8.778584 0.422137 5.828152
2019-06-30 -11.006192 11.447237 9.015907 5.024943
df.iloc[0:3, 0:2] = 0
df
c1 c2 c3 c4
2019-01-31 0.000000 0.000000 -5.281718 -10.729686
2019-02-28 0.000000 0.000000 17.448118 -7.612069
2019-03-31 0.000000 0.000000 14.621079 -20.601407
2019-04-30 -3.224172 -3.840544 11.337694 -10.998913
2019-05-31 -1.724282 -8.778584 0.422137 5.828152
2019-06-30 -11.006192 11.447237 9.015907 5.024943
df['c3'] > 10
2019-01-31    False
2019-02-28     True
2019-03-31     True
2019-04-30     True
2019-05-31    False
2019-06-30    False
Freq: M, Name: c3, dtype: bool
# 針對行作處理
df[df['c3'] > 10] = 100
df
c1 c2 c3 c4
2019-01-31 0.000000 0.000000 -5.281718 -10.729686
2019-02-28 100.000000 100.000000 100.000000 100.000000
2019-03-31 100.000000 100.000000 100.000000 100.000000
2019-04-30 100.000000 100.000000 100.000000 100.000000
2019-05-31 -1.724282 -8.778584 0.422137 5.828152
2019-06-30 -11.006192 11.447237 9.015907 5.024943
# 針對行作處理
df = df.astype(np.int32)
df[df['c3'].isin([100])] = 1000
df
c1 c2 c3 c4
2019-01-31 0 0 -5 -10
2019-02-28 1000 1000 1000 1000
2019-03-31 1000 1000 1000 1000
2019-04-30 1000 1000 1000 1000
2019-05-31 -1 -8 0 5
2019-06-30 -11 11 9 5

6、讀取CSV文件

import pandas as pd
from io import StringIO
test_data = '''
5.1,,1.4,0.2
4.9,3.0,1.4,0.2
4.7,3.2,,0.2
7.0,3.2,4.7,1.4
6.4,3.2,4.5,1.5
6.9,3.1,4.9,
,,,
'''

test_data = StringIO(test_data)
df = pd.read_csv(test_data, header=None)
df.columns = ['c1', 'c2', 'c3', 'c4']
df
c1 c2 c3 c4
0 5.1 NaN 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 NaN 0.2
3 7.0 3.2 4.7 1.4
4 6.4 3.2 4.5 1.5
5 6.9 3.1 4.9 NaN
6 NaN NaN NaN NaN

7、處理丟失數據

df.isnull()
c1 c2 c3 c4
0 False True False False
1 False False False False
2 False False True False
3 False False False False
4 False False False False
5 False False False True
6 True True True True
# 經過在isnull()方法後使用sum()方法便可得到該數據集某個特徵含有多少個缺失值
print(df.isnull().sum())
c1    1
c2    2
c3    2
c4    2
dtype: int64
# axis=0刪除有NaN值的行
df.dropna(axis=0)
c1 c2 c3 c4
1 4.9 3.0 1.4 0.2
3 7.0 3.2 4.7 1.4
4 6.4 3.2 4.5 1.5
# axis=1刪除有NaN值的列
df.dropna(axis=1)
0
1
2
3
4
5
6
# 刪除全爲NaN值得行或列
df.dropna(how='all')
c1 c2 c3 c4
0 5.1 NaN 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 NaN 0.2
3 7.0 3.2 4.7 1.4
4 6.4 3.2 4.5 1.5
5 6.9 3.1 4.9 NaN
# 刪除行不爲4個值的
df.dropna(thresh=4)
c1 c2 c3 c4
1 4.9 3.0 1.4 0.2
3 7.0 3.2 4.7 1.4
4 6.4 3.2 4.5 1.5
# 刪除c2中有NaN值的行
df.dropna(subset=['c2'])
c1 c2 c3 c4
1 4.9 3.0 1.4 0.2
2 4.7 3.2 NaN 0.2
3 7.0 3.2 4.7 1.4
4 6.4 3.2 4.5 1.5
5 6.9 3.1 4.9 NaN
# 填充nan值
df.fillna(value=10)
c1 c2 c3 c4
0 5.1 10.0 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 10.0 0.2
3 7.0 3.2 4.7 1.4
4 6.4 3.2 4.5 1.5
5 6.9 3.1 4.9 10.0
6 10.0 10.0 10.0 10.0

8、合併數據

df1 = pd.DataFrame(np.zeros((3, 4)))
df1
0 1 2 3
0 0.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0
2 0.0 0.0 0.0 0.0
df2 = pd.DataFrame(np.ones((3, 4)))
df2
0 1 2 3
0 1.0 1.0 1.0 1.0
1 1.0 1.0 1.0 1.0
2 1.0 1.0 1.0 1.0
# axis=0合併列
pd.concat((df1, df2), axis=0)
0 1 2 3
0 0.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0
2 0.0 0.0 0.0 0.0
0 1.0 1.0 1.0 1.0
1 1.0 1.0 1.0 1.0
2 1.0 1.0 1.0 1.0
# axis=1合併行
pd.concat((df1, df2), axis=1)
0 1 2 3 0 1 2 3
0 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0
1 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0
2 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0
# append只能合併列
df1.append(df2)
0 1 2 3
0 0.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0
2 0.0 0.0 0.0 0.0
0 1.0 1.0 1.0 1.0
1 1.0 1.0 1.0 1.0
2 1.0 1.0 1.0 1.0

9、導入導出數據

使用df = pd.read_excel(filename)讀取文件,使用df.to_excel(filename)保存文件。

9.1 讀取文件導入數據

讀取文件導入數據函數主要參數:

參數 詳解
sep 指定分隔符,可用正則表達式如'\s+'
header=None 指定文件無行名
name 指定列名
index_col 指定某列做爲索引
skip_row 指定跳過某些行
na_values 指定某些字符串表示缺失值
parse_dates 指定某些列是否被解析爲日期,布爾值或列表
df = pd.read_excel(filename)
df = pd.read_csv(filename)

9.2 寫入文件導出數據

寫入文件函數的主要參數:

參數 詳解
sep 分隔符
na_rep 指定缺失值轉換的字符串,默認爲空字符串
header=False 不保存列名
index=False 不保存行索引
cols 指定輸出的列,傳入列表
df.to_excel(filename)

10、pandas讀取json文件

strtext = '[{"ttery":"min","issue":"20130801-3391","code":"8,4,5,2,9","code1":"297734529","code2":null,"time":1013395466000},\
{"ttery":"min","issue":"20130801-3390","code":"7,8,2,1,2","code1":"298058212","code2":null,"time":1013395406000},\
{"ttery":"min","issue":"20130801-3389","code":"5,9,1,2,9","code1":"298329129","code2":null,"time":1013395346000},\
{"ttery":"min","issue":"20130801-3388","code":"3,8,7,3,3","code1":"298588733","code2":null,"time":1013395286000},\
{"ttery":"min","issue":"20130801-3387","code":"0,8,5,2,7","code1":"298818527","code2":null,"time":1013395226000}]'

df = pd.read_json(strtext, orient='records')
df
code code1 code2 issue time ttery
0 8,4,5,2,9 297734529 NaN 20130801-3391 1013395466000 min
1 7,8,2,1,2 298058212 NaN 20130801-3390 1013395406000 min
2 5,9,1,2,9 298329129 NaN 20130801-3389 1013395346000 min
3 3,8,7,3,3 298588733 NaN 20130801-3388 1013395286000 min
4 0,8,5,2,7 298818527 NaN 20130801-3387 1013395226000 min
df.to_excel('pandas處理json.xlsx',
            index=False,
            columns=["ttery", "issue", "code", "code1", "code2", "time"])

10.1 orient參數的五種形式

orient是代表預期的json字符串格式。orient的設置有如下五個值:

1.'split' : dict like {index -> [index], columns -> [columns], data -> [values]}

這種就是有索引,有列字段,和數據矩陣構成的json格式。key名稱只能是index,columns和data。

s = '{"index":[1,2,3],"columns":["a","b"],"data":[[1,3],[2,8],[3,9]]}'
df = pd.read_json(s, orient='split')
df
a b
1 1 3
2 2 8
3 3 9

2.'records' : list like [{column -> value}, ... , {column -> value}]

這種就是成員爲字典的列表。如我今天要處理的json數據示例所見。構成是列字段爲鍵,值爲鍵值,每個字典成員就構成了dataframe的一行數據。

strtext = '[{"ttery":"min","issue":"20130801-3391","code":"8,4,5,2,9","code1":"297734529","code2":null,"time":1013395466000},\
{"ttery":"min","issue":"20130801-3390","code":"7,8,2,1,2","code1":"298058212","code2":null,"time":1013395406000}]'

df = pd.read_json(strtext, orient='records')
df
code code1 code2 issue time ttery
0 8,4,5,2,9 297734529 NaN 20130801-3391 1013395466000 min
1 7,8,2,1,2 298058212 NaN 20130801-3390 1013395406000 min

3.'index' : dict like {index -> {column -> value}}

以索引爲key,以列字段構成的字典爲鍵值。如:

s = '{"0":{"a":1,"b":2},"1":{"a":9,"b":11}}'
df = pd.read_json(s, orient='index')
df
a b
0 1 2
1 9 11

4.'columns' : dict like {column -> {index -> value}}

這種處理的就是以列爲鍵,對應一個值字典的對象。這個字典對象以索引爲鍵,以值爲鍵值構成的json字符串。以下圖所示:

s = '{"a":{"0":1,"1":9},"b":{"0":2,"1":11}}'
df = pd.read_json(s, orient='columns')
df
a b
0 1 2
1 9 11

5.'values' : just the values array。

values這種咱們就很常見了。就是一個嵌套的列表。裏面的成員也是列表,2層的。

s = '[["a",1],["b",2]]'
df = pd.read_json(s, orient='values')
df
0 1
0 a 1
1 b 2

11、pandas讀取sql語句

import numpy as np
import pandas as pd
import pymysql


def conn(sql):
    # 鏈接到mysql數據庫
    conn = pymysql.connect(
        host="localhost",
        port=3306,
        user="root",
        passwd="123",
        db="db1",
    )
    try:
        data = pd.read_sql(sql, con=conn)
        return data
    except Exception as e:
        print("SQL is not correct!")
    finally:
        conn.close()


sql = "select * from test1 limit 0, 10"  # sql語句
data = conn(sql)
print(data.columns.tolist())  # 查看字段
print(data)  # 查看數據

點擊查看源網頁

matplotlib模塊

matplotlib官方文檔:https://matplotlib.org/contents.html?v=20190307135750

matplotlib是一個繪圖庫,它能夠建立經常使用的統計圖,包括條形圖、箱型圖、折線圖、散點圖、餅圖和直方圖。

1、條形圖

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
%matplotlib inline
font = FontProperties(fname='/Library/Fonts/Heiti.ttc')

# 修改背景爲條紋
plt.style.use('ggplot')

classes = ['3班', '4班', '5班', '6班']

classes_index = range(len(classes))
print(list(classes_index))
[0, 1, 2, 3]
student_amounts = [66, 55, 45, 70]

# 畫布設置
fig = plt.figure()
# 1,1,1表示一張畫布切割成1行1列共一張圖的第1個;2,2,1表示一張畫布切割成2行2列共4張圖的第一個(左上角)
ax1 = fig.add_subplot(1, 1, 1)
ax1.bar(classes_index, student_amounts, align='center', color='darkblue')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')

plt.xticks(classes_index,
           classes,
           rotation=0,
           fontsize=13,
           fontproperties=font)
plt.xlabel('班級', fontproperties=font, fontsize=15)
plt.ylabel('學生人數', fontproperties=font, fontsize=15)
plt.title('班級-學生人數', fontproperties=font, fontsize=20)
# 保存圖片,bbox_inches='tight'去掉圖形四周的空白
# plt.savefig('classes_students.png?x-oss-process=style/watermark', dpi=400, bbox_inches='tight')
plt.show()

img

2、直方圖

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
%matplotlib inline
font = FontProperties(fname='/Library/Fonts/Heiti.ttc')

# 修改背景爲條紋
plt.style.use('ggplot')

mu1, mu2, sigma = 50, 100, 10
# 構造均值爲50的符合正態分佈的數據
x1 = mu1 + sigma * np.random.randn(10000)
print(x1)
[59.00855949 43.16272141 48.77109774 ... 57.94645859 54.70312714
 58.94125528]
# 構造均值爲100的符合正態分佈的數據
x2 = mu2 + sigma * np.random.randn(10000)
print(x2)
[115.19915511  82.09208214 110.88092454 ...  95.0872103  104.21549068
 133.36025251]
fig = plt.figure()
ax1 = fig.add_subplot(121)
# bins=50表示每一個變量的值分紅50份,即會有50根柱子
ax1.hist(x1, bins=50, color='darkgreen')

ax2 = fig.add_subplot(122)
ax2.hist(x2, bins=50, color='orange')

fig.suptitle('兩個正態分佈', fontproperties=font, fontweight='bold', fontsize=15)
ax1.set_title('綠色的正態分佈', fontproperties=font)
ax2.set_title('橙色的正態分佈', fontproperties=font)
plt.show()

img

3、折線圖

import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
%matplotlib inline
font = FontProperties(fname='/Library/Fonts/Heiti.ttc')

# 修改背景爲條紋
plt.style.use('ggplot')

np.random.seed(1)

# 使用numpy的累加和,保證數據取值範圍不會在(0,1)內波動
plot_data1 = randn(40).cumsum()
print(plot_data1)
[ 1.62434536  1.01258895  0.4844172  -0.58855142  0.2768562  -2.02468249
 -0.27987073 -1.04107763 -0.72203853 -0.97140891  0.49069903 -1.56944168
 -1.89185888 -2.27591324 -1.1421438  -2.24203506 -2.41446327 -3.29232169
 -3.25010794 -2.66729273 -3.76791191 -2.6231882  -1.72159748 -1.21910314
 -0.31824719 -1.00197505 -1.12486527 -2.06063471 -2.32852279 -1.79816732
 -2.48982807 -2.8865816  -3.5737543  -4.41895994 -5.09020607 -5.10287067
 -6.22018102 -5.98576532 -4.32596314 -3.58391898]
plot_data2 = randn(40).cumsum()
plot_data3 = randn(40).cumsum()
plot_data4 = randn(40).cumsum()

plt.plot(plot_data1, marker='o', color='red', linestyle='-', label='紅實線')
plt.plot(plot_data2, marker='x', color='orange', linestyle='--', label='橙虛線')
plt.plot(plot_data3, marker='*', color='yellow', linestyle='-.', label='黃點線')
plt.plot(plot_data4, marker='s', color='green', linestyle=':', label='綠點圖')

# loc='best'給label自動選擇最好的位置
plt.legend(loc='best', prop=font)
plt.show()

img

4、散點圖+直線圖

import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
%matplotlib inline
font = FontProperties(fname='/Library/Fonts/Heiti.ttc')

# 修改背景爲條紋
plt.style.use('ggplot')

x = np.arange(1, 20, 1)
print(x)
[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
# 擬合一條水平散點線
np.random.seed(1)
y_linear = x + 10 * np.random.randn(19)
print(y_linear)
[ 17.24345364  -4.11756414  -2.28171752  -6.72968622  13.65407629
 -17.01538697  24.44811764   0.38793099  12.19039096   7.50629625
  25.62107937  -8.60140709   9.77582796  10.15945645  26.33769442
   5.00108733  15.27571792   9.22141582  19.42213747]
# 擬合一條x²的散點線
y_quad = x**2 + 10 * np.random.randn(19)
print(y_quad)
[  6.82815214  -7.00619177  20.4472371   25.01590721  30.02494339
  45.00855949  42.16272141  62.77109774  71.64230566  97.3211192
 126.30355467 137.08339248 165.03246473 189.128273   216.54794359
 249.28753869 288.87335401 312.82689651 363.34415698]
# s是散點大小
fig = plt.figure()
ax1 = fig.add_subplot(121)
plt.scatter(x, y_linear, s=30, color='r', label='藍點')
plt.scatter(x, y_quad, s=100, color='b', label='紅點')

ax2 = fig.add_subplot(122)
plt.plot(x, y_linear, color='r')
plt.plot(x, y_quad, color='b')

# 限制x軸和y軸的範圍取值
plt.xlim(min(x) - 1, max(x) + 1)
plt.ylim(min(y_quad) - 10, max(y_quad) + 10)
fig.suptitle('散點圖+直線圖', fontproperties=font, fontsize=20)
ax1.set_title('散點圖', fontproperties=font)
ax1.legend(prop=font)
ax2.set_title('直線圖', fontproperties=font)
plt.show()

img

5、餅圖

import numpy as np
import matplotlib.pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']

fig, ax = plt.subplots(subplot_kw=dict(aspect="equal"))

recipe = ['優', '良', '輕度污染', '中度污染', '重度污染', '嚴重污染', '缺']

data = [2, 49, 21, 9, 11, 6, 2]
colors = ['lime', 'yellow', 'darkorange', 'red', 'purple', 'maroon', 'grey']
wedges, texts, texts2 = ax.pie(data,
                               wedgeprops=dict(width=0.5),
                               startangle=40,
                               colors=colors,
                               autopct='%1.0f%%',
                               pctdistance=0.8)
plt.setp(texts2, size=14, weight="bold")

bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(xycoords='data',
          textcoords='data',
          arrowprops=dict(arrowstyle="->"),
          bbox=None,
          zorder=0,
          va="center")

for i, p in enumerate(wedges):
    ang = (p.theta2 - p.theta1) / 2. + p.theta1
    y = np.sin(np.deg2rad(ang))
    x = np.cos(np.deg2rad(ang))
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = "angle,angleA=0,angleB={}".format(ang)
    kw["arrowprops"].update({"connectionstyle": connectionstyle})
    ax.annotate(recipe[i],
                xy=(x, y),
                xytext=(1.25 * np.sign(x), 1.3 * y),
                size=16,
                horizontalalignment=horizontalalignment,
                fontproperties=font,
                **kw)

ax.set_title("餅圖示例",fontproperties=font)

plt.show()
# plt.savefig('jiaopie2.png?x-oss-process=style/watermark')

img

6、箱型圖

箱型圖:又稱爲盒須圖、盒式圖、盒狀圖或箱線圖,是一種用做顯示一組數據分散狀況資料的統計圖(在數據分析中經常使用在異常值檢測)

包含一組數據的:最大值、最小值、中位數、上四分位數(Q3)、下四分位數(Q1)、異常值

  1. 中位數 → 一組數據平均分紅兩份,中間的數
  2. 上四分位數Q1 → 是將序列平均分紅四份,計算(n+1)/4與(n-1)/4兩種,通常使用(n+1)/4
  3. 下四分位數Q3 → 是將序列平均分紅四份,計算(1+n)/4*3=6.75
  4. 內限 → T形的盒須就是內限,最大值區間Q3+1.5IQR,最小值區間Q1-1.5IQR (IQR=Q3-Q1)
  5. 外限 → T形的盒須就是內限,最大值區間Q3+3IQR,最小值區間Q1-3IQR (IQR=Q3-Q1)
  6. 異常值 → 內限以外 - 中度異常,外限以外 - 極度異常
import numpy as np
import pandas as pd
from numpy.random import randn
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
%matplotlib inline
font = FontProperties(fname='/Library/Fonts/Heiti.ttc')
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
plt.figure(figsize=(10, 4))
# 建立圖表、數據

f = df.boxplot(
    sym='o',  # 異常點形狀,參考marker
    vert=True,  # 是否垂直
    whis=1.5,  # IQR,默認1.5,也能夠設置區間好比[5,95],表明強制上下邊緣爲數據95%和5%位置
    patch_artist=True,  # 上下四分位框內是否填充,True爲填充
    meanline=False,
    showmeans=True,  # 是否有均值線及其形狀
    showbox=True,  # 是否顯示箱線
    showcaps=True,  # 是否顯示邊緣線
    showfliers=True,  # 是否顯示異常值
    notch=False,  # 中間箱體是否缺口
    return_type='dict'  # 返回類型爲字典
)
plt.title('boxplot')

for box in f['boxes']:
    box.set(color='b', linewidth=1)  # 箱體邊框顏色
    box.set(facecolor='b', alpha=0.5)  # 箱體內部填充顏色
for whisker in f['whiskers']:
    whisker.set(color='k', linewidth=0.5, linestyle='-')
for cap in f['caps']:
    cap.set(color='gray', linewidth=2)
for median in f['medians']:
    median.set(color='DarkBlue', linewidth=2)
for flier in f['fliers']:
    flier.set(marker='o', color='y', alpha=0.5)
# boxes, 箱線
# medians, 中位值的橫線,
# whiskers, 從box到error bar之間的豎線.
# fliers, 異常值
# caps, error bar橫線
# means, 均值的橫線

img

7、plot函數參數

  • 線型linestyle(-,-.,--,..)
  • 點型marker(v,^,s,*,H,+,x,D,o,…)
  • 顏色color(b,g,r,y,k,w,…)

8、圖像標註參數

  • 設置圖像標題:plt.title()
  • 設置x軸名稱:plt.xlabel()
  • 設置y軸名稱:plt.ylabel()
  • 設置X軸範圍:plt.xlim()
  • 設置Y軸範圍:plt.ylim()
  • 設置X軸刻度:plt.xticks()
  • 設置Y軸刻度:plt.yticks()
  • 設置曲線圖例:plt.legend()

9、Matplolib應用

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
%matplotlib inline

# 找到本身電腦的字體路徑,而後修改字體路徑
font = FontProperties(fname='/Library/Fonts/Heiti.ttc')

header_list = ['方程組', '函數', '導數', '微積分', '線性代數', '機率論', '統計學']
py3_df = pd.read_excel('py3.xlsx', header=None,
                       skiprows=[0, 1], names=header_list)
# 處理帶有NaN的行
py3_df = py3_df.dropna(axis=0)
print(py3_df)

# 自定義映射
map_dict = {
    '不會': 0,
    '瞭解': 1,
    '熟悉': 2,
    '使用過': 3,
}

for header in header_list:
    py3_df[header] = py3_df[header].map(map_dict)

unable_series = (py3_df == 0).sum(axis=0)
know_series = (py3_df == 1).sum(axis=0)
familiar_series = (py3_df == 2).sum(axis=0)
use_series = (py3_df == 3).sum(axis=0)

unable_label = '不會'
know_label = '瞭解'
familiar_label = '熟悉'
use_label = '使用過'
for i in range(len(header_list)):
    bottom = 0

    # 描繪不會的條形圖
    plt.bar(x=header_list[i], height=unable_series[i],
            width=0.60, color='r', label=unable_label)
    if unable_series[i] != 0:
        plt.text(header_list[i], bottom, s=unable_series[i],
                 ha='center', va='bottom', fontsize=15, color='white')
    bottom += unable_series[i]

    # 描繪瞭解的條形圖
    plt.bar(x=header_list[i], height=know_series[i],
            width=0.60, color='y', bottom=bottom, label=know_label)
    if know_series[i] != 0:
        plt.text(header_list[i], bottom, s=know_series[i],
                 ha='center', va='bottom', fontsize=15, color='white')
    bottom += know_series[i]

    # 描繪熟悉的條形圖
    plt.bar(x=header_list[i], height=familiar_series[i],
            width=0.60, color='g', bottom=bottom, label=familiar_label)
    if familiar_series[i] != 0:
        plt.text(header_list[i], bottom, s=familiar_series[i],
                 ha='center', va='bottom', fontsize=15, color='white')
    bottom += familiar_series[i]

    # 描繪使用過的條形圖
    plt.bar(x=header_list[i], height=use_series[i],
            width=0.60, color='b', bottom=bottom, label=use_label)
    if use_series[i] != 0:
        plt.text(header_list[i], bottom, s=use_series[i],
                 ha='center', va='bottom', fontsize=15, color='white')

    unable_label = know_label = familiar_label = use_label = ''

plt.xticks(header_list, fontproperties=font)
plt.ylabel('人數', fontproperties=font)
plt.title('Python3期數學摸底可視化', fontproperties=font)
plt.legend(prop=font, loc='upper left')
plt.show()
    方程組   函數   導數        微積分       線性代數  機率論  統計學
0   使用過  使用過   不會         不會         不會   不會   不會
1   使用過  使用過   瞭解         不會         不會   不會   不會
2   使用過  使用過   熟悉         不會         不會   不會   不會
3    熟悉   熟悉   熟悉         瞭解         瞭解   瞭解   瞭解
4   使用過  使用過  使用過        使用過        使用過  使用過  使用過
5   使用過  使用過  使用過         不會         不會   不會   瞭解
6    熟悉   熟悉   熟悉         熟悉         熟悉   熟悉   不會
7   使用過  使用過  使用過        使用過        使用過  使用過  使用過
8    熟悉   熟悉   熟悉         熟悉         熟悉  使用過  使用過
9    熟悉   熟悉  使用過         不會        使用過  使用過   不會
10  使用過  使用過   熟悉         熟悉         熟悉   熟悉   熟悉
11  使用過  使用過  使用過        使用過        使用過   不會   不會
12  使用過  使用過  使用過        使用過        使用過  使用過  使用過
13  使用過  使用過   瞭解         不會         不會   不會   不會
14  使用過  使用過  使用過        使用過        使用過   不會   不會
15  使用過  使用過   熟悉         不會         不會   不會   不會
16   熟悉   熟悉  使用過        使用過        使用過   不會   不會
17  使用過  使用過  使用過         瞭解         不會   不會   不會
18  使用過  使用過  使用過        使用過         熟悉   熟悉   熟悉
19  使用過  使用過  使用過         瞭解         不會   不會   不會
20  使用過  使用過  使用過        使用過        使用過  使用過  使用過
21  使用過  使用過  使用過        使用過        使用過  使用過  使用過
22  使用過  很瞭解   熟悉  瞭解一點,不會運用  瞭解一點,不會運用   瞭解   不會
23  使用過  使用過  使用過        使用過         熟悉  使用過   熟悉
24   熟悉   熟悉   熟悉        使用過         不會   不會   不會
25  使用過  使用過  使用過        使用過        使用過  使用過  使用過
26  使用過  使用過  使用過        使用過        使用過   不會   不會
27  使用過  使用過   不會         不會         不會   不會   不會
28  使用過  使用過  使用過        使用過        使用過  使用過   瞭解
29  使用過  使用過  使用過        使用過        使用過   瞭解   不會
30  使用過  使用過  使用過        使用過        使用過   不會   不會
31  使用過  使用過  使用過        使用過         不會  使用過  使用過
32   熟悉   熟悉  使用過        使用過        使用過   不會   不會
33  使用過  使用過  使用過        使用過         熟悉  使用過   熟悉
34   熟悉   熟悉   熟悉        使用過        使用過   熟悉   不會
35  使用過  使用過  使用過        使用過        使用過  使用過  使用過
36  使用過  使用過  使用過        使用過        使用過  使用過   瞭解
37  使用過  使用過  使用過        使用過        使用過   不會   不會
38  使用過  使用過  使用過         不會         不會   不會   不會
39  使用過  使用過   不會         不會         不會   不會   不會
40  使用過  使用過  使用過        使用過        使用過   不會   不會
41  使用過  使用過   熟悉         瞭解         瞭解   瞭解   不會
42  使用過  使用過  使用過         不會         不會   不會   不會
43   熟悉  使用過   瞭解         瞭解         不會   不會   不會

img

點擊查看源網頁

...

點擊查看源網頁

...

點擊查看源網頁

hhhhhhhhhge...

相關文章
相關標籤/搜索