Numpy 数组并不完全适合类似表的结构。但是,pandas.DataFrames 是。
如需,请使用pandas.
对于你的例子,你会这样做
data = pandas.read_csv('filename.txt', delim_whitespace=True, index_col=0)
作为更完整的示例(使用StringIO 模拟您的文件):
from StringIO import StringIO
import pandas as pd
f = StringIO("""A B C D
X 5 4 3 2
Y 1 0 9 9
Z 8 7 6 5""")
x = pd.read_csv(f, delim_whitespace=True, index_col=0)
print 'The DataFrame:'
print x
print 'Selecting a column'
print x['D'] # or "x.D" if there aren't spaces in the name
print 'Selecting a row'
print x.loc['Y']
这会产生:
The DataFrame:
A B C D
X 5 4 3 2
Y 1 0 9 9
Z 8 7 6 5
Selecting a column
X 2
Y 9
Z 5
Name: D, dtype: int64
Selecting a row
A 1
B 0
C 9
D 9
Name: Y, dtype: int64
另外,正如@DSM 所指出的,如果您确实需要一个“原始”numpy 数组,那么了解DataFrame.values 或DataFrame.to_records() 之类的内容非常有用。 (pandas 建立在 numpy 之上。在简单的非严格意义上,DataFrame 的每一列都存储为一维 numpy 数组。)
例如:
In [2]: x.values
Out[2]:
array([[5, 4, 3, 2],
[1, 0, 9, 9],
[8, 7, 6, 5]])
In [3]: x.to_records()
Out[3]:
rec.array([('X', 5, 4, 3, 2), ('Y', 1, 0, 9, 9), ('Z', 8, 7, 6, 5)],
dtype=[('index', 'O'), ('A', '<i8'), ('B', '<i8'), ('C', '<i8'), ('D', '<i8')])