【发布时间】:2016-05-22 13:18:32
【问题描述】:
有几种方法可以读取数据为二维数组的文件。
- 读取为列表/元组列表
- 使用模块 csv
- 使用模块 numpy
- 使用模块 pandas
它们的应用场景是什么?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
filename = 'test.txt'
# the content of `test.txt`
'''
a b c
d e f
g h i
j k l
'''
# Way 1: read as a list of lists/tuples
lists = list()
with open(filename) as fp:
for line in fp:
lists.append(line.split())
# Way 2: use the module csv
import csv
with open(filename) as fp:
reader = csv.reader(fp, delimiter="\t")
#table = [line for line in reader] # [['a b c'], ['d e f'], ['g h i'], ['j k l']]
table = [line[0].split() for line in reader]
# Way 3: use the module numpy
import numpy as np
table = np.loadtxt(filename, dtype='str')
# Way 4: use the module pandas
import pandas as pd
table = pd.read_csv(filename)
【问题讨论】:
-
如果所有 3 种方法都能达到您想要的效果,则没有“最佳”方法。一个可能更可取,具体取决于您在阅读后要对数据做什么。
-
没有最好的解决方案——不同的程序需要不同的方法。
-
如果满足您的需求,请使用 Way1。如果解析行变得太复杂,请切换到 2。如果您需要使用
numpy数组,请使用 3,而不是元组/列表列表。 -
太糟糕了,这个问题被关闭了,我真的很想知道是否有 明确的情况 numpy 的 loadtxt 或 genfrontxt 比 pandas 的平面文件读取方法更受欢迎
-
@BhargavRao,我编辑了我的问题。请您检查一下并重新打开这个问题吗?
标签: python csv numpy pandas read-write