一、 python數據分析基礎庫的導入
基本是固定搭配
import numpy as np #科學計算基礎庫,多維數組對象ndarray
import pandas as pd #數據處理庫,DataFrame(二維數組)
import matplotlib as mpl #畫圖基礎庫
import matplotlib.pyplot as plt #最常用的繪圖庫
mpl.rcParams["font.family"]="SimHei" #使用支持的黑體中文字體
mpl.rcParams["axes.unicode_minus"]=False # 用來正常顯示負號 "-"
plt.rcParams['font.sans-serif']=['SimHei'] # 用來正常顯示中文標籤
# % matplotlib inline #jupyter中用於直接嵌入圖表,不用plt.show()
import warnings
warnings.filterwarnings("ignore") #用於排除警告
#用於顯示使用庫的版本
print("numpy_" + np.__version__)
print("pandas_" + pd.__version__)
print("matplotlib_"+ mpl.__version__)
numpy_1.17.4
pandas_0.23.4
matplotlib_2.2.3
二、基礎回顧
基本使用簡單描述統計1
統計:
sum, mean, std, var,
min, max, argmin, argmax
cumsum, cumprod
排序相關
sort(axis)、
unique( )
隨機數生成
from numpy.random import **
numpy.random
簡單的隨機數據
rand(d0, d1, …, dn),
randn(d0, d1, …, dn)
sigma * np.random.randn(…) + mu
randint(low[, high, size])
random_integers(low[, high, size])
choice(a[, size, replace, p])
排列
shuffle(x) #洗牌
permutation(x) #轉置
changes=pd.DataFrame(np.random.normal(loc=0.001,scale=np.sqrt(0.005),size=(100,100)))
#np.random.normal(loc=期望值,scale=標準差,size=(行個數,列個數)),
#生成期望爲0.001,方差爲0.005(標準差sqrt(0.005))的服從正態分佈的100 rows × 100 columns個數,然後放入二維表中
#print(changes.head()) #獲取前5行
display(changes.loc[:3,:3]) #切片獲取前4行,前4列
#changes.plot() 簡單的化一個折線圖
returns = changes.cumsum(axis=0) #cumsum(0)表示按照行進行累加
display(returns.loc[97:100,:3])
#returns.plot()簡單的化一個折線圖
print(returns.loc[99,].mean())#計算最後一行的均值
print(returns.loc[99,].std()) #計算最後一行的標準差
print(returns.loc[99,].var()) #計算最後一行的方差
0 | 1 | 2 | 3 | |
---|---|---|---|---|
0 | -0.073265 | 0.027694 | -0.005274 | 0.018362 |
1 | -0.162326 | -0.027650 | 0.013609 | -0.002829 |
2 | 0.027491 | 0.108222 | -0.079539 | -0.007628 |
3 | -0.063755 | -0.032045 | 0.076477 | 0.084774 |
0 | 1 | 2 | 3 | |
---|---|---|---|---|
97 | -0.621215 | -0.131843 | -0.440428 | -1.508183 |
98 | -0.508074 | -0.243702 | -0.522049 | -1.435103 |
99 | -0.447405 | -0.366133 | -0.471084 | -1.376747 |
-0.0037164612652884122
0.6395170858647697
0.40898210311296734
基本使用分佈函數2
三、數據分析流程
任務描述:
–理解數據類型和數據結構
–載入數據
–清洗數據
–做簡單的統計分析
–使用基礎的可視化
數據分析的步驟:
–獲取數據
–數據預處理
–數據分析
–數據挖掘
–可視化展現
數據預處理(數據分析和挖掘的瓶頸):
–獲取數據
–載入數據
–清洗數據:異常
–清洗數據:維度
–清洗數據:粒度
–缺失值;無效值;格式轉換;命名變換;類型轉換
數據預處理案例
1、 理解和獲取數據
# 理解和獲取數據
# 頭部導入庫在最前面一中:此處略
df = pd.read_csv(r"E:\tips.csv",encoding='utf-8') #導入csv格式數據
display(df.sample(5)) #隨機抽樣5行
#某餐廳顧客消費記錄
#解釋數據結構:total_bill 消費, tip 小費,sex 服務員性別,smoker 是否抽菸,day 星期幾,time 午餐/晚餐,size 本桌人數
total_bill | tip | sex | smoker | day | time | size | |
---|---|---|---|---|---|---|---|
235 | 10.07 | 1.25 | Male | No | Sat | Dinner | 2 |
110 | 14.00 | 3.00 | Male | No | Sat | Dinner | 2 |
48 | 28.55 | 2.05 | Male | No | Sun | Dinner | 3 |
133 | 12.26 | 2.00 | Female | No | Thur | Lunch | 2 |
131 | 20.27 | 2.83 | Female | No | Thur | Lunch | 2 |
2、數據清洗及簡單統計
清洗數據:https://blog.csdn.net/weixin_41685388/article/details/103841296
# 對數據做基本統計,檢查異常,看看數據質量
print("行列數:",df.shape) #查看總的有n行,m列
print("info統計:",df.info()) #查看數據是否有缺失值,這裏無
display("查看重複值:",df[df.duplicated(subset=["total_bill","tip"],keep=False)])#這組數據查看重複值沒什麼意義,true無重複
#df1 = df.drop_duplicates(subset=["total_bill","tip"],keep='first',inplace=False) #當然這裏沒必要刪除
display("數值列統計:",df.describe()) # 數值列 和 非數值列 的統計結果不一樣!默認統計數值列
display("非數值列統計:",df[["sex","smoker","day","time"]].describe()) #統計非數值列
行列數: (244, 7)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 244 entries, 0 to 243
Data columns (total 7 columns):
total_bill 244 non-null float64
tip 244 non-null float64
sex 244 non-null object
smoker 244 non-null object
day 244 non-null object
time 244 non-null object
size 244 non-null int64
dtypes: float64(2), int64(1), object(4)
memory usage: 13.4+ KB
info統計: None
'查看重複值:'
total_bill | tip | sex | smoker | day | time | size | |
---|---|---|---|---|---|---|---|
61 | 13.81 | 2.0 | Male | Yes | Sat | Dinner | 2 |
163 | 13.81 | 2.0 | Male | No | Sun | Dinner | 2 |
198 | 13.00 | 2.0 | Female | Yes | Thur | Lunch | 2 |
202 | 13.00 | 2.0 | Female | Yes | Thur | Lunch | 2 |
'數值列統計:'
total_bill | tip | size | |
---|---|---|---|
count | 244.000000 | 244.000000 | 244.000000 |
mean | 19.785943 | 2.998279 | 2.569672 |
std | 8.902412 | 1.383638 | 0.951100 |
min | 3.070000 | 1.000000 | 1.000000 |
25% | 13.347500 | 2.000000 | 2.000000 |
50% | 17.795000 | 2.900000 | 2.000000 |
75% | 24.127500 | 3.562500 | 3.000000 |
max | 50.810000 | 10.000000 | 6.000000 |
'非數值列統計:'
sex | smoker | day | time | |
---|---|---|---|---|
count | 244 | 244 | 244 | 244 |
unique | 2 | 2 | 4 | 2 |
top | Male | No | Sat | Dinner |
freq | 157 | 151 | 87 | 176 |
3、位置度量
-
-算數平均:mean
-
-中位數:median
-
-截尾均值:去除部分小/大的離散值之後再算均值
-
-M估計:估計的初衷是爲了解決最小二乘法的不穩健問題,但從它的發展來看永遠超越了它最初的目的,實際上它是包括了穩健估計、最小二乘估計在內的一個廣義的估計類。
-
-位置估計的比較:
-
-自助法估計位置度量的變異性:
#均值和中位數比較
pd.DataFrame({"mean":df.mean(),"median":df.median()})
mean | median | |
---|---|---|
total_bill | 19.785943 | 17.795 |
tip | 2.998279 | 2.900 |
size | 2.569672 | 2.000 |
4、畫圖檢驗
簡單畫一下箱型圖,看看離羣點的分佈,可以根據實際業務對離羣點進行處理(這裏就不做處理了)
matplotlib畫圖庫:https://blog.csdn.net/weixin_41685388/article/details/103947701
import numpy as np
import matplotlib.pyplot as plt
figure = plt.figure(num="箱型圖",figsize=(12,4),dpi=80,facecolor="LightGray",edgecolor="blue",frameon=True)
total_bill = df["total_bill"]
tip = df["tip"]
axes1= plt.subplot(1,2,1)
plt.title("total_bill箱型圖")
plt.xlabel("total_bill")
plt.ylabel("value")
axes1.boxplot(total_bill,sym="o",whis=1.5)
axes2= plt.subplot(1,2,2)
plt.title("tip箱型圖")
plt.xlabel("tip")
plt.ylabel("value")
axes2.boxplot(tip,sym="o",whis=1.5)
plt.show()
畫圖看一下total_bill和tip關係圖,根據直方圖,發現似乎有兩個離羣點,但這裏樣本量不大的情況,暫時就不做處理啦。
import numpy as np
import matplotlib.pyplot as plt
figure = plt.figure(num="total_bill和tip",figsize=(12,4),dpi=80,facecolor="LightGray",edgecolor="blue",frameon=True)
x = df["tip"]
y = df["total_bill"]
axes1= plt.subplot(1,2,1)
plt.title("total_bill和tip關係圖")
plt.xlabel("tip")
plt.ylabel("total_bill")
plt.grid(True, color="g", axis="both", ls="--", lw=0.5) #設置網格線
axes1.plot(x, y, 'bo')
x=df['tip']/df['total_bill']
num_bins = 25 #直方圖柱子數量
axes2= plt.subplot(1,2,2)
plt.title("tip/total_bill直方圖")
plt.xlabel("tip/total_bill")
plt.ylabel("數量")
plt.grid(True, color="g", axis="both", ls="--", lw=0.5) #設置網格線
n, bins, patches = axes2.hist(x, num_bins)
plt.show()
畫圖看一下total_bill和size是否存在某種函數關係
import numpy as np
import matplotlib.pyplot as plt
x = df["size"]
y = df["total_bill"]
#按照size分組聚合total_bill 獲取均值
g_a = df[["size","total_bill"]].groupby("size").agg(["count","sum","mean"])
x2 = g_a.index
y2 =g_a["total_bill"]["mean"]
fig, ax = plt.subplots()
plt.title("total_bill和size關係圖")
plt.xlabel("size")
plt.ylabel("values")
ax.plot(x, y, 'ro',x2, y2, 'b--')
plt.legend(["total_bill","mean(total_bill)"],loc="best", frameon=False, ncol=2)
plt.show()