Python數據分析與挖掘實戰-第1-3章

非原創,僅個人關於《Python數據分析與挖掘實戰》的學習筆記

第一章 基礎

第二章 數據分析簡介

基本概念

元組、列表、字典、集合

函數式編程:

  • map()函數:定義一個函數,然後用map()逐一應用到map列表中的每個元素。map(lambda x+2:a)
  • reduce()函數:用於遞歸計算。reduce(lambda x,y:x*y,range(1,n+1))

數據分析常用庫

  • numpy 數組,高效處理函數
  • scipy 矩陣相關計算
  • matplotlib 可視化
  • pandas 數據分析
  • statsmodels 統計建模
  • scikit-learn 迴歸、分類、聚類等機器學習
  • keras 深度學習,建立神經網絡及深度學習模型
  • gensim 文本主題模型,文本挖掘

第三章 數據探索

3.1 數據質量分析

  • 缺失值分析
  • 異常值
import pandas as pd
from scipy import stats

# 讀取CSV文件
data = pd.read_csv(f'E:\中經社\中資美元債\PVR\CEIS_Corps_Pricing_Liquidity_20240409.csv')

# 假設我們對數值型數據進行異常值檢測,這裏以'amountOutstanding'列爲例
# 首先,確保數據是數值型的
data['amountOutstanding'] = pd.to_numeric(data['amountOutstanding'], errors='coerce')

# 計算Z-score
z_scores = stats.zscore(data['amountOutstanding'])

# 找出Z-score的絕對值大於1的點作爲異常值
threshold = 1
abs_z_scores = abs(z_scores)
anomaly_indices = abs_z_scores > threshold

# 標記異常值
data['anomaly'] = False
data.loc[anomaly_indices, 'anomaly'] = True

# 顯示含有異常值的行
data[data['anomaly']]

alt text
箱型圖異常值檢測

import pandas as pd
import matplotlib.pyplot as plt
# 解決中文亂碼
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 請確保您的文件路徑是正確的
file_path = r'E:\中經社\中資美元債\PVR\CEIS_Corps_Pricing_Liquidity_20240409.csv'

# 讀取CSV文件
data = pd.read_csv(file_path)

# 選擇'bidPrice'列數據進行箱型圖繪製,並確保數據是數值型的
data['bidPrice'] = pd.to_numeric(data['bidPrice'], errors='coerce')

# 計算箱線圖的統計數據,quantile()樣本分位數 (不同 % 的值)
Q1 = data['bidPrice'].quantile(0.25)
Q3 = data['bidPrice'].quantile(0.75)
IQR = Q3 - Q1

# 計算異常值的閾值
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR

# 過濾出數據中的異常值
outliers = data[(data['bidPrice'] < lower_bound) | (data['bidPrice'] > upper_bound)]

# 繪製箱線圖
plt.figure(figsize=(10, 6))  # 設置圖表的大小

# 繪製箱型圖,這裏notch=True表示帶有凹槽的箱型圖,vert=True表示垂直箱型圖
box = plt.boxplot(data['bidPrice'], notch=True, vert=True)

# 添加異常值標記
plt.plot([1]*len(outliers), outliers['bidPrice'], 'ro', markersize=5) 

# 設置標題和軸標籤
plt.title('異常值檢測箱型圖分析')
plt.xlabel('Bid Price')

# 由於只有一個箱體,我們將X軸的刻度和標籤設置爲一個點,以避免混淆
plt.xticks([1])

# 顯示圖表
plt.show()

alt text

  • 不一致的值
  • 重複數據及含有特殊符號的數據

3.2 數據特徵分析

3.2.1 分佈分析

3.2.1.1 定量

從df中提取銷售額數據

方法1:

sales = df['銷售額(元)']

# 繪製直方圖
plt.hist(sales, bins=10, edgecolor='black')

# 添加標題和標籤
plt.title('頻率分佈直方圖')
plt.xlabel('銷售額(元)')
plt.ylabel('頻次')

# 顯示圖形
plt.show()

alt text
方法2:

import matplotlib.pyplot as plt
import numpy as np
# 從df中提取銷售額數據
sales = df['銷售額(元)']

# 計算頻率分佈
values, base = np.histogram(sales, bins=10, density=True)

# 計算直方圖的寬度,即每個bin的寬度
width = (df['銷售額(元)'].max() - df['銷售額(元)'].min()) / 10

# 計算直方圖的中心點
center = (base[1:] + base[:-1]) * 0.5

# 繪製直方圖
plt.bar(center, values, width=width, label='頻率分佈', edgecolor='black')

# 添加標題和標籤
plt.title('頻率分佈直方圖')
plt.xlabel('銷售額(元)')
plt.ylabel('頻率')

# 顯示圖例
plt.legend()

# 顯示圖形
plt.show()

alt text

3.2.1.2 定性

常常採用餅圖和條形圖來描述。

3.2.2 對比分析

  • 絕對比較
  • 相對比較

3.2.3 統計量分析

3.2.3.1 集中趨勢度量
  • 均值
  • 中位數
  • 衆數
3.2.3.1 離中趨勢度量
  • 極差
statistics = sales.describe()

alt text

\[極差=max-min \]

statistics.loc['range'] = statistics.loc['max']-statistics.loc['min']
  • 標準差

\[s=\sqrt \frac{\sum(x_i-\overline x)^2}{n} \]

  • 變異係數
    變異係數度量標準差相對於均值的離中趨勢,計算公式爲:

\[CV=\frac{s}{\overline x}\times 100\% \]

statistics.loc['var'] = statistics.loc['std']-statistics.loc['mean']
  • 四分位數區距
statistics.loc['dis'] = statistics.loc['75%']-statistics.loc['25%']

3.2.4 週期性分析

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章