驾驶行为指标构建方法:
1.行驶时长
#1、行驶时长(小时)
driving_hour=(datetime.datetime.strptime(max(data['location_time']), "%Y-%m-%d %H:%M:%S")-
datetime.datetime.strptime(min(data['location_time']), "%Y-%m-%d %H:%M:%S")).seconds/3600
driving_hour #行驶时长
#2、行驶里程(公里/小时)
#方法1
mileage=data['mileage'].max()-data['mileage'].min()
mileage
dm = data.drop_duplicates(['mileage'],inplace = False) #去除完全重复的行数据
dm = dm.reset_index(drop = True)
dm.head()
#方法2
mileage2=dm.shape[0]
mileage2
mileage0 = data['mileage'][:-1]
mileage1 = data['mileage'][1:]
mileage_diff=(np.array(mileage1)-np.array(mileage0)).tolist()
mileage_diff.insert(0,0) #初始里程为0
data['mileage_diff'] =mileage_diff
data.head()
data['mileage_diff'].value_counts()
data.loc[data['mileage_diff']==8]
data[58365:58368]
#3、平均速度
#去除速度为0的行
d = data[(data.gps_speed == 0)].index.tolist()
data1 = data.drop(d)
data1 = data1.reset_index(drop = True)
avg_speed = data1['gps_speed'].describe().values[1]
avg_speed
#速度变化
speed0 = data['gps_speed'][:-1]
speed1 = data['gps_speed'][1:]
speed_diff=(np.array(speed1)-np.array(speed0)).tolist()
speed_diff.insert(0,0) #初始差为0
data['speed_diff'] =speed_diff
data.head()
data['speed_diff'].describe()
figure = plt.figure(1, figsize=(6, 5))
plt.hist(data['speed_diff'],bins=50,color = 'steelblue')
plt.xlabel('speed_diff') # 设置横坐标
plt.show()
#4、急加速(次数/公里)
speed_plus=data[data['speed_diff']>4].shape[0]
speed_plus
#5、急减速(次数/公里)
speed_minus=data[data['speed_diff']<-5].shape[0]
speed_minus #平均一小时次数
#6、疲劳驾驶
#data1是速度不为0的
time_diff=[0]
for i in range(1,len(data1)):
t1 = datetime.datetime.strptime(str(data1['location_time'].iloc[i]),'%Y-%m-%d %H:%M:%S')
t2 = datetime.datetime.strptime(str(data1['location_time'].iloc[i-1]),'%Y-%m-%d %H:%M:%S')
time_diff0= (t1-t2).seconds
time_diff.append(time_diff0)
data1['time_diff']=time_diff
data1.head()
data1['time_diff'].describe()
cut=data1[data1['time_diff']>20*60].index.tolist() #休息时长超过20分钟的划分为不同trip,并取出对应索引
cut.append(len(data1))
cut
cut0 = cut[:-1]
cut1 = cut[1:]
reps=(np.array(cut1)-np.array(cut0)).tolist()
reps.insert(0,cut[0])
reps #大致为每个trip的时长(单位:秒)
tired=len([x for x in reps if x >= 4*60*60]) #疲劳驾驶次数
tired #方法1
data1['trip']=np.repeat(range(len(reps)),reps).tolist()
data1.head()
#驾驶时长,单位:秒
def f(x):
sec=(datetime.datetime.strptime(max(x['location_time']), "%Y-%m-%d %H:%M:%S")-
datetime.datetime.strptime(min(x['location_time']), "%Y-%m-%d %H:%M:%S")).seconds
return sec
sec=data1.groupby('trip').apply(f)
sec
#疲劳驾驶次数
#超过4个小时
tired=sec[sec>4*60*60].count()
tired
data1.head()
#7、长时间怠速
idle_cut=data.loc[(data['acc_state']==1) & (data['gps_speed']==0) & (data['speed_diff']==0)].index.tolist()
idle_cut[:5]
idle_cut0 = idle_cut[:-1]
idle_cut1 = idle_cut[1:]
idle=(np.array(idle_cut1)-np.array(idle_cut0)).tolist()
idle[:5]
[x for x in idle if x >= 60][:5]
longis=len([x for x in idle if x >= 60]) #怠速次数
longis
#8、熄火滑行
data2=data.loc[(data['acc_state']==0)] #熄火数据
data2['lng_lat']=data2['lng']+data2['lat']
data2.head()
lng_lat0 = data2['lng_lat'][:-1]
lng_lat1 = data2['lng_lat'][1:]
slide_off=(np.array(lng_lat1)-np.array(lng_lat0)).tolist()
slide_off[:5]
slip=len([x for x in slide_off if x != 0]) #熄火滑行次数
slip
#9.标准差指标
#速度标准差
sd_speed=np.std(data1['gps_speed'])
sd_speed
#变速标准差
sd_speed_diff=np.std(data1['speed_diff'])
sd_speed_diff
#其他指标……
veh_number=data['vehicleplatenumber'].iloc[0]
veh_number
pd.Series({
'车辆编号':veh_number,
'行驶时长(小时)':driving_hour,
'行驶里程(公里)':mileage,
'平均速度(公里/小时)':avg_speed,
'急加速次数(次数)':speed_plus,
'急减速次数(次数)':speed_minus,
'疲劳驾驶时长(次数)':tired,
'长时间怠速(次数)':longis,
'熄火滑行(次数)':slip,
'速度标准差':sd_speed,
'变速标准差':sd_speed_diff
})
Data_r.describe()
雷达图代码
# 绘制雷达图
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111,polar=True)
labels = np.array(num_sets.columns) # 数据标签
colors = ['r','g']
angles = np.linspace(0,2*np.pi,len(labels),endpoint=False) # 计算各区间角度
angles=np.concatenate((angles,[angles[0]]))#首尾相连
for i in range(len(num_sets)):
df= num_sets.iloc[i,:] #取出第i行
df=np.concatenate((df,[df[i]])) #首尾相连
ax.plot(angles,df,'o--',c=colors[i],label=i) #绘制虚线
ax.fill(angles,df, facecolor=colors[i], alpha=0.1)# 填充颜色和透明度
plt.thetagrids(angles*180/np.pi,labels,fontsize=12) #设置标签
plt.title("车辆",fontsize=20) # 设置标题放置
plt.legend(loc=2) # 设置图例位置
plt.show() # 展示图像
还可以这样展示–1
cluster=pd.DataFrame(kmodel.labels_,columns=['cluster'])
merge_data = pd.concat((data,cluster),axis=1)
merge_data.head()
#从原始数据再看看特征
#速度与急加速
plt.scatter(merge_data.iloc[:, 3], merge_data.iloc[:, 4], marker='o',c=merge_data.iloc[:, 10])
plt.show()
#驾驶时长与急加速
plt.scatter(merge_data.iloc[:, 1], merge_data.iloc[:,4], marker='o',c=merge_data.iloc[:, 10])
plt.show()
还可以这样展示–2
import seaborn as sns
for k in range(1,10):
#sns.boxplot(x=merge_data.iloc[:, 10],y=merge_data.iloc[:, k])
#sns.boxenplot(x=merge_data.iloc[:, 10],y=merge_data.iloc[:, k])
sns.violinplot(x=merge_data.iloc[:, 10],y=merge_data.iloc[:, k])
plt.show()