20191228_Python语言课程设计

2023-11-05

在这里插入图片描述

#用 pandas 库读取“pollution_us_5city_2006_2010_SO2.csv”文件,查看前五行、后两行。
import pandas as pd
import matplotlib.pyplot as plt
test=pd.read_csv('pollution_us_5city_2006_2010_SO2.csv')
print(test.head(5))
print(test.tail(2))
   ID  State Code  County Code  Site Num                      Address  \
0   1           6           37      1103  1630 N MAIN ST, LOS ANGELES   
1   2           6           37      1103  1630 N MAIN ST, LOS ANGELES   
2   3           6           37      1103  1630 N MAIN ST, LOS ANGELES   
3   4           6           37      1103  1630 N MAIN ST, LOS ANGELES   
4   5           6           37      1103  1630 N MAIN ST, LOS ANGELES   

        State       County         City Date Local          SO2 Units  \
0  California  Los Angeles  Los Angeles   2006/1/1  Parts per billion   
1  California  Los Angeles  Los Angeles   2006/1/1  Parts per billion   
2  California  Los Angeles  Los Angeles   2006/1/1  Parts per billion   
3  California  Los Angeles  Los Angeles   2006/1/1  Parts per billion   
4  California  Los Angeles  Los Angeles   2006/1/2  Parts per billion   

   SO2 Mean  SO2 1st Max Value  SO2 1st Max Hour  SO2 AQI  
0  2.043478                3.0                 5      4.0  
1  2.043478                3.0                 5      4.0  
2  2.000000                2.0                 2      NaN  
3  2.000000                2.0                 2      NaN  
4  2.000000                2.0                 0      3.0  
          ID  State Code  County Code  Site Num  \
53218  53219          36           81       124   
53219  53220          36           81       124   

                                                 Address     State  County  \
53218  Queens College   65-30 Kissena Blvd  Parking L...  New York  Queens   
53219  Queens College   65-30 Kissena Blvd  Parking L...  New York  Queens   

           City  Date Local          SO2 Units  SO2 Mean  SO2 1st Max Value  \
53218  New York  2010/12/31  Parts per billion   14.8875               16.9   
53219  New York  2010/12/31  Parts per billion   14.8875               16.9   

       SO2 1st Max Hour  SO2 AQI  
53218                 5      NaN  
53219                 5      NaN  

用 pandas 数据预处理模块将缺失值填充为该列的平均值,删除列 StateCode、County Code、Site Num、Address,并将剩余列导出到 Excel 文件
“pollution_us_5city_2006_2010_SO2.xlsx”。

test.isnull().sum()
mean_cols=test['SO2 AQI'].mean()
test['SO2 AQI'] = test['SO2 AQI'].fillna(mean_cols)
test1=test.drop(['State Code','County Code','Site Num','Address'],axis=1)
test1.to_excel('pollution_us_5city_2006_2010_SO2.xlsx')

读取新的数据集“pollution_us_5city_2006_2010_SO2.xlsx”,并选择字段
City==“New York”的所有数据集,导出为文本文件“pollution_us_NewYork_2006_2010_SO2.txt”,要求数据之间用空格分隔,
每行末尾包含换行符。

test=pd.read_excel('pollution_us_5city_2006_2010_SO2.xlsx')
test2=test.loc[test['City']=="New York"]
test2.to_csv('pollution_us_NewYork_2006_2010_SO2.txt',index=0)

读取文本文件“pollution_us_NewYork_2006_2010_SO2.txt”,并选择字段
Date Local 位于[2007/1/1, 2009/12/31] 区间的所有数据集转存到 CSV 文件
“pollution_us_NewYork_2007_2009_SO2.csv”中。

test=pd.read_csv('pollution_us_NewYork_2006_2010_SO2.txt')
test['Date Local'] = pd.to_datetime(test['Date Local'])
test = test.set_index('Date Local') # 将date设置为index
test=test['2007-01-01':'2009-12-31']
test.to_csv('pollution_us_NewYork_2007_2009_SO2.csv')

读取 CSV 文件“pollution_us_NewYork_2007_2009_SO2.csv”,计算同一个
城市(字段 City)的 SO2 Mean、SO2 1st Max Hour、SO2 AQI 的月均值,
并利用 matplotlib 库可视化显示,要求包括图例、图标题,x 轴刻度以年显
示,y 轴显示刻度值,曲线颜色为红色

test=pd.read_csv('pollution_us_NewYork_2007_2009_SO2.csv')          
test.head()
Date Local ID State County City SO2 Units SO2 Mean SO2 1st Max Value SO2 1st Max Hour SO2 AQI
0 2007-01-01 15225 New York Bronx New York Parts per billion 6.583333 20.0 16 29.000000
1 2007-01-01 15226 New York Bronx New York Parts per billion 6.583333 20.0 16 29.000000
2 2007-01-01 15227 New York Bronx New York Parts per billion 6.562500 13.3 20 10.957132
3 2007-01-01 15228 New York Bronx New York Parts per billion 6.562500 13.3 20 10.957132
4 2007-01-02 15229 New York Bronx New York Parts per billion 7.909091 19.0 20 27.000000
test['Date Local'] = test['Date Local'].apply(lambda x: pd.Timestamp(x))
# 年份
test['年']=test['Date Local'].apply(lambda x: x.year)
# 月份
test['月']=test['Date Local'].apply(lambda x: x.month)
test=test.drop(['ID','SO2 1st Max Value'],axis=1)
test_num=test.groupby(by=['年','月'],as_index=False).mean()
test_num.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 36 entries, 0 to 35
Data columns (total 5 columns):
年                   36 non-null int64
月                   36 non-null int64
SO2 Mean            36 non-null float64
SO2 1st Max Hour    36 non-null float64
SO2 AQI             36 non-null float64
dtypes: float64(3), int64(2)
memory usage: 1.7 KB
test_num['年']=test_num['年'].astype('str')
test_num['月']=test_num['月'].astype('str')
test_num['all']=test_num['年']+'/'+test_num['月']
test_num.columns
Index(['年', '月', 'SO2 Mean', 'SO2 1st Max Hour', 'SO2 AQI', 'all'], dtype='object')
x=test_num['all']
y=test_num['SO2 Mean']
plt.figure(figsize=(20,10))
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False
plt.plot(x,y, 'r', label='SO2 Mean')
plt.xlabel('年')
plt.ylabel('label value')
Text(0,0.5,'label value')

在这里插入图片描述

x=test_num['all']
y=test_num['SO2 1st Max Hour']
plt.figure(figsize=(20,10))
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False
plt.plot(x,y, 'r', label='SO2 Mean')
plt.xlabel('年')
plt.ylabel('label value')
Text(0,0.5,'label value')

在这里插入图片描述

x=test_num['all']
y=test_num['SO2 AQI']
plt.figure(figsize=(20,10))
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False
plt.plot(x,y, 'r', label='SO2 Mean')
plt.xlabel('年')
plt.ylabel('label value')
Text(0,0.5,'label value')

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

20191228_Python语言课程设计 的相关文章

  • 如何从特定类获取特定链接?

    我想提取这个href从那个特定的class tr class even td a href italy serie a 2015 2016 Serie A 2015 2016 a td 这是我写的 Sub ExtractHrefClass
  • 为什么我不能导入 geopandas?

    我唯一的代码行是 import geopandas 它给了我错误 OSError Could not find libspatialindex c library file 以前有人遇到过这个吗 我的脚本运行得很好 直到出现此错误 请注意
  • 获取单个方程的脚本

    在文本文件中输入 a 2 8 b 3 9 c 4 8 d 5 9 e a b f c d g 0 6 h 1 7 i e g j f h output i j 期望的输出 输出 2 8 3 9 0 6 4 8 5 9 1 7 如果输入文件名
  • 在 python-docx 中搜索和替换

    我有一个包含以下字符串的文档 模板 你好 我的名字是鲍勃 鲍勃是一个很好的名字 我想使用 python docx 打开此文档并使用 查找和替换 方法 如果存在 来更改每个字符串 Bob gt Mark 最后 我想生成一个新文档 其中包含字符
  • Python:当前目录是否自动包含在路径中?

    Python 3 4 通过阅读其他一些 SO 问题 似乎如果moduleName py文件位于当前目录之外 如果要导入它 必须将其添加到路径中sys path insert 0 path to application app folder
  • 将 subprocess.Popen 的输出通过管道传输到文件

    我需要启动一些长时间运行的进程subprocess Popen 并希望拥有stdout and stderr从每个自动管道到单独的日志文件 每个进程将同时运行几分钟 我想要两个日志文件 stdout and stderr 每个进程当进程运行
  • 如何使用 openpyxl 对工作簿中的 Excel 工作表/选项卡进行排序

    我需要按字母数字对工作簿中的选项卡 工作表进行排序 我在用openpyxl https openpyxl readthedocs io en default 操作工作表 您可以尝试排序workbook sheets list workboo
  • Pandas:根据列名进行列的成对乘法

    我有以下数据框 gt gt gt df pd DataFrame ap1 X 1 2 3 4 as1 X 1 2 3 4 ap2 X 2 2 2 2 as2 X 3 3 3 3 gt gt gt df ap1 X as1 X ap2 X a
  • Python While 循环,and (&) 运算符不起作用

    我正在努力寻找最大公因数 我写了一个糟糕的 运算密集型 算法 它将较低的值减一 使用 检查它是否均匀地划分了分子和分母 如果是 则退出程序 但是 我的 while 循环没有使用 and 运算符 因此一旦分子可整除 它就会停止 即使它不是正确
  • 字典的嵌套列表

    我正在尝试创建dict通过嵌套list groups Group1 A B Group2 C D L y x 0 for y in x if y x 0 for x in groups d k v for d in L for k v in
  • 在 Mac 上安装 Pygame 到 Enthought 构建中

    关于在 Mac 上安装 Pygame 有许多未解答的问题 但我将在这里提出我的具体问题并希望得到答案 我在 Mac 上安装 Pygame 时遇到了难以置信的困难 我使用 Enthought 版本 EPD 7 3 2 32 位 它是我的默认框
  • urllib2.urlopen() 是否实际获取页面?

    当我使用 urllib2 urlopen 时 我在考虑它只是为了读取标题还是实际上带回整个网页 IE 是否真的通过 urlopen 调用或 read 调用获取 HTML 页面 handle urllib2 urlopen url html
  • 在 pip.conf 中指定多个可信主机

    这是我尝试在我的中设置的 etc pip conf global trusted host pypi org files pythonhosted org 但是 它无法正常工作 参考 https pip pypa io en stable
  • 在谷歌C​​olab中使用cv2.imshow()

    我正在尝试通过输入视频来对视频进行对象检测 cap cv2 VideoCapture video3 mp4 在处理部分之后 我想使用实时对象检测来显示视频 while True ret image np cap read Expand di
  • python中的sys.stdin.fileno()是什么

    如果这是非常基本的或之前已经问过的 我很抱歉 我用谷歌搜索但找不到简单且令人满意的解释 我想知道什么sys stdin fileno is 我在代码中看到了它 但不明白它的作用 这是实际的代码块 fileno sys stdin filen
  • 是否可以写一个负的python类型注释

    这可能听起来不合理 但现在我需要否定类型注释 我的意思是这样的 an int Not Iterable a string Iterable 这是因为我为一个函数编写了一个重载 而 mypy 不理解我 我的功能看起来像这样 overload
  • Plotly:如何避免巨大的 html 文件大小

    我有一个 3D 装箱模型 它使用绘图来绘制输出图 我注意到 绘制了 600 个项目 生成 html 文件需要很长时间 文件大小为 89M 这太疯狂了 我怀疑可能存在一些巨大的重复 或者是由单个项目的 add trace 方法引起的 阴谋 为
  • asyncio - 多次等待协程(周期性任务)

    我正在尝试为异步事件循环创建定期任务 如下所示 但是我收到 RuntimeError 无法重用已等待的协程 异常 显然 asyncio 不允许等待相同的可等待函数 如中讨论的这个错误线程 https bugs python org issu
  • 从 dask 数据框中的日期时间序列获取年份和星期?

    如果我有一个 Pandas 数据框和一个日期时间类型的列 我可以按如下方式获取年份 df year df date dt year 对于 dask 数据框 这是行不通的 如果我先计算 像这样 df year df date compute
  • 使用“pythonw”(而不是“python”)运行应用程序时找不到模块

    我尝试了这个最小的例子 from flask import Flask app Flask name app route def hello world return Hello World if name main app run deb

随机推荐