python处理CSV文件格式数据

1、CSV文件

要在文本文件中存储数据,最简单的方式是将数据作为一系列以逗号分隔的值(CSV)写入文件,这样的文件称为CSV文件。

2、分析CSV文件头

1)调用csv.reader()将存储的文件对象作为实参传递给它,从而创建一个与文件相关联的阅读器对象。模块csv包含函数next(),调用它并将阅读器对象传递给它时,它将返回文件中的下一行。

import csv

filename="sitka_weather_2014.csv"
with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)
    print(header_row)

这里写图片描述
reader处理文件中以逗号分隔的第一行数据,并将每项数据都作为一个元素存储在列表中。
2)打印文件头及其位置

for index,column_header in enumerate(header_row):
        print(index,column_header)

这里写图片描述

对列表调用enumerate()来获取每个元素的索引及其值。

3、绘制最高最低气温图表

#highs_lows.py
# coding=gbk
import csv
from matplotlib import pyplot as plt
from datetime import datetime

filename="sitka_weather_2014.csv"
with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)

    dates,highs,lows=[],[],[]
    for row in reader:
        current_date=datetime.strptime(row[0],"%Y-%m-%d")
        dates.append(current_date)

        high=int(row[1])
        highs.append(high)

        low=int(row[3])
        lows.append(low)

# 根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red')
plt.plot(dates,lows,c='blue')

# 设置图形格式
plt.title("Daily high and low temperatures - 2014",fontsize=24)
plt.xlabel('',fontsize=16)
fig.autofmt_xdate()   #绘制斜的日期标签,以免它们彼此重叠
plt.ylabel("Temperture (F)",fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)

plt.show()
plt.savefig("tmp3.png",bbox_inches='tight')

这里写图片描述

补充:模块datetime中的datetime类,方法strptime()将包含所需日期的字符串作为第一个实参,第二个实参告诉python如何设置日期的格式。

4、文件错误检查

for row in reader:
        try:
            current_date=datetime.strptime(row[0],"%Y-%m-%d")
            high=int(row[1])
            low=int(row[3])
        except ValueError:
            print(current_date,'missing data')
        else:
            dates.append(current_date)
            highs.append(high)
            lows.append(low)
# 根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
#实参alpha指定颜色透明度,0表示完全透明,1表示完全不透明
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)

这里写图片描述

这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值