1.pandas 简介
-
Pandas 是一个开放源码、BSD 许可的库,提供高性能、易于使用的数据结构和数据分析工具。
-
Pandas 名字衍生自术语 “panel data”(面板数据)和 “Python data analysis”(Python 数据分析)。
-
Pandas 一个强大的分析结构化数据的工具集,基础是 Numpy(提供高性能的矩阵运算)。
-
Pandas 可以从各种文件格式比如 CSV、JSON、SQL、Microsoft Excel 导入数据。
-
Pandas 可以对各种数据进行运算操作,比如归并、再成形、选择,还有数据清洗和数据加工特征。
-
Pandas 广泛应用在学术、金融、统计学等各个数据分析领域。
2.根据文件大小读取csv
一般我们读取文件都是直接使用read_csv()函数来完成csv文件的读取,但是当我们需要进行一个比较大的csv 文件时,则需要对文件进行分片读取,加快读取速度.
具体的封装函数如下
import codecs
import csv
import os
import pandas as pd
def pandas_read_csv(file, encoding='utf-8', header=None, names=None):
"""
直接采用pd.read_csv()函数无法处理文件名中的中文,需要结合open()函数来完成处理
注意 : 如果文件采用的是ansi格式,应当将encoding设置成为gbk
"""
file_size = os.path.getsize(file)
# 判断文件的大小
if 10240 > file_size:
# 文件小于10MB 不需要进行分片读取
with codecs.open(file) as f:
if names is not None:
df = pd.read_csv(f, encoding=encoding, names=names,
low_memory=False, index_col=False)
else:
df = pd.read_csv(f, encoding=encoding, header=header,
low_memory=False, index_col=False)
else:
# 分片读取 读取加速
with codecs.open(file) as f:
if names is not None:
df = pd.read_csv(f, encoding=encoding, names=names,
iterator=True, low_memory=False, index_col=False)
df = get_section_data(df)
else:
df = pd.read_csv(f, encoding=encoding, header=header,
iterator=True, low_memory=False, index_col=False)
df = get_section_data(df)
return df
def get_section_data(df, encoding='utf-8'):
# 每片读取10000行
chunk_size = 10000
chunks = []
df_chunk = pd.read_csv(df, encoding=encoding)
for chunk in df_chunk:
chunks.append(chunk)
df = pd.concat(chunks,ignore_index = True)
return df
3.读取excel
def read_xls(file, encoding='utf-8', header=None, nrows=0, sheet_name=0, skiprow=None):
if 10240 > file_size:
# 文件小于10MB 不需要进行分片读取
with codecs.open(file) as f:
df = pd .read_excel()
else:
# 分片读取 读取加速
chunks = []
i_chunk = 0
skiprows = 1
while True:
with codecs.open(file) as f:
df = pd.read_excel(file_path, sheetname=sheetname,
nrows=nrows, skiprows=skiprows, header=None)
skiprows += nrows
if not df.shape[0]:
break
else:
chunks.append(df_chunk)
i_chunk += 1
df = pd.concat(chunks)
return df