结构化2D Numpy Array:设置列名和行名

时间:2017-06-22 20:35:05

标签: python arrays numpy structured-array

我试图找到一种很好的方法来获取一个2d numpy数组并将列和行名称作为结构化数组附加。例如:

matrix[2]['a']

我已经能够使用这样设置列:

matrix['3']['a']

这让我可以{{1}},但现在我想重命名行,以便我可以{{1}}。

1 个答案:

答案 0 :(得分:5)

据我所知," name"具有纯结构化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