Fork me on GitHub

Pandas读取大文件

Pandas技巧-如何读取大文件

本文中记录的是如何利用pandas来读取大文件,4个技巧:

  • 如何利用read_csv函数读取没有表头的文件
  • get_chunk()方法来分块读取数据
  • concat()方法将数据库进行叠加(垂直方向)
  • 若数据量过大,采取随机抽放(是否放回)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
filepath = open("taobao.csv",errors="ignore")  # 指定文件路径
reader = pd.read_csv(filepath,
header=None,
names=["user_id","item_id","cat_id","type","time"], # 指定列属性名称
iterator=True)

# loop,chunkSize,chunks = True, 10000000, [] # 连续赋值语句
loop = True
chunkSize = 10000000
chunks = []

while loop: # loop一直为True,执行循环
try:
chunk = reader.get_chunk(chunkSize)
chunks.append(chunk)
except StopIteration:
loop = False
print("Iteration is stopped.")

# 如果考虑数据量过大,只抽取部分的数据来进行分析,采取不放回抽样的方式
# pd.concat(chunks, ignore_index=True).sample(frac=0.05, replace=False) 不放回抽样、记录不重复

df = pd.concat(chunks, ignore_index=True)

参考文章:https://www.cnblogs.com/frchen/p/5749814.html

本文标题:Pandas读取大文件

发布时间:2021年01月21日 - 18:01

原始链接:http://www.renpeter.cn/2021/01/21/Pandas%E8%AF%BB%E5%8F%96%E5%A4%A7%E6%96%87%E4%BB%B6.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea