數據分析專欄記錄之 -基礎數學與統計知識:
1、描述性統計
'''均值'''
data_set = [10, 20, 30, 40, 50]
mean = sum(data_set)/len(data_set)'''np 里面的函數,對二維進行操作時, 默認每一列 '''
mean1 = np.mean(data_set)
print(mean, mean1)s = 0
for i in data_set:s = s + i
print(s/len(data_set))
30.0 30.0
30.0
""" 平均數 、 加權平均數 的實現"""
import numpy as np
average = np.average(data_set)
print(average)weight_average = np.average(data_set, weights=[1, 2, 1, 2, 1])
print(weight_average)
30.0
30.0
"""標準差 / 均方差 / 歐氏距離"""
import numpy as np
std = np.std(data_set)
print(std)"""方差"""var = np.var(data_set)
print(var)def avg(var_Calculation):s = 0for i in var_Calculation:s = s+ireturn (s/len(var_Calculation))
av = avg(data_set)
sum_var = 0
for i in data_set:sum_var += ((i-av)**2)
print(sum_var/len(data_set))
14.142135623730951
200.0
200.0
"""中位數"""
print(np.median(data_set))speed = [99,86,87,88,111,86,103,87,94,78,77,85,86]
i = 0
while i<=len(speed)-2:j = i+1while j <= len(speed)-1:if speed[i] < speed[j]:t = speed[i]speed[i] = speed[j]speed[j] = tj = j+1i = i+1if len(speed)%2 ==1:print(speed[int(len(speed)/2)])
else:print((speed[int(len(speed)/2)] + speed[int(len(speed)/2)-1])/2)
30.0
87
"""眾數"""
from scipy import stats
speed = [99,86,87,88,111,86,103,87,94,78,77,85,86]
x = stats.mode(speed)
print(x)zd = {}
for i in speed:zd[i]=0
print(zd)for j in speed:if j in zd.keys():zd[j] += 1
print(zd)maxkey = 0
maxvalue = 0
for key in zd.keys():if zd[key]>maxvalue:maxkey = keymaxvalue = zd[key]
print(maxkey, maxvalue)
ModeResult(mode=np.int64(86), count=np.int64(3))
{99: 0, 86: 0, 87: 0, 88: 0, 111: 0, 103: 0, 94: 0, 78: 0, 77: 0, 85: 0}
{99: 1, 86: 3, 87: 2, 88: 1, 111: 1, 103: 1, 94: 1, 78: 1, 77: 1, 85: 1}
86 3
"""
百分位數
例如:假設我們有一個數組,包含住在一條街上的人的年齡。
ages = [5,31,43,48,50,41,7,11,15,39,80,82,32,2,8,6,25,36,27,61,31]
什么是 75 百分位數?答案是 43,這意味著 75% 的人是 43 歲或以下。
"""
ages = [5,31,43,48,50,41,7,11,15,39,80,82,32,2,8,6,25,36,27,61,31]
x = np.percentile(ages, 80)
print(x)def per(sz, pe):sz.sort()slen = len(sz)return sz[int((pe * slen)/100)]
print(per(ages, 80))
48.0
48
"""
定義:偏度(skewness),是統計數據分布偏斜方向和程度的度量,或者說是統計數據分布非對稱程度的數字特征。說人話:偏度或偏態系數或偏度系數(Skewness)用來度量分布是否對稱,一個分布如果不對稱,則被稱為偏度。分布分為三種:對稱分布(正態分布)、正偏分布(右偏分布)、負偏分布(左偏分布)
對稱分布的特點:左右對稱,均值 = 中位數 = 眾數,偏度 = 0
正偏分布的特點:右側長尾,均值 >中位數 >眾數,偏度 > 0
負偏分布的特點:左側長尾,均值 < 中位數 < 眾數,偏度 < 0step
繪制圖像展示
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
fig, axs = plt.subplots(1, 3, figsize=(10, 4))def plot():""" 標準正態 :draw standard deviation normal distribution"""mu = 0.0 #均值sd = 1.0 #標準差x = np.linspace(mu-4*sd, mu+4*sd, 100)y = stats.norm.pdf(x)""" 正偏分布 """x1 = np.linspace(mu-3*sd, mu+5*sd, 100)y1 = stats.norm.pdf(x1)""" 負偏分布 """x2 = np.linspace(mu-5*sd, mu+3*sd, 100)y2 = stats.norm.pdf(x2)axs[0].plot(x, y, "g", linewidth=2, color='black')axs[1].plot(x1, y1, "g1", linewidth=2, color='orange')axs[2].plot(x2, y2, "g2", linewidth=2, color='green')plt.grid(True)plt.show()if __name__ == '__main__':plot()
"""
偏度:
根據數據, 計算均值、中位數、眾數 得出偏度
"""
import pandas as pd
from scipy import stats
import numpy as np
speed_ = [1,4,6,8,10,20]# 計算公式1
mean = np.mean(speed_)
std = np.std(speed_, ddof=1)
n = len(speed_)
a1 = sum(((speed_-mean)/std)**3)
a2 = a1*(n)/((n-1)*(n-2))
print("偏度:",a2)# 計算公式2
mean = np.mean(speed_)
std = np.std(speed_, ddof=1)
n = len(speed_)
a1 = sum(((speed_-mean)/std)**3)
a2 = a1/(n)
print(a2)'''
可以看到使用不同公式計算得到的偏度不同:
公式1得到的偏度:1.2737636108819756
公式2得到的偏度:0.7076464504899865
'''# 調用函數計算
d = stats.skew(speed_, bias=False)
print("偏度:", d)
偏度: 1.2737636108819756
0.7076464504899865
偏度: 1.2737636108819756
計算公式1:
S=n(n?1)(n?2)∑i=1n[(Xi?μσ)3]S=\frac{n}{(n-1)(n-2)} \sum_{i=1}^{n}\left[\left(\frac{X_{i}-\mu}{\sigma}\right)^{3}\right]S=(n?1)(n?2)n?∑i=1n?[(σXi??μ?)3]
計算公式2:
S=1n∑i=1n[(Xi?μσ)3]S=\frac{1}{n} \sum_{i=1}^{n}\left[\left(\frac{X_{i}-\mu}{\sigma}\right)^{3}\right]S=n1?∑i=1n?[(σXi??μ?)3]
"""
峰度
定義:峰度(peakedness;kurtosis)又稱峰態系數。表征概率密度分布曲線在平均值處峰值高低的特征數。
說人話:峰度反映了峰部的尖度,用來度量數據在中心聚集程度,峰度越大分布圖越尖,峰度越小分布圖越矮胖。
"""import numpy as np
import matplotlib.pyplot as plt
from scipy import statsdef plot():"""draw standard deviation normal distribution"""mu = 0.0 # meansd1 = 1.0 # stdsd2 = 2.0sd3 = 3.0# 特征:x參數一致,但是擴散開的程度不一樣。y不一致,向上的程度不一樣# red linex = np.linspace(mu-3*sd1, mu+3*sd1, 50)y = stats.norm.pdf(x)plt.plot(x, y , "r", linewidth=2)# green linex2 = np.linspace(mu-6*sd1, mu+6*sd1, 50)y2 = stats.norm.pdf(x2, mu, sd2)plt.plot(x2, y2, "g", linewidth=2)# blue linex3 = np.linspace(mu-10*sd1, mu+10*sd1, 50)y3 = stats.norm.pdf(x3, mu, sd3)plt.plot(x3, y3, "b", linewidth=2)plt.grid(True) # 顯示網格線plt.show()if __name__ == '__main__':plot()
"""
對于正態分布來說峰度=3,部分統計軟件會給出超額峰度,超額峰度=峰度-3。
中鋒分布的超額峰度=0, 尖峰分布的超額峰度>0,低峰分布的超額峰度<0。
"""import numpy as np
import pandas as pd
from scipy import statsarr = np.array([1,4,6,8,10,20])
#標準差
std = stats.tstd(arr, ddof=1)
# 偏度
skew_ = stats.skew(arr, bias=False)
# 峰度
e = stats.kurtosis(arr, bias=False)
print(e)""" 面對pd數據 """
data = pd.DataFrame(arr)
print(data.kurt())
2.154642470375478
0 2.154642
dtype: float64
"""一維數據 曲線圖"""
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np# 讀取csv文件
reviews = pd.read_csv("/content/drive/MyDrive/數據分析/HC.csv")# 第一列、第二列的數據
# print(reviews['0'], reviews['0.1'])
# 繪制曲線圖
plt.plot(reviews['0'], reviews['0.1'])
plt.xlabel('Time')
plt.ylabel("Position")
plt.title("Position vs Time")
plt.tight_layout()
plt.show()# 根據速度 求 加速度, 繪制加速度曲線,【 time a 】
t = reviews['0']
s = reviews['0.1']
# 計算速度 (前向差分法)
velocity = np.diff(s)/ np.diff(t) # v = Δp / Δt
# 為了方便繪圖,給速度數組添加一個最后值,與時間點對齊
velocity = np.append(velocity, velocity[-1])
# 繪制位置和速度的圖像
plt.plot(reviews['0'], velocity*100)
plt.xlabel('Time')
plt.ylabel("Velocity")
plt.title("Velocity vs Time")
plt.tight_layout()
plt.show()# 根據速度 求 加速度, 繪制加速度曲線,【 time a 】
t = reviews['0']
# 計算速度 (前向差分法)
Acceleration = np.diff(velocity)/ np.diff(t) # v = Δp / Δt
# 為了方便繪圖,給速度數組添加一個最后值,與時間點對齊
Acceleration = np.append(Acceleration, Acceleration[-1])
# 繪制位置和速度的圖像
plt.plot(reviews['0'], Acceleration)
plt.xlabel('Time')
plt.ylabel("a")
plt.title("a vs Time")
plt.tight_layout()
plt.show()
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np# 讀取 CSV 文件
reviews = pd.read_csv("/content/drive/MyDrive/數據分析/HC.csv")# 時間 (t) 和位置 (s)
t = reviews['0'].to_numpy()
s = reviews['0.1'].to_numpy()# === 使用中心差分法計算速度和加速度 ===
velocity = np.gradient(s, t) # 速度 v = ds/dt
acceleration = np.gradient(velocity, t) # 加速度 a = dv/dt# === 繪制三個曲線 ===
plt.figure(figsize=(10, 8))# 路程-時間
plt.subplot(3, 1, 1)
plt.plot(t, s, 'b', linewidth=2)
plt.ylabel('Position')
plt.title('Position, Velocity, and Acceleration vs Time')# 速度-時間
plt.subplot(3, 1, 2)
plt.plot(t, velocity, 'g', linewidth=2)
plt.ylabel('Velocity')# 加速度-時間
plt.subplot(3, 1, 3)
plt.plot(t, acceleration, 'r', linewidth=2)
plt.xlabel('Time')
plt.ylabel('Acceleration')plt.tight_layout()
plt.show()# === 計算指定時間點的速度(例如 t=2.5s)===
target_time = 2.5
velocity_at_target = np.interp(target_time, t, velocity)
print(f"t = {target_time}s 時的速度: {velocity_at_target:.4f}")
致謝
靠咖啡續命的牛馬,👍點贊 📁 關注 💬評論 💰打賞。
參考
[1] deepseek等ai
往期回顧
- 無,新手上車