数据挖掘-用python分析汽车油耗的csv数据(环境anaconda3和python3.6.1)
数据文件:(汽车油耗分析都是基于这个文件进行分析的)
下载地址:https://www.fueleconomy.gov/feg/download.shtml
一、环境安装与配置
1、下载安装jupyter notebook之前 ,先下载安装anaconda(我的电脑系统:windows10,64位)官网下载: https://www.anaconda.com/download/#windows
安装成功后,打开命令行窗口,输入【pip install jupyter】就可以下载安装jupyter,详见步骤3。
2、下载安装python3.6.1(提前已经安装并配置python环境),关于python的下载安装和配置可以百度,主要是配置环境变量path。安装配置成功后,在命令行中输入python,如图:
3、在安装好的Anaconda Prompt命令窗口中,输入pip install jupyter(图为安装成功后命令行显示)
4、安装ggplot(运行代码时报错,发现问题后,安装解决)
ggplot for python:ggplot是一个python的库,基本上是对R语言ggplot的功能移植到Python上。运行安装:pip install ggplot
5、将文件:vehicles.csv放到磁盘目录下:D:/model/vehicles.csv
(这里的路径要和代码中此处的路径一致 vehicles = pd.read_csv(“D:/model/vehicles.csv”) )
二、在Jupyter Notebook中开始项目
1、打开Jupyter Notebook,新建python文件:
在In[ ]单元格中输入python命令:
import pandas as pd
import numpy as np
from ggplot import *
import matplotlib.pyplot as plt
%matplotlib inline
vehicles = pd.read_csv(“D:/model/vehicles.csv”)
print(vehicles.head())
按Shift+enter执行单元格代码,结果如图:
2、描述汽车油耗等数据:
接着上面的代码,继续输入:(将之前的代码注释掉,简化页面)
(1)、查看观测点(行):len(vehicles)
(2)、查看变量数(列):print (len(vehicles.columns))
print(vehicles.columns)
(3)、查看年份信息:print(len(pd.unique(vehicles.year)))
print(min(vehicles.year))
print(max(vehicles.year))
(4)、查看燃料类型:print(pd.value_counts(vehicles.fuelType))
(5)、查看变速箱类型: pd.value_counts(vehicles.trany)
trany变量自动挡是以A开头,手动挡是以M开头;故创建一个新变量trany2:
vehicles[‘trany2’] = vehicles.trany.str[0]
pd.value_counts(vehicles.trany2)
3、分析汽车油耗随时间变化的规律
(1)、先按年份分组:grouped = vehicles.groupby(‘year’)
再计算其中三列的均值:
averaged= grouped[‘comb08’, ‘highway08’, ‘city08’].agg([np.mean])
为方便分析,对其进行重命名,然后创建一个‘year’的列,包含该数据框data frame的索引:
averaged.columns = [‘comb08_mean’, ‘highwayo8_mean’, ‘city08_mean’]
averaged[‘year’] = averaged.index
print(averaged )
(2)、使用ggplot包将结果绘成散点图:allCarPlt = ggplot(averaged, aes(‘year’, ‘comb08_mean’)) + geom_point(colour=’steelblue’) + xlab(“Year”) + ylab(“Average MPG”) + ggtitle(“All cars”)
print(allCarPlt)
(3)、去除混合动力汽车:
criteria1 = vehicles.fuelType1.isin([‘Regular Gasoline’, ‘Premium Gasoline’, ‘Midgrade Gasoline’])
criteria2 = vehicles.fuelType2.isnull()
criteria3 = vehicles.atvType != ‘Hybrid’
vehicles_non_hybrid = vehicles[criteria1 & criteria2 & criteria3]
将得到的数据框data frame按年份分组,并计算平均油耗:
grouped = vehicles_non_hybrid.groupby([‘year’])
averaged = grouped[‘comb08’].agg([np.mean])
averaged[‘hahhahah’] = averaged.index
print(averaged)
(4)、查看是否大引擎的汽车越来越少:print(pd.unique(vehicles_non_hybrid.displ))
(5)、去掉nan值,并用astype方法保证各个值都是float型的:
criteria = vehicles_non_hybrid.displ.notnull()
vehicles_non_hybrid = vehicles_non_hybrid[criteria]
vehicles_non_hybrid.loc[:,’displ’] = vehicles_non_hybrid.displ.astype(‘float’)
criteria = vehicles_non_hybrid.comb08.notnull()
vehicles_non_hybrid = vehicles_non_hybrid[criteria]
vehicles_non_hybrid.loc[:,’comb08’] = vehicles_non_hybrid.comb08.astype(‘float’)
最后用ggplot包来绘图:
gasOnlineCarsPlt = ggplot(vehicles_non_hybrid, aes(‘displ’, ‘comb08’)) + geom_point(color=’steelblue’) +xlab(‘Engine Displacement’) + ylab(‘Average MPG’) + ggtitle(‘Gasoline cars’)
print(gasOnlineCarsPlt)
(6)、查看是否平均起来汽车越来越少了:
grouped_by_year = vehicles_non_hybrid.groupby([‘year’])
avg_grouped_by_year = grouped_by_year[‘displ’, ‘comb08’].agg([np.mean])
计算displ和conm08的均值,并改造数据框data frame:
avg_grouped_by_year[‘year’] = avg_grouped_by_year.index
melted_avg_grouped_by_year = pd.melt(avg_grouped_by_year, id_vars=’year’)
创建分屏绘图:
p = ggplot(aes(x=’year’, y=’value’, color = ‘variable_0’), data=melted_avg_grouped_by_year)
p + geom_point() + facet_grid(“variable_0”,scales=”free”) #scales参数fixed表示固定坐标轴刻度,free表示反馈坐标轴刻度
print(p)
4、调查汽车的制造商和型号
接下来的步骤会引导我们继续深入完成数据探索
(1)、首先查看cylinders变量有哪些可能的值:print(pd.unique(vehicles_non_hybrid.cylinders))
(2)、再将cylinders变量转换为float类型,这样可以轻松方便地找到data frame的子集:
vehicles_non_hybrid.cylinders = vehicles_non_hybrid.cylinders.astype(‘float’)
pd.unique(vehicles_non_hybrid.cylinders)
(3)、现在,我们可以查看各个时间段有四缸引擎汽车的品牌数量:
vehicles_non_hybrid_4 = vehicles_non_hybrid[(vehicles_non_hybrid.cylinders==4.0)]
grouped_by_year_4_cylinder =vehicles_non_hybrid_4.groupby([‘year’]).make.nunique()
plt.plot(grouped_by_year_4_cylinder)
plt.xlabel(“Year”)
plt.ylabel(“Number of 4-Cylinder Maker”)
plt.show()
分析:
我们可以从上图中看到,从1980年以来四缸引擎汽车的品牌数量呈下降趋势。然而,需要注意的是,这张图可能会造成误导,因为我们并不知道汽车品牌总数是否在同期也发生了变化。为了一探究竟,我们继续一下操作。
(4)、查看各年有四缸引擎汽车的品牌的列表,找出每年的品牌列表:
grouped_by_year_4_cylinder = vehicles_non_hybrid_4.groupby([‘year’])
unique_makes = []
from functools import reduce
for name, group in grouped_by_year_4_cylinder:
#list中存入set(),set里包含每年中的不同品牌:
unique_makes.append(set(pd.unique(group[‘make’])))
unique_makes = reduce(set.intersection, unique_makes)
print(unique_makes)
我们发现,在此期间只有12家制造商每年都制造四缸引擎汽车。
接下来,我们去发现这些汽车生产商的型号随时间的油耗表现。这里采用一个较复杂的方式。首先,创建一个空列表,最终用来产生布尔值Booleans。我们用iterrows生成器generator遍历data frame中的各行来产生每行及索引。然后判断每行的品牌是否在此前计算的unique_makes集合中,在将此布尔值Blooeans添加在Booleans_mask集合后面。
(5)、创建一个空列表,最终用来产生布尔值Booleans
boolean_mask = []
这里是注释#—用iterrows生成器generator遍历data frame中的各行来产生每行及索引:
for index, row in vehicles_non_hybrid_4.iterrows():
这里是注释#—判断每行的品牌是否在此前计算的unique_makes集合中,在将此布尔值Blooeans添加在Booleans_mask集合后面:
make = row[‘make’]
boolean_mask.append(make in unique_makes)
df_common_makes = vehicles_non_hybrid_4[boolean_mask]
这里是注释#—先将数据框data frame按year和make分组,然后计算各组的均值:
df_common_makes_grouped = df_common_makes.groupby([‘year’, ‘make’]).agg(np.mean).reset_index()
这里是注释#—最后利用ggplot提供的分屏图来显示结果:
oilWithTime = ggplot(aes(x=’year’, y=’comb08’), data = df_common_makes_grouped) + geom_line() + facet_wrap(‘make’)
print(oilWithTime)
这是使用python进行数据分析的简单实践,有利于进一步加深对数据挖掘的认识。
数据挖掘-用python分析汽车油耗的csv数据(环境anaconda3和python3.6.1)相关推荐
- python计算汽车的平均油耗_用python对汽车油耗进行数据分析
原标题:用python对汽车油耗进行数据分析 - 从http://fueleconomy.gov/geg/epadata/vehicles.csv.zip 下载汽车油耗数据集并解压 - 进入jupyt ...
- python汽车数据分析_用python对汽车油耗进行数据分析
原标题:用python对汽车油耗进行数据分析 - 从http://fueleconomy.gov/geg/epadata/vehicles.csv.zip 下载汽车油耗数据集并解压 - 进入jupyt ...
- python计算汽车的平均油耗_用python对汽车油耗进行数据分析(anaconda python3.6完全跑通)...
原标题:用python对汽车油耗进行数据分析(anaconda python3.6完全跑通) 编者按:前两天我们微信发了一篇文章<用python对汽车油耗进行数据分析 >,有一网友学习后用 ...
- R语言主成分回归(PCR)、 多元线性回归特征降维分析光谱数据和汽车油耗、性能数据...
原文链接:http://tecdat.cn/?p=24152 什么是PCR?(PCR = PCA + MLR)(点击文末"阅读原文"获取完整代码数据). • PCR是处理许多 x ...
- 用python对汽车油耗进行数据分析(anaconda python3.6完全跑通)
1.下载汽车油耗数据集并解压 下载地址:https://www.fueleconomy.gov/feg/download.shtml vehiclesData.py: #encoding = utf- ...
- 用Python分析了1w四六级数据,教你如何通过四六级!
微信改版,加星标不迷路! 用Python分析了1w四六级数据,教你如何通过四六级! 作者:阿广 概述 前言 数据介绍 预期结果 实现过程 搞笑一刻 阿广说 每日问题 前言 陈奕迅说过:在有生的瞬间,考 ...
- python数据处理系列之读写csv数据
python数据处理系列之读写csv数据 导入csv文件 pandas中导入csv数据用的方法是read_csv() import pandas as pd df = pd.read_csv(r'c: ...
- Python分析抖音用户行为数据,看看发什么样的视频才会爆!
前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理. Python分析抖音用户行为数据视频讲解地址 https://www.bilibili.co ...
- Python实现汽车油耗预测_基于Tensorflow2.X
目录 一.开发环境 二 .代码实现 2.1 准备操作 2.1.1 导入所需模块 2.1.2 matplotlib无法正常显示中文的解决方案(若无此情况可跳过) 2.2 加载数据集 2.3 数据处理 2 ...
最新文章
- Java 多线程编程(锁优化)
- 开源跨平台移动项目Ngui【Action动作系统】
- 微信小程序隐藏标题栏navigationBar的方法
- 图解Oracle 11g physical standby Rolling Upgrade物理备库滚动升级特性
- 覆盖 19 个城市,19,000 个样本,零售业深度研究报告发布
- 深入Java内存模型
- python 中cPickle学习二
- 隐藏网页文件的后缀(IIS测试通过)!
- .NET和Java之争
- bi power 两个日期挑较早的日期_功率 BI 中的时间智能:利用时间
- 解决透视变换后图片信息丢失的问题
- redis专题:redis的主从、哨兵、集群架构的配置和部署详情、以及问题分析
- 聊聊零基础的我是如何学python的_零基础学python-4.3 对象的比较
- 单片机流水灯源代码+仿真
- 怎么根据分隔符号将Excel数据换行复制
- Kubernetes能成大事,华为云的眼光“真毒”
- [leetcode] 379. Design Phone Directory 解题报告
- 【金猿投融展】易观数科——智能用户运营服务商
- 百度网盘秒传链接怎么用及实现原理
- Spring AOP @Aspect没反应的处理