用Python处理"大"XLS文件

本文通过Python分析了来自data.gov.uk的交通事故数据集,探讨了不同条件下的事故发生频率,如天气、时间和地点等,并展示了如何使用Pandas进行数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

权当学习Python练手用的.

数据来data.gov.uk,大小有58.4MB

  • 文件都是些什么内容?

    • ’Accident_Index’,
    • ‘Location_Easting_OSGR’,
    • ‘Location_Northing_OSGR’,
    • ‘Longitude’,
    • ‘Latitude’,
    • ‘Police_Force’,
    • ‘Accident_Severity’,
    • ‘Number_of_Vehicles’,
    • ‘Number_of_Casualties’,
    • ‘Date’,
    • ‘Day_of_Week’,
    • ‘Time’,
    • ‘Local_Authority_(District)’,
    • ‘Local_Authority_(Highway)’,
    • ‘1st_Road_Class’, ‘1st_Road_Number’,
    • ‘Road_Type’,
    • ‘Speed_limit’,
    • ‘Junction_Detail’,
    • ‘Junction_Control’,
    • ‘2nd_Road_Class’,
    • ‘2nd_Road_Number’,
    • ‘Pedestrian_Crossing-Human_Control’,
    • ‘Pedestrian_Crossing_Physical_Facilities’,
      • ’Light_Conditions’,
      • ‘Weather_Conditions’,
      • ‘Road_Surface_Conditions’,
      • ‘Special_Conditions_at_Site’,
      • ‘Carriageway_Hazards’,
      • ‘Urban_or_Rural_Area’,
      • ‘Did_Police_Officer_Attend_Scene_of_Accident’,
      • ‘LSOA_of_Accident_Location’

    这里写图片描述

LowMemory 方式读取文件

#read the file
filedir='/home/derek/Desktop/python-data-analyis/large-excel-files/Accidents_2013.csv'
data = pd.read_csv(filedir,low_memory=False)
print data.ix[:10]['Day_of_Week']
  • SQL likes 提取数据信息
print 'Accidents'
print '----------'
#选择星期日发生的事故
accidents_sunday = data[data.Day_of_Week==1]
print 'Accidents which happended on a Sunday: ',len(accidents_sunday)
#选择星期日发生的且涉事人数在十人以上的事故
accidents_sunday_twenty_cars = data[(data.Day_of_Week==1) & (data.Number_of_Vehicles>10)]
print'Accidents which happened on a Sunday involving > 10 cars: ' , len(accidents_sunday_twenty_cars)
#选择星期日发生的且涉事人数在十人以上且天气情况是下雨的事故(2对应的是无风下雨)
accidents_sunday_twenty_cars_rain = data[(data.Day_of_Week==1) & (data.Number_of_Vehicles>10) & (data.Weather_Conditions==2)]
print'Accidents which happened on a Sunday involving > 10 cars with rainning: ' , len(accidents_sunday_twenty_cars_rain)
#选择在伦敦的星期日发生的事故
london_data = data[(data['Police_Force'] == 1) & (data.Day_of_Week==1)]
print 'Accidents in London on a Sunday',len(london_data)
#选择在2000年的伦敦的星期日发生的事故
london_data_2000 = london_data[((pd.to_datetime('2000-1-1', errors='coerce')) > (pd.to_datetime(london_data['Date'],errors='coerce'))) & (pd.to_datetime(london_data['Date'],errors='coerce') < (pd.to_datetime('2000-12-31', errors='coerce')))]
print 'Accidents in London on a Sunday in 2000:',len(london_data_2000)

给人的感觉是特别像SQL语句,DataFrame的这种切片,方式特别好用,对不对?

pd.to_datetime(london_data['Date'],errors='coerce')

这里是日期转换函数.

输出:

Accidents
----------
Accidents which happended on a Sunday:  14854
Accidents which happened on a Sunday involving > 10 cars:  1
Accidents which happened on a Sunday involving > 10 cars with rainning:  1
Accidents in London on a Sunday 2374
Accidents in London on a Sunday in 2000: 0


  • 将部分DataFrame数据以XLSX文件存储下来
    确保你安装了XlsxWriter

sudo pip install XlsxWriter

writer = pd.ExcelWriter('london_data.xlsx', engine='xlsxwriter')
london_data.to_excel(writer, 'sheet1')
writer.save()
writer.close()
  • 块读取,分析一个星期中那一天最有出事故的概率最大
    代码.2013,2014,2015三年的事故记录,在’Accidents_2013.csv’,’Accidents_2014.csv’, ‘Accidents_2015.csv’这三个文件中
import pandas as pd
from pandas import Series
import matplotlib.pyplot as plt
#read the file
dir='/home/derek/Desktop/python-data-analyis/large-excel-files/'
filedir=['Accidents_2013.csv','Accidents_2014.csv', 'Accidents_2015.csv']
tot = Series([])
for i in range(3):
    #块读取文件, 每次读1000条记录
    data = pd.read_csv(dir + filedir[i],chunksize=1000)
    for piece in data:
        tot = tot.add(piece['Day_of_Week'].value_counts(), fill_value=0)

day_index = ['Sun', 'Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat']
print 'data like:'
#tot = tot.sort_values(ascending=False)
print tot
#重新构造一个Series,是为了给索引命名
new_Series = Series(tot.values, index=day_index)
new_Series.plot()
plt.show()
plt.close()

控制台输出:

data like:
1    46052
2    60956
3    65006
4    64039
5    64445
6    69378
7    55162
dtype: float64

图:
这里写图片描述
三年记录在案的有425038条记录.

结论: 看来,英国人在工作日出行要比在休息日造成更多的事故.星期五的出行造成的事故最多,或许,星期五急着回家,哈哈.相比起来,星期五不适合外出.

参考文章来源

文件没有提供,是因为:读者可以自己去下载,可能找到更想更好用Python分析的数据.

### 如何使用 Python 处理 XLS 文件 对于处理 `.xls` 文件,存在多种库可以选择。其中 `xlrd` 是专门针对旧版本 Excel 文件(即 `.xls`)的一个有效工具[^4]。 #### 使用 `xlrd` 库读取 XLS 文件 为了能够顺利地打开并读取 `.xls` 文件中的数据,下面给出了一段简单的例子来说明具体的操作方式: ```python import xlrd # 加载指定路径下的 .xls 文件 excel = xlrd.open_workbook("example.xls") # 获取第一个工作表对象 sheet = excel.sheet_by_index(0) # 提取出首行作为字段名列表 header_row = sheet.row_values(0) # 定位特定列的位置索引 column_index = header_row.index('username') # 取得整列的数据值 data_column = sheet.col_values(column_index)[1:] # 排除标题行 for item in data_column: print(item) ``` 这段代码展示了如何通过 `xlrd` 来访问存储于本地磁盘上的 `.xls` 表格文档,并从中提取所需的信息。需要注意的是,在实际应用中应当替换 `"example.xls"` 和 `'username'` 成具体的文件位置以及目标列名称。 然而值得注意的一点是,`xlrd` 自 2.0 版本起不再支持写入功能;如果需要对 `.xls` 进行修改保存,则需考虑其他替代方案如 `xlwt` 或者升级到更新格式的 Excel 文档再利用更现代的技术栈来进行编辑操作。 另外一种常用的方式就是借助 `pandas` 结合 `xlrd` 实现更加便捷高效的数据分析任务。Pandas 的强之处在于它提供了简洁易懂的 API 设计风格,使得开发者可以快速完成复杂的数据转换逻辑而不必深入理解底层细节。 #### 利用 Pandas 读取 XLS 文件 当涉及到更为复杂的表格结构或是希望简化流程时,推荐采用集成度更高的解决方案——比如结合 `pandas` 工具包一起使用: ```python import pandas as pd file_path = 'path/to/your/file.xls' df = pd.read_excel(file_path, engine='xlrd') print(df.head()) titles = df.iloc[:, 0] answers = df.iloc[:, 1] for title, answer in zip(titles, answers): print(f"Title: {title}, Answer: {answer}") ``` 这里特别指出了要显式声明引擎参数为 `'xlrd'` ,这是因为默认情况下 `read_excel()` 函数会尝试自动检测适合的解析器,但对于某些较早版本的 `.xls` 文件来说可能无法正常识别,因此手动设置能确保兼容性[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值