首页 > 其他分享 >水流数据分析

水流数据分析

时间:2023-04-13 16:25:12浏览次数:30  
标签:数据分析 loc plt sj pd import data 水流

import pandas as pd
import matplotlib.pyplot as plt

inputfile="D:\数据分析\original_data.xls"
data=pd.read_excel(inputfile)

lv_non=pd.value_counts(data['有无水流'])['无']
lv_move=pd.value_counts(data['有无水流'])['有']

fig=plt.figure(figsize=(6,5))
plt.rcParams['font.sans-serif']='SimHei'
plt.rcParams['axes.unicode_minus']=False
plt.bar(x=range(2),height=[lv_non,lv_move],width=0.4,alpha=0.8,color='skyblue')
plt.xticks([index for index in range(2)],['无','有'])
plt.xlabel('水流状态')
plt.ylabel('记录数')
plt.title('学号3108不同水流状态记录数')
plt.show()
plt.close()

water=data['水流量']
fig=plt.figure(figsize=(5,8))
plt.boxplot(water,
            patch_artist=True,
            labels=['水流量'],
            boxprops={'facecolor':'lightblue'})
plt.title('学号3106水流量分布箱型图')
plt.grid(axis='y')
plt.show()

 

 

 

 

 

import pandas as pd
import numpy as np
data=pd.read_excel("D:\数据分析\original_data.xls")
print('初始状态的数据形状为:',data.shape)
data.drop(labels=["热水器编号","有无水流","节能模式"],axis=1,inplace=True)
print('删除冗余属性后的数据形状为:',data.shape)
data.to_csv("D:\数据分析\water_heart.csv",index=False)

 

data=pd.read_csv("D:\数据分析\water_heart.csv")
threshold=pd.Timedelta('4 min')
data['发生时间']=pd.to_datetime(data['发生时间'],format='%Y%m%d%H%M%S')
data=data[data['水流量']>0]
sjKs=data['发生时间'].diff()>threshold
sjKs.iloc[0]=True
sjJs=sjKs.iloc[1:]
sjJs=pd.concat([sjJs,pd.Series(True)])
sj=pd.DataFrame(np.arange(1,sum(sjKs)+1),columns=["事件序号"])
sj["事件起始编号"]=data.index[sjKs==1]+1
sj["事件终止编号"]=data.index[sjJs==1]+1
print('当阈值为4分钟的时候事件数目为:',sj.shape[0])
sj.to_csv("D:\数据分析\sj.csv",index=False)

 

n=4
threshold=pd.Timedelta(minutes=5)
data['发生时间']=pd.to_datetime(data['发生时间'],format='%Y%m%d%H%M%S')
data=data[data['水流量']>0]
def event_num(ts):
    d=data['发生时间'].diff()>ts
    return d.sum()+1
dt=[pd.Timedelta(minutes=i) for i in np.arange(1,9,0.25)]
h=pd.DataFrame(dt,columns=['阈值'])
h['事件数']=h['阈值'].apply(event_num)
h['斜率']=h['事件数'].diff()/0.25
h['斜率指标']=h['斜率'].abs().rolling(4).mean()
ts=h['阈值'][h['斜率指标'].idxmin()-n]
if ts>threshold:
    ts=pd.Timedelta(minutes=4)
print('计算出的单次用水时长的阈值为:',ts)

 

data=pd.read_csv("D:\数据分析\water_heart.csv")
sj=pd.read_csv("D:\数据分析\sj.csv")
data["发生时间"]=pd.to_datetime(data["发生时间"],format="%Y%m%d%H%M%S")

timeDel=pd.Timedelta("0.5 sec")
sj["事件开始时间"]=data.iloc[sj["事件起始编号"]-1,0].values-timeDel
sj["事件结束时间"]=data.iloc[sj["事件终止编号"]-1,0].values+timeDel
sj['洗浴时间点']=[i.hour for i in sj["事件开始时间"]]
sj["总用水时长"]=np.int64(sj["事件结束时间"]-sj["事件开始时间"])/1000000000+1

for i in range(len(data)-1):
    if(data.loc[i,"水流量"]!=0)&(data.loc[i+1,"水流量"]==0):
        data.loc[i+1,"停顿开始时间"]=data.loc[i+1,"发生时间"]-timeDel
    if(data.loc[i,"水流量"]==0)&(data.loc[i+1,"水流量"]!=0):
        data.loc[i,"停顿结束时间"]=data.loc[i,"发生时间"]+timeDel

indStopStart=data.index[data["停顿开始时间"].notnull()]+1
indStopEnd=data.index[data["停顿结束时间"].notnull()]+1
Stop=pd.DataFrame(data={"停顿开始编号":indStopStart[:-1],
                        "停顿结束编号":indStopEnd[1:]})

Stop["停顿时长"]=np.int64(data.loc[indStopEnd[1:]-1,"停顿结束时间"].values-data.loc[indStopStart[:-1]-1,"停顿开始时间"].values)/1000000000

for i in range(len(sj)):
    Stop.loc[(Stop["停顿开始编号"]>sj.loc[i,"事件起始编号"])&
             (Stop["停顿结束编号"]<sj.loc[i,"事件终止编号"]),"停顿归属事件"]=i+1

Stop=Stop[Stop["停顿归属事件"].notnull()]

stopAgg=Stop.groupby("停顿归属事件").agg({"停顿时长":sum,"停顿开始编号":len})
sj.loc[stopAgg.index-1,"总停顿时长"]=stopAgg.loc[:,"停顿时长"].values
sj.loc[stopAgg.index-1,"停顿次数"]=stopAgg.loc[:,"停顿开始编号"].values
sj.fillna(0,inplace=True)
stopNo0=sj["停顿次数"]!=0
sj.loc[stopNo0,"平均停顿时长"]=sj.loc[stopNo0,"总停顿时长"]/sj.loc[stopNo0,"停顿次数"]
sj.fillna(0,inplace=True)
sj["用水时长"]=sj["总用水时长"]-sj["总停顿时长"]
sj["用水/总时长"]=sj["用水时长"]/sj["总用水时长"]
print('用水事件用水时长与频率属性构造完成后数据的属性为:\n',sj.columns)
print('用水事件用水时长与频率属性构造完成后数据的前5行5列属性为:\n',sj.iloc[:5,:5])

 

 

sj_bool=(sj['用水时长']>100)&(sj['总用水时长']>120)&(sj['总用水量']>5)
sj_final=sj.loc[sj_bool,:]
sj_final.to_excel("D:/数据分析/sj_final.xlsx",index=False)
print('筛选出候选洗浴事件前的数据形状为:',sj.shape)
print('筛选出候选洗浴事件后的数据形状为:',sj_final.shape)

 

import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
import joblib

Xtrain=pd.read_excel("D:/数据分析/sj_final.xlsx")
ytrain=pd.read_excel("D:/数据分析/water_heater_log.xlsx")
test=pd.read_excel("D:/数据分析/test_data.xlsx")

x_train,x_test,y_train,y_test=Xtrain.iloc[:,5:],test.iloc[:,4:-1],\
                              ytrain.iloc[:,-1],test.iloc[:,-1]
stdScaler=StandardScaler().fit(x_train)
x_stdtrain=stdScaler.transform(x_train)
x_stdtest=stdScaler.transform(x_test)
bpnn=MLPClassifier(hidden_layer_sizes=(17,10),max_iter=200,solver='lbfgs',random_state=50)
bpnn.fit(x_stdtrain,y_train)
joblib.dump(bpnn,'./water_heater_nnet.m')
print('构建的模型为;\n',bpnn)

 

 

 

 

from sklearn.metrics import classification_report
from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt

bpnn=joblib.load('./water_heater_nnet.m')
y_pred=bpnn.predict(x_stdtest)
print('神经网络预测结果评价报告:\n',classification_report(y_test,y_pred))
plt.rcParams['font.sans-serif']='SimHei'
plt.rcParams['axes.unicode_minus']=False
fpr,tpr,thresholds=roc_curve(y_pred,y_test)
plt.figure(figsize=(6,4))
plt.plot(fpr,tpr)
plt.title('用户用水事件识别ROC曲线学号3108')
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.savefig('用户用水事件识别ROC曲线.png')
plt.show()

 

 

 

 



 

标签:数据分析,loc,plt,sj,pd,import,data,水流
From: https://www.cnblogs.com/021128yc/p/17315230.html

相关文章

  • 天猫数据分析软件:2023年3月防蚊防虫用品十大品牌排行榜
    随着露营、飞盘、冲浪等户外运动掀起热潮后,蚊虫叮咬成了不少户外运动玩家的心头痛。不过从市场端来看,这却是一个不可多得的商机。“户外防蚊防虫”,成为户外经济的垂类增长点。户外消费场景的持续火爆,带动了防蚊防虫产品销量的增长。根据鲸参谋电商数据显示,2023年3月份在天猫平台上,......
  • NumPy 和 Pandas 数据分析实用指南:1~6 全
    原文:Hands-OnDataAnalysiswithNumPyandpandas协议:CCBY-NC-SA4.0译者:飞龙一、配置Python数据分析环境在本章中,我们将介绍以下主题:安装Anaconda探索Jupyter笔记本探索Jupyter的替代品管理Anaconda包配置数据库在本章中,我们将讨论如何安装和管理Anac......
  • 003.方差&回归分析以及pandas数据分析流程
    一、方差分析   二、回归分析 三、案例讲解 ......
  • 每日学习记录20230316_转录组测序数据分析
    20230316:转录组测序转录组测序数据分析最根本的是基础知识,不然给你数据你都不知道是干啥的.要多看综述,并且要多看几遍.下载GEO数据之前,需要先下载参考基因组数据.可以在三个平台上下载:ucsc,ncbi和ensemble,使用下面的检索式在搜索引擎中检索:hg38ftpucsc就得到比......
  • 数据分析之电子商务网站用户行为分析及服务推荐
    01-mysql_access.py#-*-coding:utf-8-*-#代码11-1importosimportpandasaspd#修改工作路径到指定文件夹os.chdir("D:/chapter11/demo")#第一种连接方式fromsqlalchemyimportcreate_engineengine=create_engine('mysql+pymysql://root:[email protected].......
  • 数据分析第十二章实践
    #代码12-1评论去重的代码importpandasaspdimportreimportjieba.possegaspsgimportnumpyasnp#去重,去除完全重复的数据reviews=pd.read_csv("C:/Users/Lenore/Desktop/data/reviews.csv")reviews=reviews[['content','content_type']].d......
  • 最新中国福彩分析大数据分析大师拥有双色球数据展示微信小程序源码支持双色球数据分析
    demo软件园每日更新资源,请看到最后就能获取你想要的: 1.最新中国福彩分析大数据分析大师拥有双色球数据展示微信小程序源码支持双色球数据分析多个接口福彩大数据分析小程序,数据来自于中国福利彩票 拥有双色球数据展示 双色球数据分析多个接口 数据有每日奖金和往期记录......
  • Python数据分析库介绍及引入惯例
    文章和代码等已经归档至【Github仓库:https://github.com/timerring/dive-into-AI】或者公众号【AIShareLab】回复python数据分析也可获取。python的缺点Python有一个叫做全局解释器锁(GlobalInterpreterLock,GIL)的组件,这是一种防止解释器同时执行多条Python字节码指令的机制。这......
  • 天猫食品饮料数据分析:2月份茶饮料品牌销量TOP10排行榜!
    近年来,茶饮料品类逐渐丰富,也在潜移默化中激发消费者的购物欲望,茶饮料行业的整体市场规模也不断增长。根据鲸参谋电商数据显示,2023年2月份在天猫平台上,茶饮料相关产品的月销量将近149万件,环比增长约15%;月销售额达到6675万元,环比增长约6%。*数据源于鲸参谋-行业趋势分析根据2月份茶饮......
  • 宠物app如何借助大数据分析提供更贴心的宠物养护
    宠物越来越成为了人们生活中不可或缺的一部分。越来越多的人开始养宠物,而宠物的养护也变得越来越重要。为了更好地照顾宠物,宠物app应运而生。但是,如何利用大数据分析来提供更贴心的宠物养护呢?一、宠物健康监测宠物健康监测是宠物app的一个重要功能。通过在app中记录宠物的体重......