11

我正在尝试找到一种采用 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']

4

1 回答 1

17

据我所知,不可能用纯结构化 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
于 2017-06-22T20:45:10.653 回答