python数据分析之CSV文件

之前有提到过CSV文件:这里

CSV文件:将数据作为一系列以逗号分隔的值写入文件。在excel中就是以表格线代替逗号

csv模块

包含在Python标准库里,可以用于分析CSV文件中的数据行,让我们提取感兴趣的数值。

import csv

filename=r'C:\Users\LPH\Desktop\pythoncrashcourse配套资源\ehmatthes-pcc-6bfeca0\chapter_16\sitka_weather_07-2014.csv'

#调用csv.reader(),把前面存储的文件对象f作为参数传递给它,并创建一个与文件相关的阅读器对象
#模块csv包含函数next(),调用它并将阅读器对象f传递给它,它将返回文件中下一行。
#下面得到的是文件的第一行。
with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)
    print(header_row)

从输出的文件头看出,文件每一行的第一个位置日期,第二个位置表示最高华氏气温,第三个位置表示最低华氏气温等。

打印头文件及其位置

with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)
    
    for index,column_hesder in enumerate(header_row):
        print(index,column_hesder)

发现日期和最高气温分别存储在第0列和第一列,其索引为0和1

模块datetime

在CSV文件中有日期就要使用datetime这个模块来进行正确读取。

from datetime import datetime
firstdate=datetime.strptime('2014-7-1','%Y-%m-%d')
print(firstdate)

strptime方法将包含所需日期的字符串作为第一个实参。第二个实参告诉python如何设置日期的格式。

模块datetime中设置日期和时间格式的实参

实参含义
%A星期的名称,如Monday
%B月份名,如January
%m用数字表示的月份(01-12)
%d用数字表示月份中的一天(01-31)
%Y四位的年份,如2015
%y两位的年份,如15
%H24小时制的小时数(00-23)
%I12小时制的小时数(00-12)
%pam或pm
%M分钟数(00-59)
%S秒数(00-61)

提取并读取数据

import csv
import matplotlib.pyplot as plt
from datetime import datetime

filename=r'C:\Users\LPH\Desktop\pythoncrashcourse配套资源\ehmatthes-pcc-6bfeca0\chapter_16\sitka_weather_07-2014.csv'

#调用csv.reader(),把前面存储的文件对象f作为参数传递给它,并创建一个与文件相关的阅读器对象next
#模块csv包含函数next(),调用它并将阅读器对象f传递给它,它将返回文件中下一行。
#下面得到的是文件的第一行。
with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)
    
    dates,highs,lows=[],[],[]
    for row in reader:
        date=datetime.strptime(row[0],'%Y-%m-%d')
        high=int(row[1])
        low=int(row[3])
        
        dates.append(date)
        highs.append(high)
        lows.append(low)
print(dates)       
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red',alpha=0.5)
plt.plot(dates,lows,c='blue',alpha=0.5)
#填充二者之间的区域
plt.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1)

plt.title('Daily high and low temperature - 2014',fontsize=24)
plt.xlabel('',fontsize=12)
#绘制斜的日期标签,以免彼此重叠。
fig.autofmt_xdate()
plt.ylabel('Temperature(F)',fontsize=10)
plt.tick_params(axis='both',labelsize=12)

#修改坐标的标注
x_ticks=dates[::3]
plt.xticks(x_ticks)
y_ticks=list(range(45,75,5))
plt.yticks(y_ticks)

plt.show()

效果如图所示:

拉长时间线(分析整年)

找到某地区一年的气温CSV数据,执行上述程序,发现出现了错误。

无法读取某一天的最高气温,回看文件发现2014-2-16这一天的气温数据都是空

因此要进行空数据判断。可以使用try-except-else语句。

with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)
    
    dates,highs,lows=[],[],[]
    for row in reader:
        try:
            date=datetime.strptime(row[0],'%Y-%m-%d')
            high=int(row[1])
            low=int(row[3])
        except:
            print(date,'missing date')
        else:
            dates.append(date)
            highs.append(high)
            lows.append(low)

完整代码如下:

import csv
import matplotlib.pyplot as plt
from datetime import datetime

filename=r'C:\Users\LPH\Desktop\pythoncrashcourse配套资源\ehmatthes-pcc-6bfeca0\chapter_16\death_valley_2014.csv'

#调用csv.reader(),把前面存储的文件对象f作为参数传递给它,并创建一个与文件相关的阅读器对象next
#模块csv包含函数next(),调用它并将阅读器对象f传递给它,它将返回文件中下一行。
#下面得到的是文件的第一行。
with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)
    
    dates,highs,lows=[],[],[]
    for row in reader:
        try:
            date=datetime.strptime(row[0],'%Y-%m-%d')
            high=int(row[1])
            low=int(row[3])
        except:
            print(date,'missing date')
        else:
            dates.append(date)
            highs.append(high)
            lows.append(low)
            
print(dates)       
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red',alpha=0.5)
plt.plot(dates,lows,c='blue',alpha=0.5)
#填充二者之间的区域
plt.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1)

plt.title('Daily high and low temperature - 2014\nDeath Valley,CA',fontsize=24)
plt.xlabel('',fontsize=12)
#绘制斜的日期标签,以免彼此重叠。
fig.autofmt_xdate()
plt.ylabel('Temperature(F)',fontsize=10)
plt.tick_params(axis='both',labelsize=12)

#修改坐标的标注
y_ticks=list(range(20,120,5))
plt.yticks(y_ticks)

plt.show()

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值