何时使用 numpy、csv 和 pandas,读取 Python 中的文件(二维数组)?

When to use numpy, csv and pandas, reading a file (2D array) in Python?

有几种方法可以读取数据为二维数组的文件。

它们的应用场景是什么?


#!/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)

如果您想根据文件中的数据对矩阵进行矩阵乘法或其他运算,一定要使用 numpy,因为它 比纯 快得多 Python 代码做同样的事情。

如果您想只存储数据然后以某种方式输出它,请使用纯文本或 csv。