我想在 numpy 中加载一个表,以便第一行和第一列被视为文本标签。与此 R 代码等效的内容:
read.table("filename.txt", row.header=T)
文件是这样的带分隔符的文本文件:
A B C D
X 5 4 3 2
Y 1 0 9 9
Z 8 7 6 5
所以读入我会有一个数组:
[[5,4,3,2],
[1,0,9,9],
[8,7,6,5]]
与某种: 行名 ["X","Y","Z"] colnames ["A","B","C","D"]
有没有这样的类/机制?
最佳答案
Numpy 数组并不完全适合类似表的结构。然而,pandas.DataFrame
是。
对于你想要的,使用 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 指出的那样,如果您确实需要“原始”数据,了解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')])
关于python - 使用行和列索引在 numpy 中加载表,就像在 R 中一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21196363/