使用行和列索引在numpy中加载表,就像在R中一样?

Idd*_*ddo 2 python numpy header row-number indices

我想在numpy中加载一个表,以便第一行和第一列被视为文本标签.相当于这个R代码的东西:

read.table("filename.txt", row.header=T)
Run Code Online (Sandbox Code Playgroud)

文件是分隔的文本文件,如下所示:

   A    B    C    D
X  5    4    3    2
Y  1    0    9    9
Z  8    7    6    5
Run Code Online (Sandbox Code Playgroud)

因此,读入我将有一个数组:

[[5,4,3,2],
 [1,0,9,9],
 [8,7,6,5]]
Run Code Online (Sandbox Code Playgroud)

某种:rownames ["X","Y","Z"] colnames ["A","B","C","D"]

有没有这样的阶级/机制?

Joe*_*ton 7

Numpy数组不完全适合表格式结构.但是,pandas.DataFrames是.

对于你想要的东西,请使用pandas.

举个例子,你可以做到

data = pandas.read_csv('filename.txt', delim_whitespace=True, index_col=0)
Run Code Online (Sandbox Code Playgroud)

作为一个更完整的示例(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']
Run Code Online (Sandbox Code Playgroud)

这会产生:

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
Run Code Online (Sandbox Code Playgroud)

另外,正如@DSM指出的那样,了解类似的内容DataFrame.values或者DataFrame.to_records()是否需要"原始"numpy数组非常有用.(pandas建立在numpy之上.在一个简单的非严格意义上,a的每一列DataFrame都存储为1D 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')])
Run Code Online (Sandbox Code Playgroud)