结构化的二维Numpy数组:设置列和行名称

16

我想找到一种好的方法将一个2D的numpy数组转化为带有列名和行名的结构化数组。例如:

import numpy as np

column_names = ['a', 'b', 'c']
row_names    = ['1', '2', '3']

matrix = np.reshape((1, 2, 3, 4, 5, 6, 7, 8, 9), (3, 3))

# TODO: insert magic here

matrix['3']['a']  # 7

我已经能够像这样设置列:

matrix.dtype = [(n, matrix.dtype) for n in column_names]

这使得我可以执行matrix[2]['a'],但现在我想重命名行,以便我可以执行matrix['3']['a']


1
据我所知,使用结构化的NumPy数组是不可能实现的。你是否安装了pandas库? - MSeifert
我确实有pandas。你是在建议使用Pandas中的Series进行行索引吗? - freebie
1
不,我建议使用“索引”来访问行 :) - MSeifert
1个回答

23
据我所知,使用纯结构化的NumPy数组无法为行“命名”。 但是,如果您有,可以提供一个“索引”(实际上就像一个“行名称”):
>>> import pandas as pd
>>> import numpy as np
>>> column_names = ['a', 'b', 'c']
>>> row_names    = ['1', '2', '3']

>>> matrix = np.reshape((1, 2, 3, 4, 5, 6, 7, 8, 9), (3, 3))
>>> df = pd.DataFrame(matrix, columns=column_names, index=row_names)
>>> df
   a  b  c
1  1  2  3
2  4  5  6
3  7  8  9

>>> df['a']['3']      # first "column" then "row"
7

>>> df.loc['3', 'a']  # another way to index "row" and "column"
7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接