一、 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()