数据分析应用实战(一)

Part 1.前言介绍

  • 数据集地址:http://jse.amstat.org/datasets/normtemp.dat.txt
  • 数据问题描述与简介:http://jse.amstat.org/v4n2/datasets.shoemaker.html
  • 解决目标问题:
    1. Is the true population mean really 98.6 degrees F?
    2. Is the distribution of temperatures normal?
    3. At what temperature should we consider someone's temperature to be "abnormal"?
    4. Is there a significant difference between males and females in normal temperature?
    5. Is there a relationship between body temperature and heart rate?

Part 2.问题解决

  • Q1: 人体体温的总体均值是否为98.6华氏度
  • A1:通过数据本身的.mean()方法可以得到测试数据集的均值并进行比较
tep_mean = named_df["Temperature"].mean()
tep_round = round(tep_mean, 1) 
  • Q2: 判断人体温度是否符合正太分布
  • A2:本文采用shapiro_wiki进行判断,由返回的p_value进行判断,若p_value>0.05,则可认为该数据集近似于正态分布
shapiro_stats, shapiro_p_value = stats.shapiro(named_df["Temperature"]) 
  • Q3:找出体温的异常数据
  • A3:本文采用箱型图的四分位距进行判断,落在设定的上下限以外的即认定为异常数据
percentile = np.percentile(named_df["Temperature"], [0, 25, 50, 75, 100])                               # 利用箱型图的四分位距来对数据进行异常的判断
IQR = percentile[3] - percentile[1]
up_limit = percentile[3] + IQR * 1.5                                                                    # 上限设定为上四分位+1.5倍IQR(四分位距)距离
down_limit = percentile[1] - IQR * 1.5 
  • Q4:男女提问正常数据下是否存在明显差异
  • A4:这里通过T检验(先检验方差齐性),在已经提出异常数据的前提下进行检验判断,返回的p_value小于阈值0.05(95%置信度)则可认定为存在明显差异
sorted_df = named_df[(named_df["Temperature"] <= up_limit) & (named_df["Temperature"] >= down_limit)]   # 剔除上回所显示的异常数据
males = sorted_df[sorted_df["Gender"] == 1]                                                             # 将原数据进行男女判断分类
females = sorted_df[sorted_df["Gender"] == 2]
bool_sta,bool_p_value = stats.levene(males["Temperature"],females["Temperature"])
equal_v = bool_p_value>0.05
t_stats,t_p_value = stats.ttest_ind(males["Temperature"],females["Temperature"],equal_var=equal_v)      # 利用T检验进行两组方差是否相同仍未知的独立数据的比较,equal_v=True则可认为其方差相等
  • Q5:体温与心率间的相关性
  • A5:由上述可知数据符合正态分布,所以可以采用皮尔森相关系数进行判断两者之间的相关性
pearson = sorted_df.corr()
temp_and_rate = pearson["Temperature"]["HeartRate"]                                                     # 取人体温度与心率的系数结果
if temp_and_rate > 0.8 & temp_and_rate <= 1.0:                                                          # python中不存在switch-case语句
    print("人体的温度与心率具有相关性:极强")
elif temp_and_rate > 0.6 & temp_and_rate <= 0.8:
    print("人体的温度与心率具有相关性:强")
elif temp_and_rate > 0.4 & temp_and_rate <= 0.6:
    print("人体的温度与心率具有相关性:中等")
elif temp_and_rate > 0.2 & temp_and_rate <= 0.4:
    print("人体的温度与心率具有相关性:弱")
elif temp_and_rate >= 0 & temp_and_rate <= 0.2:
    print("人体的温度与心率具有相关性:极弱")

Part 3.完整代码

import pandas as pd
import requests as req
from scipy import stats
import numpy as np

r = req.get('http://jse.amstat.org/datasets/normtemp.dat.txt')                                          # 利用request爬取指定路径下的数据
content = r.text                                                                                        # 获取爬取数据的内容

cell_list = []                                                                                          # 建立新列表用于存储处理规整后的数据的元素

cells = content.split('\n')                                                                             # 进行相关的数据清洗与切割处理
for x in cells:
    if (x):
        cell_list.append(list(map(lambda y: float(y), x.split())))                                      # 进行一步str转float确保数值可参与后续计算

df = pd.DataFrame(cell_list)                                                                            # 将list数据列表转换为DataFrame
named_df = df.rename(columns={0: 'Temperature', 1: 'Gender', 2: 'HeartRate'})                           # 更正列索引名

# Q1:Is the true population mean really 98.6 degrees F?
tep_mean = named_df["Temperature"].mean()
tep_round = round(tep_mean, 1)                                                                          # 取一位小数位
if tep_round == 98.6:
    print("真正的总体均值确实是98.6华氏度")
else:
    print("真正的总体均值不是98.6华氏度,真实的总体均温为" + str(tep_round))

# Q2:Is the distribution of temperatures normal?
shapiro_stats, shapiro_p_value = stats.shapiro(named_df["Temperature"])                                 # shapiro_stats:统计数 shapiro_p_value:测试指标
if shapiro_p_value > 0.05:                                                                              # 依据shapiro_wiki测试判断是否近似于正态分布
    print("依据shapiro_wiki,该分布近似于正态分布")
else:
    print("依据shapiro_wiki,该分布无法近似于正态分布")

# Q3:At what temperature should we consider someone's temperature to be "abnormal"?
percentile = np.percentile(named_df["Temperature"], [0, 25, 50, 75, 100])                               # 利用箱型图的四分位距来对数据进行异常的判断
IQR = percentile[3] - percentile[1]
up_limit = percentile[3] + IQR * 1.5                                                                    # 上限设定为上四分位+1.5倍IQR(四分位距)距离
down_limit = percentile[1] - IQR * 1.5                                                                  # 下限设定为下四分位+1.5倍IQR(四分位距)距离
abnormal = named_df[(named_df["Temperature"] > up_limit) | (named_df["Temperature"] < down_limit)]
print("依据箱型图测试异常数据为\n", abnormal)

# Q4:Is there a significant difference between males and females in normal temperature?
sorted_df = named_df[(named_df["Temperature"] <= up_limit) & (named_df["Temperature"] >= down_limit)]   # 剔除上回所显示的异常数据
males = sorted_df[sorted_df["Gender"] == 1]                                                             # 将原数据进行男女判断分类
females = sorted_df[sorted_df["Gender"] == 2]
bool_sta,bool_p_value = stats.levene(males["Temperature"],females["Temperature"])
equal_v = bool_p_value>0.05
t_stats,t_p_value = stats.ttest_ind(males["Temperature"],females["Temperature"],equal_var=equal_v)      # 利用T检验进行两组方差是否相同仍未知的独立数据的比较,equal_v=True则可认为其方差相等
if t_p_value <= 0.05:                                                                                      # 远小于0.05则可认定为两组数据间存在明显差异
    print("异性之间在正常温度下存在明显差异")
else:
    print("异性之间在正常温度下并无明显差异")

# Q5:Is there a relationship between body temperature and heart rate?
pearson = sorted_df.corr()                                                                                          # 获取各个数据之间的相关性表
temp_and_rate = pearson["Temperature"]["HeartRate"]                                                     # 取人体温度与心率的系数结果
if 0.8 < temp_and_rate <= 1.0:                                                          # python中不存在switch-case语句
    print("人体的温度与心率具有相关性:极强")
elif 0.6 < temp_and_rate <= 0.8:
    print("人体的温度与心率具有相关性:强")
elif 0.4 < temp_and_rate <= 0.6:
    print("人体的温度与心率具有相关性:中等")
elif 0.2 < temp_and_rate <= 0.4:
    print("人体的温度与心率具有相关性:弱")
elif 0 <= temp_and_rate <= 0.2:
    print("人体的温度与心率具有相关性:极弱")

Part 4.运行结果

真正的总体均值不是98.6华氏度,真实的总体均温为98.2
依据shapiro_wiki,该分布近似于正态分布
依据箱型图测试异常数据为
      Temperature  Gender  HeartRate
0           96.3     1.0       70.0
65          96.4     2.0       69.0
129        100.8     2.0       77.0
异性之间在正常温度下存在明显差异
人体的温度与心率具有相关性:弱

猜你喜欢

转载自www.cnblogs.com/S031602219/p/11364400.html